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