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
75enum {
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
83enum 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
90struct cpcap_interrupt_desc {
91	const char *name;
92	struct list_head node;
93	int irq;
94	enum cpcap_battery_irq_action action;
95};
96
97struct cpcap_battery_config {
98	int cd_factor;
99	struct power_supply_info info;
100	struct power_supply_battery_info bat;
101};
102
103struct 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
110enum cpcap_battery_state {
111	CPCAP_BATTERY_STATE_PREVIOUS,
112	CPCAP_BATTERY_STATE_LATEST,
113	CPCAP_BATTERY_STATE_NR,
114};
115
116struct 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
125struct 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
141static struct cpcap_battery_state_data *
142cpcap_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
151static struct cpcap_battery_state_data *
152cpcap_battery_latest(struct cpcap_battery_ddata *ddata)
153{
154	return cpcap_battery_get_state(ddata, CPCAP_BATTERY_STATE_LATEST);
155}
156
157static struct cpcap_battery_state_data *
158cpcap_battery_previous(struct cpcap_battery_ddata *ddata)
159{
160	return cpcap_battery_get_state(ddata, CPCAP_BATTERY_STATE_PREVIOUS);
161}
162
163static 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
183static 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
199static 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 */
236static 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 */
255static 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
264static 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 */
289static int
290cpcap_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 */
340static 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
369static 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
380static 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
414static 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
433static 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
548static 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		goto out_put;
565
566	/* Allow charger const voltage lower than battery const voltage */
567	if (const_charge_voltage > prop.intval)
568		goto out_put;
569
570	val.intval = const_charge_voltage;
571
572	error = power_supply_set_property(charger,
573			POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
574			&val);
575out_put:
576	power_supply_put(charger);
577
578	return error;
579}
580
581static int cpcap_battery_set_property(struct power_supply *psy,
582				      enum power_supply_property psp,
583				      const union power_supply_propval *val)
584{
585	struct cpcap_battery_ddata *ddata = power_supply_get_drvdata(psy);
586
587	switch (psp) {
588	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
589		if (val->intval < ddata->config.info.voltage_min_design)
590			return -EINVAL;
591		if (val->intval > ddata->config.info.voltage_max_design)
592			return -EINVAL;
593
594		ddata->config.bat.constant_charge_voltage_max_uv = val->intval;
595
596		return cpcap_battery_update_charger(ddata, val->intval);
597	default:
598		return -EINVAL;
599	}
600
601	return 0;
602}
603
604static int cpcap_battery_property_is_writeable(struct power_supply *psy,
605					       enum power_supply_property psp)
606{
607	switch (psp) {
608	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
609		return 1;
610	default:
611		return 0;
612	}
613}
614
615static irqreturn_t cpcap_battery_irq_thread(int irq, void *data)
616{
617	struct cpcap_battery_ddata *ddata = data;
618	struct cpcap_battery_state_data *latest;
619	struct cpcap_interrupt_desc *d;
620
621	if (!atomic_read(&ddata->active))
622		return IRQ_NONE;
623
624	list_for_each_entry(d, &ddata->irq_list, node) {
625		if (irq == d->irq)
626			break;
627	}
628
629	if (list_entry_is_head(d, &ddata->irq_list, node))
630		return IRQ_NONE;
631
632	latest = cpcap_battery_latest(ddata);
633
634	switch (d->action) {
635	case CPCAP_BATTERY_IRQ_ACTION_CC_CAL_DONE:
636		dev_info(ddata->dev, "Coulomb counter calibration done\n");
637		break;
638	case CPCAP_BATTERY_IRQ_ACTION_BATTERY_LOW:
639		if (latest->current_ua >= 0)
640			dev_warn(ddata->dev, "Battery low at %imV!\n",
641				latest->voltage / 1000);
642		break;
643	case CPCAP_BATTERY_IRQ_ACTION_POWEROFF:
644		if (latest->current_ua >= 0 && latest->voltage <= 3200000) {
645			dev_emerg(ddata->dev,
646				  "Battery empty at %imV, powering off\n",
647				  latest->voltage / 1000);
648			orderly_poweroff(true);
649		}
650		break;
651	default:
652		break;
653	}
654
655	power_supply_changed(ddata->psy);
656
657	return IRQ_HANDLED;
658}
659
660static int cpcap_battery_init_irq(struct platform_device *pdev,
661				  struct cpcap_battery_ddata *ddata,
662				  const char *name)
663{
664	struct cpcap_interrupt_desc *d;
665	int irq, error;
666
667	irq = platform_get_irq_byname(pdev, name);
668	if (irq < 0)
669		return irq;
670
671	error = devm_request_threaded_irq(ddata->dev, irq, NULL,
672					  cpcap_battery_irq_thread,
673					  IRQF_SHARED | IRQF_ONESHOT,
674					  name, ddata);
675	if (error) {
676		dev_err(ddata->dev, "could not get irq %s: %i\n",
677			name, error);
678
679		return error;
680	}
681
682	d = devm_kzalloc(ddata->dev, sizeof(*d), GFP_KERNEL);
683	if (!d)
684		return -ENOMEM;
685
686	d->name = name;
687	d->irq = irq;
688
689	if (!strncmp(name, "cccal", 5))
690		d->action = CPCAP_BATTERY_IRQ_ACTION_CC_CAL_DONE;
691	else if (!strncmp(name, "lowbph", 6))
692		d->action = CPCAP_BATTERY_IRQ_ACTION_BATTERY_LOW;
693	else if (!strncmp(name, "lowbpl", 6))
694		d->action = CPCAP_BATTERY_IRQ_ACTION_POWEROFF;
695
696	list_add(&d->node, &ddata->irq_list);
697
698	return 0;
699}
700
701static int cpcap_battery_init_interrupts(struct platform_device *pdev,
702					 struct cpcap_battery_ddata *ddata)
703{
704	static const char * const cpcap_battery_irqs[] = {
705		"eol", "lowbph", "lowbpl",
706		"chrgcurr1", "battdetb"
707	};
708	int i, error;
709
710	for (i = 0; i < ARRAY_SIZE(cpcap_battery_irqs); i++) {
711		error = cpcap_battery_init_irq(pdev, ddata,
712					       cpcap_battery_irqs[i]);
713		if (error)
714			return error;
715	}
716
717	/* Enable calibration interrupt if already available in dts */
718	cpcap_battery_init_irq(pdev, ddata, "cccal");
719
720	/* Enable low battery interrupts for 3.3V high and 3.1V low */
721	error = regmap_update_bits(ddata->reg, CPCAP_REG_BPEOL,
722				   0xffff,
723				   CPCAP_REG_BPEOL_BIT_BATTDETEN);
724	if (error)
725		return error;
726
727	return 0;
728}
729
730static int cpcap_battery_init_iio(struct cpcap_battery_ddata *ddata)
731{
732	const char * const names[CPCAP_BATTERY_IIO_NR] = {
733		"battdetb", "battp", "chg_isense", "batti",
734	};
735	int error, i;
736
737	for (i = 0; i < CPCAP_BATTERY_IIO_NR; i++) {
738		ddata->channels[i] = devm_iio_channel_get(ddata->dev,
739							  names[i]);
740		if (IS_ERR(ddata->channels[i])) {
741			error = PTR_ERR(ddata->channels[i]);
742			goto out_err;
743		}
744
745		if (!ddata->channels[i]->indio_dev) {
746			error = -ENXIO;
747			goto out_err;
748		}
749	}
750
751	return 0;
752
753out_err:
754	return dev_err_probe(ddata->dev, error,
755			     "could not initialize VBUS or ID IIO\n");
756}
757
758/* Calibrate coulomb counter */
759static int cpcap_battery_calibrate(struct cpcap_battery_ddata *ddata)
760{
761	int error, ccc1, value;
762	unsigned long timeout;
763
764	error = regmap_read(ddata->reg, CPCAP_REG_CCC1, &ccc1);
765	if (error)
766		return error;
767
768	timeout = jiffies + msecs_to_jiffies(6000);
769
770	/* Start calibration */
771	error = regmap_update_bits(ddata->reg, CPCAP_REG_CCC1,
772				   0xffff,
773				   CPCAP_REG_CCC1_CAL_EN);
774	if (error)
775		goto restore;
776
777	while (time_before(jiffies, timeout)) {
778		error = regmap_read(ddata->reg, CPCAP_REG_CCC1, &value);
779		if (error)
780			goto restore;
781
782		if (!(value & CPCAP_REG_CCC1_CAL_EN))
783			break;
784
785		error = regmap_read(ddata->reg, CPCAP_REG_CCM, &value);
786		if (error)
787			goto restore;
788
789		msleep(300);
790	}
791
792	/* Read calibration offset from CCM */
793	error = regmap_read(ddata->reg, CPCAP_REG_CCM, &value);
794	if (error)
795		goto restore;
796
797	dev_info(ddata->dev, "calibration done: 0x%04x\n", value);
798
799restore:
800	if (error)
801		dev_err(ddata->dev, "%s: error %i\n", __func__, error);
802
803	error = regmap_update_bits(ddata->reg, CPCAP_REG_CCC1,
804				   0xffff, ccc1);
805	if (error)
806		dev_err(ddata->dev, "%s: restore error %i\n",
807			__func__, error);
808
809	return error;
810}
811
812/*
813 * Based on the values from Motorola mapphone Linux kernel. In the
814 * the Motorola mapphone Linux kernel tree the value for pm_cd_factor
815 * is passed to the kernel via device tree. If it turns out to be
816 * something device specific we can consider that too later.
817 *
818 * And looking at the battery full and shutdown values for the stock
819 * kernel on droid 4, full is 4351000 and software initiates shutdown
820 * at 3078000. The device will die around 2743000.
821 */
822static const struct cpcap_battery_config cpcap_battery_default_data = {
823	.cd_factor = 0x3cc,
824	.info.technology = POWER_SUPPLY_TECHNOLOGY_LION,
825	.info.voltage_max_design = 4351000,
826	.info.voltage_min_design = 3100000,
827	.info.charge_full_design = 1740000,
828	.bat.constant_charge_voltage_max_uv = 4200000,
829};
830
831#ifdef CONFIG_OF
832static const struct of_device_id cpcap_battery_id_table[] = {
833	{
834		.compatible = "motorola,cpcap-battery",
835		.data = &cpcap_battery_default_data,
836	},
837	{},
838};
839MODULE_DEVICE_TABLE(of, cpcap_battery_id_table);
840#endif
841
842static int cpcap_battery_probe(struct platform_device *pdev)
843{
844	struct power_supply_desc *psy_desc;
845	struct cpcap_battery_ddata *ddata;
846	const struct of_device_id *match;
847	struct power_supply_config psy_cfg = {};
848	int error;
849
850	match = of_match_device(of_match_ptr(cpcap_battery_id_table),
851				&pdev->dev);
852	if (!match)
853		return -EINVAL;
854
855	if (!match->data) {
856		dev_err(&pdev->dev, "no configuration data found\n");
857
858		return -ENODEV;
859	}
860
861	ddata = devm_kzalloc(&pdev->dev, sizeof(*ddata), GFP_KERNEL);
862	if (!ddata)
863		return -ENOMEM;
864
865	INIT_LIST_HEAD(&ddata->irq_list);
866	ddata->dev = &pdev->dev;
867	memcpy(&ddata->config, match->data, sizeof(ddata->config));
868
869	ddata->reg = dev_get_regmap(ddata->dev->parent, NULL);
870	if (!ddata->reg)
871		return -ENODEV;
872
873	error = cpcap_get_vendor(ddata->dev, ddata->reg, &ddata->vendor);
874	if (error)
875		return error;
876
877	switch (ddata->vendor) {
878	case CPCAP_VENDOR_ST:
879		ddata->cc_lsb = 95374;	/* μAms per LSB */
880		break;
881	case CPCAP_VENDOR_TI:
882		ddata->cc_lsb = 91501;	/* μAms per LSB */
883		break;
884	default:
885		return -EINVAL;
886	}
887	ddata->cc_lsb = (ddata->cc_lsb * ddata->config.cd_factor) / 1000;
888
889	platform_set_drvdata(pdev, ddata);
890
891	error = cpcap_battery_init_interrupts(pdev, ddata);
892	if (error)
893		return error;
894
895	error = cpcap_battery_init_iio(ddata);
896	if (error)
897		return error;
898
899	psy_desc = devm_kzalloc(ddata->dev, sizeof(*psy_desc), GFP_KERNEL);
900	if (!psy_desc)
901		return -ENOMEM;
902
903	psy_desc->name = "battery";
904	psy_desc->type = POWER_SUPPLY_TYPE_BATTERY;
905	psy_desc->properties = cpcap_battery_props;
906	psy_desc->num_properties = ARRAY_SIZE(cpcap_battery_props);
907	psy_desc->get_property = cpcap_battery_get_property;
908	psy_desc->set_property = cpcap_battery_set_property;
909	psy_desc->property_is_writeable = cpcap_battery_property_is_writeable;
910
911	psy_cfg.of_node = pdev->dev.of_node;
912	psy_cfg.drv_data = ddata;
913
914	ddata->psy = devm_power_supply_register(ddata->dev, psy_desc,
915						&psy_cfg);
916	error = PTR_ERR_OR_ZERO(ddata->psy);
917	if (error) {
918		dev_err(ddata->dev, "failed to register power supply\n");
919		return error;
920	}
921
922	atomic_set(&ddata->active, 1);
923
924	error = cpcap_battery_calibrate(ddata);
925	if (error)
926		return error;
927
928	return 0;
929}
930
931static int cpcap_battery_remove(struct platform_device *pdev)
932{
933	struct cpcap_battery_ddata *ddata = platform_get_drvdata(pdev);
934	int error;
935
936	atomic_set(&ddata->active, 0);
937	error = regmap_update_bits(ddata->reg, CPCAP_REG_BPEOL,
938				   0xffff, 0);
939	if (error)
940		dev_err(&pdev->dev, "could not disable: %i\n", error);
941
942	return 0;
943}
944
945static struct platform_driver cpcap_battery_driver = {
946	.driver	= {
947		.name		= "cpcap_battery",
948		.of_match_table = of_match_ptr(cpcap_battery_id_table),
949	},
950	.probe	= cpcap_battery_probe,
951	.remove = cpcap_battery_remove,
952};
953module_platform_driver(cpcap_battery_driver);
954
955MODULE_LICENSE("GPL v2");
956MODULE_AUTHOR("Tony Lindgren <tony@atomide.com>");
957MODULE_DESCRIPTION("CPCAP PMIC Battery Driver");
958