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