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