summaryrefslogtreecommitdiff
path: root/common/charge_state.c
blob: a519de17c559bb89094d5bac5751b85a2b8bcb6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 *
 * Battery charging task and state machine.
 */


#include "battery.h"
#include "battery_pack.h"
#include "board.h"
#include "charge_state.h"
#include "charger.h"
#include "chipset.h"
#include "console.h"
#include "gpio.h"
#include "lpc.h"
#include "ec_commands.h"
#include "power_button.h"
#include "power_led.h"
#include "smart_battery.h"
#include "system.h"
#include "timer.h"
#include "util.h"
#include "x86_power.h"

/* Console output macros */
#define CPUTS(outstr) cputs(CC_CHARGER, outstr)
#define CPRINTF(format, args...) cprintf(CC_CHARGER, format, ## args)

/* Stop charge when state of charge reaches this percentage */
#define STOP_CHARGE_THRESHOLD 100

static const char * const state_name[] = POWER_STATE_NAME_TABLE;

/* Battery information used to fill ACPI _BIF and/or _BIX */
static void update_battery_info(void)
{
	char *batt_str;
	int batt_serial;

	/* Design Capacity of Full */
	battery_design_capacity((int *)(lpc_get_memmap_range() +
					EC_MEMMAP_BATT_DCAP));

	/* Design Voltage */
	battery_design_voltage((int *)(lpc_get_memmap_range() +
				       EC_MEMMAP_BATT_DVLT));

	/* Last Full Charge Capacity */
	battery_full_charge_capacity((int *)(lpc_get_memmap_range() +
					     EC_MEMMAP_BATT_LFCC));

	/* Cycle Count */
	battery_cycle_count((int *)(lpc_get_memmap_range() +
				    EC_MEMMAP_BATT_CCNT));

	/* Battery Manufacturer string */
	batt_str = (char *)(lpc_get_memmap_range() + EC_MEMMAP_BATT_MFGR);
	memset(batt_str, 0, EC_MEMMAP_TEXT_MAX);
	battery_manufacturer_name(batt_str, EC_MEMMAP_TEXT_MAX);

	/* Battery Model string */
	batt_str = (char *)(lpc_get_memmap_range() + EC_MEMMAP_BATT_MODEL);
	memset(batt_str, 0, EC_MEMMAP_TEXT_MAX);
	battery_device_name(batt_str, EC_MEMMAP_TEXT_MAX);

	/* Battery Type string */
	batt_str = (char *)(lpc_get_memmap_range() + EC_MEMMAP_BATT_TYPE);
	battery_device_chemistry(batt_str, EC_MEMMAP_TEXT_MAX);

	/* Smart battery serial number is 16 bits */
	batt_str = (char *)(lpc_get_memmap_range() + EC_MEMMAP_BATT_SERIAL);
	memset(batt_str, 0, EC_MEMMAP_TEXT_MAX);
	if (battery_serial_number(&batt_serial) == 0) {
		*batt_str++ = hex2asc(0xf & (batt_serial >> 12));
		*batt_str++ = hex2asc(0xf & (batt_serial >> 8));
		*batt_str++ = hex2asc(0xf & (batt_serial >> 4));
		*batt_str++ = hex2asc(0xf & batt_serial);
	}
}

/* Prevent battery from going into deep discharge state */
static void poweroff_wait_ac(void)
{
	/* Shutdown the main processor */
	if (chipset_in_state(CHIPSET_STATE_ON)) {
		/* chipset_force_state(CHIPSET_STATE_SOFT_OFF);
		 * TODO(rong): remove platform dependent code
		 */
#ifdef CONFIG_POWER_X86POWER
		x86_power_force_shutdown();
#endif /* CONFIG_POWER_X86POWER */
	}

	/* TODO(rong): remove this workaround after ec deep sleep */
	while (!power_ac_present()) {
		/* Check ac_present every 5 seconds */
		usleep(SECOND * 5);
	}
}

/* Common handler for charging states.
 * This handler gets battery charging parameters, charger state, ac state,
 * and timestamp. It also fills memory map and issues power events on state
 * change.
 */
