GNU Linux-libre 4.14.332-gnu1
[releases.git] / drivers / power / supply / max17042_battery.c
1 /*
2  * Fuel gauge driver for Maxim 17042 / 8966 / 8997
3  *  Note that Maxim 8966 and 8997 are mfd and this is its subdevice.
4  *
5  * Copyright (C) 2011 Samsung Electronics
6  * MyungJoo Ham <myungjoo.ham@samsung.com>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  * This driver is based on max17040_battery.c
23  */
24
25 #include <linux/acpi.h>
26 #include <linux/init.h>
27 #include <linux/module.h>
28 #include <linux/slab.h>
29 #include <linux/i2c.h>
30 #include <linux/delay.h>
31 #include <linux/interrupt.h>
32 #include <linux/pm.h>
33 #include <linux/mod_devicetable.h>
34 #include <linux/power_supply.h>
35 #include <linux/power/max17042_battery.h>
36 #include <linux/of.h>
37 #include <linux/regmap.h>
38
39 /* Status register bits */
40 #define STATUS_POR_BIT         (1 << 1)
41 #define STATUS_BST_BIT         (1 << 3)
42 #define STATUS_VMN_BIT         (1 << 8)
43 #define STATUS_TMN_BIT         (1 << 9)
44 #define STATUS_SMN_BIT         (1 << 10)
45 #define STATUS_BI_BIT          (1 << 11)
46 #define STATUS_VMX_BIT         (1 << 12)
47 #define STATUS_TMX_BIT         (1 << 13)
48 #define STATUS_SMX_BIT         (1 << 14)
49 #define STATUS_BR_BIT          (1 << 15)
50
51 /* Interrupt mask bits */
52 #define CONFIG_ALRT_BIT_ENBL    (1 << 2)
53 #define STATUS_INTR_SOCMIN_BIT  (1 << 10)
54 #define STATUS_INTR_SOCMAX_BIT  (1 << 14)
55
56 #define VFSOC0_LOCK             0x0000
57 #define VFSOC0_UNLOCK           0x0080
58 #define MODEL_UNLOCK1   0X0059
59 #define MODEL_UNLOCK2   0X00C4
60 #define MODEL_LOCK1             0X0000
61 #define MODEL_LOCK2             0X0000
62
63 #define dQ_ACC_DIV      0x4
64 #define dP_ACC_100      0x1900
65 #define dP_ACC_200      0x3200
66
67 #define MAX17042_VMAX_TOLERANCE         50 /* 50 mV */
68
69 struct max17042_chip {
70         struct i2c_client *client;
71         struct regmap *regmap;
72         struct power_supply *battery;
73         enum max170xx_chip_type chip_type;
74         struct max17042_platform_data *pdata;
75         struct work_struct work;
76         int    init_complete;
77 };
78
79 static enum power_supply_property max17042_battery_props[] = {
80         POWER_SUPPLY_PROP_STATUS,
81         POWER_SUPPLY_PROP_PRESENT,
82         POWER_SUPPLY_PROP_TECHNOLOGY,
83         POWER_SUPPLY_PROP_CYCLE_COUNT,
84         POWER_SUPPLY_PROP_VOLTAGE_MAX,
85         POWER_SUPPLY_PROP_VOLTAGE_MIN,
86         POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
87         POWER_SUPPLY_PROP_VOLTAGE_NOW,
88         POWER_SUPPLY_PROP_VOLTAGE_AVG,
89         POWER_SUPPLY_PROP_VOLTAGE_OCV,
90         POWER_SUPPLY_PROP_CAPACITY,
91         POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
92         POWER_SUPPLY_PROP_CHARGE_FULL,
93         POWER_SUPPLY_PROP_CHARGE_NOW,
94         POWER_SUPPLY_PROP_CHARGE_COUNTER,
95         POWER_SUPPLY_PROP_TEMP,
96         POWER_SUPPLY_PROP_TEMP_ALERT_MIN,
97         POWER_SUPPLY_PROP_TEMP_ALERT_MAX,
98         POWER_SUPPLY_PROP_TEMP_MIN,
99         POWER_SUPPLY_PROP_TEMP_MAX,
100         POWER_SUPPLY_PROP_HEALTH,
101         POWER_SUPPLY_PROP_SCOPE,
102         POWER_SUPPLY_PROP_CURRENT_NOW,
103         POWER_SUPPLY_PROP_CURRENT_AVG,
104 };
105
106 static int max17042_get_temperature(struct max17042_chip *chip, int *temp)
107 {
108         int ret;
109         u32 data;
110         struct regmap *map = chip->regmap;
111
112         ret = regmap_read(map, MAX17042_TEMP, &data);
113         if (ret < 0)
114                 return ret;
115
116         *temp = sign_extend32(data, 15);
117         /* The value is converted into deci-centigrade scale */
118         /* Units of LSB = 1 / 256 degree Celsius */
119         *temp = *temp * 10 / 256;
120         return 0;
121 }
122
123 static int max17042_get_status(struct max17042_chip *chip, int *status)
124 {
125         int ret, charge_full, charge_now;
126
127         ret = power_supply_am_i_supplied(chip->battery);
128         if (ret < 0) {
129                 *status = POWER_SUPPLY_STATUS_UNKNOWN;
130                 return 0;
131         }
132         if (ret == 0) {
133                 *status = POWER_SUPPLY_STATUS_DISCHARGING;
134                 return 0;
135         }
136
137         /*
138          * The MAX170xx has builtin end-of-charge detection and will update
139          * FullCAP to match RepCap when it detects end of charging.
140          *
141          * When this cycle the battery gets charged to a higher (calculated)
142          * capacity then the previous cycle then FullCAP will get updated
143          * contineously once end-of-charge detection kicks in, so allow the
144          * 2 to differ a bit.
145          */
146
147         ret = regmap_read(chip->regmap, MAX17042_FullCAP, &charge_full);
148         if (ret < 0)
149                 return ret;
150
151         ret = regmap_read(chip->regmap, MAX17042_RepCap, &charge_now);
152         if (ret < 0)
153                 return ret;
154
155         if ((charge_full - charge_now) <= MAX17042_FULL_THRESHOLD)
156                 *status = POWER_SUPPLY_STATUS_FULL;
157         else
158                 *status = POWER_SUPPLY_STATUS_CHARGING;
159
160         return 0;
161 }
162
163 static int max17042_get_battery_health(struct max17042_chip *chip, int *health)
164 {
165         int temp, vavg, vbatt, ret;
166         u32 val;
167
168         ret = regmap_read(chip->regmap, MAX17042_AvgVCELL, &val);
169         if (ret < 0)
170                 goto health_error;
171
172         /* bits [0-3] unused */
173         vavg = val * 625 / 8;
174         /* Convert to millivolts */
175         vavg /= 1000;
176
177         ret = regmap_read(chip->regmap, MAX17042_VCELL, &val);
178         if (ret < 0)
179                 goto health_error;
180
181         /* bits [0-3] unused */
182         vbatt = val * 625 / 8;
183         /* Convert to millivolts */
184         vbatt /= 1000;
185
186         if (vavg < chip->pdata->vmin) {
187                 *health = POWER_SUPPLY_HEALTH_DEAD;
188                 goto out;
189         }
190
191         if (vbatt > chip->pdata->vmax + MAX17042_VMAX_TOLERANCE) {
192                 *health = POWER_SUPPLY_HEALTH_OVERVOLTAGE;
193                 goto out;
194         }
195
196         ret = max17042_get_temperature(chip, &temp);
197         if (ret < 0)
198                 goto health_error;
199
200         if (temp < chip->pdata->temp_min) {
201                 *health = POWER_SUPPLY_HEALTH_COLD;
202                 goto out;
203         }
204
205         if (temp > chip->pdata->temp_max) {
206                 *health = POWER_SUPPLY_HEALTH_OVERHEAT;
207                 goto out;
208         }
209
210         *health = POWER_SUPPLY_HEALTH_GOOD;
211
212 out:
213         return 0;
214
215 health_error:
216         return ret;
217 }
218
219 static int max17042_get_property(struct power_supply *psy,
220                             enum power_supply_property psp,
221                             union power_supply_propval *val)
222 {
223         struct max17042_chip *chip = power_supply_get_drvdata(psy);
224         struct regmap *map = chip->regmap;
225         int ret;
226         u32 data;
227         u64 data64;
228
229         if (!chip->init_complete)
230                 return -EAGAIN;
231
232         switch (psp) {
233         case POWER_SUPPLY_PROP_STATUS:
234                 ret = max17042_get_status(chip, &val->intval);
235                 if (ret < 0)
236                         return ret;
237                 break;
238         case POWER_SUPPLY_PROP_PRESENT:
239                 ret = regmap_read(map, MAX17042_STATUS, &data);
240                 if (ret < 0)
241                         return ret;
242
243                 if (data & MAX17042_STATUS_BattAbsent)
244                         val->intval = 0;
245                 else
246                         val->intval = 1;
247                 break;
248         case POWER_SUPPLY_PROP_TECHNOLOGY:
249                 val->intval = POWER_SUPPLY_TECHNOLOGY_LION;
250                 break;
251         case POWER_SUPPLY_PROP_CYCLE_COUNT:
252                 ret = regmap_read(map, MAX17042_Cycles, &data);
253                 if (ret < 0)
254                         return ret;
255
256                 val->intval = data;
257                 break;
258         case POWER_SUPPLY_PROP_VOLTAGE_MAX:
259                 ret = regmap_read(map, MAX17042_MinMaxVolt, &data);
260                 if (ret < 0)
261                         return ret;
262
263                 val->intval = data >> 8;
264                 val->intval *= 20000; /* Units of LSB = 20mV */
265                 break;
266         case POWER_SUPPLY_PROP_VOLTAGE_MIN:
267                 ret = regmap_read(map, MAX17042_MinMaxVolt, &data);
268                 if (ret < 0)
269                         return ret;
270
271                 val->intval = (data & 0xff) * 20000; /* Units of 20mV */
272                 break;
273         case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
274                 if (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17042)
275                         ret = regmap_read(map, MAX17042_V_empty, &data);
276                 else
277                         ret = regmap_read(map, MAX17047_V_empty, &data);
278                 if (ret < 0)
279                         return ret;
280
281                 val->intval = data >> 7;
282                 val->intval *= 10000; /* Units of LSB = 10mV */
283                 break;
284         case POWER_SUPPLY_PROP_VOLTAGE_NOW:
285                 ret = regmap_read(map, MAX17042_VCELL, &data);
286                 if (ret < 0)
287                         return ret;
288
289                 val->intval = data * 625 / 8;
290                 break;
291         case POWER_SUPPLY_PROP_VOLTAGE_AVG:
292                 ret = regmap_read(map, MAX17042_AvgVCELL, &data);
293                 if (ret < 0)
294                         return ret;
295
296                 val->intval = data * 625 / 8;
297                 break;
298         case POWER_SUPPLY_PROP_VOLTAGE_OCV:
299                 ret = regmap_read(map, MAX17042_OCVInternal, &data);
300                 if (ret < 0)
301                         return ret;
302
303                 val->intval = data * 625 / 8;
304                 break;
305         case POWER_SUPPLY_PROP_CAPACITY:
306                 if (chip->pdata->enable_current_sense)
307                         ret = regmap_read(map, MAX17042_RepSOC, &data);
308                 else
309                         ret = regmap_read(map, MAX17042_VFSOC, &data);
310                 if (ret < 0)
311                         return ret;
312
313                 val->intval = data >> 8;
314                 break;
315         case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
316                 ret = regmap_read(map, MAX17042_DesignCap, &data);
317                 if (ret < 0)
318                         return ret;
319
320                 data64 = data * 5000000ll;
321                 do_div(data64, chip->pdata->r_sns);
322                 val->intval = data64;
323                 break;
324         case POWER_SUPPLY_PROP_CHARGE_FULL:
325                 ret = regmap_read(map, MAX17042_FullCAP, &data);
326                 if (ret < 0)
327                         return ret;
328
329                 data64 = data * 5000000ll;
330                 do_div(data64, chip->pdata->r_sns);
331                 val->intval = data64;
332                 break;
333         case POWER_SUPPLY_PROP_CHARGE_NOW:
334                 ret = regmap_read(map, MAX17042_RepCap, &data);
335                 if (ret < 0)
336                         return ret;
337
338                 data64 = data * 5000000ll;
339                 do_div(data64, chip->pdata->r_sns);
340                 val->intval = data64;
341                 break;
342         case POWER_SUPPLY_PROP_CHARGE_COUNTER:
343                 ret = regmap_read(map, MAX17042_QH, &data);
344                 if (ret < 0)
345                         return ret;
346
347                 val->intval = data * 1000 / 2;
348                 break;
349         case POWER_SUPPLY_PROP_TEMP:
350                 ret = max17042_get_temperature(chip, &val->intval);
351                 if (ret < 0)
352                         return ret;
353                 break;
354         case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
355                 ret = regmap_read(map, MAX17042_TALRT_Th, &data);
356                 if (ret < 0)
357                         return ret;
358                 /* LSB is Alert Minimum. In deci-centigrade */
359                 val->intval = sign_extend32(data & 0xff, 7) * 10;
360                 break;
361         case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
362                 ret = regmap_read(map, MAX17042_TALRT_Th, &data);
363                 if (ret < 0)
364                         return ret;
365                 /* MSB is Alert Maximum. In deci-centigrade */
366                 val->intval = sign_extend32(data >> 8, 7) * 10;
367                 break;
368         case POWER_SUPPLY_PROP_TEMP_MIN:
369                 val->intval = chip->pdata->temp_min;
370                 break;
371         case POWER_SUPPLY_PROP_TEMP_MAX:
372                 val->intval = chip->pdata->temp_max;
373                 break;
374         case POWER_SUPPLY_PROP_HEALTH:
375                 ret = max17042_get_battery_health(chip, &val->intval);
376                 if (ret < 0)
377                         return ret;
378                 break;
379         case POWER_SUPPLY_PROP_SCOPE:
380                 val->intval = POWER_SUPPLY_SCOPE_SYSTEM;
381                 break;
382         case POWER_SUPPLY_PROP_CURRENT_NOW:
383                 if (chip->pdata->enable_current_sense) {
384                         ret = regmap_read(map, MAX17042_Current, &data);
385                         if (ret < 0)
386                                 return ret;
387
388                         val->intval = sign_extend32(data, 15);
389                         val->intval *= 1562500 / chip->pdata->r_sns;
390                 } else {
391                         return -EINVAL;
392                 }
393                 break;
394         case POWER_SUPPLY_PROP_CURRENT_AVG:
395                 if (chip->pdata->enable_current_sense) {
396                         ret = regmap_read(map, MAX17042_AvgCurrent, &data);
397                         if (ret < 0)
398                                 return ret;
399
400                         val->intval = sign_extend32(data, 15);
401                         val->intval *= 1562500 / chip->pdata->r_sns;
402                 } else {
403                         return -EINVAL;
404                 }
405                 break;
406         default:
407                 return -EINVAL;
408         }
409         return 0;
410 }
411
412 static int max17042_set_property(struct power_supply *psy,
413                             enum power_supply_property psp,
414                             const union power_supply_propval *val)
415 {
416         struct max17042_chip *chip = power_supply_get_drvdata(psy);
417         struct regmap *map = chip->regmap;
418         int ret = 0;
419         u32 data;
420         int8_t temp;
421
422         switch (psp) {
423         case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
424                 ret = regmap_read(map, MAX17042_TALRT_Th, &data);
425                 if (ret < 0)
426                         return ret;
427
428                 /* Input in deci-centigrade, convert to centigrade */
429                 temp = val->intval / 10;
430                 /* force min < max */
431                 if (temp >= (int8_t)(data >> 8))
432                         temp = (int8_t)(data >> 8) - 1;
433                 /* Write both MAX and MIN ALERT */
434                 data = (data & 0xff00) + temp;
435                 ret = regmap_write(map, MAX17042_TALRT_Th, data);
436                 break;
437         case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
438                 ret = regmap_read(map, MAX17042_TALRT_Th, &data);
439                 if (ret < 0)
440                         return ret;
441
442                 /* Input in Deci-Centigrade, convert to centigrade */
443                 temp = val->intval / 10;
444                 /* force max > min */
445                 if (temp <= (int8_t)(data & 0xff))
446                         temp = (int8_t)(data & 0xff) + 1;
447                 /* Write both MAX and MIN ALERT */
448                 data = (data & 0xff) + (temp << 8);
449                 ret = regmap_write(map, MAX17042_TALRT_Th, data);
450                 break;
451         default:
452                 ret = -EINVAL;
453         }
454
455         return ret;
456 }
457
458 static int max17042_property_is_writeable(struct power_supply *psy,
459                 enum power_supply_property psp)
460 {
461         int ret;
462
463         switch (psp) {
464         case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
465         case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
466                 ret = 1;
467                 break;
468         default:
469                 ret = 0;
470         }
471
472         return ret;
473 }
474
475 static void max17042_external_power_changed(struct power_supply *psy)
476 {
477         power_supply_changed(psy);
478 }
479
480 static int max17042_write_verify_reg(struct regmap *map, u8 reg, u32 value)
481 {
482         int retries = 8;
483         int ret;
484         u32 read_value;
485
486         do {
487                 ret = regmap_write(map, reg, value);
488                 regmap_read(map, reg, &read_value);
489                 if (read_value != value) {
490                         ret = -EIO;
491                         retries--;
492                 }
493         } while (retries && read_value != value);
494
495         if (ret < 0)
496                 pr_err("%s: err %d\n", __func__, ret);
497
498         return ret;
499 }
500
501 static inline void max17042_override_por(struct regmap *map,
502                                          u8 reg, u16 value)
503 {
504         if (value)
505                 regmap_write(map, reg, value);
506 }
507
508 static inline void max10742_unlock_model(struct max17042_chip *chip)
509 {
510         struct regmap *map = chip->regmap;
511
512         regmap_write(map, MAX17042_MLOCKReg1, MODEL_UNLOCK1);
513         regmap_write(map, MAX17042_MLOCKReg2, MODEL_UNLOCK2);
514 }
515
516 static inline void max10742_lock_model(struct max17042_chip *chip)
517 {
518         struct regmap *map = chip->regmap;
519
520         regmap_write(map, MAX17042_MLOCKReg1, MODEL_LOCK1);
521         regmap_write(map, MAX17042_MLOCKReg2, MODEL_LOCK2);
522 }
523
524 static inline void max17042_write_model_data(struct max17042_chip *chip,
525                                         u8 addr, int size)
526 {
527         struct regmap *map = chip->regmap;
528         int i;
529
530         for (i = 0; i < size; i++)
531                 regmap_write(map, addr + i,
532                         chip->pdata->config_data->cell_char_tbl[i]);
533 }
534
535 static inline void max17042_read_model_data(struct max17042_chip *chip,
536                                         u8 addr, u16 *data, int size)
537 {
538         struct regmap *map = chip->regmap;
539         int i;
540         u32 tmp;
541
542         for (i = 0; i < size; i++) {
543                 regmap_read(map, addr + i, &tmp);
544                 data[i] = (u16)tmp;
545         }
546 }
547
548 static inline int max17042_model_data_compare(struct max17042_chip *chip,
549                                         u16 *data1, u16 *data2, int size)
550 {
551         int i;
552
553         if (memcmp(data1, data2, size)) {
554                 dev_err(&chip->client->dev, "%s compare failed\n", __func__);
555                 for (i = 0; i < size; i++)
556                         dev_info(&chip->client->dev, "0x%x, 0x%x",
557                                 data1[i], data2[i]);
558                 dev_info(&chip->client->dev, "\n");
559                 return -EINVAL;
560         }
561         return 0;
562 }
563
564 static int max17042_init_model(struct max17042_chip *chip)
565 {
566         int ret;
567         int table_size = ARRAY_SIZE(chip->pdata->config_data->cell_char_tbl);
568         u16 *temp_data;
569
570         temp_data = kcalloc(table_size, sizeof(*temp_data), GFP_KERNEL);
571         if (!temp_data)
572                 return -ENOMEM;
573
574         max10742_unlock_model(chip);
575         max17042_write_model_data(chip, MAX17042_MODELChrTbl,
576                                 table_size);
577         max17042_read_model_data(chip, MAX17042_MODELChrTbl, temp_data,
578                                 table_size);
579
580         ret = max17042_model_data_compare(
581                 chip,
582                 chip->pdata->config_data->cell_char_tbl,
583                 temp_data,
584                 table_size);
585
586         max10742_lock_model(chip);
587         kfree(temp_data);
588
589         return ret;
590 }
591
592 static int max17042_verify_model_lock(struct max17042_chip *chip)
593 {
594         int i;
595         int table_size = ARRAY_SIZE(chip->pdata->config_data->cell_char_tbl);
596         u16 *temp_data;
597         int ret = 0;
598
599         temp_data = kcalloc(table_size, sizeof(*temp_data), GFP_KERNEL);
600         if (!temp_data)
601                 return -ENOMEM;
602
603         max17042_read_model_data(chip, MAX17042_MODELChrTbl, temp_data,
604                                 table_size);
605         for (i = 0; i < table_size; i++)
606                 if (temp_data[i])
607                         ret = -EINVAL;
608
609         kfree(temp_data);
610         return ret;
611 }
612
613 static void max17042_write_config_regs(struct max17042_chip *chip)
614 {
615         struct max17042_config_data *config = chip->pdata->config_data;
616         struct regmap *map = chip->regmap;
617
618         regmap_write(map, MAX17042_CONFIG, config->config);
619         regmap_write(map, MAX17042_LearnCFG, config->learn_cfg);
620         regmap_write(map, MAX17042_FilterCFG,
621                         config->filter_cfg);
622         regmap_write(map, MAX17042_RelaxCFG, config->relax_cfg);
623         if (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17047 ||
624                         chip->chip_type == MAXIM_DEVICE_TYPE_MAX17050)
625                 regmap_write(map, MAX17047_FullSOCThr,
626                                                 config->full_soc_thresh);
627 }
628
629 static void  max17042_write_custom_regs(struct max17042_chip *chip)
630 {
631         struct max17042_config_data *config = chip->pdata->config_data;
632         struct regmap *map = chip->regmap;
633
634         max17042_write_verify_reg(map, MAX17042_RCOMP0, config->rcomp0);
635         max17042_write_verify_reg(map, MAX17042_TempCo, config->tcompc0);
636         max17042_write_verify_reg(map, MAX17042_ICHGTerm, config->ichgt_term);
637         if (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17042) {
638                 regmap_write(map, MAX17042_EmptyTempCo, config->empty_tempco);
639                 max17042_write_verify_reg(map, MAX17042_K_empty0,
640                                         config->kempty0);
641         } else {
642                 max17042_write_verify_reg(map, MAX17047_QRTbl00,
643                                                 config->qrtbl00);
644                 max17042_write_verify_reg(map, MAX17047_QRTbl10,
645                                                 config->qrtbl10);
646                 max17042_write_verify_reg(map, MAX17047_QRTbl20,
647                                                 config->qrtbl20);
648                 max17042_write_verify_reg(map, MAX17047_QRTbl30,
649                                                 config->qrtbl30);
650         }
651 }
652
653 static void max17042_update_capacity_regs(struct max17042_chip *chip)
654 {
655         struct max17042_config_data *config = chip->pdata->config_data;
656         struct regmap *map = chip->regmap;
657
658         max17042_write_verify_reg(map, MAX17042_FullCAP,
659                                 config->fullcap);
660         regmap_write(map, MAX17042_DesignCap, config->design_cap);
661         max17042_write_verify_reg(map, MAX17042_FullCAPNom,
662                                 config->fullcapnom);
663 }
664
665 static void max17042_reset_vfsoc0_reg(struct max17042_chip *chip)
666 {
667         unsigned int vfSoc;
668         struct regmap *map = chip->regmap;
669
670         regmap_read(map, MAX17042_VFSOC, &vfSoc);
671         regmap_write(map, MAX17042_VFSOC0Enable, VFSOC0_UNLOCK);
672         max17042_write_verify_reg(map, MAX17042_VFSOC0, vfSoc);
673         regmap_write(map, MAX17042_VFSOC0Enable, VFSOC0_LOCK);
674 }
675
676 static void max17042_load_new_capacity_params(struct max17042_chip *chip)
677 {
678         u32 full_cap0, rep_cap, dq_acc, vfSoc;
679         u32 rem_cap;
680
681         struct max17042_config_data *config = chip->pdata->config_data;
682         struct regmap *map = chip->regmap;
683
684         regmap_read(map, MAX17042_FullCAP0, &full_cap0);
685         regmap_read(map, MAX17042_VFSOC, &vfSoc);
686
687         /* fg_vfSoc needs to shifted by 8 bits to get the
688          * perc in 1% accuracy, to get the right rem_cap multiply
689          * full_cap0, fg_vfSoc and devide by 100
690          */
691         rem_cap = ((vfSoc >> 8) * full_cap0) / 100;
692         max17042_write_verify_reg(map, MAX17042_RemCap, rem_cap);
693
694         rep_cap = rem_cap;
695         max17042_write_verify_reg(map, MAX17042_RepCap, rep_cap);
696
697         /* Write dQ_acc to 200% of Capacity and dP_acc to 200% */
698         dq_acc = config->fullcap / dQ_ACC_DIV;
699         max17042_write_verify_reg(map, MAX17042_dQacc, dq_acc);
700         max17042_write_verify_reg(map, MAX17042_dPacc, dP_ACC_200);
701
702         max17042_write_verify_reg(map, MAX17042_FullCAP,
703                         config->fullcap);
704         regmap_write(map, MAX17042_DesignCap,
705                         config->design_cap);
706         max17042_write_verify_reg(map, MAX17042_FullCAPNom,
707                         config->fullcapnom);
708         /* Update SOC register with new SOC */
709         regmap_write(map, MAX17042_RepSOC, vfSoc);
710 }
711
712 /*
713  * Block write all the override values coming from platform data.
714  * This function MUST be called before the POR initialization proceedure
715  * specified by maxim.
716  */
717 static inline void max17042_override_por_values(struct max17042_chip *chip)
718 {
719         struct regmap *map = chip->regmap;
720         struct max17042_config_data *config = chip->pdata->config_data;
721
722         max17042_override_por(map, MAX17042_TGAIN, config->tgain);
723         max17042_override_por(map, MAX17042_TOFF, config->toff);
724         max17042_override_por(map, MAX17042_CGAIN, config->cgain);
725         max17042_override_por(map, MAX17042_COFF, config->coff);
726
727         max17042_override_por(map, MAX17042_VALRT_Th, config->valrt_thresh);
728         max17042_override_por(map, MAX17042_TALRT_Th, config->talrt_thresh);
729         max17042_override_por(map, MAX17042_SALRT_Th,
730                                                 config->soc_alrt_thresh);
731         max17042_override_por(map, MAX17042_CONFIG, config->config);
732         max17042_override_por(map, MAX17042_SHDNTIMER, config->shdntimer);
733
734         max17042_override_por(map, MAX17042_DesignCap, config->design_cap);
735         max17042_override_por(map, MAX17042_ICHGTerm, config->ichgt_term);
736
737         max17042_override_por(map, MAX17042_AtRate, config->at_rate);
738         max17042_override_por(map, MAX17042_LearnCFG, config->learn_cfg);
739         max17042_override_por(map, MAX17042_FilterCFG, config->filter_cfg);
740         max17042_override_por(map, MAX17042_RelaxCFG, config->relax_cfg);
741         max17042_override_por(map, MAX17042_MiscCFG, config->misc_cfg);
742         max17042_override_por(map, MAX17042_MaskSOC, config->masksoc);
743
744         max17042_override_por(map, MAX17042_FullCAP, config->fullcap);
745         max17042_override_por(map, MAX17042_FullCAPNom, config->fullcapnom);
746         if (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17042)
747                 max17042_override_por(map, MAX17042_SOC_empty,
748                                                 config->socempty);
749         max17042_override_por(map, MAX17042_LAvg_empty, config->lavg_empty);
750         max17042_override_por(map, MAX17042_dQacc, config->dqacc);
751         max17042_override_por(map, MAX17042_dPacc, config->dpacc);
752
753         if (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17042)
754                 max17042_override_por(map, MAX17042_V_empty, config->vempty);
755         else
756                 max17042_override_por(map, MAX17047_V_empty, config->vempty);
757         max17042_override_por(map, MAX17042_TempNom, config->temp_nom);
758         max17042_override_por(map, MAX17042_TempLim, config->temp_lim);
759         max17042_override_por(map, MAX17042_FCTC, config->fctc);
760         max17042_override_por(map, MAX17042_RCOMP0, config->rcomp0);
761         max17042_override_por(map, MAX17042_TempCo, config->tcompc0);
762         if (chip->chip_type) {
763                 max17042_override_por(map, MAX17042_EmptyTempCo,
764                                                 config->empty_tempco);
765                 max17042_override_por(map, MAX17042_K_empty0,
766                                                 config->kempty0);
767         }
768 }
769
770 static int max17042_init_chip(struct max17042_chip *chip)
771 {
772         struct regmap *map = chip->regmap;
773         int ret;
774
775         max17042_override_por_values(chip);
776         /* After Power up, the MAX17042 requires 500mS in order
777          * to perform signal debouncing and initial SOC reporting
778          */
779         msleep(500);
780
781         /* Initialize configaration */
782         max17042_write_config_regs(chip);
783
784         /* write cell characterization data */
785         ret = max17042_init_model(chip);
786         if (ret) {
787                 dev_err(&chip->client->dev, "%s init failed\n",
788                         __func__);
789                 return -EIO;
790         }
791
792         ret = max17042_verify_model_lock(chip);
793         if (ret) {
794                 dev_err(&chip->client->dev, "%s lock verify failed\n",
795                         __func__);
796                 return -EIO;
797         }
798         /* write custom parameters */
799         max17042_write_custom_regs(chip);
800
801         /* update capacity params */
802         max17042_update_capacity_regs(chip);
803
804         /* delay must be atleast 350mS to allow VFSOC
805          * to be calculated from the new configuration
806          */
807         msleep(350);
808
809         /* reset vfsoc0 reg */
810         max17042_reset_vfsoc0_reg(chip);
811
812         /* load new capacity params */
813         max17042_load_new_capacity_params(chip);
814
815         /* Init complete, Clear the POR bit */
816         regmap_update_bits(map, MAX17042_STATUS, STATUS_POR_BIT, 0x0);
817         return 0;
818 }
819
820 static void max17042_set_soc_threshold(struct max17042_chip *chip, u16 off)
821 {
822         struct regmap *map = chip->regmap;
823         u32 soc, soc_tr;
824
825         /* program interrupt thesholds such that we should
826          * get interrupt for every 'off' perc change in the soc
827          */
828         regmap_read(map, MAX17042_RepSOC, &soc);
829         soc >>= 8;
830         soc_tr = (soc + off) << 8;
831         if (off < soc)
832                 soc_tr |= soc - off;
833         regmap_write(map, MAX17042_SALRT_Th, soc_tr);
834 }
835
836 static irqreturn_t max17042_thread_handler(int id, void *dev)
837 {
838         struct max17042_chip *chip = dev;
839         u32 val;
840         int ret;
841
842         ret = regmap_read(chip->regmap, MAX17042_STATUS, &val);
843         if (ret)
844                 return IRQ_HANDLED;
845
846         if ((val & STATUS_INTR_SOCMIN_BIT) ||
847                 (val & STATUS_INTR_SOCMAX_BIT)) {
848                 dev_info(&chip->client->dev, "SOC threshold INTR\n");
849                 max17042_set_soc_threshold(chip, 1);
850         }
851
852         power_supply_changed(chip->battery);
853         return IRQ_HANDLED;
854 }
855
856 static void max17042_init_worker(struct work_struct *work)
857 {
858         struct max17042_chip *chip = container_of(work,
859                                 struct max17042_chip, work);
860         int ret;
861
862         /* Initialize registers according to values from the platform data */
863         if (chip->pdata->enable_por_init && chip->pdata->config_data) {
864                 ret = max17042_init_chip(chip);
865                 if (ret)
866                         return;
867         }
868
869         chip->init_complete = 1;
870 }
871
872 #ifdef CONFIG_OF
873 static struct max17042_platform_data *
874 max17042_get_pdata(struct max17042_chip *chip)
875 {
876         struct device *dev = &chip->client->dev;
877         struct device_node *np = dev->of_node;
878         u32 prop;
879         struct max17042_platform_data *pdata;
880
881         if (!np)
882                 return dev->platform_data;
883
884         pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
885         if (!pdata)
886                 return NULL;
887
888         /*
889          * Require current sense resistor value to be specified for
890          * current-sense functionality to be enabled at all.
891          */
892         if (of_property_read_u32(np, "maxim,rsns-microohm", &prop) == 0) {
893                 pdata->r_sns = prop;
894                 pdata->enable_current_sense = true;
895         }
896
897         if (of_property_read_s32(np, "maxim,cold-temp", &pdata->temp_min))
898                 pdata->temp_min = INT_MIN;
899         if (of_property_read_s32(np, "maxim,over-heat-temp", &pdata->temp_max))
900                 pdata->temp_max = INT_MAX;
901         if (of_property_read_s32(np, "maxim,dead-volt", &pdata->vmin))
902                 pdata->vmin = INT_MIN;
903         if (of_property_read_s32(np, "maxim,over-volt", &pdata->vmax))
904                 pdata->vmax = INT_MAX;
905
906         return pdata;
907 }
908 #else
909 static struct max17042_reg_data max17047_default_pdata_init_regs[] = {
910         /*
911          * Some firmwares do not set FullSOCThr, Enable End-of-Charge Detection
912          * when the voltage FG reports 95%, as recommended in the datasheet.
913          */
914         { MAX17047_FullSOCThr, MAX17042_BATTERY_FULL << 8 },
915 };
916
917 static struct max17042_platform_data *
918 max17042_get_pdata(struct max17042_chip *chip)
919 {
920         struct device *dev = &chip->client->dev;
921         struct max17042_platform_data *pdata;
922         int ret, misc_cfg;
923
924         if (dev->platform_data)
925                 return dev->platform_data;
926
927         /*
928          * The MAX17047 gets used on x86 where we might not have pdata, assume
929          * the firmware will already have initialized the fuel-gauge and provide
930          * default values for the non init bits to make things work.
931          */
932         pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
933         if (!pdata)
934                 return pdata;
935
936         if (chip->chip_type != MAXIM_DEVICE_TYPE_MAX17042) {
937                 pdata->init_data = max17047_default_pdata_init_regs;
938                 pdata->num_init_data =
939                         ARRAY_SIZE(max17047_default_pdata_init_regs);
940         }
941
942         ret = regmap_read(chip->regmap, MAX17042_MiscCFG, &misc_cfg);
943         if (ret < 0)
944                 return NULL;
945
946         /* If bits 0-1 are set to 3 then only Voltage readings are used */
947         if ((misc_cfg & 0x3) == 0x3)
948                 pdata->enable_current_sense = false;
949         else
950                 pdata->enable_current_sense = true;
951
952         pdata->vmin = MAX17042_DEFAULT_VMIN;
953         pdata->vmax = MAX17042_DEFAULT_VMAX;
954         pdata->temp_min = MAX17042_DEFAULT_TEMP_MIN;
955         pdata->temp_max = MAX17042_DEFAULT_TEMP_MAX;
956
957         return pdata;
958 }
959 #endif
960
961 static const struct regmap_config max17042_regmap_config = {
962         .reg_bits = 8,
963         .val_bits = 16,
964         .val_format_endian = REGMAP_ENDIAN_NATIVE,
965 };
966
967 static const struct power_supply_desc max17042_psy_desc = {
968         .name           = "max170xx_battery",
969         .type           = POWER_SUPPLY_TYPE_BATTERY,
970         .get_property   = max17042_get_property,
971         .set_property   = max17042_set_property,
972         .property_is_writeable  = max17042_property_is_writeable,
973         .external_power_changed = max17042_external_power_changed,
974         .properties     = max17042_battery_props,
975         .num_properties = ARRAY_SIZE(max17042_battery_props),
976 };
977
978 static const struct power_supply_desc max17042_no_current_sense_psy_desc = {
979         .name           = "max170xx_battery",
980         .type           = POWER_SUPPLY_TYPE_BATTERY,
981         .get_property   = max17042_get_property,
982         .set_property   = max17042_set_property,
983         .property_is_writeable  = max17042_property_is_writeable,
984         .properties     = max17042_battery_props,
985         .num_properties = ARRAY_SIZE(max17042_battery_props) - 2,
986 };
987
988 static int max17042_probe(struct i2c_client *client,
989                         const struct i2c_device_id *id)
990 {
991         struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
992         const struct power_supply_desc *max17042_desc = &max17042_psy_desc;
993         struct power_supply_config psy_cfg = {};
994         const struct acpi_device_id *acpi_id = NULL;
995         struct device *dev = &client->dev;
996         struct max17042_chip *chip;
997         int ret;
998         int i;
999         u32 val;
1000
1001         if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA))
1002                 return -EIO;
1003
1004         chip = devm_kzalloc(&client->dev, sizeof(*chip), GFP_KERNEL);
1005         if (!chip)
1006                 return -ENOMEM;
1007
1008         chip->client = client;
1009         if (id) {
1010                 chip->chip_type = id->driver_data;
1011         } else {
1012                 acpi_id = acpi_match_device(dev->driver->acpi_match_table, dev);
1013                 if (!acpi_id)
1014                         return -ENODEV;
1015
1016                 chip->chip_type = acpi_id->driver_data;
1017         }
1018         chip->regmap = devm_regmap_init_i2c(client, &max17042_regmap_config);
1019         if (IS_ERR(chip->regmap)) {
1020                 dev_err(&client->dev, "Failed to initialize regmap\n");
1021                 return -EINVAL;
1022         }
1023
1024         chip->pdata = max17042_get_pdata(chip);
1025         if (!chip->pdata) {
1026                 dev_err(&client->dev, "no platform data provided\n");
1027                 return -EINVAL;
1028         }
1029
1030         i2c_set_clientdata(client, chip);
1031         psy_cfg.drv_data = chip;
1032         psy_cfg.of_node = dev->of_node;
1033
1034         /* When current is not measured,
1035          * CURRENT_NOW and CURRENT_AVG properties should be invisible. */
1036         if (!chip->pdata->enable_current_sense)
1037                 max17042_desc = &max17042_no_current_sense_psy_desc;
1038
1039         if (chip->pdata->r_sns == 0)
1040                 chip->pdata->r_sns = MAX17042_DEFAULT_SNS_RESISTOR;
1041
1042         if (chip->pdata->init_data)
1043                 for (i = 0; i < chip->pdata->num_init_data; i++)
1044                         regmap_write(chip->regmap,
1045                                         chip->pdata->init_data[i].addr,
1046                                         chip->pdata->init_data[i].data);
1047
1048         if (!chip->pdata->enable_current_sense) {
1049                 regmap_write(chip->regmap, MAX17042_CGAIN, 0x0000);
1050                 regmap_write(chip->regmap, MAX17042_MiscCFG, 0x0003);
1051                 regmap_write(chip->regmap, MAX17042_LearnCFG, 0x0007);
1052         }
1053
1054         chip->battery = devm_power_supply_register(&client->dev, max17042_desc,
1055                                                    &psy_cfg);
1056         if (IS_ERR(chip->battery)) {
1057                 dev_err(&client->dev, "failed: power supply register\n");
1058                 return PTR_ERR(chip->battery);
1059         }
1060
1061         if (client->irq) {
1062                 unsigned int flags = IRQF_ONESHOT;
1063
1064                 /*
1065                  * On ACPI systems the IRQ may be handled by ACPI-event code,
1066                  * so we need to share (if the ACPI code is willing to share).
1067                  */
1068                 if (acpi_id)
1069                         flags |= IRQF_SHARED | IRQF_PROBE_SHARED;
1070
1071                 ret = devm_request_threaded_irq(&client->dev, client->irq,
1072                                                 NULL,
1073                                                 max17042_thread_handler, flags,
1074                                                 chip->battery->desc->name,
1075                                                 chip);
1076                 if (!ret) {
1077                         regmap_update_bits(chip->regmap, MAX17042_CONFIG,
1078                                         CONFIG_ALRT_BIT_ENBL,
1079                                         CONFIG_ALRT_BIT_ENBL);
1080                         max17042_set_soc_threshold(chip, 1);
1081                 } else {
1082                         client->irq = 0;
1083                         if (ret != -EBUSY)
1084                                 dev_err(&client->dev, "Failed to get IRQ\n");
1085                 }
1086         }
1087         /* Not able to update the charge threshold when exceeded? -> disable */
1088         if (!client->irq)
1089                 regmap_write(chip->regmap, MAX17042_SALRT_Th, 0xff00);
1090
1091         regmap_read(chip->regmap, MAX17042_STATUS, &val);
1092         if (val & STATUS_POR_BIT) {
1093                 INIT_WORK(&chip->work, max17042_init_worker);
1094                 schedule_work(&chip->work);
1095         } else {
1096                 chip->init_complete = 1;
1097         }
1098
1099         return 0;
1100 }
1101
1102 #ifdef CONFIG_PM_SLEEP
1103 static int max17042_suspend(struct device *dev)
1104 {
1105         struct max17042_chip *chip = dev_get_drvdata(dev);
1106
1107         /*
1108          * disable the irq and enable irq_wake
1109          * capability to the interrupt line.
1110          */
1111         if (chip->client->irq) {
1112                 disable_irq(chip->client->irq);
1113                 enable_irq_wake(chip->client->irq);
1114         }
1115
1116         return 0;
1117 }
1118
1119 static int max17042_resume(struct device *dev)
1120 {
1121         struct max17042_chip *chip = dev_get_drvdata(dev);
1122
1123         if (chip->client->irq) {
1124                 disable_irq_wake(chip->client->irq);
1125                 enable_irq(chip->client->irq);
1126                 /* re-program the SOC thresholds to 1% change */
1127                 max17042_set_soc_threshold(chip, 1);
1128         }
1129
1130         return 0;
1131 }
1132 #endif
1133
1134 static SIMPLE_DEV_PM_OPS(max17042_pm_ops, max17042_suspend,
1135                         max17042_resume);
1136
1137 #ifdef CONFIG_ACPI
1138 static const struct acpi_device_id max17042_acpi_match[] = {
1139         { "MAX17047", MAXIM_DEVICE_TYPE_MAX17047 },
1140         { }
1141 };
1142 MODULE_DEVICE_TABLE(acpi, max17042_acpi_match);
1143 #endif
1144
1145 #ifdef CONFIG_OF
1146 static const struct of_device_id max17042_dt_match[] = {
1147         { .compatible = "maxim,max17042" },
1148         { .compatible = "maxim,max17047" },
1149         { .compatible = "maxim,max17050" },
1150         { },
1151 };
1152 MODULE_DEVICE_TABLE(of, max17042_dt_match);
1153 #endif
1154
1155 static const struct i2c_device_id max17042_id[] = {
1156         { "max17042", MAXIM_DEVICE_TYPE_MAX17042 },
1157         { "max17047", MAXIM_DEVICE_TYPE_MAX17047 },
1158         { "max17050", MAXIM_DEVICE_TYPE_MAX17050 },
1159         { }
1160 };
1161 MODULE_DEVICE_TABLE(i2c, max17042_id);
1162
1163 static struct i2c_driver max17042_i2c_driver = {
1164         .driver = {
1165                 .name   = "max17042",
1166                 .acpi_match_table = ACPI_PTR(max17042_acpi_match),
1167                 .of_match_table = of_match_ptr(max17042_dt_match),
1168                 .pm     = &max17042_pm_ops,
1169         },
1170         .probe          = max17042_probe,
1171         .id_table       = max17042_id,
1172 };
1173 module_i2c_driver(max17042_i2c_driver);
1174
1175 MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>");
1176 MODULE_DESCRIPTION("MAX17042 Fuel Gauge");
1177 MODULE_LICENSE("GPL");