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