static int state_common(struct power_state_context *ctx)
{
	int rv, d;

	struct power_state_data *curr = &ctx->curr;
	struct power_state_data *prev = &ctx->prev;
	struct batt_params *batt = &ctx->curr.batt;
	uint8_t *batt_flags = ctx->memmap_batt_flags;

	/* Copy previous state and init new state */
	ctx->prev = ctx->curr;
	curr->ts = get_time();
	curr->error = 0;

	/* Detect AC change */
	curr->ac = power_ac_present();
	if (curr->ac != prev->ac) {
		if (curr->ac) {
			/* AC on
			 *   Initialize charger to power on reset mode
			 */
			rv = charger_post_init();
			if (rv)
				curr->error |= F_CHARGER_INIT;
			lpc_set_host_events(EC_HOST_EVENT_MASK(
				EC_HOST_EVENT_AC_CONNECTED));
		} else {
			/* AC off */
			lpc_set_host_events(EC_HOST_EVENT_MASK(
				EC_HOST_EVENT_AC_DISCONNECTED));
		}
	}

	if (curr->ac) {
		*batt_flags |= EC_BATT_FLAG_AC_PRESENT;
		rv = charger_get_voltage(&curr->charging_voltage);
		if (rv) {
			charger_set_voltage(0);
			charger_set_current(0);
			curr->error |= F_CHARGER_VOLTAGE;
		}
		rv = charger_get_current(&curr->charging_current);
		if (rv) {
			charger_set_voltage(0);
			charger_set_current(0);
			curr->error |= F_CHARGER_CURRENT;
		}
	} else
		*batt_flags &= ~EC_BATT_FLAG_AC_PRESENT;

	rv = battery_temperature(&batt->temperature);
	if (rv) {
		/* Check low battery condition and retry */
		if (curr->ac && !(curr->error & F_CHARGER_MASK) &&
				(curr->charging_voltage == 0 ||
				curr->charging_current == 0)) {
			charger_set_voltage(ctx->battery->voltage_min);
			charger_set_current(ctx->charger->current_min);
			usleep(SECOND);
			rv = battery_temperature(&batt->temperature);
		}
	}

	if (rv)
		curr->error |= F_BATTERY_TEMPERATURE;

	rv = battery_voltage(&batt->voltage);
	if (rv)
		curr->error |= F_BATTERY_VOLTAGE;
	*ctx->memmap_batt_volt = batt->voltage;

	rv = battery_current(&batt->current);
	if (rv)
		curr->error |= F_BATTERY_CURRENT;
	/* Memory mapped value: discharge rate */
	*ctx->memmap_batt_rate = batt->current < 0 ?
		-batt->current : batt->current;

	rv = battery_desired_voltage(&batt->desired_voltage);
	if (rv)
		curr->error |= F_DESIRED_VOLTAGE;

	rv = battery_desired_current(&batt->desired_current);
	if (rv)
		curr->error |= F_DESIRED_CURRENT;

	rv = battery_state_of_charge(&batt->state_of_charge);
	if (rv)
		curr->error |= F_BATTERY_STATE_OF_CHARGE;

	/* Prevent deep discharging */
	if (!curr->ac)
		if ((batt->state_of_charge < BATTERY_LEVEL_SHUTDOWN &&
		    !(curr->error & F_BATTERY_STATE_OF_CHARGE)) ||
		    (batt->voltage <= ctx->battery->voltage_min &&
		    !(curr->error & F_BATTERY_VOLTAGE)))
			poweroff_wait_ac();

	/* Check battery presence */
	if (curr->error & F_BATTERY_MASK) {
		*ctx->memmap_batt_flags &= ~EC_BATT_FLAG_BATT_PRESENT;
		return curr->error;
	}

	*ctx->memmap_batt_flags |= EC_BATT_FLAG_BATT_PRESENT;

	/* Battery charge level low */
	if (batt->state_of_charge <= BATTERY_LEVEL_LOW &&
			prev->batt.state_of_charge > BATTERY_LEVEL_LOW)
		lpc_set_host_events(EC_HOST_EVENT_MASK(
			EC_HOST_EVENT_BATTERY_LOW));

	/* Battery charge level critical */
	if (batt->state_of_charge <= BATTERY_LEVEL_CRITICAL) {
		*ctx->memmap_batt_flags |= EC_BATT_FLAG_LEVEL_CRITICAL;
		/* Send battery critical host event */
		if (prev->batt.state_of_charge > BATTERY_LEVEL_CRITICAL)
			lpc_set_host_events(EC_HOST_EVENT_MASK(
					EC_HOST_EVENT_BATTERY_CRITICAL));
	} else
		*ctx->memmap_batt_flags &= ~EC_BATT_FLAG_LEVEL_CRITICAL;


	/* Apply battery pack vendor charging method */
	battery_vendor_params(batt);

#ifdef CONFIG_CHARGING_CURRENT_LIMIT
	if (batt->desired_current > CONFIG_CHARGING_CURRENT_LIMIT)
		batt->desired_current = CONFIG_CHARGING_CURRENT_LIMIT;
#endif

	rv = battery_get_battery_mode(&d);
	if (rv) {
		curr->error |= F_BATTERY_MODE;
	} else {
		if (d & MODE_CAPACITY) {
			/* Battery capacity mode was set to mW
			 * reset it back to mAh
			 */
			d &= ~MODE_CAPACITY;
			rv = battery_set_battery_mode(d);
			if (rv)
				ctx->curr.error |= F_BATTERY_MODE;
		}
	}
	rv = battery_remaining_capacity(&d);
	if (rv)
		ctx->curr.error |= F_BATTERY_CAPACITY;
	else
		*ctx->memmap_batt_cap = d;

	return ctx->curr.error;
}

