1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (C) 2018 Spreadtrum Communications Inc.
3 
4 #include <linux/gpio/consumer.h>
5 #include <linux/iio/consumer.h>
6 #include <linux/interrupt.h>
7 #include <linux/kernel.h>
8 #include <linux/module.h>
9 #include <linux/nvmem-consumer.h>
10 #include <linux/of.h>
11 #include <linux/platform_device.h>
12 #include <linux/power_supply.h>
13 #include <linux/regmap.h>
14 #include <linux/slab.h>
15 
16 /* PMIC global control registers definition */
17 #define SC27XX_MODULE_EN0		0xc08
18 #define SC27XX_CLK_EN0			0xc18
19 #define SC27XX_FGU_EN			BIT(7)
20 #define SC27XX_FGU_RTC_EN		BIT(6)
21 
22 /* FGU registers definition */
23 #define SC27XX_FGU_START		0x0
24 #define SC27XX_FGU_CONFIG		0x4
25 #define SC27XX_FGU_ADC_CONFIG		0x8
26 #define SC27XX_FGU_STATUS		0xc
27 #define SC27XX_FGU_INT_EN		0x10
28 #define SC27XX_FGU_INT_CLR		0x14
29 #define SC27XX_FGU_INT_STS		0x1c
30 #define SC27XX_FGU_VOLTAGE		0x20
31 #define SC27XX_FGU_OCV			0x24
32 #define SC27XX_FGU_POCV			0x28
33 #define SC27XX_FGU_CURRENT		0x2c
34 #define SC27XX_FGU_LOW_OVERLOAD		0x34
35 #define SC27XX_FGU_CLBCNT_SETH		0x50
36 #define SC27XX_FGU_CLBCNT_SETL		0x54
37 #define SC27XX_FGU_CLBCNT_DELTH		0x58
38 #define SC27XX_FGU_CLBCNT_DELTL		0x5c
39 #define SC27XX_FGU_CLBCNT_VALH		0x68
40 #define SC27XX_FGU_CLBCNT_VALL		0x6c
41 #define SC27XX_FGU_CLBCNT_QMAXL		0x74
42 #define SC27XX_FGU_USER_AREA_SET	0xa0
43 #define SC27XX_FGU_USER_AREA_CLEAR	0xa4
44 #define SC27XX_FGU_USER_AREA_STATUS	0xa8
45 
46 #define SC27XX_WRITE_SELCLB_EN		BIT(0)
47 #define SC27XX_FGU_CLBCNT_MASK		GENMASK(15, 0)
48 #define SC27XX_FGU_CLBCNT_SHIFT		16
49 #define SC27XX_FGU_LOW_OVERLOAD_MASK	GENMASK(12, 0)
50 
51 #define SC27XX_FGU_INT_MASK		GENMASK(9, 0)
52 #define SC27XX_FGU_LOW_OVERLOAD_INT	BIT(0)
53 #define SC27XX_FGU_CLBCNT_DELTA_INT	BIT(2)
54 
55 #define SC27XX_FGU_MODE_AREA_MASK	GENMASK(15, 12)
56 #define SC27XX_FGU_CAP_AREA_MASK	GENMASK(11, 0)
57 #define SC27XX_FGU_MODE_AREA_SHIFT	12
58 
59 #define SC27XX_FGU_FIRST_POWERTON	GENMASK(3, 0)
60 #define SC27XX_FGU_DEFAULT_CAP		GENMASK(11, 0)
61 #define SC27XX_FGU_NORMAIL_POWERTON	0x5
62 
63 #define SC27XX_FGU_CUR_BASIC_ADC	8192
64 #define SC27XX_FGU_SAMPLE_HZ		2
65 
66 /*
67  * struct sc27xx_fgu_data: describe the FGU device
68  * @regmap: regmap for register access
69  * @dev: platform device
70  * @battery: battery power supply
71  * @base: the base offset for the controller
72  * @lock: protect the structure
73  * @gpiod: GPIO for battery detection
74  * @channel: IIO channel to get battery temperature
75  * @charge_chan: IIO channel to get charge voltage
76  * @internal_resist: the battery internal resistance in mOhm
77  * @total_cap: the total capacity of the battery in mAh
78  * @init_cap: the initial capacity of the battery in mAh
79  * @alarm_cap: the alarm capacity
80  * @init_clbcnt: the initial coulomb counter
81  * @max_volt: the maximum constant input voltage in millivolt
82  * @min_volt: the minimum drained battery voltage in microvolt
83  * @table_len: the capacity table length
84  * @cur_1000ma_adc: ADC value corresponding to 1000 mA
85  * @vol_1000mv_adc: ADC value corresponding to 1000 mV
86  * @cap_table: capacity table with corresponding ocv
87  */
88 struct sc27xx_fgu_data {
89 	struct regmap *regmap;
90 	struct device *dev;
91 	struct power_supply *battery;
92 	u32 base;
93 	struct mutex lock;
94 	struct gpio_desc *gpiod;
95 	struct iio_channel *channel;
96 	struct iio_channel *charge_chan;
97 	bool bat_present;
98 	int internal_resist;
99 	int total_cap;
100 	int init_cap;
101 	int alarm_cap;
102 	int init_clbcnt;
103 	int max_volt;
104 	int min_volt;
105 	int table_len;
106 	int cur_1000ma_adc;
107 	int vol_1000mv_adc;
108 	struct power_supply_battery_ocv_table *cap_table;
109 };
110 
111 static int sc27xx_fgu_cap_to_clbcnt(struct sc27xx_fgu_data *data, int capacity);
112 
113 static const char * const sc27xx_charger_supply_name[] = {
114 	"sc2731_charger",
115 	"sc2720_charger",
116 	"sc2721_charger",
117 	"sc2723_charger",
118 };
119 
120 static int sc27xx_fgu_adc_to_current(struct sc27xx_fgu_data *data, int adc)
121 {
122 	return DIV_ROUND_CLOSEST(adc * 1000, data->cur_1000ma_adc);
123 }
124 
125 static int sc27xx_fgu_adc_to_voltage(struct sc27xx_fgu_data *data, int adc)
126 {
127 	return DIV_ROUND_CLOSEST(adc * 1000, data->vol_1000mv_adc);
128 }
129 
130 static int sc27xx_fgu_voltage_to_adc(struct sc27xx_fgu_data *data, int vol)
131 {
132 	return DIV_ROUND_CLOSEST(vol * data->vol_1000mv_adc, 1000);
133 }
134 
135 static bool sc27xx_fgu_is_first_poweron(struct sc27xx_fgu_data *data)
136 {
137 	int ret, status, cap, mode;
138 
139 	ret = regmap_read(data->regmap,
140 			  data->base + SC27XX_FGU_USER_AREA_STATUS, &status);
141 	if (ret)
142 		return false;
143 
144 	/*
145 	 * We use low 4 bits to save the last battery capacity and high 12 bits
146 	 * to save the system boot mode.
147 	 */
148 	mode = (status & SC27XX_FGU_MODE_AREA_MASK) >> SC27XX_FGU_MODE_AREA_SHIFT;
149 	cap = status & SC27XX_FGU_CAP_AREA_MASK;
150 
151 	/*
152 	 * When FGU has been powered down, the user area registers became
153 	 * default value (0xffff), which can be used to valid if the system is
154 	 * first power on or not.
155 	 */
156 	if (mode == SC27XX_FGU_FIRST_POWERTON || cap == SC27XX_FGU_DEFAULT_CAP)
157 		return true;
158 
159 	return false;
160 }
161 
162 static int sc27xx_fgu_save_boot_mode(struct sc27xx_fgu_data *data,
163 				     int boot_mode)
164 {
165 	int ret;
166 
167 	ret = regmap_update_bits(data->regmap,
168 				 data->base + SC27XX_FGU_USER_AREA_CLEAR,
169 				 SC27XX_FGU_MODE_AREA_MASK,
170 				 SC27XX_FGU_MODE_AREA_MASK);
171 	if (ret)
172 		return ret;
173 
174 	/*
175 	 * Since the user area registers are put on power always-on region,
176 	 * then these registers changing time will be a little long. Thus
177 	 * here we should delay 200us to wait until values are updated
178 	 * successfully according to the datasheet.
179 	 */
180 	udelay(200);
181 
182 	ret = regmap_update_bits(data->regmap,
183 				 data->base + SC27XX_FGU_USER_AREA_SET,
184 				 SC27XX_FGU_MODE_AREA_MASK,
185 				 boot_mode << SC27XX_FGU_MODE_AREA_SHIFT);
186 	if (ret)
187 		return ret;
188 
189 	/*
190 	 * Since the user area registers are put on power always-on region,
191 	 * then these registers changing time will be a little long. Thus
192 	 * here we should delay 200us to wait until values are updated
193 	 * successfully according to the datasheet.
194 	 */
195 	udelay(200);
196 
197 	/*
198 	 * According to the datasheet, we should set the USER_AREA_CLEAR to 0 to
199 	 * make the user area data available, otherwise we can not save the user
200 	 * area data.
201 	 */
202 	return regmap_update_bits(data->regmap,
203 				  data->base + SC27XX_FGU_USER_AREA_CLEAR,
204 				  SC27XX_FGU_MODE_AREA_MASK, 0);
205 }
206 
207 static int sc27xx_fgu_save_last_cap(struct sc27xx_fgu_data *data, int cap)
208 {
209 	int ret;
210 
211 	ret = regmap_update_bits(data->regmap,
212 				 data->base + SC27XX_FGU_USER_AREA_CLEAR,
213 				 SC27XX_FGU_CAP_AREA_MASK,
214 				 SC27XX_FGU_CAP_AREA_MASK);
215 	if (ret)
216 		return ret;
217 
218 	/*
219 	 * Since the user area registers are put on power always-on region,
220 	 * then these registers changing time will be a little long. Thus
221 	 * here we should delay 200us to wait until values are updated
222 	 * successfully according to the datasheet.
223 	 */
224 	udelay(200);
225 
226 	ret = regmap_update_bits(data->regmap,
227 				 data->base + SC27XX_FGU_USER_AREA_SET,
228 				 SC27XX_FGU_CAP_AREA_MASK, cap);
229 	if (ret)
230 		return ret;
231 
232 	/*
233 	 * Since the user area registers are put on power always-on region,
234 	 * then these registers changing time will be a little long. Thus
235 	 * here we should delay 200us to wait until values are updated
236 	 * successfully according to the datasheet.
237 	 */
238 	udelay(200);
239 
240 	/*
241 	 * According to the datasheet, we should set the USER_AREA_CLEAR to 0 to
242 	 * make the user area data available, otherwise we can not save the user
243 	 * area data.
244 	 */
245 	return regmap_update_bits(data->regmap,
246 				  data->base + SC27XX_FGU_USER_AREA_CLEAR,
247 				  SC27XX_FGU_CAP_AREA_MASK, 0);
248 }
249 
250 static int sc27xx_fgu_read_last_cap(struct sc27xx_fgu_data *data, int *cap)
251 {
252 	int ret, value;
253 
254 	ret = regmap_read(data->regmap,
255 			  data->base + SC27XX_FGU_USER_AREA_STATUS, &value);
256 	if (ret)
257 		return ret;
258 
259 	*cap = value & SC27XX_FGU_CAP_AREA_MASK;
260 	return 0;
261 }
262 
263 /*
264  * When system boots on, we can not read battery capacity from coulomb
265  * registers, since now the coulomb registers are invalid. So we should
266  * calculate the battery open circuit voltage, and get current battery
267  * capacity according to the capacity table.
268  */
269 static int sc27xx_fgu_get_boot_capacity(struct sc27xx_fgu_data *data, int *cap)
270 {
271 	int volt, cur, oci, ocv, ret;
272 	bool is_first_poweron = sc27xx_fgu_is_first_poweron(data);
273 
274 	/*
275 	 * If system is not the first power on, we should use the last saved
276 	 * battery capacity as the initial battery capacity. Otherwise we should
277 	 * re-calculate the initial battery capacity.
278 	 */
279 	if (!is_first_poweron) {
280 		ret = sc27xx_fgu_read_last_cap(data, cap);
281 		if (ret)
282 			return ret;
283 
284 		return sc27xx_fgu_save_boot_mode(data, SC27XX_FGU_NORMAIL_POWERTON);
285 	}
286 
287 	/*
288 	 * After system booting on, the SC27XX_FGU_CLBCNT_QMAXL register saved
289 	 * the first sampled open circuit current.
290 	 */
291 	ret = regmap_read(data->regmap, data->base + SC27XX_FGU_CLBCNT_QMAXL,
292 			  &cur);
293 	if (ret)
294 		return ret;
295 
296 	cur <<= 1;
297 	oci = sc27xx_fgu_adc_to_current(data, cur - SC27XX_FGU_CUR_BASIC_ADC);
298 
299 	/*
300 	 * Should get the OCV from SC27XX_FGU_POCV register at the system
301 	 * beginning. It is ADC values reading from registers which need to
302 	 * convert the corresponding voltage.
303 	 */
304 	ret = regmap_read(data->regmap, data->base + SC27XX_FGU_POCV, &volt);
305 	if (ret)
306 		return ret;
307 
308 	volt = sc27xx_fgu_adc_to_voltage(data, volt);
309 	ocv = volt * 1000 - oci * data->internal_resist;
310 
311 	/*
312 	 * Parse the capacity table to look up the correct capacity percent
313 	 * according to current battery's corresponding OCV values.
314 	 */
315 	*cap = power_supply_ocv2cap_simple(data->cap_table, data->table_len,
316 					   ocv);
317 
318 	ret = sc27xx_fgu_save_last_cap(data, *cap);
319 	if (ret)
320 		return ret;
321 
322 	return sc27xx_fgu_save_boot_mode(data, SC27XX_FGU_NORMAIL_POWERTON);
323 }
324 
325 static int sc27xx_fgu_set_clbcnt(struct sc27xx_fgu_data *data, int clbcnt)
326 {
327 	int ret;
328 
329 	clbcnt *= SC27XX_FGU_SAMPLE_HZ;
330 
331 	ret = regmap_update_bits(data->regmap,
332 				 data->base + SC27XX_FGU_CLBCNT_SETL,
333 				 SC27XX_FGU_CLBCNT_MASK, clbcnt);
334 	if (ret)
335 		return ret;
336 
337 	ret = regmap_update_bits(data->regmap,
338 				 data->base + SC27XX_FGU_CLBCNT_SETH,
339 				 SC27XX_FGU_CLBCNT_MASK,
340 				 clbcnt >> SC27XX_FGU_CLBCNT_SHIFT);
341 	if (ret)
342 		return ret;
343 
344 	return regmap_update_bits(data->regmap, data->base + SC27XX_FGU_START,
345 				 SC27XX_WRITE_SELCLB_EN,
346 				 SC27XX_WRITE_SELCLB_EN);
347 }
348 
349 static int sc27xx_fgu_get_clbcnt(struct sc27xx_fgu_data *data, int *clb_cnt)
350 {
351 	int ccl, cch, ret;
352 
353 	ret = regmap_read(data->regmap, data->base + SC27XX_FGU_CLBCNT_VALL,
354 			  &ccl);
355 	if (ret)
356 		return ret;
357 
358 	ret = regmap_read(data->regmap, data->base + SC27XX_FGU_CLBCNT_VALH,
359 			  &cch);
360 	if (ret)
361 		return ret;
362 
363 	*clb_cnt = ccl & SC27XX_FGU_CLBCNT_MASK;
364 	*clb_cnt |= (cch & SC27XX_FGU_CLBCNT_MASK) << SC27XX_FGU_CLBCNT_SHIFT;
365 	*clb_cnt /= SC27XX_FGU_SAMPLE_HZ;
366 
367 	return 0;
368 }
369 
370 static int sc27xx_fgu_get_capacity(struct sc27xx_fgu_data *data, int *cap)
371 {
372 	int ret, cur_clbcnt, delta_clbcnt, delta_cap, temp;
373 
374 	/* Get current coulomb counters firstly */
375 	ret = sc27xx_fgu_get_clbcnt(data, &cur_clbcnt);
376 	if (ret)
377 		return ret;
378 
379 	delta_clbcnt = cur_clbcnt - data->init_clbcnt;
380 
381 	/*
382 	 * Convert coulomb counter to delta capacity (mAh), and set multiplier
383 	 * as 100 to improve the precision.
384 	 */
385 	temp = DIV_ROUND_CLOSEST(delta_clbcnt, 360);
386 	temp = sc27xx_fgu_adc_to_current(data, temp);
387 
388 	/*
389 	 * Convert to capacity percent of the battery total capacity,
390 	 * and multiplier is 100 too.
391 	 */
392 	delta_cap = DIV_ROUND_CLOSEST(temp * 100, data->total_cap);
393 	*cap = delta_cap + data->init_cap;
394 
395 	return 0;
396 }
397 
398 static int sc27xx_fgu_get_vbat_vol(struct sc27xx_fgu_data *data, int *val)
399 {
400 	int ret, vol;
401 
402 	ret = regmap_read(data->regmap, data->base + SC27XX_FGU_VOLTAGE, &vol);
403 	if (ret)
404 		return ret;
405 
406 	/*
407 	 * It is ADC values reading from registers which need to convert to
408 	 * corresponding voltage values.
409 	 */
410 	*val = sc27xx_fgu_adc_to_voltage(data, vol);
411 
412 	return 0;
413 }
414 
415 static int sc27xx_fgu_get_current(struct sc27xx_fgu_data *data, int *val)
416 {
417 	int ret, cur;
418 
419 	ret = regmap_read(data->regmap, data->base + SC27XX_FGU_CURRENT, &cur);
420 	if (ret)
421 		return ret;
422 
423 	/*
424 	 * It is ADC values reading from registers which need to convert to
425 	 * corresponding current values.
426 	 */
427 	*val = sc27xx_fgu_adc_to_current(data, cur - SC27XX_FGU_CUR_BASIC_ADC);
428 
429 	return 0;
430 }
431 
432 static int sc27xx_fgu_get_vbat_ocv(struct sc27xx_fgu_data *data, int *val)
433 {
434 	int vol, cur, ret;
435 
436 	ret = sc27xx_fgu_get_vbat_vol(data, &vol);
437 	if (ret)
438 		return ret;
439 
440 	ret = sc27xx_fgu_get_current(data, &cur);
441 	if (ret)
442 		return ret;
443 
444 	/* Return the battery OCV in micro volts. */
445 	*val = vol * 1000 - cur * data->internal_resist;
446 
447 	return 0;
448 }
449 
450 static int sc27xx_fgu_get_charge_vol(struct sc27xx_fgu_data *data, int *val)
451 {
452 	int ret, vol;
453 
454 	ret = iio_read_channel_processed(data->charge_chan, &vol);
455 	if (ret < 0)
456 		return ret;
457 
458 	*val = vol * 1000;
459 	return 0;
460 }
461 
462 static int sc27xx_fgu_get_temp(struct sc27xx_fgu_data *data, int *temp)
463 {
464 	return iio_read_channel_processed(data->channel, temp);
465 }
466 
467 static int sc27xx_fgu_get_health(struct sc27xx_fgu_data *data, int *health)
468 {
469 	int ret, vol;
470 
471 	ret = sc27xx_fgu_get_vbat_vol(data, &vol);
472 	if (ret)
473 		return ret;
474 
475 	if (vol > data->max_volt)
476 		*health = POWER_SUPPLY_HEALTH_OVERVOLTAGE;
477 	else
478 		*health = POWER_SUPPLY_HEALTH_GOOD;
479 
480 	return 0;
481 }
482 
483 static int sc27xx_fgu_get_status(struct sc27xx_fgu_data *data, int *status)
484 {
485 	union power_supply_propval val;
486 	struct power_supply *psy;
487 	int i, ret = -EINVAL;
488 
489 	for (i = 0; i < ARRAY_SIZE(sc27xx_charger_supply_name); i++) {
490 		psy = power_supply_get_by_name(sc27xx_charger_supply_name[i]);
491 		if (!psy)
492 			continue;
493 
494 		ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_STATUS,
495 						&val);
496 		power_supply_put(psy);
497 		if (ret)
498 			return ret;
499 
500 		*status = val.intval;
501 	}
502 
503 	return ret;
504 }
505 
506 static int sc27xx_fgu_get_property(struct power_supply *psy,
507 				   enum power_supply_property psp,
508 				   union power_supply_propval *val)
509 {
510 	struct sc27xx_fgu_data *data = power_supply_get_drvdata(psy);
511 	int ret = 0;
512 	int value;
513 
514 	mutex_lock(&data->lock);
515 
516 	switch (psp) {
517 	case POWER_SUPPLY_PROP_STATUS:
518 		ret = sc27xx_fgu_get_status(data, &value);
519 		if (ret)
520 			goto error;
521 
522 		val->intval = value;
523 		break;
524 
525 	case POWER_SUPPLY_PROP_HEALTH:
526 		ret = sc27xx_fgu_get_health(data, &value);
527 		if (ret)
528 			goto error;
529 
530 		val->intval = value;
531 		break;
532 
533 	case POWER_SUPPLY_PROP_PRESENT:
534 		val->intval = data->bat_present;
535 		break;
536 
537 	case POWER_SUPPLY_PROP_TEMP:
538 		ret = sc27xx_fgu_get_temp(data, &value);
539 		if (ret)
540 			goto error;
541 
542 		val->intval = value;
543 		break;
544 
545 	case POWER_SUPPLY_PROP_TECHNOLOGY:
546 		val->intval = POWER_SUPPLY_TECHNOLOGY_LION;
547 		break;
548 
549 	case POWER_SUPPLY_PROP_CAPACITY:
550 		ret = sc27xx_fgu_get_capacity(data, &value);
551 		if (ret)
552 			goto error;
553 
554 		val->intval = value;
555 		break;
556 
557 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
558 		ret = sc27xx_fgu_get_vbat_vol(data, &value);
559 		if (ret)
560 			goto error;
561 
562 		val->intval = value * 1000;
563 		break;
564 
565 	case POWER_SUPPLY_PROP_VOLTAGE_OCV:
566 		ret = sc27xx_fgu_get_vbat_ocv(data, &value);
567 		if (ret)
568 			goto error;
569 
570 		val->intval = value;
571 		break;
572 
573 	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
574 		ret = sc27xx_fgu_get_charge_vol(data, &value);
575 		if (ret)
576 			goto error;
577 
578 		val->intval = value;
579 		break;
580 
581 	case POWER_SUPPLY_PROP_CURRENT_NOW:
582 	case POWER_SUPPLY_PROP_CURRENT_AVG:
583 		ret = sc27xx_fgu_get_current(data, &value);
584 		if (ret)
585 			goto error;
586 
587 		val->intval = value * 1000;
588 		break;
589 
590 	default:
591 		ret = -EINVAL;
592 		break;
593 	}
594 
595 error:
596 	mutex_unlock(&data->lock);
597 	return ret;
598 }
599 
600 static int sc27xx_fgu_set_property(struct power_supply *psy,
601 				   enum power_supply_property psp,
602 				   const union power_supply_propval *val)
603 {
604 	struct sc27xx_fgu_data *data = power_supply_get_drvdata(psy);
605 	int ret;
606 
607 	if (psp != POWER_SUPPLY_PROP_CAPACITY)
608 		return -EINVAL;
609 
610 	mutex_lock(&data->lock);
611 
612 	ret = sc27xx_fgu_save_last_cap(data, val->intval);
613 
614 	mutex_unlock(&data->lock);
615 
616 	if (ret < 0)
617 		dev_err(data->dev, "failed to save battery capacity\n");
618 
619 	return ret;
620 }
621 
622 static void sc27xx_fgu_external_power_changed(struct power_supply *psy)
623 {
624 	struct sc27xx_fgu_data *data = power_supply_get_drvdata(psy);
625 
626 	power_supply_changed(data->battery);
627 }
628 
629 static int sc27xx_fgu_property_is_writeable(struct power_supply *psy,
630 					    enum power_supply_property psp)
631 {
632 	return psp == POWER_SUPPLY_PROP_CAPACITY;
633 }
634 
635 static enum power_supply_property sc27xx_fgu_props[] = {
636 	POWER_SUPPLY_PROP_STATUS,
637 	POWER_SUPPLY_PROP_HEALTH,
638 	POWER_SUPPLY_PROP_PRESENT,
639 	POWER_SUPPLY_PROP_TEMP,
640 	POWER_SUPPLY_PROP_TECHNOLOGY,
641 	POWER_SUPPLY_PROP_CAPACITY,
642 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
643 	POWER_SUPPLY_PROP_VOLTAGE_OCV,
644 	POWER_SUPPLY_PROP_CURRENT_NOW,
645 	POWER_SUPPLY_PROP_CURRENT_AVG,
646 	POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
647 };
648 
649 static const struct power_supply_desc sc27xx_fgu_desc = {
650 	.name			= "sc27xx-fgu",
651 	.type			= POWER_SUPPLY_TYPE_BATTERY,
652 	.properties		= sc27xx_fgu_props,
653 	.num_properties		= ARRAY_SIZE(sc27xx_fgu_props),
654 	.get_property		= sc27xx_fgu_get_property,
655 	.set_property		= sc27xx_fgu_set_property,
656 	.external_power_changed	= sc27xx_fgu_external_power_changed,
657 	.property_is_writeable	= sc27xx_fgu_property_is_writeable,
658 };
659 
660 static void sc27xx_fgu_adjust_cap(struct sc27xx_fgu_data *data, int cap)
661 {
662 	data->init_cap = cap;
663 	data->init_clbcnt = sc27xx_fgu_cap_to_clbcnt(data, data->init_cap);
664 }
665 
666 static irqreturn_t sc27xx_fgu_interrupt(int irq, void *dev_id)
667 {
668 	struct sc27xx_fgu_data *data = dev_id;
669 	int ret, cap, ocv, adc;
670 	u32 status;
671 
672 	mutex_lock(&data->lock);
673 
674 	ret = regmap_read(data->regmap, data->base + SC27XX_FGU_INT_STS,
675 			  &status);
676 	if (ret)
677 		goto out;
678 
679 	ret = regmap_update_bits(data->regmap, data->base + SC27XX_FGU_INT_CLR,
680 				 status, status);
681 	if (ret)
682 		goto out;
683 
684 	/*
685 	 * When low overload voltage interrupt happens, we should calibrate the
686 	 * battery capacity in lower voltage stage.
687 	 */
688 	if (!(status & SC27XX_FGU_LOW_OVERLOAD_INT))
689 		goto out;
690 
691 	ret = sc27xx_fgu_get_capacity(data, &cap);
692 	if (ret)
693 		goto out;
694 
695 	ret = sc27xx_fgu_get_vbat_ocv(data, &ocv);
696 	if (ret)
697 		goto out;
698 
699 	/*
700 	 * If current OCV value is less than the minimum OCV value in OCV table,
701 	 * which means now battery capacity is 0%, and we should adjust the
702 	 * inititial capacity to 0.
703 	 */
704 	if (ocv <= data->cap_table[data->table_len - 1].ocv) {
705 		sc27xx_fgu_adjust_cap(data, 0);
706 	} else if (ocv <= data->min_volt) {
707 		/*
708 		 * If current OCV value is less than the low alarm voltage, but
709 		 * current capacity is larger than the alarm capacity, we should
710 		 * adjust the inititial capacity to alarm capacity.
711 		 */
712 		if (cap > data->alarm_cap) {
713 			sc27xx_fgu_adjust_cap(data, data->alarm_cap);
714 		} else if (cap <= 0) {
715 			int cur_cap;
716 
717 			/*
718 			 * If current capacity is equal with 0 or less than 0
719 			 * (some error occurs), we should adjust inititial
720 			 * capacity to the capacity corresponding to current OCV
721 			 * value.
722 			 */
723 			cur_cap = power_supply_ocv2cap_simple(data->cap_table,
724 							      data->table_len,
725 							      ocv);
726 			sc27xx_fgu_adjust_cap(data, cur_cap);
727 		}
728 
729 		/*
730 		 * After adjusting the battery capacity, we should set the
731 		 * lowest alarm voltage instead.
732 		 */
733 		data->min_volt = data->cap_table[data->table_len - 1].ocv;
734 		adc = sc27xx_fgu_voltage_to_adc(data, data->min_volt / 1000);
735 		regmap_update_bits(data->regmap, data->base + SC27XX_FGU_LOW_OVERLOAD,
736 				   SC27XX_FGU_LOW_OVERLOAD_MASK, adc);
737 	}
738 
739 out:
740 	mutex_unlock(&data->lock);
741 
742 	power_supply_changed(data->battery);
743 	return IRQ_HANDLED;
744 }
745 
746 static irqreturn_t sc27xx_fgu_bat_detection(int irq, void *dev_id)
747 {
748 	struct sc27xx_fgu_data *data = dev_id;
749 	int state;
750 
751 	mutex_lock(&data->lock);
752 
753 	state = gpiod_get_value_cansleep(data->gpiod);
754 	if (state < 0) {
755 		dev_err(data->dev, "failed to get gpio state\n");
756 		mutex_unlock(&data->lock);
757 		return IRQ_RETVAL(state);
758 	}
759 
760 	data->bat_present = !!state;
761 
762 	mutex_unlock(&data->lock);
763 
764 	power_supply_changed(data->battery);
765 	return IRQ_HANDLED;
766 }
767 
768 static void sc27xx_fgu_disable(void *_data)
769 {
770 	struct sc27xx_fgu_data *data = _data;
771 
772 	regmap_update_bits(data->regmap, SC27XX_CLK_EN0, SC27XX_FGU_RTC_EN, 0);
773 	regmap_update_bits(data->regmap, SC27XX_MODULE_EN0, SC27XX_FGU_EN, 0);
774 }
775 
776 static int sc27xx_fgu_cap_to_clbcnt(struct sc27xx_fgu_data *data, int capacity)
777 {
778 	/*
779 	 * Get current capacity (mAh) = battery total capacity (mAh) *
780 	 * current capacity percent (capacity / 100).
781 	 */
782 	int cur_cap = DIV_ROUND_CLOSEST(data->total_cap * capacity, 100);
783 
784 	/*
785 	 * Convert current capacity (mAh) to coulomb counter according to the
786 	 * formula: 1 mAh =3.6 coulomb.
787 	 */
788 	return DIV_ROUND_CLOSEST(cur_cap * 36 * data->cur_1000ma_adc, 10);
789 }
790 
791 static int sc27xx_fgu_calibration(struct sc27xx_fgu_data *data)
792 {
793 	struct nvmem_cell *cell;
794 	int calib_data, cal_4200mv;
795 	void *buf;
796 	size_t len;
797 
798 	cell = nvmem_cell_get(data->dev, "fgu_calib");
799 	if (IS_ERR(cell))
800 		return PTR_ERR(cell);
801 
802 	buf = nvmem_cell_read(cell, &len);
803 	nvmem_cell_put(cell);
804 
805 	if (IS_ERR(buf))
806 		return PTR_ERR(buf);
807 
808 	memcpy(&calib_data, buf, min(len, sizeof(u32)));
809 
810 	/*
811 	 * Get the ADC value corresponding to 4200 mV from eFuse controller
812 	 * according to below formula. Then convert to ADC values corresponding
813 	 * to 1000 mV and 1000 mA.
814 	 */
815 	cal_4200mv = (calib_data & 0x1ff) + 6963 - 4096 - 256;
816 	data->vol_1000mv_adc = DIV_ROUND_CLOSEST(cal_4200mv * 10, 42);
817 	data->cur_1000ma_adc = data->vol_1000mv_adc * 4;
818 
819 	kfree(buf);
820 	return 0;
821 }
822 
823 static int sc27xx_fgu_hw_init(struct sc27xx_fgu_data *data)
824 {
825 	struct power_supply_battery_info info = { };
826 	struct power_supply_battery_ocv_table *table;
827 	int ret, delta_clbcnt, alarm_adc;
828 
829 	ret = power_supply_get_battery_info(data->battery, &info);
830 	if (ret) {
831 		dev_err(data->dev, "failed to get battery information\n");
832 		return ret;
833 	}
834 
835 	data->total_cap = info.charge_full_design_uah / 1000;
836 	data->max_volt = info.constant_charge_voltage_max_uv / 1000;
837 	data->internal_resist = info.factory_internal_resistance_uohm / 1000;
838 	data->min_volt = info.voltage_min_design_uv;
839 
840 	/*
841 	 * For SC27XX fuel gauge device, we only use one ocv-capacity
842 	 * table in normal temperature 20 Celsius.
843 	 */
844 	table = power_supply_find_ocv2cap_table(&info, 20, &data->table_len);
845 	if (!table)
846 		return -EINVAL;
847 
848 	data->cap_table = devm_kmemdup(data->dev, table,
849 				       data->table_len * sizeof(*table),
850 				       GFP_KERNEL);
851 	if (!data->cap_table) {
852 		power_supply_put_battery_info(data->battery, &info);
853 		return -ENOMEM;
854 	}
855 
856 	data->alarm_cap = power_supply_ocv2cap_simple(data->cap_table,
857 						      data->table_len,
858 						      data->min_volt);
859 
860 	power_supply_put_battery_info(data->battery, &info);
861 
862 	ret = sc27xx_fgu_calibration(data);
863 	if (ret)
864 		return ret;
865 
866 	/* Enable the FGU module */
867 	ret = regmap_update_bits(data->regmap, SC27XX_MODULE_EN0,
868 				 SC27XX_FGU_EN, SC27XX_FGU_EN);
869 	if (ret) {
870 		dev_err(data->dev, "failed to enable fgu\n");
871 		return ret;
872 	}
873 
874 	/* Enable the FGU RTC clock to make it work */
875 	ret = regmap_update_bits(data->regmap, SC27XX_CLK_EN0,
876 				 SC27XX_FGU_RTC_EN, SC27XX_FGU_RTC_EN);
877 	if (ret) {
878 		dev_err(data->dev, "failed to enable fgu RTC clock\n");
879 		goto disable_fgu;
880 	}
881 
882 	ret = regmap_update_bits(data->regmap, data->base + SC27XX_FGU_INT_CLR,
883 				 SC27XX_FGU_INT_MASK, SC27XX_FGU_INT_MASK);
884 	if (ret) {
885 		dev_err(data->dev, "failed to clear interrupt status\n");
886 		goto disable_clk;
887 	}
888 
889 	/*
890 	 * Set the voltage low overload threshold, which means when the battery
891 	 * voltage is lower than this threshold, the controller will generate
892 	 * one interrupt to notify.
893 	 */
894 	alarm_adc = sc27xx_fgu_voltage_to_adc(data, data->min_volt / 1000);
895 	ret = regmap_update_bits(data->regmap, data->base + SC27XX_FGU_LOW_OVERLOAD,
896 				 SC27XX_FGU_LOW_OVERLOAD_MASK, alarm_adc);
897 	if (ret) {
898 		dev_err(data->dev, "failed to set fgu low overload\n");
899 		goto disable_clk;
900 	}
901 
902 	/*
903 	 * Set the coulomb counter delta threshold, that means when the coulomb
904 	 * counter change is multiples of the delta threshold, the controller
905 	 * will generate one interrupt to notify the users to update the battery
906 	 * capacity. Now we set the delta threshold as a counter value of 1%
907 	 * capacity.
908 	 */
909 	delta_clbcnt = sc27xx_fgu_cap_to_clbcnt(data, 1);
910 
911 	ret = regmap_update_bits(data->regmap, data->base + SC27XX_FGU_CLBCNT_DELTL,
912 				 SC27XX_FGU_CLBCNT_MASK, delta_clbcnt);
913 	if (ret) {
914 		dev_err(data->dev, "failed to set low delta coulomb counter\n");
915 		goto disable_clk;
916 	}
917 
918 	ret = regmap_update_bits(data->regmap, data->base + SC27XX_FGU_CLBCNT_DELTH,
919 				 SC27XX_FGU_CLBCNT_MASK,
920 				 delta_clbcnt >> SC27XX_FGU_CLBCNT_SHIFT);
921 	if (ret) {
922 		dev_err(data->dev, "failed to set high delta coulomb counter\n");
923 		goto disable_clk;
924 	}
925 
926 	/*
927 	 * Get the boot battery capacity when system powers on, which is used to
928 	 * initialize the coulomb counter. After that, we can read the coulomb
929 	 * counter to measure the battery capacity.
930 	 */
931 	ret = sc27xx_fgu_get_boot_capacity(data, &data->init_cap);
932 	if (ret) {
933 		dev_err(data->dev, "failed to get boot capacity\n");
934 		goto disable_clk;
935 	}
936 
937 	/*
938 	 * Convert battery capacity to the corresponding initial coulomb counter
939 	 * and set into coulomb counter registers.
940 	 */
941 	data->init_clbcnt = sc27xx_fgu_cap_to_clbcnt(data, data->init_cap);
942 	ret = sc27xx_fgu_set_clbcnt(data, data->init_clbcnt);
943 	if (ret) {
944 		dev_err(data->dev, "failed to initialize coulomb counter\n");
945 		goto disable_clk;
946 	}
947 
948 	return 0;
949 
950 disable_clk:
951 	regmap_update_bits(data->regmap, SC27XX_CLK_EN0, SC27XX_FGU_RTC_EN, 0);
952 disable_fgu:
953 	regmap_update_bits(data->regmap, SC27XX_MODULE_EN0, SC27XX_FGU_EN, 0);
954 
955 	return ret;
956 }
957 
958 static int sc27xx_fgu_probe(struct platform_device *pdev)
959 {
960 	struct device_node *np = pdev->dev.of_node;
961 	struct power_supply_config fgu_cfg = { };
962 	struct sc27xx_fgu_data *data;
963 	int ret, irq;
964 
965 	data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
966 	if (!data)
967 		return -ENOMEM;
968 
969 	data->regmap = dev_get_regmap(pdev->dev.parent, NULL);
970 	if (!data->regmap) {
971 		dev_err(&pdev->dev, "failed to get regmap\n");
972 		return -ENODEV;
973 	}
974 
975 	ret = device_property_read_u32(&pdev->dev, "reg", &data->base);
976 	if (ret) {
977 		dev_err(&pdev->dev, "failed to get fgu address\n");
978 		return ret;
979 	}
980 
981 	data->channel = devm_iio_channel_get(&pdev->dev, "bat-temp");
982 	if (IS_ERR(data->channel)) {
983 		dev_err(&pdev->dev, "failed to get IIO channel\n");
984 		return PTR_ERR(data->channel);
985 	}
986 
987 	data->charge_chan = devm_iio_channel_get(&pdev->dev, "charge-vol");
988 	if (IS_ERR(data->charge_chan)) {
989 		dev_err(&pdev->dev, "failed to get charge IIO channel\n");
990 		return PTR_ERR(data->charge_chan);
991 	}
992 
993 	data->gpiod = devm_gpiod_get(&pdev->dev, "bat-detect", GPIOD_IN);
994 	if (IS_ERR(data->gpiod)) {
995 		dev_err(&pdev->dev, "failed to get battery detection GPIO\n");
996 		return PTR_ERR(data->gpiod);
997 	}
998 
999 	ret = gpiod_get_value_cansleep(data->gpiod);
1000 	if (ret < 0) {
1001 		dev_err(&pdev->dev, "failed to get gpio state\n");
1002 		return ret;
1003 	}
1004 
1005 	data->bat_present = !!ret;
1006 	mutex_init(&data->lock);
1007 	data->dev = &pdev->dev;
1008 	platform_set_drvdata(pdev, data);
1009 
1010 	fgu_cfg.drv_data = data;
1011 	fgu_cfg.of_node = np;
1012 	data->battery = devm_power_supply_register(&pdev->dev, &sc27xx_fgu_desc,
1013 						   &fgu_cfg);
1014 	if (IS_ERR(data->battery)) {
1015 		dev_err(&pdev->dev, "failed to register power supply\n");
1016 		return PTR_ERR(data->battery);
1017 	}
1018 
1019 	ret = sc27xx_fgu_hw_init(data);
1020 	if (ret) {
1021 		dev_err(&pdev->dev, "failed to initialize fgu hardware\n");
1022 		return ret;
1023 	}
1024 
1025 	ret = devm_add_action(&pdev->dev, sc27xx_fgu_disable, data);
1026 	if (ret) {
1027 		sc27xx_fgu_disable(data);
1028 		dev_err(&pdev->dev, "failed to add fgu disable action\n");
1029 		return ret;
1030 	}
1031 
1032 	irq = platform_get_irq(pdev, 0);
1033 	if (irq < 0) {
1034 		dev_err(&pdev->dev, "no irq resource specified\n");
1035 		return irq;
1036 	}
1037 
1038 	ret = devm_request_threaded_irq(data->dev, irq, NULL,
1039 					sc27xx_fgu_interrupt,
1040 					IRQF_NO_SUSPEND | IRQF_ONESHOT,
1041 					pdev->name, data);
1042 	if (ret) {
1043 		dev_err(data->dev, "failed to request fgu IRQ\n");
1044 		return ret;
1045 	}
1046 
1047 	irq = gpiod_to_irq(data->gpiod);
1048 	if (irq < 0) {
1049 		dev_err(&pdev->dev, "failed to translate GPIO to IRQ\n");
1050 		return irq;
1051 	}
1052 
1053 	ret = devm_request_threaded_irq(&pdev->dev, irq, NULL,
1054 					sc27xx_fgu_bat_detection,
1055 					IRQF_ONESHOT | IRQF_TRIGGER_RISING |
1056 					IRQF_TRIGGER_FALLING,
1057 					pdev->name, data);
1058 	if (ret) {
1059 		dev_err(&pdev->dev, "failed to request IRQ\n");
1060 		return ret;
1061 	}
1062 
1063 	return 0;
1064 }
1065 
1066 #ifdef CONFIG_PM_SLEEP
1067 static int sc27xx_fgu_resume(struct device *dev)
1068 {
1069 	struct sc27xx_fgu_data *data = dev_get_drvdata(dev);
1070 	int ret;
1071 
1072 	ret = regmap_update_bits(data->regmap, data->base + SC27XX_FGU_INT_EN,
1073 				 SC27XX_FGU_LOW_OVERLOAD_INT |
1074 				 SC27XX_FGU_CLBCNT_DELTA_INT, 0);
1075 	if (ret) {
1076 		dev_err(data->dev, "failed to disable fgu interrupts\n");
1077 		return ret;
1078 	}
1079 
1080 	return 0;
1081 }
1082 
1083 static int sc27xx_fgu_suspend(struct device *dev)
1084 {
1085 	struct sc27xx_fgu_data *data = dev_get_drvdata(dev);
1086 	int ret, status, ocv;
1087 
1088 	ret = sc27xx_fgu_get_status(data, &status);
1089 	if (ret)
1090 		return ret;
1091 
1092 	/*
1093 	 * If we are charging, then no need to enable the FGU interrupts to
1094 	 * adjust the battery capacity.
1095 	 */
1096 	if (status != POWER_SUPPLY_STATUS_NOT_CHARGING)
1097 		return 0;
1098 
1099 	ret = regmap_update_bits(data->regmap, data->base + SC27XX_FGU_INT_EN,
1100 				 SC27XX_FGU_LOW_OVERLOAD_INT,
1101 				 SC27XX_FGU_LOW_OVERLOAD_INT);
1102 	if (ret) {
1103 		dev_err(data->dev, "failed to enable low voltage interrupt\n");
1104 		return ret;
1105 	}
1106 
1107 	ret = sc27xx_fgu_get_vbat_ocv(data, &ocv);
1108 	if (ret)
1109 		goto disable_int;
1110 
1111 	/*
1112 	 * If current OCV is less than the minimum voltage, we should enable the
1113 	 * coulomb counter threshold interrupt to notify events to adjust the
1114 	 * battery capacity.
1115 	 */
1116 	if (ocv < data->min_volt) {
1117 		ret = regmap_update_bits(data->regmap,
1118 					 data->base + SC27XX_FGU_INT_EN,
1119 					 SC27XX_FGU_CLBCNT_DELTA_INT,
1120 					 SC27XX_FGU_CLBCNT_DELTA_INT);
1121 		if (ret) {
1122 			dev_err(data->dev,
1123 				"failed to enable coulomb threshold int\n");
1124 			goto disable_int;
1125 		}
1126 	}
1127 
1128 	return 0;
1129 
1130 disable_int:
1131 	regmap_update_bits(data->regmap, data->base + SC27XX_FGU_INT_EN,
1132 			   SC27XX_FGU_LOW_OVERLOAD_INT, 0);
1133 	return ret;
1134 }
1135 #endif
1136 
1137 static const struct dev_pm_ops sc27xx_fgu_pm_ops = {
1138 	SET_SYSTEM_SLEEP_PM_OPS(sc27xx_fgu_suspend, sc27xx_fgu_resume)
1139 };
1140 
1141 static const struct of_device_id sc27xx_fgu_of_match[] = {
1142 	{ .compatible = "sprd,sc2731-fgu", },
1143 	{ }
1144 };
1145 
1146 static struct platform_driver sc27xx_fgu_driver = {
1147 	.probe = sc27xx_fgu_probe,
1148 	.driver = {
1149 		.name = "sc27xx-fgu",
1150 		.of_match_table = sc27xx_fgu_of_match,
1151 		.pm = &sc27xx_fgu_pm_ops,
1152 	}
1153 };
1154 
1155 module_platform_driver(sc27xx_fgu_driver);
1156 
1157 MODULE_DESCRIPTION("Spreadtrum SC27XX PMICs Fual Gauge Unit Driver");
1158 MODULE_LICENSE("GPL v2");
1159