Merge tag 'libata-5.14-2021-07-30' of git://git.kernel.dk/linux-block
[linux-2.6-microblaze.git] / drivers / power / supply / cpcap-battery.c
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                         /* Assume invalid config if CHARGE_NOW is -20% */
672                         if (ddata->charge_full && abs(val->intval) > ddata->charge_full/5) {
673                                 empty->voltage = 0;
674                                 ddata->charge_full = 0;
675                                 return -ENODATA;
676                         }
677                         val->intval = 0;
678                 } else if (ddata->charge_full && ddata->charge_full < val->intval) {
679                         /* Assume invalid config if CHARGE_NOW exceeds CHARGE_FULL by 20% */
680                         if (val->intval > (6*ddata->charge_full)/5) {
681                                 empty->voltage = 0;
682                                 ddata->charge_full = 0;
683                                 return -ENODATA;
684                         }
685                         val->intval = ddata->charge_full;
686                 }
687                 break;
688         case POWER_SUPPLY_PROP_CHARGE_FULL:
689                 if (!ddata->charge_full)
690                         return -ENODATA;
691                 val->intval = ddata->charge_full;
692                 break;
693         case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
694                 val->intval = ddata->config.info.charge_full_design;
695                 break;
696         case POWER_SUPPLY_PROP_SCOPE:
697                 val->intval = POWER_SUPPLY_SCOPE_SYSTEM;
698                 break;
699         case POWER_SUPPLY_PROP_TEMP:
700                 if (ignore_temperature_probe)
701                         return -ENODATA;
702                 val->intval = latest->temperature;
703                 break;
704         default:
705                 return -EINVAL;
706         }
707
708         return 0;
709 }
710
711 static int cpcap_battery_update_charger(struct cpcap_battery_ddata *ddata,
712                                         int const_charge_voltage)
713 {
714         union power_supply_propval prop;
715         union power_supply_propval val;
716         struct power_supply *charger;
717         int error;
718
719         charger = power_supply_get_by_name("usb");
720         if (!charger)
721                 return -ENODEV;
722
723         error = power_supply_get_property(charger,
724                                 POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
725                                 &prop);
726         if (error)
727                 goto out_put;
728
729         /* Allow charger const voltage lower than battery const voltage */
730         if (const_charge_voltage > prop.intval)
731                 goto out_put;
732
733         val.intval = const_charge_voltage;
734
735         error = power_supply_set_property(charger,
736                         POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
737                         &val);
738 out_put:
739         power_supply_put(charger);
740
741         return error;
742 }
743
744 static int cpcap_battery_set_property(struct power_supply *psy,
745                                       enum power_supply_property psp,
746                                       const union power_supply_propval *val)
747 {
748         struct cpcap_battery_ddata *ddata = power_supply_get_drvdata(psy);
749
750         switch (psp) {
751         case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
752                 if (val->intval < ddata->config.info.voltage_min_design)
753                         return -EINVAL;
754                 if (val->intval > ddata->config.info.voltage_max_design)
755                         return -EINVAL;
756
757                 ddata->config.bat.constant_charge_voltage_max_uv = val->intval;
758
759                 return cpcap_battery_update_charger(ddata, val->intval);
760         case POWER_SUPPLY_PROP_CHARGE_FULL:
761                 if (val->intval < 0)
762                         return -EINVAL;
763                 if (val->intval > (6*ddata->config.info.charge_full_design)/5)
764                         return -EINVAL;
765
766                 ddata->charge_full = val->intval;
767
768                 return 0;
769         default:
770                 return -EINVAL;
771         }
772
773         return 0;
774 }
775
776 static int cpcap_battery_property_is_writeable(struct power_supply *psy,
777                                                enum power_supply_property psp)
778 {
779         switch (psp) {
780         case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
781         case POWER_SUPPLY_PROP_CHARGE_FULL:
782                 return 1;
783         default:
784                 return 0;
785         }
786 }
787
788 static irqreturn_t cpcap_battery_irq_thread(int irq, void *data)
789 {
790         struct cpcap_battery_ddata *ddata = data;
791         struct cpcap_battery_state_data *latest;
792         struct cpcap_interrupt_desc *d;
793
794         if (!atomic_read(&ddata->active))
795                 return IRQ_NONE;
796
797         list_for_each_entry(d, &ddata->irq_list, node) {
798                 if (irq == d->irq)
799                         break;
800         }
801
802         if (list_entry_is_head(d, &ddata->irq_list, node))
803                 return IRQ_NONE;
804
805         latest = cpcap_battery_latest(ddata);
806
807         switch (d->action) {
808         case CPCAP_BATTERY_IRQ_ACTION_CC_CAL_DONE:
809                 dev_info(ddata->dev, "Coulomb counter calibration done\n");
810                 break;
811         case CPCAP_BATTERY_IRQ_ACTION_BATTERY_LOW:
812                 if (latest->current_ua >= 0)
813                         dev_warn(ddata->dev, "Battery low at %imV!\n",
814                                 latest->voltage / 1000);
815                 break;
816         case CPCAP_BATTERY_IRQ_ACTION_POWEROFF:
817                 if (latest->current_ua >= 0 && latest->voltage <= 3200000) {
818                         dev_emerg(ddata->dev,
819                                   "Battery empty at %imV, powering off\n",
820                                   latest->voltage / 1000);
821                         orderly_poweroff(true);
822                 }
823                 break;
824         default:
825                 break;
826         }
827
828         power_supply_changed(ddata->psy);
829
830         return IRQ_HANDLED;
831 }
832
833 static int cpcap_battery_init_irq(struct platform_device *pdev,
834                                   struct cpcap_battery_ddata *ddata,
835                                   const char *name)
836 {
837         struct cpcap_interrupt_desc *d;
838         int irq, error;
839
840         irq = platform_get_irq_byname(pdev, name);
841         if (irq < 0)
842                 return irq;
843
844         error = devm_request_threaded_irq(ddata->dev, irq, NULL,
845                                           cpcap_battery_irq_thread,
846                                           IRQF_SHARED | IRQF_ONESHOT,
847                                           name, ddata);
848         if (error) {
849                 dev_err(ddata->dev, "could not get irq %s: %i\n",
850                         name, error);
851
852                 return error;
853         }
854
855         d = devm_kzalloc(ddata->dev, sizeof(*d), GFP_KERNEL);
856         if (!d)
857                 return -ENOMEM;
858
859         d->name = name;
860         d->irq = irq;
861
862         if (!strncmp(name, "cccal", 5))
863                 d->action = CPCAP_BATTERY_IRQ_ACTION_CC_CAL_DONE;
864         else if (!strncmp(name, "lowbph", 6))
865                 d->action = CPCAP_BATTERY_IRQ_ACTION_BATTERY_LOW;
866         else if (!strncmp(name, "lowbpl", 6))
867                 d->action = CPCAP_BATTERY_IRQ_ACTION_POWEROFF;
868
869         list_add(&d->node, &ddata->irq_list);
870
871         return 0;
872 }
873
874 static int cpcap_battery_init_interrupts(struct platform_device *pdev,
875                                          struct cpcap_battery_ddata *ddata)
876 {
877         static const char * const cpcap_battery_irqs[] = {
878                 "eol", "lowbph", "lowbpl",
879                 "chrgcurr1", "battdetb"
880         };
881         int i, error;
882
883         for (i = 0; i < ARRAY_SIZE(cpcap_battery_irqs); i++) {
884                 error = cpcap_battery_init_irq(pdev, ddata,
885                                                cpcap_battery_irqs[i]);
886                 if (error)
887                         return error;
888         }
889
890         /* Enable calibration interrupt if already available in dts */
891         cpcap_battery_init_irq(pdev, ddata, "cccal");
892
893         /* Enable low battery interrupts for 3.3V high and 3.1V low */
894         error = regmap_update_bits(ddata->reg, CPCAP_REG_BPEOL,
895                                    0xffff,
896                                    CPCAP_REG_BPEOL_BIT_BATTDETEN);
897         if (error)
898                 return error;
899
900         return 0;
901 }
902
903 static int cpcap_battery_init_iio(struct cpcap_battery_ddata *ddata)
904 {
905         const char * const names[CPCAP_BATTERY_IIO_NR] = {
906                 "battdetb", "battp", "chg_isense", "batti",
907         };
908         int error, i;
909
910         for (i = 0; i < CPCAP_BATTERY_IIO_NR; i++) {
911                 ddata->channels[i] = devm_iio_channel_get(ddata->dev,
912                                                           names[i]);
913                 if (IS_ERR(ddata->channels[i])) {
914                         error = PTR_ERR(ddata->channels[i]);
915                         goto out_err;
916                 }
917
918                 if (!ddata->channels[i]->indio_dev) {
919                         error = -ENXIO;
920                         goto out_err;
921                 }
922         }
923
924         return 0;
925
926 out_err:
927         return dev_err_probe(ddata->dev, error,
928                              "could not initialize VBUS or ID IIO\n");
929 }
930
931 /* Calibrate coulomb counter */
932 static int cpcap_battery_calibrate(struct cpcap_battery_ddata *ddata)
933 {
934         int error, ccc1, value;
935         unsigned long timeout;
936
937         error = regmap_read(ddata->reg, CPCAP_REG_CCC1, &ccc1);
938         if (error)
939                 return error;
940
941         timeout = jiffies + msecs_to_jiffies(6000);
942
943         /* Start calibration */
944         error = regmap_update_bits(ddata->reg, CPCAP_REG_CCC1,
945                                    0xffff,
946                                    CPCAP_REG_CCC1_CAL_EN);
947         if (error)
948                 goto restore;
949
950         while (time_before(jiffies, timeout)) {
951                 error = regmap_read(ddata->reg, CPCAP_REG_CCC1, &value);
952                 if (error)
953                         goto restore;
954
955                 if (!(value & CPCAP_REG_CCC1_CAL_EN))
956                         break;
957
958                 error = regmap_read(ddata->reg, CPCAP_REG_CCM, &value);
959                 if (error)
960                         goto restore;
961
962                 msleep(300);
963         }
964
965         /* Read calibration offset from CCM */
966         error = regmap_read(ddata->reg, CPCAP_REG_CCM, &value);
967         if (error)
968                 goto restore;
969
970         dev_info(ddata->dev, "calibration done: 0x%04x\n", value);
971
972 restore:
973         if (error)
974                 dev_err(ddata->dev, "%s: error %i\n", __func__, error);
975
976         error = regmap_update_bits(ddata->reg, CPCAP_REG_CCC1,
977                                    0xffff, ccc1);
978         if (error)
979                 dev_err(ddata->dev, "%s: restore error %i\n",
980                         __func__, error);
981
982         return error;
983 }
984
985 /*
986  * Based on the values from Motorola mapphone Linux kernel. In the
987  * the Motorola mapphone Linux kernel tree the value for pm_cd_factor
988  * is passed to the kernel via device tree. If it turns out to be
989  * something device specific we can consider that too later.
990  *
991  * And looking at the battery full and shutdown values for the stock
992  * kernel on droid 4, full is 4351000 and software initiates shutdown
993  * at 3078000. The device will die around 2743000.
994  */
995 static const struct cpcap_battery_config cpcap_battery_default_data = {
996         .cd_factor = 0x3cc,
997         .info.technology = POWER_SUPPLY_TECHNOLOGY_LION,
998         .info.voltage_max_design = 4351000,
999         .info.voltage_min_design = 3100000,
1000         .info.charge_full_design = 1740000,
1001         .bat.constant_charge_voltage_max_uv = 4200000,
1002 };
1003
1004 #ifdef CONFIG_OF
1005 static const struct of_device_id cpcap_battery_id_table[] = {
1006         {
1007                 .compatible = "motorola,cpcap-battery",
1008                 .data = &cpcap_battery_default_data,
1009         },
1010         {},
1011 };
1012 MODULE_DEVICE_TABLE(of, cpcap_battery_id_table);
1013 #endif
1014
1015 static const struct power_supply_desc cpcap_charger_battery_desc = {
1016         .name           = "battery",
1017         .type           = POWER_SUPPLY_TYPE_BATTERY,
1018         .properties     = cpcap_battery_props,
1019         .num_properties = ARRAY_SIZE(cpcap_battery_props),
1020         .get_property   = cpcap_battery_get_property,
1021         .set_property   = cpcap_battery_set_property,
1022         .property_is_writeable = cpcap_battery_property_is_writeable,
1023         .external_power_changed = cpcap_battery_external_power_changed,
1024 };
1025
1026 static int cpcap_battery_probe(struct platform_device *pdev)
1027 {
1028         struct cpcap_battery_ddata *ddata;
1029         const struct of_device_id *match;
1030         struct power_supply_config psy_cfg = {};
1031         int error;
1032
1033         match = of_match_device(of_match_ptr(cpcap_battery_id_table),
1034                                 &pdev->dev);
1035         if (!match)
1036                 return -EINVAL;
1037
1038         if (!match->data) {
1039                 dev_err(&pdev->dev, "no configuration data found\n");
1040
1041                 return -ENODEV;
1042         }
1043
1044         ddata = devm_kzalloc(&pdev->dev, sizeof(*ddata), GFP_KERNEL);
1045         if (!ddata)
1046                 return -ENOMEM;
1047
1048         INIT_LIST_HEAD(&ddata->irq_list);
1049         ddata->dev = &pdev->dev;
1050         memcpy(&ddata->config, match->data, sizeof(ddata->config));
1051
1052         ddata->reg = dev_get_regmap(ddata->dev->parent, NULL);
1053         if (!ddata->reg)
1054                 return -ENODEV;
1055
1056         error = cpcap_get_vendor(ddata->dev, ddata->reg, &ddata->vendor);
1057         if (error)
1058                 return error;
1059
1060         switch (ddata->vendor) {
1061         case CPCAP_VENDOR_ST:
1062                 ddata->cc_lsb = 95374;  /* μAms per LSB */
1063                 break;
1064         case CPCAP_VENDOR_TI:
1065                 ddata->cc_lsb = 91501;  /* μAms per LSB */
1066                 break;
1067         default:
1068                 return -EINVAL;
1069         }
1070         ddata->cc_lsb = (ddata->cc_lsb * ddata->config.cd_factor) / 1000;
1071
1072         platform_set_drvdata(pdev, ddata);
1073
1074         error = cpcap_battery_init_interrupts(pdev, ddata);
1075         if (error)
1076                 return error;
1077
1078         error = cpcap_battery_init_iio(ddata);
1079         if (error)
1080                 return error;
1081
1082         psy_cfg.of_node = pdev->dev.of_node;
1083         psy_cfg.drv_data = ddata;
1084
1085         ddata->psy = devm_power_supply_register(ddata->dev,
1086                                                 &cpcap_charger_battery_desc,
1087                                                 &psy_cfg);
1088         error = PTR_ERR_OR_ZERO(ddata->psy);
1089         if (error) {
1090                 dev_err(ddata->dev, "failed to register power supply\n");
1091                 return error;
1092         }
1093
1094         atomic_set(&ddata->active, 1);
1095
1096         error = cpcap_battery_calibrate(ddata);
1097         if (error)
1098                 return error;
1099
1100         return 0;
1101 }
1102
1103 static int cpcap_battery_remove(struct platform_device *pdev)
1104 {
1105         struct cpcap_battery_ddata *ddata = platform_get_drvdata(pdev);
1106         int error;
1107
1108         atomic_set(&ddata->active, 0);
1109         error = regmap_update_bits(ddata->reg, CPCAP_REG_BPEOL,
1110                                    0xffff, 0);
1111         if (error)
1112                 dev_err(&pdev->dev, "could not disable: %i\n", error);
1113
1114         return 0;
1115 }
1116
1117 static struct platform_driver cpcap_battery_driver = {
1118         .driver = {
1119                 .name           = "cpcap_battery",
1120                 .of_match_table = of_match_ptr(cpcap_battery_id_table),
1121         },
1122         .probe  = cpcap_battery_probe,
1123         .remove = cpcap_battery_remove,
1124 };
1125 module_platform_driver(cpcap_battery_driver);
1126
1127 MODULE_LICENSE("GPL v2");
1128 MODULE_AUTHOR("Tony Lindgren <tony@atomide.com>");
1129 MODULE_DESCRIPTION("CPCAP PMIC Battery Driver");