/* Init state handler
 *	- check ac, charger, battery and temperature
 *	- initialize charger
 *	- new states: DISCHARGE, IDLE
 */
static enum power_state state_init(struct power_state_context *ctx)
{
	/* Stop charger, unconditionally */
	charger_set_current(0);
	charger_set_voltage(0);

	/* If AC is not present, switch to discharging state */
	if (!ctx->curr.ac)
		return PWR_STATE_DISCHARGE;

	/* Check general error conditions */
	if (ctx->curr.error)
		return PWR_STATE_ERROR;

	/* Update static battery info */
	update_battery_info();

	/* Send battery event to host */
	lpc_set_host_events(EC_HOST_EVENT_MASK(
			    EC_HOST_EVENT_BATTERY));

	return PWR_STATE_IDLE;
}

/* Idle state handler
 *	- both charger and battery are online
 *	- detect charger and battery status change
 *	- new states: CHARGE, INIT
 */
static enum power_state state_idle(struct power_state_context *ctx)
{
	struct batt_params *batt = &ctx->curr.batt;
	const struct charger_info *c_info = ctx->charger;

	if (!ctx->curr.ac)
		return PWR_STATE_INIT;

	if (ctx->curr.error)
		return PWR_STATE_ERROR;

	/* Prevent charging in idle mode */
	if (ctx->curr.charging_voltage ||
	    ctx->curr.charging_current)
		return PWR_STATE_INIT;

	if (ctx->curr.batt.state_of_charge >= STOP_CHARGE_THRESHOLD)
		return PWR_STATE_UNCHANGE;

	/* Configure init charger state and switch to charge state */
	if (ctx->curr.batt.desired_voltage &&
	    ctx->curr.batt.desired_current) {
		/* Set charger output constraints */
		if (batt->desired_current < ctx->charger->current_min) {
			/* Trickle charging */
			if (charger_set_current(c_info->current_min) ||
			    charger_set_voltage(batt->voltage))
				return PWR_STATE_ERROR;
			ctx->trickle_charging_time = get_time();
		} else {
			/* Normal charging */
			if (charger_set_voltage(batt->desired_voltage) ||
			    charger_set_current(batt->desired_current))
				return PWR_STATE_ERROR;
		}
		ctx->charger_update_time = get_time();
		return PWR_STATE_CHARGE;
	}

	return PWR_STATE_UNCHANGE;
}

/* Charge state handler
 *	- detect battery status change
 *	- new state: INIT
 */
static enum power_state state_charge(struct power_state_context *ctx)
{
	if (ctx->curr.error)
		return PWR_STATE_ERROR;

