xref: /linux/drivers/power/supply/cpcap-battery.c (revision bba2c3615bd6cfee7456d1130f2e6b01b3f4e9ba)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Battery driver for CPCAP PMIC
4  *
5  * Copyright (C) 2017 Tony Lindgren <tony@atomide.com>
6  *
7  * Some parts of the code based on earlier Motorola mapphone Linux kernel
8  * drivers:
9  *
10  * Copyright (C) 2009-2010 Motorola, Inc.
11  */
12 
13 #include <linux/delay.h>
14 #include <linux/err.h>
15 #include <linux/interrupt.h>
16 #include <linux/kernel.h>
17 #include <linux/module.h>
18 #include <linux/of.h>
19 #include <linux/platform_device.h>
20 #include <linux/power_supply.h>
21 #include <linux/reboot.h>
22 #include <linux/regmap.h>
23 #include <linux/nvmem-consumer.h>
24 #include <linux/moduleparam.h>
25 
26 #include <linux/iio/consumer.h>
27 #include <linux/iio/types.h>
28 #include <linux/mfd/motorola-cpcap.h>
29 
30 /*
31  * Register bit defines for CPCAP_REG_BPEOL. Some of these seem to
32  * map to MC13783UG.pdf "Table 5-19. Register 13, Power Control 0"
33  * to enable BATTDETEN, LOBAT and EOL features. We currently use
34  * LOBAT interrupts instead of EOL.
35  */
36 #define CPCAP_REG_BPEOL_BIT_EOL9	BIT(9)	/* Set for EOL irq */
37 #define CPCAP_REG_BPEOL_BIT_EOL8	BIT(8)	/* Set for EOL irq */
38 #define CPCAP_REG_BPEOL_BIT_UNKNOWN7	BIT(7)
39 #define CPCAP_REG_BPEOL_BIT_UNKNOWN6	BIT(6)
40 #define CPCAP_REG_BPEOL_BIT_UNKNOWN5	BIT(5)
41 #define CPCAP_REG_BPEOL_BIT_EOL_MULTI	BIT(4)	/* Set for multiple EOL irqs */
42 #define CPCAP_REG_BPEOL_BIT_UNKNOWN3	BIT(3)
43 #define CPCAP_REG_BPEOL_BIT_UNKNOWN2	BIT(2)
44 #define CPCAP_REG_BPEOL_BIT_BATTDETEN	BIT(1)	/* Enable battery detect */
45 #define CPCAP_REG_BPEOL_BIT_EOLSEL	BIT(0)	/* BPDET = 0, EOL = 1 */
46 
47 /*
48  * Register bit defines for CPCAP_REG_CCC1. These seem similar to the twl6030
49  * coulomb counter registers rather than the mc13892 registers. Both twl6030
50  * and mc13892 set bits 2 and 1 to reset and clear registers. But mc13892
51  * sets bit 0 to start the coulomb counter while twl6030 sets bit 0 to stop
52  * the coulomb counter like cpcap does. So for now, we use the twl6030 style
53  * naming for the registers.
54  */
55 #define CPCAP_REG_CCC1_ACTIVE_MODE1	BIT(4)	/* Update rate */
56 #define CPCAP_REG_CCC1_ACTIVE_MODE0	BIT(3)	/* Update rate */
57 #define CPCAP_REG_CCC1_AUTOCLEAR	BIT(2)	/* Resets sample registers */
58 #define CPCAP_REG_CCC1_CAL_EN		BIT(1)	/* Clears after write in 1s */
59 #define CPCAP_REG_CCC1_PAUSE		BIT(0)	/* Stop counters, allow write */
60 #define CPCAP_REG_CCC1_RESET_MASK	(CPCAP_REG_CCC1_AUTOCLEAR | \
61 					 CPCAP_REG_CCC1_CAL_EN)
62 
63 #define CPCAP_REG_CCCC2_RATE1		BIT(5)
64 #define CPCAP_REG_CCCC2_RATE0		BIT(4)
65 #define CPCAP_REG_CCCC2_ENABLE		BIT(3)
66 
67 #define CPCAP_BATTERY_CC_SAMPLE_PERIOD_MS	250
68 
69 #define CPCAP_BATTERY_EB41_HW4X_ID 0x9E
70 #define CPCAP_BATTERY_BW8X_ID 0x98
71 
72 enum {
73 	CPCAP_BATTERY_IIO_BATTDET,
74 	CPCAP_BATTERY_IIO_VOLTAGE,
75 	CPCAP_BATTERY_IIO_CHRG_CURRENT,
76 	CPCAP_BATTERY_IIO_BATT_CURRENT,
77 	CPCAP_BATTERY_IIO_NR,
78 };
79 
80 enum cpcap_battery_irq_action {
81 	CPCAP_BATTERY_IRQ_ACTION_NONE,
82 	CPCAP_BATTERY_IRQ_ACTION_CC_CAL_DONE,
83 	CPCAP_BATTERY_IRQ_ACTION_BATTERY_LOW,
84 	CPCAP_BATTERY_IRQ_ACTION_POWEROFF,
85 };
86 
87 struct cpcap_interrupt_desc {
88 	const char *name;
89 	struct list_head node;
90 	int irq;
91 	enum cpcap_battery_irq_action action;
92 };
93 
94 struct cpcap_battery_config {
95 	int cd_factor;
96 	struct power_supply_info info;
97 	struct power_supply_battery_info bat;
98 };
99 
100 struct cpcap_coulomb_counter_data {
101 	s32 sample;		/* 24 or 32 bits */
102 	s32 accumulator;
103 	s16 offset;		/* 9 bits */
104 	s16 integrator;		/* 13 or 16 bits */
105 };
106 
107 enum cpcap_battery_state {
108 	CPCAP_BATTERY_STATE_PREVIOUS,
109 	CPCAP_BATTERY_STATE_LATEST,
110 	CPCAP_BATTERY_STATE_EMPTY,
111 	CPCAP_BATTERY_STATE_FULL,
112 	CPCAP_BATTERY_STATE_NR,
113 };
114 
115 struct cpcap_battery_state_data {
116 	int voltage;
117 	int current_ua;
118 	int counter_uah;
119 	int temperature;
120 	ktime_t time;
121 	struct cpcap_coulomb_counter_data cc;
122 };
123 
124 struct cpcap_battery_ddata {
125 	struct device *dev;
126 	struct regmap *reg;
127 	struct list_head irq_list;
128 	struct iio_channel *channels[CPCAP_BATTERY_IIO_NR];
129 	struct power_supply *psy;
130 	struct cpcap_battery_config config;
131 	struct cpcap_battery_state_data state[CPCAP_BATTERY_STATE_NR];
132 	u32 cc_lsb;		/* μAms per LSB */
133 	atomic_t active;
134 	int charge_full;
135 	int status;
136 	u16 vendor;
137 	bool check_nvmem;
138 	unsigned int is_full:1;
139 };
140 
141 #define CPCAP_NO_BATTERY	-400
142 
143 static bool ignore_temperature_probe;
144 module_param(ignore_temperature_probe, bool, 0660);
145 
146 static struct cpcap_battery_state_data *
147 cpcap_battery_get_state(struct cpcap_battery_ddata *ddata,
148 			enum cpcap_battery_state state)
149 {
150 	if (state >= CPCAP_BATTERY_STATE_NR)
151 		return NULL;
152 
153 	return &ddata->state[state];
154 }
155 
156 static struct cpcap_battery_state_data *
157 cpcap_battery_latest(struct cpcap_battery_ddata *ddata)
158 {
159 	return cpcap_battery_get_state(ddata, CPCAP_BATTERY_STATE_LATEST);
160 }
161 
162 static struct cpcap_battery_state_data *
163 cpcap_battery_previous(struct cpcap_battery_ddata *ddata)
164 {
165 	return cpcap_battery_get_state(ddata, CPCAP_BATTERY_STATE_PREVIOUS);
166 }
167 
168 static struct cpcap_battery_state_data *
169 cpcap_battery_get_empty(struct cpcap_battery_ddata *ddata)
170 {
171 	return cpcap_battery_get_state(ddata, CPCAP_BATTERY_STATE_EMPTY);
172 }
173 
174 static struct cpcap_battery_state_data *
175 cpcap_battery_get_full(struct cpcap_battery_ddata *ddata)
176 {
177 	return cpcap_battery_get_state(ddata, CPCAP_BATTERY_STATE_FULL);
178 }
179 
180 static int cpcap_charger_battery_temperature(struct cpcap_battery_ddata *ddata,
181 					     int *value)
182 {
183 	struct iio_channel *channel;
184 	int error;
185 
186 	channel = ddata->channels[CPCAP_BATTERY_IIO_BATTDET];
187 	error = iio_read_channel_processed(channel, value);
188 	if (error < 0) {
189 		if (!ignore_temperature_probe)
190 			dev_warn(ddata->dev, "%s failed: %i\n", __func__, error);
191 		*value = CPCAP_NO_BATTERY;
192 
193 		return error;
194 	}
195 
196 	*value /= 100;
197 
198 	return 0;
199 }
200 
201 static int cpcap_battery_get_voltage(struct cpcap_battery_ddata *ddata)
202 {
203 	struct iio_channel *channel;
204 	int error, value = 0;
205 
206 	channel = ddata->channels[CPCAP_BATTERY_IIO_VOLTAGE];
207 	error = iio_read_channel_processed(channel, &value);
208 	if (error < 0) {
209 		dev_warn(ddata->dev, "%s failed: %i\n", __func__, error);
210 
211 		return 0;
212 	}
213 
214 	return value * 1000;
215 }
216 
217 static int cpcap_battery_get_current(struct cpcap_battery_ddata *ddata)
218 {
219 	struct iio_channel *channel;
220 	int error, value = 0;
221 
222 	channel = ddata->channels[CPCAP_BATTERY_IIO_BATT_CURRENT];
223 	error = iio_read_channel_processed(channel, &value);
224 	if (error < 0) {
225 		dev_warn(ddata->dev, "%s failed: %i\n", __func__, error);
226 
227 		return 0;
228 	}
229 
230 	return value * 1000;
231 }
232 
233 /**
234  * cpcap_battery_cc_raw_div - calculate and divide coulomb counter μAms values
235  * @ddata: device driver data
236  * @sample: coulomb counter sample value
237  * @accumulator: coulomb counter integrator value
238  * @offset: coulomb counter offset value
239  * @divider: conversion divider
240  *
241  * Note that cc_lsb and cc_dur values are from Motorola Linux kernel
242  * function data_get_avg_curr_ua() and seem to be based on measured test
243  * results. It also has the following comment:
244  *
245  * Adjustment factors are applied here as a temp solution per the test
246  * results. Need to work out a formal solution for this adjustment.
247  *
248  * A coulomb counter for similar hardware seems to be documented in
249  * "TWL6030 Gas Gauging Basics (Rev. A)" swca095a.pdf in chapter
250  * "10 Calculating Accumulated Current". We however follow what the
251  * Motorola mapphone Linux kernel is doing as there may be either a
252  * TI or ST coulomb counter in the PMIC.
253  */
254 static int cpcap_battery_cc_raw_div(struct cpcap_battery_ddata *ddata,
255 				    s32 sample, s32 accumulator,
256 				    s16 offset, u32 divider)
257 {
258 	s64 acc;
259 
260 	if (!divider)
261 		return 0;
262 
263 	acc = accumulator;
264 	acc -= (s64)sample * offset;
265 	acc *= ddata->cc_lsb;
266 	acc *= -1;
267 	acc = div_s64(acc, divider);
268 
269 	return acc;
270 }
271 
272 /* 3600000μAms = 1μAh */
273 static int cpcap_battery_cc_to_uah(struct cpcap_battery_ddata *ddata,
274 				   s32 sample, s32 accumulator,
275 				   s16 offset)
276 {
277 	return cpcap_battery_cc_raw_div(ddata, sample,
278 					accumulator, offset,
279 					3600000);
280 }
281 
282 static int cpcap_battery_cc_to_ua(struct cpcap_battery_ddata *ddata,
283 				  s32 sample, s32 accumulator,
284 				  s16 offset)
285 {
286 	return cpcap_battery_cc_raw_div(ddata, sample,
287 					accumulator, offset,
288 					sample *
289 					CPCAP_BATTERY_CC_SAMPLE_PERIOD_MS);
290 }
291 
292 /**
293  * cpcap_battery_read_accumulated - reads cpcap coulomb counter
294  * @ddata: device driver data
295  * @ccd: coulomb counter values
296  *
297  * Based on Motorola mapphone kernel function data_read_regs().
298  * Looking at the registers, the coulomb counter seems similar to
299  * the coulomb counter in TWL6030. See "TWL6030 Gas Gauging Basics
300  * (Rev. A) swca095a.pdf for "10 Calculating Accumulated Current".
301  *
302  * Note that swca095a.pdf instructs to stop the coulomb counter
303  * before reading to avoid values changing. Motorola mapphone
304  * Linux kernel does not do it, so let's assume they've verified
305  * the data produced is correct.
306  */
307 static int
308 cpcap_battery_read_accumulated(struct cpcap_battery_ddata *ddata,
309 			       struct cpcap_coulomb_counter_data *ccd)
310 {
311 	u16 buf[7];	/* CPCAP_REG_CCS1 to CCI */
312 	int error;
313 
314 	ccd->sample = 0;
315 	ccd->accumulator = 0;
316 	ccd->offset = 0;
317 	ccd->integrator = 0;
318 
319 	/* Read coulomb counter register range */
320 	error = regmap_bulk_read(ddata->reg, CPCAP_REG_CCS1,
321 				 buf, ARRAY_SIZE(buf));
322 	if (error)
323 		return 0;
324 
325 	/* Sample value CPCAP_REG_CCS1 & 2 */
326 	ccd->sample = (buf[1] & 0x0fff) << 16;
327 	ccd->sample |= buf[0];
328 	if (ddata->vendor == CPCAP_VENDOR_TI)
329 		ccd->sample = sign_extend32(24, ccd->sample);
330 
331 	/* Accumulator value CPCAP_REG_CCA1 & 2 */
332 	ccd->accumulator = ((s16)buf[3]) << 16;
333 	ccd->accumulator |= buf[2];
334 
335 	/*
336 	 * Coulomb counter calibration offset is CPCAP_REG_CCM,
337 	 * REG_CCO seems unused
338 	 */
339 	ccd->offset = buf[4];
340 	ccd->offset = sign_extend32(ccd->offset, 9);
341 
342 	/* Integrator register CPCAP_REG_CCI */
343 	if (ddata->vendor == CPCAP_VENDOR_TI)
344 		ccd->integrator = sign_extend32(buf[6], 13);
345 	else
346 		ccd->integrator = (s16)buf[6];
347 
348 	return cpcap_battery_cc_to_uah(ddata,
349 				       ccd->sample,
350 				       ccd->accumulator,
351 				       ccd->offset);
352 }
353 
354 
355 /*
356  * Based on the values from Motorola mapphone Linux kernel for the
357  * stock Droid 4 battery eb41. In the Motorola mapphone Linux
358  * kernel tree the value for pm_cd_factor is passed to the kernel
359  * via device tree. If it turns out to be something device specific
360  * we can consider that too later. These values are also fine for
361  * Bionic's hw4x.
362  *
363  * And looking at the battery full and shutdown values for the stock
364  * kernel on droid 4, full is 4351000 and software initiates shutdown
365  * at 3078000. The device will die around 2743000.
366  */
367 static const struct cpcap_battery_config cpcap_battery_eb41_data = {
368 	.cd_factor = 0x3cc,
369 	.info.technology = POWER_SUPPLY_TECHNOLOGY_LION,
370 	.info.voltage_max_design = 4351000,
371 	.info.voltage_min_design = 3100000,
372 	.info.charge_full_design = 1740000,
373 	.bat.constant_charge_voltage_max_uv = 4200000,
374 };
375 
376 /* Values for the extended Droid Bionic battery bw8x. */
377 static const struct cpcap_battery_config cpcap_battery_bw8x_data = {
378 	.cd_factor = 0x3cc,
379 	.info.technology = POWER_SUPPLY_TECHNOLOGY_LION,
380 	.info.voltage_max_design = 4200000,
381 	.info.voltage_min_design = 3200000,
382 	.info.charge_full_design = 2760000,
383 	.bat.constant_charge_voltage_max_uv = 4200000,
384 };
385 
386 /*
387  * Safe values for any lipo battery likely to fit into a mapphone
388  * battery bay.
389  */
390 static const struct cpcap_battery_config cpcap_battery_unknown_data = {
391 	.cd_factor = 0x3cc,
392 	.info.technology = POWER_SUPPLY_TECHNOLOGY_LION,
393 	.info.voltage_max_design = 4200000,
394 	.info.voltage_min_design = 3200000,
395 	.info.charge_full_design = 3000000,
396 	.bat.constant_charge_voltage_max_uv = 4200000,
397 };
398 
399 static int cpcap_battery_match_nvmem(struct device *dev, const void *data)
400 {
401 	if (strcmp(dev_name(dev), "89-500029ba0f73") == 0)
402 		return 1;
403 	else
404 		return 0;
405 }
406 
407 static void cpcap_battery_update_battery_data(struct cpcap_battery_ddata *ddata)
408 {
409 	struct power_supply_battery_info *info;
410 
411 	if (power_supply_get_battery_info(ddata->psy, &info) < 0)
412 		return;
413 
414 	if (info->technology > 0)
415 		ddata->config.info.technology = info->technology;
416 
417 	if (info->voltage_max_design_uv > 0)
418 		ddata->config.info.voltage_max_design = info->voltage_max_design_uv;
419 
420 	if (info->voltage_min_design_uv > 0)
421 		ddata->config.info.voltage_min_design = info->voltage_min_design_uv;
422 
423 	if (info->charge_full_design_uah > 0)
424 		ddata->config.info.charge_full_design = info->charge_full_design_uah;
425 
426 	if (info->constant_charge_voltage_max_uv > 0)
427 		ddata->config.bat.constant_charge_voltage_max_uv =
428 			info->constant_charge_voltage_max_uv;
429 }
430 
431 static void cpcap_battery_detect_battery_type(struct cpcap_battery_ddata *ddata)
432 {
433 	struct nvmem_device *nvmem;
434 	u8 battery_id = 0;
435 
436 	ddata->check_nvmem = false;
437 
438 	nvmem = nvmem_device_find(NULL, &cpcap_battery_match_nvmem);
439 	if (IS_ERR_OR_NULL(nvmem)) {
440 		ddata->check_nvmem = true;
441 		dev_info_once(ddata->dev, "Can not find battery nvmem device. Assuming generic lipo battery\n");
442 	} else {
443 		if (nvmem_device_read(nvmem, 2, 1, &battery_id) < 0) {
444 			battery_id = 0;
445 			ddata->check_nvmem = true;
446 			dev_warn(ddata->dev, "Can not read battery nvmem device. Assuming generic lipo battery\n");
447 		}
448 		nvmem_device_put(nvmem);
449 	}
450 
451 	switch (battery_id) {
452 	case CPCAP_BATTERY_EB41_HW4X_ID:
453 		ddata->config = cpcap_battery_eb41_data;
454 		break;
455 	case CPCAP_BATTERY_BW8X_ID:
456 		ddata->config = cpcap_battery_bw8x_data;
457 		break;
458 	default:
459 		ddata->config = cpcap_battery_unknown_data;
460 	}
461 
462 	if (ddata->psy)
463 		cpcap_battery_update_battery_data(ddata);
464 }
465 
466 /**
467  * cpcap_battery_cc_get_avg_current - read cpcap coulumb counter
468  * @ddata: cpcap battery driver device data
469  */
470 static int cpcap_battery_cc_get_avg_current(struct cpcap_battery_ddata *ddata)
471 {
472 	int value, acc, error;
473 	s32 sample;
474 	s16 offset;
475 
476 	/* Coulomb counter integrator */
477 	error = regmap_read(ddata->reg, CPCAP_REG_CCI, &value);
478 	if (error)
479 		return error;
480 
481 	if (ddata->vendor == CPCAP_VENDOR_TI) {
482 		acc = sign_extend32(value, 13);
483 		sample = 1;
484 	} else {
485 		acc = (s16)value;
486 		sample = 4;
487 	}
488 
489 	/* Coulomb counter calibration offset  */
490 	error = regmap_read(ddata->reg, CPCAP_REG_CCM, &value);
491 	if (error)
492 		return error;
493 
494 	offset = sign_extend32(value, 9);
495 
496 	return cpcap_battery_cc_to_ua(ddata, sample, acc, offset);
497 }
498 
499 static int cpcap_battery_get_charger_status(struct cpcap_battery_ddata *ddata,
500 					    int *val)
501 {
502 	union power_supply_propval prop;
503 	struct power_supply *charger;
504 	int error;
505 
506 	charger = power_supply_get_by_name("usb");
507 	if (!charger)
508 		return -ENODEV;
509 
510 	error = power_supply_get_property(charger, POWER_SUPPLY_PROP_STATUS,
511 					  &prop);
512 	if (error)
513 		*val = POWER_SUPPLY_STATUS_UNKNOWN;
514 	else
515 		*val = prop.intval;
516 
517 	power_supply_put(charger);
518 
519 	return error;
520 }
521 
522 static bool cpcap_battery_full(struct cpcap_battery_ddata *ddata)
523 {
524 	struct cpcap_battery_state_data *state = cpcap_battery_latest(ddata);
525 	unsigned int vfull;
526 	int error, val;
527 
528 	error = cpcap_battery_get_charger_status(ddata, &val);
529 	if (!error) {
530 		switch (val) {
531 		case POWER_SUPPLY_STATUS_DISCHARGING:
532 			dev_dbg(ddata->dev, "charger disconnected\n");
533 			ddata->is_full = 0;
534 			break;
535 		case POWER_SUPPLY_STATUS_FULL:
536 			dev_dbg(ddata->dev, "charger full status\n");
537 			ddata->is_full = 1;
538 			break;
539 		default:
540 			break;
541 		}
542 	}
543 
544 	/*
545 	 * The full battery voltage here can be inaccurate, it's used just to
546 	 * filter out any trickle charging events. We clear the is_full status
547 	 * on charger disconnect above anyways.
548 	 */
549 	vfull = ddata->config.bat.constant_charge_voltage_max_uv - 120000;
550 
551 	if (ddata->is_full && state->voltage < vfull)
552 		ddata->is_full = 0;
553 
554 	return ddata->is_full;
555 }
556 
557 static bool cpcap_battery_low(struct cpcap_battery_ddata *ddata)
558 {
559 	struct cpcap_battery_state_data *state = cpcap_battery_latest(ddata);
560 	static bool is_low;
561 
562 	if (state->current_ua > 0 && (state->voltage <= 3350000 || is_low))
563 		is_low = true;
564 	else
565 		is_low = false;
566 
567 	return is_low;
568 }
569 
570 static int cpcap_battery_update_status(struct cpcap_battery_ddata *ddata)
571 {
572 	struct cpcap_battery_state_data state, *latest, *previous,
573 					*empty, *full;
574 	ktime_t now;
575 	int error;
576 
577 	memset(&state, 0, sizeof(state));
578 	now = ktime_get();
579 
580 	latest = cpcap_battery_latest(ddata);
581 	if (latest) {
582 		s64 delta_ms = ktime_to_ms(ktime_sub(now, latest->time));
583 
584 		if (delta_ms < CPCAP_BATTERY_CC_SAMPLE_PERIOD_MS)
585 			return delta_ms;
586 	}
587 
588 	state.time = now;
589 	state.voltage = cpcap_battery_get_voltage(ddata);
590 	state.current_ua = cpcap_battery_get_current(ddata);
591 	state.counter_uah = cpcap_battery_read_accumulated(ddata, &state.cc);
592 
593 	error = cpcap_charger_battery_temperature(ddata,
594 						  &state.temperature);
595 	if (error)
596 		return error;
597 
598 	previous = cpcap_battery_previous(ddata);
599 	memcpy(previous, latest, sizeof(*previous));
600 	memcpy(latest, &state, sizeof(*latest));
601 
602 	if (cpcap_battery_full(ddata)) {
603 		full = cpcap_battery_get_full(ddata);
604 		memcpy(full, latest, sizeof(*full));
605 
606 		empty = cpcap_battery_get_empty(ddata);
607 		if (empty->voltage && empty->voltage != -1) {
608 			empty->voltage = -1;
609 			ddata->charge_full =
610 				empty->counter_uah - full->counter_uah;
611 		} else if (ddata->charge_full) {
612 			empty->voltage = -1;
613 			empty->counter_uah =
614 				full->counter_uah + ddata->charge_full;
615 		}
616 	} else if (cpcap_battery_low(ddata)) {
617 		empty = cpcap_battery_get_empty(ddata);
618 		memcpy(empty, latest, sizeof(*empty));
619 
620 		full = cpcap_battery_get_full(ddata);
621 		if (full->voltage) {
622 			full->voltage = 0;
623 			ddata->charge_full =
624 				empty->counter_uah - full->counter_uah;
625 		}
626 	}
627 
628 	return 0;
629 }
630 
631 /*
632  * Update battery status when cpcap-charger calls power_supply_changed().
633  * This allows us to detect battery full condition before the charger
634  * disconnects.
635  */
636 static void cpcap_battery_external_power_changed(struct power_supply *psy)
637 {
638 	union power_supply_propval prop;
639 
640 	power_supply_get_property(psy, POWER_SUPPLY_PROP_STATUS, &prop);
641 }
642 
643 static enum power_supply_property cpcap_battery_props[] = {
644 	POWER_SUPPLY_PROP_STATUS,
645 	POWER_SUPPLY_PROP_PRESENT,
646 	POWER_SUPPLY_PROP_TECHNOLOGY,
647 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
648 	POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
649 	POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
650 	POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
651 	POWER_SUPPLY_PROP_CURRENT_AVG,
652 	POWER_SUPPLY_PROP_CURRENT_NOW,
653 	POWER_SUPPLY_PROP_CHARGE_FULL,
654 	POWER_SUPPLY_PROP_CHARGE_NOW,
655 	POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
656 	POWER_SUPPLY_PROP_CHARGE_COUNTER,
657 	POWER_SUPPLY_PROP_POWER_NOW,
658 	POWER_SUPPLY_PROP_POWER_AVG,
659 	POWER_SUPPLY_PROP_CAPACITY,
660 	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
661 	POWER_SUPPLY_PROP_SCOPE,
662 	POWER_SUPPLY_PROP_TEMP,
663 };
664 
665 static int cpcap_battery_get_property(struct power_supply *psy,
666 				      enum power_supply_property psp,
667 				      union power_supply_propval *val)
668 {
669 	struct cpcap_battery_ddata *ddata = power_supply_get_drvdata(psy);
670 	struct cpcap_battery_state_data *latest, *previous, *empty;
671 	u32 sample;
672 	s32 accumulator;
673 	int cached;
674 	s64 tmp;
675 
676 	cached = cpcap_battery_update_status(ddata);
677 	if (cached < 0)
678 		return cached;
679 
680 	latest = cpcap_battery_latest(ddata);
681 	previous = cpcap_battery_previous(ddata);
682 
683 	if (ddata->check_nvmem)
684 		cpcap_battery_detect_battery_type(ddata);
685 
686 	switch (psp) {
687 	case POWER_SUPPLY_PROP_PRESENT:
688 		if (latest->temperature > CPCAP_NO_BATTERY || ignore_temperature_probe)
689 			val->intval = 1;
690 		else
691 			val->intval = 0;
692 		break;
693 	case POWER_SUPPLY_PROP_STATUS:
694 		if (cpcap_battery_full(ddata)) {
695 			val->intval = POWER_SUPPLY_STATUS_FULL;
696 			break;
697 		}
698 		if (cpcap_battery_cc_get_avg_current(ddata) < 0)
699 			val->intval = POWER_SUPPLY_STATUS_CHARGING;
700 		else
701 			val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
702 		break;
703 	case POWER_SUPPLY_PROP_TECHNOLOGY:
704 		val->intval = ddata->config.info.technology;
705 		break;
706 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
707 		val->intval = cpcap_battery_get_voltage(ddata);
708 		break;
709 	case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
710 		val->intval = ddata->config.info.voltage_max_design;
711 		break;
712 	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
713 		val->intval = ddata->config.info.voltage_min_design;
714 		break;
715 	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
716 		val->intval = ddata->config.bat.constant_charge_voltage_max_uv;
717 		break;
718 	case POWER_SUPPLY_PROP_CURRENT_AVG:
719 		sample = latest->cc.sample - previous->cc.sample;
720 		if (!sample) {
721 			val->intval = cpcap_battery_cc_get_avg_current(ddata);
722 			break;
723 		}
724 		accumulator = latest->cc.accumulator - previous->cc.accumulator;
725 		val->intval = cpcap_battery_cc_to_ua(ddata, sample,
726 						     accumulator,
727 						     latest->cc.offset);
728 		break;
729 	case POWER_SUPPLY_PROP_CURRENT_NOW:
730 		val->intval = latest->current_ua;
731 		break;
732 	case POWER_SUPPLY_PROP_CHARGE_COUNTER:
733 		val->intval = latest->counter_uah;
734 		break;
735 	case POWER_SUPPLY_PROP_POWER_NOW:
736 		tmp = (latest->voltage / 10000) * latest->current_ua;
737 		val->intval = div64_s64(tmp, 100);
738 		break;
739 	case POWER_SUPPLY_PROP_POWER_AVG:
740 		sample = latest->cc.sample - previous->cc.sample;
741 		if (!sample) {
742 			tmp = cpcap_battery_cc_get_avg_current(ddata);
743 			tmp *= (latest->voltage / 10000);
744 			val->intval = div64_s64(tmp, 100);
745 			break;
746 		}
747 		accumulator = latest->cc.accumulator - previous->cc.accumulator;
748 		tmp = cpcap_battery_cc_to_ua(ddata, sample, accumulator,
749 					     latest->cc.offset);
750 		tmp *= ((latest->voltage + previous->voltage) / 20000);
751 		val->intval = div64_s64(tmp, 100);
752 		break;
753 	case POWER_SUPPLY_PROP_CAPACITY:
754 		empty = cpcap_battery_get_empty(ddata);
755 		if (!empty->voltage || !ddata->charge_full)
756 			return -ENODATA;
757 		/* (ddata->charge_full / 200) is needed for rounding */
758 		val->intval = empty->counter_uah - latest->counter_uah +
759 			ddata->charge_full / 200;
760 		val->intval = clamp(val->intval, 0, ddata->charge_full);
761 		val->intval = val->intval * 100 / ddata->charge_full;
762 		break;
763 	case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
764 		if (cpcap_battery_full(ddata))
765 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
766 		else if (latest->voltage >= 3750000)
767 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
768 		else if (latest->voltage >= 3300000)
769 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
770 		else if (latest->voltage > 3100000)
771 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
772 		else if (latest->voltage <= 3100000)
773 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
774 		else
775 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
776 		break;
777 	case POWER_SUPPLY_PROP_CHARGE_NOW:
778 		empty = cpcap_battery_get_empty(ddata);
779 		if (!empty->voltage)
780 			return -ENODATA;
781 		val->intval = empty->counter_uah - latest->counter_uah;
782 		if (val->intval < 0) {
783 			/* Assume invalid config if CHARGE_NOW is -20% */
784 			if (ddata->charge_full && abs(val->intval) > ddata->charge_full/5) {
785 				empty->voltage = 0;
786 				ddata->charge_full = 0;
787 				return -ENODATA;
788 			}
789 			val->intval = 0;
790 		} else if (ddata->charge_full && ddata->charge_full < val->intval) {
791 			/* Assume invalid config if CHARGE_NOW exceeds CHARGE_FULL by 20% */
792 			if (val->intval > (6*ddata->charge_full)/5) {
793 				empty->voltage = 0;
794 				ddata->charge_full = 0;
795 				return -ENODATA;
796 			}
797 			val->intval = ddata->charge_full;
798 		}
799 		break;
800 	case POWER_SUPPLY_PROP_CHARGE_FULL:
801 		if (!ddata->charge_full)
802 			return -ENODATA;
803 		val->intval = ddata->charge_full;
804 		break;
805 	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
806 		val->intval = ddata->config.info.charge_full_design;
807 		break;
808 	case POWER_SUPPLY_PROP_SCOPE:
809 		val->intval = POWER_SUPPLY_SCOPE_SYSTEM;
810 		break;
811 	case POWER_SUPPLY_PROP_TEMP:
812 		if (ignore_temperature_probe)
813 			return -ENODATA;
814 		val->intval = latest->temperature;
815 		break;
816 	default:
817 		return -EINVAL;
818 	}
819 
820 	return 0;
821 }
822 
823 static int cpcap_battery_update_charger(struct cpcap_battery_ddata *ddata,
824 					int const_charge_voltage)
825 {
826 	union power_supply_propval prop;
827 	union power_supply_propval val;
828 	struct power_supply *charger;
829 	int error;
830 
831 	charger = power_supply_get_by_name("usb");
832 	if (!charger)
833 		return -ENODEV;
834 
835 	error = power_supply_get_property(charger,
836 				POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
837 				&prop);
838 	if (error)
839 		goto out_put;
840 
841 	/* Allow charger const voltage lower than battery const voltage */
842 	if (const_charge_voltage > prop.intval)
843 		goto out_put;
844 
845 	val.intval = const_charge_voltage;
846 
847 	error = power_supply_set_property(charger,
848 			POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
849 			&val);
850 out_put:
851 	power_supply_put(charger);
852 
853 	return error;
854 }
855 
856 static int cpcap_battery_set_property(struct power_supply *psy,
857 				      enum power_supply_property psp,
858 				      const union power_supply_propval *val)
859 {
860 	struct cpcap_battery_ddata *ddata = power_supply_get_drvdata(psy);
861 
862 	switch (psp) {
863 	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
864 		if (val->intval < ddata->config.info.voltage_min_design)
865 			return -EINVAL;
866 		if (val->intval > ddata->config.info.voltage_max_design)
867 			return -EINVAL;
868 
869 		ddata->config.bat.constant_charge_voltage_max_uv = val->intval;
870 
871 		return cpcap_battery_update_charger(ddata, val->intval);
872 	case POWER_SUPPLY_PROP_CHARGE_FULL:
873 		if (val->intval < 0)
874 			return -EINVAL;
875 		if (val->intval > (6*ddata->config.info.charge_full_design)/5)
876 			return -EINVAL;
877 
878 		ddata->charge_full = val->intval;
879 
880 		return 0;
881 	default:
882 		return -EINVAL;
883 	}
884 
885 	return 0;
886 }
887 
888 static int cpcap_battery_property_is_writeable(struct power_supply *psy,
889 					       enum power_supply_property psp)
890 {
891 	switch (psp) {
892 	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
893 	case POWER_SUPPLY_PROP_CHARGE_FULL:
894 		return 1;
895 	default:
896 		return 0;
897 	}
898 }
899 
900 static irqreturn_t cpcap_battery_irq_thread(int irq, void *data)
901 {
902 	struct cpcap_battery_ddata *ddata = data;
903 	struct cpcap_battery_state_data *latest;
904 	struct cpcap_interrupt_desc *d;
905 
906 	if (!atomic_read(&ddata->active))
907 		return IRQ_NONE;
908 
909 	list_for_each_entry(d, &ddata->irq_list, node) {
910 		if (irq == d->irq)
911 			break;
912 	}
913 
914 	if (list_entry_is_head(d, &ddata->irq_list, node))
915 		return IRQ_NONE;
916 
917 	latest = cpcap_battery_latest(ddata);
918 
919 	switch (d->action) {
920 	case CPCAP_BATTERY_IRQ_ACTION_CC_CAL_DONE:
921 		dev_info(ddata->dev, "Coulomb counter calibration done\n");
922 		break;
923 	case CPCAP_BATTERY_IRQ_ACTION_BATTERY_LOW:
924 		if (latest->current_ua >= 0)
925 			dev_warn(ddata->dev, "Battery low at %imV!\n",
926 				latest->voltage / 1000);
927 		break;
928 	case CPCAP_BATTERY_IRQ_ACTION_POWEROFF:
929 		if (latest->current_ua >= 0 && latest->voltage <= 3200000) {
930 			dev_emerg(ddata->dev,
931 				  "Battery empty at %imV, powering off\n",
932 				  latest->voltage / 1000);
933 			orderly_poweroff(true);
934 		}
935 		break;
936 	default:
937 		break;
938 	}
939 
940 	power_supply_changed(ddata->psy);
941 
942 	return IRQ_HANDLED;
943 }
944 
945 static int cpcap_battery_init_irq(struct platform_device *pdev,
946 				  struct cpcap_battery_ddata *ddata,
947 				  const char *name)
948 {
949 	struct cpcap_interrupt_desc *d;
950 	int irq, error;
951 
952 	irq = platform_get_irq_byname(pdev, name);
953 	if (irq < 0)
954 		return irq;
955 
956 	error = devm_request_threaded_irq(ddata->dev, irq, NULL,
957 					  cpcap_battery_irq_thread,
958 					  IRQF_SHARED | IRQF_ONESHOT,
959 					  name, ddata);
960 	if (error) {
961 		dev_err(ddata->dev, "could not get irq %s: %i\n",
962 			name, error);
963 
964 		return error;
965 	}
966 
967 	d = devm_kzalloc(ddata->dev, sizeof(*d), GFP_KERNEL);
968 	if (!d)
969 		return -ENOMEM;
970 
971 	d->name = name;
972 	d->irq = irq;
973 
974 	if (!strncmp(name, "cccal", 5))
975 		d->action = CPCAP_BATTERY_IRQ_ACTION_CC_CAL_DONE;
976 	else if (!strncmp(name, "lowbph", 6))
977 		d->action = CPCAP_BATTERY_IRQ_ACTION_BATTERY_LOW;
978 	else if (!strncmp(name, "lowbpl", 6))
979 		d->action = CPCAP_BATTERY_IRQ_ACTION_POWEROFF;
980 
981 	list_add(&d->node, &ddata->irq_list);
982 
983 	return 0;
984 }
985 
986 static int cpcap_battery_init_interrupts(struct platform_device *pdev,
987 					 struct cpcap_battery_ddata *ddata)
988 {
989 	static const char * const cpcap_battery_irqs[] = {
990 		"eol", "lowbph", "lowbpl",
991 		"chrgcurr1", "battdetb"
992 	};
993 	int i, error;
994 
995 	for (i = 0; i < ARRAY_SIZE(cpcap_battery_irqs); i++) {
996 		error = cpcap_battery_init_irq(pdev, ddata,
997 					       cpcap_battery_irqs[i]);
998 		if (error)
999 			return error;
1000 	}
1001 
1002 	/* Enable calibration interrupt if already available in dts */
1003 	cpcap_battery_init_irq(pdev, ddata, "cccal");
1004 
1005 	/* Enable low battery interrupts for 3.3V high and 3.1V low */
1006 	error = regmap_update_bits(ddata->reg, CPCAP_REG_BPEOL,
1007 				   0xffff,
1008 				   CPCAP_REG_BPEOL_BIT_BATTDETEN);
1009 	if (error)
1010 		return error;
1011 
1012 	return 0;
1013 }
1014 
1015 static int cpcap_battery_init_iio(struct cpcap_battery_ddata *ddata)
1016 {
1017 	const char * const names[CPCAP_BATTERY_IIO_NR] = {
1018 		"battdetb", "battp", "chg_isense", "batti",
1019 	};
1020 	int error, i;
1021 
1022 	for (i = 0; i < CPCAP_BATTERY_IIO_NR; i++) {
1023 		ddata->channels[i] = devm_iio_channel_get(ddata->dev,
1024 							  names[i]);
1025 		if (IS_ERR(ddata->channels[i])) {
1026 			error = PTR_ERR(ddata->channels[i]);
1027 			goto out_err;
1028 		}
1029 
1030 		if (!ddata->channels[i]->indio_dev) {
1031 			error = -ENXIO;
1032 			goto out_err;
1033 		}
1034 	}
1035 
1036 	return 0;
1037 
1038 out_err:
1039 	return dev_err_probe(ddata->dev, error,
1040 			     "could not initialize VBUS or ID IIO\n");
1041 }
1042 
1043 /* Calibrate coulomb counter */
1044 static int cpcap_battery_calibrate(struct cpcap_battery_ddata *ddata)
1045 {
1046 	int error, ccc1, value;
1047 	unsigned long timeout;
1048 
1049 	error = regmap_read(ddata->reg, CPCAP_REG_CCC1, &ccc1);
1050 	if (error)
1051 		return error;
1052 
1053 	timeout = jiffies + msecs_to_jiffies(6000);
1054 
1055 	/* Start calibration */
1056 	error = regmap_update_bits(ddata->reg, CPCAP_REG_CCC1,
1057 				   0xffff,
1058 				   CPCAP_REG_CCC1_CAL_EN);
1059 	if (error)
1060 		goto restore;
1061 
1062 	while (time_before(jiffies, timeout)) {
1063 		error = regmap_read(ddata->reg, CPCAP_REG_CCC1, &value);
1064 		if (error)
1065 			goto restore;
1066 
1067 		if (!(value & CPCAP_REG_CCC1_CAL_EN))
1068 			break;
1069 
1070 		error = regmap_read(ddata->reg, CPCAP_REG_CCM, &value);
1071 		if (error)
1072 			goto restore;
1073 
1074 		msleep(300);
1075 	}
1076 
1077 	/* Read calibration offset from CCM */
1078 	error = regmap_read(ddata->reg, CPCAP_REG_CCM, &value);
1079 	if (error)
1080 		goto restore;
1081 
1082 	dev_info(ddata->dev, "calibration done: 0x%04x\n", value);
1083 
1084 restore:
1085 	if (error)
1086 		dev_err(ddata->dev, "%s: error %i\n", __func__, error);
1087 
1088 	error = regmap_update_bits(ddata->reg, CPCAP_REG_CCC1,
1089 				   0xffff, ccc1);
1090 	if (error)
1091 		dev_err(ddata->dev, "%s: restore error %i\n",
1092 			__func__, error);
1093 
1094 	return error;
1095 }
1096 
1097 #ifdef CONFIG_OF
1098 static const struct of_device_id cpcap_battery_id_table[] = {
1099 	{
1100 		.compatible = "motorola,cpcap-battery",
1101 	},
1102 	{},
1103 };
1104 MODULE_DEVICE_TABLE(of, cpcap_battery_id_table);
1105 #endif
1106 
1107 static const struct power_supply_desc cpcap_charger_battery_desc = {
1108 	.name		= "battery",
1109 	.type		= POWER_SUPPLY_TYPE_BATTERY,
1110 	.properties	= cpcap_battery_props,
1111 	.num_properties	= ARRAY_SIZE(cpcap_battery_props),
1112 	.get_property	= cpcap_battery_get_property,
1113 	.set_property	= cpcap_battery_set_property,
1114 	.property_is_writeable = cpcap_battery_property_is_writeable,
1115 	.external_power_changed = cpcap_battery_external_power_changed,
1116 };
1117 
1118 static int cpcap_battery_probe(struct platform_device *pdev)
1119 {
1120 	struct cpcap_battery_ddata *ddata;
1121 	struct power_supply_config psy_cfg = {};
1122 	int error;
1123 
1124 	ddata = devm_kzalloc(&pdev->dev, sizeof(*ddata), GFP_KERNEL);
1125 	if (!ddata)
1126 		return -ENOMEM;
1127 
1128 	cpcap_battery_detect_battery_type(ddata);
1129 
1130 	INIT_LIST_HEAD(&ddata->irq_list);
1131 	ddata->dev = &pdev->dev;
1132 
1133 	ddata->reg = dev_get_regmap(ddata->dev->parent, NULL);
1134 	if (!ddata->reg)
1135 		return -ENODEV;
1136 
1137 	error = cpcap_get_vendor(ddata->dev, ddata->reg, &ddata->vendor);
1138 	if (error)
1139 		return error;
1140 
1141 	switch (ddata->vendor) {
1142 	case CPCAP_VENDOR_ST:
1143 		ddata->cc_lsb = 95374;	/* μAms per LSB */
1144 		break;
1145 	case CPCAP_VENDOR_TI:
1146 		ddata->cc_lsb = 91501;	/* μAms per LSB */
1147 		break;
1148 	default:
1149 		return -EINVAL;
1150 	}
1151 	ddata->cc_lsb = (ddata->cc_lsb * ddata->config.cd_factor) / 1000;
1152 
1153 	platform_set_drvdata(pdev, ddata);
1154 
1155 	error = cpcap_battery_init_iio(ddata);
1156 	if (error)
1157 		return error;
1158 
1159 	psy_cfg.fwnode = dev_fwnode(&pdev->dev);
1160 	psy_cfg.drv_data = ddata;
1161 
1162 	ddata->psy = devm_power_supply_register(ddata->dev,
1163 						&cpcap_charger_battery_desc,
1164 						&psy_cfg);
1165 	error = PTR_ERR_OR_ZERO(ddata->psy);
1166 	if (error) {
1167 		dev_err(ddata->dev, "failed to register power supply\n");
1168 		return error;
1169 	}
1170 
1171 	error = cpcap_battery_init_interrupts(pdev, ddata);
1172 	if (error)
1173 		return error;
1174 
1175 	atomic_set(&ddata->active, 1);
1176 
1177 	error = cpcap_battery_calibrate(ddata);
1178 	if (error)
1179 		return error;
1180 
1181 	return 0;
1182 }
1183 
1184 static void cpcap_battery_remove(struct platform_device *pdev)
1185 {
1186 	struct cpcap_battery_ddata *ddata = platform_get_drvdata(pdev);
1187 	int error;
1188 
1189 	atomic_set(&ddata->active, 0);
1190 	error = regmap_update_bits(ddata->reg, CPCAP_REG_BPEOL,
1191 				   0xffff, 0);
1192 	if (error)
1193 		dev_err(&pdev->dev, "could not disable: %i\n", error);
1194 }
1195 
1196 static struct platform_driver cpcap_battery_driver = {
1197 	.driver	= {
1198 		.name		= "cpcap_battery",
1199 		.of_match_table = of_match_ptr(cpcap_battery_id_table),
1200 	},
1201 	.probe	= cpcap_battery_probe,
1202 	.remove	= cpcap_battery_remove,
1203 };
1204 module_platform_driver(cpcap_battery_driver);
1205 
1206 MODULE_LICENSE("GPL v2");
1207 MODULE_AUTHOR("Tony Lindgren <tony@atomide.com>");
1208 MODULE_DESCRIPTION("CPCAP PMIC Battery Driver");
1209