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