	if (ctx->curr.batt.desired_current < ctx->charger->current_min)
		return trickle_charge(ctx);

	/* Check charger reset */
	if (ctx->curr.charging_voltage == 0 ||
	    ctx->curr.charging_current == 0)
		return PWR_STATE_INIT;

	if (!ctx->curr.ac)
		return PWR_STATE_INIT;

	if (ctx->curr.batt.state_of_charge >= STOP_CHARGE_THRESHOLD) {
		if (charger_set_voltage(0) || charger_set_current(0))
			return PWR_STATE_ERROR;
		return PWR_STATE_IDLE;
	}

	if ((ctx->curr.batt.desired_voltage != ctx->curr.charging_voltage) ||
	    (ctx->curr.batt.desired_current != ctx->curr.charging_current) ||
	    (ctx->curr.ts.val - ctx->charger_update_time.val >
						CHARGER_UPDATE_PERIOD)) {
		if (ctx->curr.batt.desired_current < ctx->charger->current_min)
			return PWR_STATE_INIT;

		if (charger_set_voltage(ctx->curr.batt.desired_voltage) ||
		    charger_set_current(ctx->curr.batt.desired_current))
			return PWR_STATE_ERROR;
		ctx->charger_update_time = get_time();
	}

	return PWR_STATE_UNCHANGE;
}

/* Discharge state handler
 *	- detect ac status
 *	- new state: INIT
 */
static enum power_state state_discharge(struct power_state_context *ctx)
{
	struct batt_params *batt = &ctx->curr.batt;
	if (ctx->curr.ac)
		return PWR_STATE_INIT;

	if (ctx->curr.error)
		return PWR_STATE_ERROR;

	/* Overtemp in discharging state
	 *   - poweroff host and ec
	 */
	if (batt->temperature > ctx->battery->temp_discharge_max ||
	    batt->temperature < ctx->battery->temp_discharge_min)
		poweroff_wait_ac();

	return PWR_STATE_UNCHANGE;
}

/* Error state handler
 *	- check charger and battery communication
 *	- log error
 *	- new state: INIT
 */
static enum power_state state_error(struct power_state_context *ctx)
{
	static int logged_error;

	if (!ctx->curr.error) {
		logged_error = 0;
		return PWR_STATE_INIT;
	}

	/* Debug output */
	if (ctx->curr.error != logged_error) {
		CPRINTF("[Charge error: flag[%08b -> %08b], ac %d, "
			" charger %s, battery %s\n",
			logged_error, ctx->curr.error, ctx->curr.ac,
			(ctx->curr.error & F_CHARGER_MASK) ?
					"(err)" : "ok",
			(ctx->curr.error & F_BATTERY_MASK) ?
					"(err)" : "ok");

		logged_error = ctx->curr.error;
	}

	return PWR_STATE_UNCHANGE;
}

static void charging_progress(struct power_state_context *ctx)
{
	int seconds, minutes;

	if (ctx->curr.batt.state_of_charge !=
	    ctx->prev.batt.state_of_charge) {
		if (ctx->curr.ac)
			battery_time_to_full(&minutes);
		else
			battery_time_to_empty(&minutes);

		CPRINTF("[Battery %3d%% / %dh:%d]\n",
			ctx->curr.batt.state_of_charge,
			minutes / 60, minutes % 60);
		return;
	}

	if (ctx->curr.charging_voltage != ctx->prev.charging_voltage &&
			ctx->trickle_charging_time.val) {
		/* Calculating minutes by dividing usec by 60 million
		 * GNU toolchain generate architecture dependent calls
		 * instead of machine code when the divisor is large.
		 * Hence following calculation was broke into 2 lines.
		 */
		seconds = (int)(get_time().val -
				ctx->trickle_charging_time.val) / (int)SECOND;
		minutes = seconds / 60;
		CPRINTF("[Precharge CHG(%dmV) BATT(%dmV %dmA) "
			"%dh:%d]\n", ctx->curr.charging_voltage,
			ctx->curr.batt.voltage, ctx->curr.batt.current,
			minutes / 60, minutes % 60);
	}
}

