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