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