/* Battery charging task */
void charge_state_machine_task(void)
{
	struct power_state_context ctx;
	timestamp_t ts;
	int sleep_usec = POLL_PERIOD_SHORT, diff_usec, sleep_next;
	enum power_state new_state;
	uint8_t batt_flags;

	ctx.prev.state = PWR_STATE_INIT;
	ctx.curr.state = PWR_STATE_INIT;
	ctx.trickle_charging_time.val = 0;
	ctx.battery = battery_get_info();
	ctx.charger = charger_get_info();

	/* Setup LPC direct memmap */
	ctx.memmap_batt_volt  = (uint32_t *)(lpc_get_memmap_range() +
					EC_MEMMAP_BATT_VOLT);
	ctx.memmap_batt_rate  = (uint32_t *)(lpc_get_memmap_range() +
					EC_MEMMAP_BATT_RATE);
	ctx.memmap_batt_cap   = (uint32_t *)(lpc_get_memmap_range() +
					EC_MEMMAP_BATT_CAP);
	ctx.memmap_batt_flags = (uint8_t *)(lpc_get_memmap_range() +
					EC_MEMMAP_BATT_FLAG);

	while (1) {

		state_common(&ctx);

		switch (ctx.prev.state) {
		case PWR_STATE_INIT:
			new_state = state_init(&ctx);
			break;
		case PWR_STATE_IDLE:
			new_state = state_idle(&ctx);
			break;
		case PWR_STATE_DISCHARGE:
			new_state = state_discharge(&ctx);
			break;
		case PWR_STATE_CHARGE:
			new_state = state_charge(&ctx);
			break;
		case PWR_STATE_ERROR:
			new_state = state_error(&ctx);
			break;
		default:
			CPRINTF("[Undefined charging state %d]\n",
				ctx.curr.state);
			ctx.curr.state = PWR_STATE_ERROR;
			new_state = PWR_STATE_ERROR;
		}

		if (new_state) {
			ctx.curr.state = new_state;
			CPRINTF("[Charge state %s -> %s]\n",
				state_name[ctx.prev.state],
				state_name[new_state]);
		}

		switch (new_state) {
		case PWR_STATE_IDLE:
			batt_flags = *ctx.memmap_batt_flags;
			batt_flags &= ~EC_BATT_FLAG_CHARGING;
			batt_flags &= ~EC_BATT_FLAG_DISCHARGING;
			*ctx.memmap_batt_flags = batt_flags;

			/* Charge done */
			powerled_set(POWERLED_GREEN);

			sleep_usec = POLL_PERIOD_LONG;
			break;
		case PWR_STATE_DISCHARGE:
			batt_flags = *ctx.memmap_batt_flags;
			batt_flags &= ~EC_BATT_FLAG_CHARGING;
			batt_flags |= EC_BATT_FLAG_DISCHARGING;
			*ctx.memmap_batt_flags = batt_flags;
			sleep_usec = POLL_PERIOD_LONG;
			break;
		case PWR_STATE_CHARGE:
			batt_flags = *ctx.memmap_batt_flags;
			batt_flags |= EC_BATT_FLAG_CHARGING;
			batt_flags &= ~EC_BATT_FLAG_DISCHARGING;
			*ctx.memmap_batt_flags = batt_flags;

			/* Charging */
			powerled_set(POWERLED_YELLOW);

			sleep_usec = POLL_PERIOD_CHARGE;
			break;
		case PWR_STATE_ERROR:
			/* Error */
			powerled_set(POWERLED_RED);

			sleep_usec = POLL_PERIOD_CHARGE;
			break;
		case PWR_STATE_UNCHANGE:
			/* Don't change sleep duration */
			break;
		default:
			/* Other state; poll quickly and hope it goes away */
			sleep_usec = POLL_PERIOD_SHORT;
		}

		/* Show charging progress in console */
		charging_progress(&ctx);

		ts = get_time();
		diff_usec = (int)(ts.val - ctx.curr.ts.val);
		sleep_next = sleep_usec - diff_usec;

		if (sleep_next < MIN_SLEEP_USEC)
			sleep_next = MIN_SLEEP_USEC;
		if (sleep_next > MAX_SLEEP_USEC)
			sleep_next = MAX_SLEEP_USEC;

		usleep(sleep_next);
	}
}