xref: /openbmc/linux/drivers/power/supply/ab8500_fg.c (revision 6a476046)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) ST-Ericsson AB 2012
4  *
5  * Main and Back-up battery management driver.
6  *
7  * Note: Backup battery management is required in case of Li-Ion battery and not
8  * for capacitive battery. HREF boards have capacitive battery and hence backup
9  * battery management is not used and the supported code is available in this
10  * driver.
11  *
12  * Author:
13  *	Johan Palsson <johan.palsson@stericsson.com>
14  *	Karl Komierowski <karl.komierowski@stericsson.com>
15  *	Arun R Murthy <arun.murthy@stericsson.com>
16  */
17 
18 #include <linux/init.h>
19 #include <linux/module.h>
20 #include <linux/component.h>
21 #include <linux/device.h>
22 #include <linux/interrupt.h>
23 #include <linux/platform_device.h>
24 #include <linux/power_supply.h>
25 #include <linux/kobject.h>
26 #include <linux/slab.h>
27 #include <linux/delay.h>
28 #include <linux/time.h>
29 #include <linux/time64.h>
30 #include <linux/of.h>
31 #include <linux/completion.h>
32 #include <linux/mfd/core.h>
33 #include <linux/mfd/abx500.h>
34 #include <linux/mfd/abx500/ab8500.h>
35 #include <linux/iio/consumer.h>
36 #include <linux/kernel.h>
37 #include <linux/fixp-arith.h>
38 
39 #include "ab8500-bm.h"
40 
41 #define FG_LSB_IN_MA			1627
42 #define QLSB_NANO_AMP_HOURS_X10		1071
43 #define INS_CURR_TIMEOUT		(3 * HZ)
44 
45 #define SEC_TO_SAMPLE(S)		(S * 4)
46 
47 #define NBR_AVG_SAMPLES			20
48 #define WAIT_FOR_INST_CURRENT_MAX	70
49 /* Currents higher than -500mA (dissipating) will make compensation unstable */
50 #define IGNORE_VBAT_HIGHCUR		-500000
51 
52 #define LOW_BAT_CHECK_INTERVAL		(HZ / 16) /* 62.5 ms */
53 
54 #define VALID_CAPACITY_SEC		(45 * 60) /* 45 minutes */
55 #define BATT_OK_MIN			2360 /* mV */
56 #define BATT_OK_INCREMENT		50 /* mV */
57 #define BATT_OK_MAX_NR_INCREMENTS	0xE
58 
59 /* FG constants */
60 #define BATT_OVV			0x01
61 
62 /**
63  * struct ab8500_fg_interrupts - ab8500 fg interrupts
64  * @name:	name of the interrupt
65  * @isr		function pointer to the isr
66  */
67 struct ab8500_fg_interrupts {
68 	char *name;
69 	irqreturn_t (*isr)(int irq, void *data);
70 };
71 
72 enum ab8500_fg_discharge_state {
73 	AB8500_FG_DISCHARGE_INIT,
74 	AB8500_FG_DISCHARGE_INITMEASURING,
75 	AB8500_FG_DISCHARGE_INIT_RECOVERY,
76 	AB8500_FG_DISCHARGE_RECOVERY,
77 	AB8500_FG_DISCHARGE_READOUT_INIT,
78 	AB8500_FG_DISCHARGE_READOUT,
79 	AB8500_FG_DISCHARGE_WAKEUP,
80 };
81 
82 static char *discharge_state[] = {
83 	"DISCHARGE_INIT",
84 	"DISCHARGE_INITMEASURING",
85 	"DISCHARGE_INIT_RECOVERY",
86 	"DISCHARGE_RECOVERY",
87 	"DISCHARGE_READOUT_INIT",
88 	"DISCHARGE_READOUT",
89 	"DISCHARGE_WAKEUP",
90 };
91 
92 enum ab8500_fg_charge_state {
93 	AB8500_FG_CHARGE_INIT,
94 	AB8500_FG_CHARGE_READOUT,
95 };
96 
97 static char *charge_state[] = {
98 	"CHARGE_INIT",
99 	"CHARGE_READOUT",
100 };
101 
102 enum ab8500_fg_calibration_state {
103 	AB8500_FG_CALIB_INIT,
104 	AB8500_FG_CALIB_WAIT,
105 	AB8500_FG_CALIB_END,
106 };
107 
108 struct ab8500_fg_avg_cap {
109 	int avg;
110 	int samples[NBR_AVG_SAMPLES];
111 	time64_t time_stamps[NBR_AVG_SAMPLES];
112 	int pos;
113 	int nbr_samples;
114 	int sum;
115 };
116 
117 struct ab8500_fg_cap_scaling {
118 	bool enable;
119 	int cap_to_scale[2];
120 	int disable_cap_level;
121 	int scaled_cap;
122 };
123 
124 struct ab8500_fg_battery_capacity {
125 	int max_mah_design;
126 	int max_mah;
127 	int mah;
128 	int permille;
129 	int level;
130 	int prev_mah;
131 	int prev_percent;
132 	int prev_level;
133 	int user_mah;
134 	struct ab8500_fg_cap_scaling cap_scale;
135 };
136 
137 struct ab8500_fg_flags {
138 	bool fg_enabled;
139 	bool conv_done;
140 	bool charging;
141 	bool fully_charged;
142 	bool force_full;
143 	bool low_bat_delay;
144 	bool low_bat;
145 	bool bat_ovv;
146 	bool batt_unknown;
147 	bool calibrate;
148 	bool user_cap;
149 	bool batt_id_received;
150 };
151 
152 struct inst_curr_result_list {
153 	struct list_head list;
154 	int *result;
155 };
156 
157 /**
158  * struct ab8500_fg - ab8500 FG device information
159  * @dev:		Pointer to the structure device
160  * @node:		a list of AB8500 FGs, hence prepared for reentrance
161  * @irq			holds the CCEOC interrupt number
162  * @vbat_uv:		Battery voltage in uV
163  * @vbat_nom_uv:	Nominal battery voltage in uV
164  * @inst_curr_ua:	Instantenous battery current in uA
165  * @avg_curr_ua:	Average battery current in uA
166  * @bat_temp		battery temperature
167  * @fg_samples:		Number of samples used in the FG accumulation
168  * @accu_charge:	Accumulated charge from the last conversion
169  * @recovery_cnt:	Counter for recovery mode
170  * @high_curr_cnt:	Counter for high current mode
171  * @init_cnt:		Counter for init mode
172  * @low_bat_cnt		Counter for number of consecutive low battery measures
173  * @nbr_cceoc_irq_cnt	Counter for number of CCEOC irqs received since enabled
174  * @recovery_needed:	Indicate if recovery is needed
175  * @high_curr_mode:	Indicate if we're in high current mode
176  * @init_capacity:	Indicate if initial capacity measuring should be done
177  * @turn_off_fg:	True if fg was off before current measurement
178  * @calib_state		State during offset calibration
179  * @discharge_state:	Current discharge state
180  * @charge_state:	Current charge state
181  * @ab8500_fg_started	Completion struct used for the instant current start
182  * @ab8500_fg_complete	Completion struct used for the instant current reading
183  * @flags:		Structure for information about events triggered
184  * @bat_cap:		Structure for battery capacity specific parameters
185  * @avg_cap:		Average capacity filter
186  * @parent:		Pointer to the struct ab8500
187  * @main_bat_v:		ADC channel for the main battery voltage
188  * @bm:           	Platform specific battery management information
189  * @fg_psy:		Structure that holds the FG specific battery properties
190  * @fg_wq:		Work queue for running the FG algorithm
191  * @fg_periodic_work:	Work to run the FG algorithm periodically
192  * @fg_low_bat_work:	Work to check low bat condition
193  * @fg_reinit_work	Work used to reset and reinitialise the FG algorithm
194  * @fg_work:		Work to run the FG algorithm instantly
195  * @fg_acc_cur_work:	Work to read the FG accumulator
196  * @fg_check_hw_failure_work:	Work for checking HW state
197  * @cc_lock:		Mutex for locking the CC
198  * @fg_kobject:		Structure of type kobject
199  */
200 struct ab8500_fg {
201 	struct device *dev;
202 	struct list_head node;
203 	int irq;
204 	int vbat_uv;
205 	int vbat_nom_uv;
206 	int inst_curr_ua;
207 	int avg_curr_ua;
208 	int bat_temp;
209 	int fg_samples;
210 	int accu_charge;
211 	int recovery_cnt;
212 	int high_curr_cnt;
213 	int init_cnt;
214 	int low_bat_cnt;
215 	int nbr_cceoc_irq_cnt;
216 	bool recovery_needed;
217 	bool high_curr_mode;
218 	bool init_capacity;
219 	bool turn_off_fg;
220 	enum ab8500_fg_calibration_state calib_state;
221 	enum ab8500_fg_discharge_state discharge_state;
222 	enum ab8500_fg_charge_state charge_state;
223 	struct completion ab8500_fg_started;
224 	struct completion ab8500_fg_complete;
225 	struct ab8500_fg_flags flags;
226 	struct ab8500_fg_battery_capacity bat_cap;
227 	struct ab8500_fg_avg_cap avg_cap;
228 	struct ab8500 *parent;
229 	struct iio_channel *main_bat_v;
230 	struct ab8500_bm_data *bm;
231 	struct power_supply *fg_psy;
232 	struct workqueue_struct *fg_wq;
233 	struct delayed_work fg_periodic_work;
234 	struct delayed_work fg_low_bat_work;
235 	struct delayed_work fg_reinit_work;
236 	struct work_struct fg_work;
237 	struct work_struct fg_acc_cur_work;
238 	struct delayed_work fg_check_hw_failure_work;
239 	struct mutex cc_lock;
240 	struct kobject fg_kobject;
241 };
242 static LIST_HEAD(ab8500_fg_list);
243 
244 /**
245  * ab8500_fg_get() - returns a reference to the primary AB8500 fuel gauge
246  * (i.e. the first fuel gauge in the instance list)
247  */
248 struct ab8500_fg *ab8500_fg_get(void)
249 {
250 	return list_first_entry_or_null(&ab8500_fg_list, struct ab8500_fg,
251 					node);
252 }
253 
254 /* Main battery properties */
255 static enum power_supply_property ab8500_fg_props[] = {
256 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
257 	POWER_SUPPLY_PROP_CURRENT_NOW,
258 	POWER_SUPPLY_PROP_CURRENT_AVG,
259 	POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
260 	POWER_SUPPLY_PROP_ENERGY_FULL,
261 	POWER_SUPPLY_PROP_ENERGY_NOW,
262 	POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
263 	POWER_SUPPLY_PROP_CHARGE_FULL,
264 	POWER_SUPPLY_PROP_CHARGE_NOW,
265 	POWER_SUPPLY_PROP_CAPACITY,
266 	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
267 };
268 
269 /*
270  * This array maps the raw hex value to lowbat voltage used by the AB8500
271  * Values taken from the UM0836, in microvolts.
272  */
273 static int ab8500_fg_lowbat_voltage_map[] = {
274 	2300000,
275 	2325000,
276 	2350000,
277 	2375000,
278 	2400000,
279 	2425000,
280 	2450000,
281 	2475000,
282 	2500000,
283 	2525000,
284 	2550000,
285 	2575000,
286 	2600000,
287 	2625000,
288 	2650000,
289 	2675000,
290 	2700000,
291 	2725000,
292 	2750000,
293 	2775000,
294 	2800000,
295 	2825000,
296 	2850000,
297 	2875000,
298 	2900000,
299 	2925000,
300 	2950000,
301 	2975000,
302 	3000000,
303 	3025000,
304 	3050000,
305 	3075000,
306 	3100000,
307 	3125000,
308 	3150000,
309 	3175000,
310 	3200000,
311 	3225000,
312 	3250000,
313 	3275000,
314 	3300000,
315 	3325000,
316 	3350000,
317 	3375000,
318 	3400000,
319 	3425000,
320 	3450000,
321 	3475000,
322 	3500000,
323 	3525000,
324 	3550000,
325 	3575000,
326 	3600000,
327 	3625000,
328 	3650000,
329 	3675000,
330 	3700000,
331 	3725000,
332 	3750000,
333 	3775000,
334 	3800000,
335 	3825000,
336 	3850000,
337 	3850000,
338 };
339 
340 static u8 ab8500_volt_to_regval(int voltage_uv)
341 {
342 	int i;
343 
344 	if (voltage_uv < ab8500_fg_lowbat_voltage_map[0])
345 		return 0;
346 
347 	for (i = 0; i < ARRAY_SIZE(ab8500_fg_lowbat_voltage_map); i++) {
348 		if (voltage_uv < ab8500_fg_lowbat_voltage_map[i])
349 			return (u8) i - 1;
350 	}
351 
352 	/* If not captured above, return index of last element */
353 	return (u8) ARRAY_SIZE(ab8500_fg_lowbat_voltage_map) - 1;
354 }
355 
356 /**
357  * ab8500_fg_is_low_curr() - Low or high current mode
358  * @di:		pointer to the ab8500_fg structure
359  * @curr_ua:	the current to base or our decision on in microampere
360  *
361  * Low current mode if the current consumption is below a certain threshold
362  */
363 static int ab8500_fg_is_low_curr(struct ab8500_fg *di, int curr_ua)
364 {
365 	/*
366 	 * We want to know if we're in low current mode
367 	 */
368 	if (curr_ua > -di->bm->fg_params->high_curr_threshold_ua)
369 		return true;
370 	else
371 		return false;
372 }
373 
374 /**
375  * ab8500_fg_add_cap_sample() - Add capacity to average filter
376  * @di:		pointer to the ab8500_fg structure
377  * @sample:	the capacity in mAh to add to the filter
378  *
379  * A capacity is added to the filter and a new mean capacity is calculated and
380  * returned
381  */
382 static int ab8500_fg_add_cap_sample(struct ab8500_fg *di, int sample)
383 {
384 	time64_t now = ktime_get_boottime_seconds();
385 	struct ab8500_fg_avg_cap *avg = &di->avg_cap;
386 
387 	do {
388 		avg->sum += sample - avg->samples[avg->pos];
389 		avg->samples[avg->pos] = sample;
390 		avg->time_stamps[avg->pos] = now;
391 		avg->pos++;
392 
393 		if (avg->pos == NBR_AVG_SAMPLES)
394 			avg->pos = 0;
395 
396 		if (avg->nbr_samples < NBR_AVG_SAMPLES)
397 			avg->nbr_samples++;
398 
399 		/*
400 		 * Check the time stamp for each sample. If too old,
401 		 * replace with latest sample
402 		 */
403 	} while (now - VALID_CAPACITY_SEC > avg->time_stamps[avg->pos]);
404 
405 	avg->avg = avg->sum / avg->nbr_samples;
406 
407 	return avg->avg;
408 }
409 
410 /**
411  * ab8500_fg_clear_cap_samples() - Clear average filter
412  * @di:		pointer to the ab8500_fg structure
413  *
414  * The capacity filter is is reset to zero.
415  */
416 static void ab8500_fg_clear_cap_samples(struct ab8500_fg *di)
417 {
418 	int i;
419 	struct ab8500_fg_avg_cap *avg = &di->avg_cap;
420 
421 	avg->pos = 0;
422 	avg->nbr_samples = 0;
423 	avg->sum = 0;
424 	avg->avg = 0;
425 
426 	for (i = 0; i < NBR_AVG_SAMPLES; i++) {
427 		avg->samples[i] = 0;
428 		avg->time_stamps[i] = 0;
429 	}
430 }
431 
432 /**
433  * ab8500_fg_fill_cap_sample() - Fill average filter
434  * @di:		pointer to the ab8500_fg structure
435  * @sample:	the capacity in mAh to fill the filter with
436  *
437  * The capacity filter is filled with a capacity in mAh
438  */
439 static void ab8500_fg_fill_cap_sample(struct ab8500_fg *di, int sample)
440 {
441 	int i;
442 	time64_t now;
443 	struct ab8500_fg_avg_cap *avg = &di->avg_cap;
444 
445 	now = ktime_get_boottime_seconds();
446 
447 	for (i = 0; i < NBR_AVG_SAMPLES; i++) {
448 		avg->samples[i] = sample;
449 		avg->time_stamps[i] = now;
450 	}
451 
452 	avg->pos = 0;
453 	avg->nbr_samples = NBR_AVG_SAMPLES;
454 	avg->sum = sample * NBR_AVG_SAMPLES;
455 	avg->avg = sample;
456 }
457 
458 /**
459  * ab8500_fg_coulomb_counter() - enable coulomb counter
460  * @di:		pointer to the ab8500_fg structure
461  * @enable:	enable/disable
462  *
463  * Enable/Disable coulomb counter.
464  * On failure returns negative value.
465  */
466 static int ab8500_fg_coulomb_counter(struct ab8500_fg *di, bool enable)
467 {
468 	int ret = 0;
469 	mutex_lock(&di->cc_lock);
470 	if (enable) {
471 		/* To be able to reprogram the number of samples, we have to
472 		 * first stop the CC and then enable it again */
473 		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
474 			AB8500_RTC_CC_CONF_REG, 0x00);
475 		if (ret)
476 			goto cc_err;
477 
478 		/* Program the samples */
479 		ret = abx500_set_register_interruptible(di->dev,
480 			AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
481 			di->fg_samples);
482 		if (ret)
483 			goto cc_err;
484 
485 		/* Start the CC */
486 		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
487 			AB8500_RTC_CC_CONF_REG,
488 			(CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
489 		if (ret)
490 			goto cc_err;
491 
492 		di->flags.fg_enabled = true;
493 	} else {
494 		/* Clear any pending read requests */
495 		ret = abx500_mask_and_set_register_interruptible(di->dev,
496 			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
497 			(RESET_ACCU | READ_REQ), 0);
498 		if (ret)
499 			goto cc_err;
500 
501 		ret = abx500_set_register_interruptible(di->dev,
502 			AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU_CTRL, 0);
503 		if (ret)
504 			goto cc_err;
505 
506 		/* Stop the CC */
507 		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
508 			AB8500_RTC_CC_CONF_REG, 0);
509 		if (ret)
510 			goto cc_err;
511 
512 		di->flags.fg_enabled = false;
513 
514 	}
515 	dev_dbg(di->dev, " CC enabled: %d Samples: %d\n",
516 		enable, di->fg_samples);
517 
518 	mutex_unlock(&di->cc_lock);
519 
520 	return ret;
521 cc_err:
522 	dev_err(di->dev, "%s Enabling coulomb counter failed\n", __func__);
523 	mutex_unlock(&di->cc_lock);
524 	return ret;
525 }
526 
527 /**
528  * ab8500_fg_inst_curr_start() - start battery instantaneous current
529  * @di:         pointer to the ab8500_fg structure
530  *
531  * Returns 0 or error code
532  * Note: This is part "one" and has to be called before
533  * ab8500_fg_inst_curr_finalize()
534  */
535 int ab8500_fg_inst_curr_start(struct ab8500_fg *di)
536 {
537 	u8 reg_val;
538 	int ret;
539 
540 	mutex_lock(&di->cc_lock);
541 
542 	di->nbr_cceoc_irq_cnt = 0;
543 	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
544 		AB8500_RTC_CC_CONF_REG, &reg_val);
545 	if (ret < 0)
546 		goto fail;
547 
548 	if (!(reg_val & CC_PWR_UP_ENA)) {
549 		dev_dbg(di->dev, "%s Enable FG\n", __func__);
550 		di->turn_off_fg = true;
551 
552 		/* Program the samples */
553 		ret = abx500_set_register_interruptible(di->dev,
554 			AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
555 			SEC_TO_SAMPLE(10));
556 		if (ret)
557 			goto fail;
558 
559 		/* Start the CC */
560 		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
561 			AB8500_RTC_CC_CONF_REG,
562 			(CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
563 		if (ret)
564 			goto fail;
565 	} else {
566 		di->turn_off_fg = false;
567 	}
568 
569 	/* Return and WFI */
570 	reinit_completion(&di->ab8500_fg_started);
571 	reinit_completion(&di->ab8500_fg_complete);
572 	enable_irq(di->irq);
573 
574 	/* Note: cc_lock is still locked */
575 	return 0;
576 fail:
577 	mutex_unlock(&di->cc_lock);
578 	return ret;
579 }
580 
581 /**
582  * ab8500_fg_inst_curr_started() - check if fg conversion has started
583  * @di:         pointer to the ab8500_fg structure
584  *
585  * Returns 1 if conversion started, 0 if still waiting
586  */
587 int ab8500_fg_inst_curr_started(struct ab8500_fg *di)
588 {
589 	return completion_done(&di->ab8500_fg_started);
590 }
591 
592 /**
593  * ab8500_fg_inst_curr_done() - check if fg conversion is done
594  * @di:         pointer to the ab8500_fg structure
595  *
596  * Returns 1 if conversion done, 0 if still waiting
597  */
598 int ab8500_fg_inst_curr_done(struct ab8500_fg *di)
599 {
600 	return completion_done(&di->ab8500_fg_complete);
601 }
602 
603 /**
604  * ab8500_fg_inst_curr_finalize() - battery instantaneous current
605  * @di:         pointer to the ab8500_fg structure
606  * @curr_ua:	battery instantenous current in microampere (on success)
607  *
608  * Returns 0 or an error code
609  * Note: This is part "two" and has to be called at earliest 250 ms
610  * after ab8500_fg_inst_curr_start()
611  */
612 int ab8500_fg_inst_curr_finalize(struct ab8500_fg *di, int *curr_ua)
613 {
614 	u8 low, high;
615 	int val;
616 	int ret;
617 	unsigned long timeout;
618 
619 	if (!completion_done(&di->ab8500_fg_complete)) {
620 		timeout = wait_for_completion_timeout(
621 			&di->ab8500_fg_complete,
622 			INS_CURR_TIMEOUT);
623 		dev_dbg(di->dev, "Finalize time: %d ms\n",
624 			jiffies_to_msecs(INS_CURR_TIMEOUT - timeout));
625 		if (!timeout) {
626 			ret = -ETIME;
627 			disable_irq(di->irq);
628 			di->nbr_cceoc_irq_cnt = 0;
629 			dev_err(di->dev, "completion timed out [%d]\n",
630 				__LINE__);
631 			goto fail;
632 		}
633 	}
634 
635 	disable_irq(di->irq);
636 	di->nbr_cceoc_irq_cnt = 0;
637 
638 	ret = abx500_mask_and_set_register_interruptible(di->dev,
639 			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
640 			READ_REQ, READ_REQ);
641 
642 	/* 100uS between read request and read is needed */
643 	usleep_range(100, 100);
644 
645 	/* Read CC Sample conversion value Low and high */
646 	ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
647 		AB8500_GASG_CC_SMPL_CNVL_REG,  &low);
648 	if (ret < 0)
649 		goto fail;
650 
651 	ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
652 		AB8500_GASG_CC_SMPL_CNVH_REG,  &high);
653 	if (ret < 0)
654 		goto fail;
655 
656 	/*
657 	 * negative value for Discharging
658 	 * convert 2's complement into decimal
659 	 */
660 	if (high & 0x10)
661 		val = (low | (high << 8) | 0xFFFFE000);
662 	else
663 		val = (low | (high << 8));
664 
665 	/*
666 	 * Convert to unit value in mA
667 	 * Full scale input voltage is
668 	 * 63.160mV => LSB = 63.160mV/(4096*res) = 1.542.000 uA
669 	 * Given a 250ms conversion cycle time the LSB corresponds
670 	 * to 107.1 nAh. Convert to current by dividing by the conversion
671 	 * time in hours (250ms = 1 / (3600 * 4)h)
672 	 * 107.1nAh assumes 10mOhm, but fg_res is in 0.1mOhm
673 	 */
674 	val = (val * QLSB_NANO_AMP_HOURS_X10 * 36 * 4) / di->bm->fg_res;
675 
676 	if (di->turn_off_fg) {
677 		dev_dbg(di->dev, "%s Disable FG\n", __func__);
678 
679 		/* Clear any pending read requests */
680 		ret = abx500_set_register_interruptible(di->dev,
681 			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG, 0);
682 		if (ret)
683 			goto fail;
684 
685 		/* Stop the CC */
686 		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
687 			AB8500_RTC_CC_CONF_REG, 0);
688 		if (ret)
689 			goto fail;
690 	}
691 	mutex_unlock(&di->cc_lock);
692 	*curr_ua = val;
693 
694 	return 0;
695 fail:
696 	mutex_unlock(&di->cc_lock);
697 	return ret;
698 }
699 
700 /**
701  * ab8500_fg_inst_curr_blocking() - battery instantaneous current
702  * @di:         pointer to the ab8500_fg structure
703  *
704  * Returns battery instantenous current in microampere (on success)
705  * else error code
706  */
707 int ab8500_fg_inst_curr_blocking(struct ab8500_fg *di)
708 {
709 	int ret;
710 	unsigned long timeout;
711 	int curr_ua = 0;
712 
713 	ret = ab8500_fg_inst_curr_start(di);
714 	if (ret) {
715 		dev_err(di->dev, "Failed to initialize fg_inst\n");
716 		return 0;
717 	}
718 
719 	/* Wait for CC to actually start */
720 	if (!completion_done(&di->ab8500_fg_started)) {
721 		timeout = wait_for_completion_timeout(
722 			&di->ab8500_fg_started,
723 			INS_CURR_TIMEOUT);
724 		dev_dbg(di->dev, "Start time: %d ms\n",
725 			jiffies_to_msecs(INS_CURR_TIMEOUT - timeout));
726 		if (!timeout) {
727 			ret = -ETIME;
728 			dev_err(di->dev, "completion timed out [%d]\n",
729 				__LINE__);
730 			goto fail;
731 		}
732 	}
733 
734 	ret = ab8500_fg_inst_curr_finalize(di, &curr_ua);
735 	if (ret) {
736 		dev_err(di->dev, "Failed to finalize fg_inst\n");
737 		return 0;
738 	}
739 
740 	dev_dbg(di->dev, "%s instant current: %d uA", __func__, curr_ua);
741 	return curr_ua;
742 fail:
743 	disable_irq(di->irq);
744 	mutex_unlock(&di->cc_lock);
745 	return ret;
746 }
747 
748 /**
749  * ab8500_fg_acc_cur_work() - average battery current
750  * @work:	pointer to the work_struct structure
751  *
752  * Updated the average battery current obtained from the
753  * coulomb counter.
754  */
755 static void ab8500_fg_acc_cur_work(struct work_struct *work)
756 {
757 	int val;
758 	int ret;
759 	u8 low, med, high;
760 
761 	struct ab8500_fg *di = container_of(work,
762 		struct ab8500_fg, fg_acc_cur_work);
763 
764 	mutex_lock(&di->cc_lock);
765 	ret = abx500_set_register_interruptible(di->dev, AB8500_GAS_GAUGE,
766 		AB8500_GASG_CC_NCOV_ACCU_CTRL, RD_NCONV_ACCU_REQ);
767 	if (ret)
768 		goto exit;
769 
770 	ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
771 		AB8500_GASG_CC_NCOV_ACCU_LOW,  &low);
772 	if (ret < 0)
773 		goto exit;
774 
775 	ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
776 		AB8500_GASG_CC_NCOV_ACCU_MED,  &med);
777 	if (ret < 0)
778 		goto exit;
779 
780 	ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
781 		AB8500_GASG_CC_NCOV_ACCU_HIGH, &high);
782 	if (ret < 0)
783 		goto exit;
784 
785 	/* Check for sign bit in case of negative value, 2's complement */
786 	if (high & 0x10)
787 		val = (low | (med << 8) | (high << 16) | 0xFFE00000);
788 	else
789 		val = (low | (med << 8) | (high << 16));
790 
791 	/*
792 	 * Convert to uAh
793 	 * Given a 250ms conversion cycle time the LSB corresponds
794 	 * to 112.9 nAh.
795 	 * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
796 	 */
797 	di->accu_charge = (val * QLSB_NANO_AMP_HOURS_X10) /
798 		(100 * di->bm->fg_res);
799 
800 	/*
801 	 * Convert to unit value in uA
802 	 * by dividing by the conversion
803 	 * time in hours (= samples / (3600 * 4)h)
804 	 */
805 	di->avg_curr_ua = (val * QLSB_NANO_AMP_HOURS_X10 * 36) /
806 		(di->bm->fg_res * (di->fg_samples / 4));
807 
808 	di->flags.conv_done = true;
809 
810 	mutex_unlock(&di->cc_lock);
811 
812 	queue_work(di->fg_wq, &di->fg_work);
813 
814 	dev_dbg(di->dev, "fg_res: %d, fg_samples: %d, gasg: %d, accu_charge: %d \n",
815 				di->bm->fg_res, di->fg_samples, val, di->accu_charge);
816 	return;
817 exit:
818 	dev_err(di->dev,
819 		"Failed to read or write gas gauge registers\n");
820 	mutex_unlock(&di->cc_lock);
821 	queue_work(di->fg_wq, &di->fg_work);
822 }
823 
824 /**
825  * ab8500_fg_bat_voltage() - get battery voltage
826  * @di:		pointer to the ab8500_fg structure
827  *
828  * Returns battery voltage in microvolts (on success) else error code
829  */
830 static int ab8500_fg_bat_voltage(struct ab8500_fg *di)
831 {
832 	int vbat, ret;
833 	static int prev;
834 
835 	ret = iio_read_channel_processed(di->main_bat_v, &vbat);
836 	if (ret < 0) {
837 		dev_err(di->dev,
838 			"%s ADC conversion failed, using previous value\n",
839 			__func__);
840 		return prev;
841 	}
842 
843 	/* IIO returns millivolts but we want microvolts */
844 	vbat *= 1000;
845 	prev = vbat;
846 	return vbat;
847 }
848 
849 /**
850  * ab8500_fg_volt_to_capacity() - Voltage based capacity
851  * @di:		pointer to the ab8500_fg structure
852  * @voltage_uv:	The voltage to convert to a capacity in microvolt
853  *
854  * Returns battery capacity in per mille based on voltage
855  */
856 static int ab8500_fg_volt_to_capacity(struct ab8500_fg *di, int voltage_uv)
857 {
858 	struct power_supply_battery_info *bi = di->bm->bi;
859 
860 	/* Multiply by 10 because the capacity is tracked in per mille */
861 	return power_supply_batinfo_ocv2cap(bi, voltage_uv, di->bat_temp) *  10;
862 }
863 
864 /**
865  * ab8500_fg_uncomp_volt_to_capacity() - Uncompensated voltage based capacity
866  * @di:		pointer to the ab8500_fg structure
867  *
868  * Returns battery capacity based on battery voltage that is not compensated
869  * for the voltage drop due to the load
870  */
871 static int ab8500_fg_uncomp_volt_to_capacity(struct ab8500_fg *di)
872 {
873 	di->vbat_uv = ab8500_fg_bat_voltage(di);
874 	return ab8500_fg_volt_to_capacity(di, di->vbat_uv);
875 }
876 
877 /**
878  * ab8500_fg_battery_resistance() - Returns the battery inner resistance
879  * @di:		pointer to the ab8500_fg structure
880  *
881  * Returns battery inner resistance added with the fuel gauge resistor value
882  * to get the total resistance in the whole link from gnd to bat+ node
883  * in milliohm.
884  */
885 static int ab8500_fg_battery_resistance(struct ab8500_fg *di)
886 {
887 	struct power_supply_battery_info *bi = di->bm->bi;
888 	int resistance_percent = 0;
889 	int resistance;
890 
891 	resistance_percent = power_supply_temp2resist_simple(bi->resist_table,
892 						 bi->resist_table_size,
893 						 di->bat_temp / 10);
894 	/*
895 	 * We get a percentage of factory resistance here so first get
896 	 * the factory resistance in milliohms then calculate how much
897 	 * resistance we have at this temperature.
898 	 */
899 	resistance = (bi->factory_internal_resistance_uohm / 1000);
900 	resistance = resistance * resistance_percent / 100;
901 
902 	dev_dbg(di->dev, "%s Temp: %d battery internal resistance: %d"
903 	    " fg resistance %d, total: %d (mOhm)\n",
904 		__func__, di->bat_temp, resistance, di->bm->fg_res / 10,
905 		(di->bm->fg_res / 10) + resistance);
906 
907 	/* fg_res variable is in 0.1mOhm */
908 	resistance += di->bm->fg_res / 10;
909 
910 	return resistance;
911 }
912 
913 /**
914  * ab8500_load_comp_fg_bat_voltage() - get load compensated battery voltage
915  * @di:		pointer to the ab8500_fg structure
916  * @always:	always return a voltage, also uncompensated
917  *
918  * Returns compensated battery voltage (on success) else error code.
919  * If always is specified, we always return a voltage but it may be
920  * uncompensated.
921  */
922 static int ab8500_load_comp_fg_bat_voltage(struct ab8500_fg *di, bool always)
923 {
924 	int i = 0;
925 	int vbat_uv = 0;
926 	int rcomp;
927 
928 	/* Average the instant current to get a stable current measurement */
929 	ab8500_fg_inst_curr_start(di);
930 
931 	do {
932 		vbat_uv += ab8500_fg_bat_voltage(di);
933 		i++;
934 		usleep_range(5000, 6000);
935 	} while (!ab8500_fg_inst_curr_done(di) &&
936 		 i <= WAIT_FOR_INST_CURRENT_MAX);
937 
938 	if (i > WAIT_FOR_INST_CURRENT_MAX) {
939 		dev_err(di->dev,
940 			"TIMEOUT: return uncompensated measurement of VBAT\n");
941 		di->vbat_uv = vbat_uv / i;
942 		return di->vbat_uv;
943 	}
944 
945 	ab8500_fg_inst_curr_finalize(di, &di->inst_curr_ua);
946 
947 	/*
948 	 * If there is too high current dissipation, the compensation cannot be
949 	 * trusted so return an error unless we must return something here, as
950 	 * enforced by the "always" parameter.
951 	 */
952 	if (!always && di->inst_curr_ua < IGNORE_VBAT_HIGHCUR)
953 		return -EINVAL;
954 
955 	vbat_uv = vbat_uv / i;
956 
957 	/* Next we apply voltage compensation from internal resistance */
958 	rcomp = ab8500_fg_battery_resistance(di);
959 	vbat_uv = vbat_uv - (di->inst_curr_ua * rcomp) / 1000;
960 
961 	/* Always keep this state at latest measurement */
962 	di->vbat_uv = vbat_uv;
963 
964 	return vbat_uv;
965 }
966 
967 /**
968  * ab8500_fg_load_comp_volt_to_capacity() - Load compensated voltage based capacity
969  * @di:		pointer to the ab8500_fg structure
970  *
971  * Returns battery capacity based on battery voltage that is load compensated
972  * for the voltage drop
973  */
974 static int ab8500_fg_load_comp_volt_to_capacity(struct ab8500_fg *di)
975 {
976 	int vbat_comp_uv;
977 
978 	vbat_comp_uv = ab8500_load_comp_fg_bat_voltage(di, true);
979 
980 	return ab8500_fg_volt_to_capacity(di, vbat_comp_uv);
981 }
982 
983 /**
984  * ab8500_fg_convert_mah_to_permille() - Capacity in mAh to permille
985  * @di:		pointer to the ab8500_fg structure
986  * @cap_mah:	capacity in mAh
987  *
988  * Converts capacity in mAh to capacity in permille
989  */
990 static int ab8500_fg_convert_mah_to_permille(struct ab8500_fg *di, int cap_mah)
991 {
992 	return (cap_mah * 1000) / di->bat_cap.max_mah_design;
993 }
994 
995 /**
996  * ab8500_fg_convert_permille_to_mah() - Capacity in permille to mAh
997  * @di:		pointer to the ab8500_fg structure
998  * @cap_pm:	capacity in permille
999  *
1000  * Converts capacity in permille to capacity in mAh
1001  */
1002 static int ab8500_fg_convert_permille_to_mah(struct ab8500_fg *di, int cap_pm)
1003 {
1004 	return cap_pm * di->bat_cap.max_mah_design / 1000;
1005 }
1006 
1007 /**
1008  * ab8500_fg_convert_mah_to_uwh() - Capacity in mAh to uWh
1009  * @di:		pointer to the ab8500_fg structure
1010  * @cap_mah:	capacity in mAh
1011  *
1012  * Converts capacity in mAh to capacity in uWh
1013  */
1014 static int ab8500_fg_convert_mah_to_uwh(struct ab8500_fg *di, int cap_mah)
1015 {
1016 	u64 div_res;
1017 	u32 div_rem;
1018 
1019 	/*
1020 	 * Capacity is in milli ampere hours (10^-3)Ah
1021 	 * Nominal voltage is in microvolts (10^-6)V
1022 	 * divide by 1000000 after multiplication to get to mWh
1023 	 */
1024 	div_res = ((u64) cap_mah) * ((u64) di->vbat_nom_uv);
1025 	div_rem = do_div(div_res, 1000000);
1026 
1027 	/* Make sure to round upwards if necessary */
1028 	if (div_rem >= 1000000 / 2)
1029 		div_res++;
1030 
1031 	return (int) div_res;
1032 }
1033 
1034 /**
1035  * ab8500_fg_calc_cap_charging() - Calculate remaining capacity while charging
1036  * @di:		pointer to the ab8500_fg structure
1037  *
1038  * Return the capacity in mAh based on previous calculated capcity and the FG
1039  * accumulator register value. The filter is filled with this capacity
1040  */
1041 static int ab8500_fg_calc_cap_charging(struct ab8500_fg *di)
1042 {
1043 	dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1044 		__func__,
1045 		di->bat_cap.mah,
1046 		di->accu_charge);
1047 
1048 	/* Capacity should not be less than 0 */
1049 	if (di->bat_cap.mah + di->accu_charge > 0)
1050 		di->bat_cap.mah += di->accu_charge;
1051 	else
1052 		di->bat_cap.mah = 0;
1053 	/*
1054 	 * We force capacity to 100% once when the algorithm
1055 	 * reports that it's full.
1056 	 */
1057 	if (di->bat_cap.mah >= di->bat_cap.max_mah_design ||
1058 		di->flags.force_full) {
1059 		di->bat_cap.mah = di->bat_cap.max_mah_design;
1060 	}
1061 
1062 	ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1063 	di->bat_cap.permille =
1064 		ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1065 
1066 	/* We need to update battery voltage and inst current when charging */
1067 	di->vbat_uv = ab8500_fg_bat_voltage(di);
1068 	di->inst_curr_ua = ab8500_fg_inst_curr_blocking(di);
1069 
1070 	return di->bat_cap.mah;
1071 }
1072 
1073 /**
1074  * ab8500_fg_calc_cap_discharge_voltage() - Capacity in discharge with voltage
1075  * @di:		pointer to the ab8500_fg structure
1076  *
1077  * Return the capacity in mAh based on the load compensated battery voltage.
1078  * This value is added to the filter and a new mean value is calculated and
1079  * returned.
1080  */
1081 static int ab8500_fg_calc_cap_discharge_voltage(struct ab8500_fg *di)
1082 {
1083 	int permille, mah;
1084 
1085 	permille = ab8500_fg_load_comp_volt_to_capacity(di);
1086 
1087 	mah = ab8500_fg_convert_permille_to_mah(di, permille);
1088 
1089 	di->bat_cap.mah = ab8500_fg_add_cap_sample(di, mah);
1090 	di->bat_cap.permille =
1091 		ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1092 
1093 	return di->bat_cap.mah;
1094 }
1095 
1096 /**
1097  * ab8500_fg_calc_cap_discharge_fg() - Capacity in discharge with FG
1098  * @di:		pointer to the ab8500_fg structure
1099  *
1100  * Return the capacity in mAh based on previous calculated capcity and the FG
1101  * accumulator register value. This value is added to the filter and a
1102  * new mean value is calculated and returned.
1103  */
1104 static int ab8500_fg_calc_cap_discharge_fg(struct ab8500_fg *di)
1105 {
1106 	int permille_volt, permille;
1107 
1108 	dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1109 		__func__,
1110 		di->bat_cap.mah,
1111 		di->accu_charge);
1112 
1113 	/* Capacity should not be less than 0 */
1114 	if (di->bat_cap.mah + di->accu_charge > 0)
1115 		di->bat_cap.mah += di->accu_charge;
1116 	else
1117 		di->bat_cap.mah = 0;
1118 
1119 	if (di->bat_cap.mah >= di->bat_cap.max_mah_design)
1120 		di->bat_cap.mah = di->bat_cap.max_mah_design;
1121 
1122 	/*
1123 	 * Check against voltage based capacity. It can not be lower
1124 	 * than what the uncompensated voltage says
1125 	 */
1126 	permille = ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1127 	permille_volt = ab8500_fg_uncomp_volt_to_capacity(di);
1128 
1129 	if (permille < permille_volt) {
1130 		di->bat_cap.permille = permille_volt;
1131 		di->bat_cap.mah = ab8500_fg_convert_permille_to_mah(di,
1132 			di->bat_cap.permille);
1133 
1134 		dev_dbg(di->dev, "%s voltage based: perm %d perm_volt %d\n",
1135 			__func__,
1136 			permille,
1137 			permille_volt);
1138 
1139 		ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1140 	} else {
1141 		ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1142 		di->bat_cap.permille =
1143 			ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1144 	}
1145 
1146 	return di->bat_cap.mah;
1147 }
1148 
1149 /**
1150  * ab8500_fg_capacity_level() - Get the battery capacity level
1151  * @di:		pointer to the ab8500_fg structure
1152  *
1153  * Get the battery capacity level based on the capacity in percent
1154  */
1155 static int ab8500_fg_capacity_level(struct ab8500_fg *di)
1156 {
1157 	int ret, percent;
1158 
1159 	percent = DIV_ROUND_CLOSEST(di->bat_cap.permille, 10);
1160 
1161 	if (percent <= di->bm->cap_levels->critical ||
1162 		di->flags.low_bat)
1163 		ret = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1164 	else if (percent <= di->bm->cap_levels->low)
1165 		ret = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1166 	else if (percent <= di->bm->cap_levels->normal)
1167 		ret = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1168 	else if (percent <= di->bm->cap_levels->high)
1169 		ret = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
1170 	else
1171 		ret = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1172 
1173 	return ret;
1174 }
1175 
1176 /**
1177  * ab8500_fg_calculate_scaled_capacity() - Capacity scaling
1178  * @di:		pointer to the ab8500_fg structure
1179  *
1180  * Calculates the capacity to be shown to upper layers. Scales the capacity
1181  * to have 100% as a reference from the actual capacity upon removal of charger
1182  * when charging is in maintenance mode.
1183  */
1184 static int ab8500_fg_calculate_scaled_capacity(struct ab8500_fg *di)
1185 {
1186 	struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1187 	int capacity = di->bat_cap.prev_percent;
1188 
1189 	if (!cs->enable)
1190 		return capacity;
1191 
1192 	/*
1193 	 * As long as we are in fully charge mode scale the capacity
1194 	 * to show 100%.
1195 	 */
1196 	if (di->flags.fully_charged) {
1197 		cs->cap_to_scale[0] = 100;
1198 		cs->cap_to_scale[1] =
1199 			max(capacity, di->bm->fg_params->maint_thres);
1200 		dev_dbg(di->dev, "Scale cap with %d/%d\n",
1201 			 cs->cap_to_scale[0], cs->cap_to_scale[1]);
1202 	}
1203 
1204 	/* Calculates the scaled capacity. */
1205 	if ((cs->cap_to_scale[0] != cs->cap_to_scale[1])
1206 					&& (cs->cap_to_scale[1] > 0))
1207 		capacity = min(100,
1208 				 DIV_ROUND_CLOSEST(di->bat_cap.prev_percent *
1209 						 cs->cap_to_scale[0],
1210 						 cs->cap_to_scale[1]));
1211 
1212 	if (di->flags.charging) {
1213 		if (capacity < cs->disable_cap_level) {
1214 			cs->disable_cap_level = capacity;
1215 			dev_dbg(di->dev, "Cap to stop scale lowered %d%%\n",
1216 				cs->disable_cap_level);
1217 		} else if (!di->flags.fully_charged) {
1218 			if (di->bat_cap.prev_percent >=
1219 			    cs->disable_cap_level) {
1220 				dev_dbg(di->dev, "Disabling scaled capacity\n");
1221 				cs->enable = false;
1222 				capacity = di->bat_cap.prev_percent;
1223 			} else {
1224 				dev_dbg(di->dev,
1225 					"Waiting in cap to level %d%%\n",
1226 					cs->disable_cap_level);
1227 				capacity = cs->disable_cap_level;
1228 			}
1229 		}
1230 	}
1231 
1232 	return capacity;
1233 }
1234 
1235 /**
1236  * ab8500_fg_update_cap_scalers() - Capacity scaling
1237  * @di:		pointer to the ab8500_fg structure
1238  *
1239  * To be called when state change from charge<->discharge to update
1240  * the capacity scalers.
1241  */
1242 static void ab8500_fg_update_cap_scalers(struct ab8500_fg *di)
1243 {
1244 	struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1245 
1246 	if (!cs->enable)
1247 		return;
1248 	if (di->flags.charging) {
1249 		di->bat_cap.cap_scale.disable_cap_level =
1250 			di->bat_cap.cap_scale.scaled_cap;
1251 		dev_dbg(di->dev, "Cap to stop scale at charge %d%%\n",
1252 				di->bat_cap.cap_scale.disable_cap_level);
1253 	} else {
1254 		if (cs->scaled_cap != 100) {
1255 			cs->cap_to_scale[0] = cs->scaled_cap;
1256 			cs->cap_to_scale[1] = di->bat_cap.prev_percent;
1257 		} else {
1258 			cs->cap_to_scale[0] = 100;
1259 			cs->cap_to_scale[1] =
1260 				max(di->bat_cap.prev_percent,
1261 				    di->bm->fg_params->maint_thres);
1262 		}
1263 
1264 		dev_dbg(di->dev, "Cap to scale at discharge %d/%d\n",
1265 				cs->cap_to_scale[0], cs->cap_to_scale[1]);
1266 	}
1267 }
1268 
1269 /**
1270  * ab8500_fg_check_capacity_limits() - Check if capacity has changed
1271  * @di:		pointer to the ab8500_fg structure
1272  * @init:	capacity is allowed to go up in init mode
1273  *
1274  * Check if capacity or capacity limit has changed and notify the system
1275  * about it using the power_supply framework
1276  */
1277 static void ab8500_fg_check_capacity_limits(struct ab8500_fg *di, bool init)
1278 {
1279 	bool changed = false;
1280 	int percent = DIV_ROUND_CLOSEST(di->bat_cap.permille, 10);
1281 
1282 	di->bat_cap.level = ab8500_fg_capacity_level(di);
1283 
1284 	if (di->bat_cap.level != di->bat_cap.prev_level) {
1285 		/*
1286 		 * We do not allow reported capacity level to go up
1287 		 * unless we're charging or if we're in init
1288 		 */
1289 		if (!(!di->flags.charging && di->bat_cap.level >
1290 			di->bat_cap.prev_level) || init) {
1291 			dev_dbg(di->dev, "level changed from %d to %d\n",
1292 				di->bat_cap.prev_level,
1293 				di->bat_cap.level);
1294 			di->bat_cap.prev_level = di->bat_cap.level;
1295 			changed = true;
1296 		} else {
1297 			dev_dbg(di->dev, "level not allowed to go up "
1298 				"since no charger is connected: %d to %d\n",
1299 				di->bat_cap.prev_level,
1300 				di->bat_cap.level);
1301 		}
1302 	}
1303 
1304 	/*
1305 	 * If we have received the LOW_BAT IRQ, set capacity to 0 to initiate
1306 	 * shutdown
1307 	 */
1308 	if (di->flags.low_bat) {
1309 		dev_dbg(di->dev, "Battery low, set capacity to 0\n");
1310 		di->bat_cap.prev_percent = 0;
1311 		di->bat_cap.permille = 0;
1312 		percent = 0;
1313 		di->bat_cap.prev_mah = 0;
1314 		di->bat_cap.mah = 0;
1315 		changed = true;
1316 	} else if (di->flags.fully_charged) {
1317 		/*
1318 		 * We report 100% if algorithm reported fully charged
1319 		 * and show 100% during maintenance charging (scaling).
1320 		 */
1321 		if (di->flags.force_full) {
1322 			di->bat_cap.prev_percent = percent;
1323 			di->bat_cap.prev_mah = di->bat_cap.mah;
1324 
1325 			changed = true;
1326 
1327 			if (!di->bat_cap.cap_scale.enable &&
1328 						di->bm->capacity_scaling) {
1329 				di->bat_cap.cap_scale.enable = true;
1330 				di->bat_cap.cap_scale.cap_to_scale[0] = 100;
1331 				di->bat_cap.cap_scale.cap_to_scale[1] =
1332 						di->bat_cap.prev_percent;
1333 				di->bat_cap.cap_scale.disable_cap_level = 100;
1334 			}
1335 		} else if (di->bat_cap.prev_percent != percent) {
1336 			dev_dbg(di->dev,
1337 				"battery reported full "
1338 				"but capacity dropping: %d\n",
1339 				percent);
1340 			di->bat_cap.prev_percent = percent;
1341 			di->bat_cap.prev_mah = di->bat_cap.mah;
1342 
1343 			changed = true;
1344 		}
1345 	} else if (di->bat_cap.prev_percent != percent) {
1346 		if (percent == 0) {
1347 			/*
1348 			 * We will not report 0% unless we've got
1349 			 * the LOW_BAT IRQ, no matter what the FG
1350 			 * algorithm says.
1351 			 */
1352 			di->bat_cap.prev_percent = 1;
1353 			percent = 1;
1354 
1355 			changed = true;
1356 		} else if (!(!di->flags.charging &&
1357 			percent > di->bat_cap.prev_percent) || init) {
1358 			/*
1359 			 * We do not allow reported capacity to go up
1360 			 * unless we're charging or if we're in init
1361 			 */
1362 			dev_dbg(di->dev,
1363 				"capacity changed from %d to %d (%d)\n",
1364 				di->bat_cap.prev_percent,
1365 				percent,
1366 				di->bat_cap.permille);
1367 			di->bat_cap.prev_percent = percent;
1368 			di->bat_cap.prev_mah = di->bat_cap.mah;
1369 
1370 			changed = true;
1371 		} else {
1372 			dev_dbg(di->dev, "capacity not allowed to go up since "
1373 				"no charger is connected: %d to %d (%d)\n",
1374 				di->bat_cap.prev_percent,
1375 				percent,
1376 				di->bat_cap.permille);
1377 		}
1378 	}
1379 
1380 	if (changed) {
1381 		if (di->bm->capacity_scaling) {
1382 			di->bat_cap.cap_scale.scaled_cap =
1383 				ab8500_fg_calculate_scaled_capacity(di);
1384 
1385 			dev_info(di->dev, "capacity=%d (%d)\n",
1386 				di->bat_cap.prev_percent,
1387 				di->bat_cap.cap_scale.scaled_cap);
1388 		}
1389 		power_supply_changed(di->fg_psy);
1390 		if (di->flags.fully_charged && di->flags.force_full) {
1391 			dev_dbg(di->dev, "Battery full, notifying.\n");
1392 			di->flags.force_full = false;
1393 			sysfs_notify(&di->fg_kobject, NULL, "charge_full");
1394 		}
1395 		sysfs_notify(&di->fg_kobject, NULL, "charge_now");
1396 	}
1397 }
1398 
1399 static void ab8500_fg_charge_state_to(struct ab8500_fg *di,
1400 	enum ab8500_fg_charge_state new_state)
1401 {
1402 	dev_dbg(di->dev, "Charge state from %d [%s] to %d [%s]\n",
1403 		di->charge_state,
1404 		charge_state[di->charge_state],
1405 		new_state,
1406 		charge_state[new_state]);
1407 
1408 	di->charge_state = new_state;
1409 }
1410 
1411 static void ab8500_fg_discharge_state_to(struct ab8500_fg *di,
1412 	enum ab8500_fg_discharge_state new_state)
1413 {
1414 	dev_dbg(di->dev, "Discharge state from %d [%s] to %d [%s]\n",
1415 		di->discharge_state,
1416 		discharge_state[di->discharge_state],
1417 		new_state,
1418 		discharge_state[new_state]);
1419 
1420 	di->discharge_state = new_state;
1421 }
1422 
1423 /**
1424  * ab8500_fg_algorithm_charging() - FG algorithm for when charging
1425  * @di:		pointer to the ab8500_fg structure
1426  *
1427  * Battery capacity calculation state machine for when we're charging
1428  */
1429 static void ab8500_fg_algorithm_charging(struct ab8500_fg *di)
1430 {
1431 	/*
1432 	 * If we change to discharge mode
1433 	 * we should start with recovery
1434 	 */
1435 	if (di->discharge_state != AB8500_FG_DISCHARGE_INIT_RECOVERY)
1436 		ab8500_fg_discharge_state_to(di,
1437 			AB8500_FG_DISCHARGE_INIT_RECOVERY);
1438 
1439 	switch (di->charge_state) {
1440 	case AB8500_FG_CHARGE_INIT:
1441 		di->fg_samples = SEC_TO_SAMPLE(
1442 			di->bm->fg_params->accu_charging);
1443 
1444 		ab8500_fg_coulomb_counter(di, true);
1445 		ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_READOUT);
1446 
1447 		break;
1448 
1449 	case AB8500_FG_CHARGE_READOUT:
1450 		/*
1451 		 * Read the FG and calculate the new capacity
1452 		 */
1453 		mutex_lock(&di->cc_lock);
1454 		if (!di->flags.conv_done && !di->flags.force_full) {
1455 			/* Wasn't the CC IRQ that got us here */
1456 			mutex_unlock(&di->cc_lock);
1457 			dev_dbg(di->dev, "%s CC conv not done\n",
1458 				__func__);
1459 
1460 			break;
1461 		}
1462 		di->flags.conv_done = false;
1463 		mutex_unlock(&di->cc_lock);
1464 
1465 		ab8500_fg_calc_cap_charging(di);
1466 
1467 		break;
1468 
1469 	default:
1470 		break;
1471 	}
1472 
1473 	/* Check capacity limits */
1474 	ab8500_fg_check_capacity_limits(di, false);
1475 }
1476 
1477 static void force_capacity(struct ab8500_fg *di)
1478 {
1479 	int cap;
1480 
1481 	ab8500_fg_clear_cap_samples(di);
1482 	cap = di->bat_cap.user_mah;
1483 	if (cap > di->bat_cap.max_mah_design) {
1484 		dev_dbg(di->dev, "Remaining cap %d can't be bigger than total"
1485 			" %d\n", cap, di->bat_cap.max_mah_design);
1486 		cap = di->bat_cap.max_mah_design;
1487 	}
1488 	ab8500_fg_fill_cap_sample(di, di->bat_cap.user_mah);
1489 	di->bat_cap.permille = ab8500_fg_convert_mah_to_permille(di, cap);
1490 	di->bat_cap.mah = cap;
1491 	ab8500_fg_check_capacity_limits(di, true);
1492 }
1493 
1494 static bool check_sysfs_capacity(struct ab8500_fg *di)
1495 {
1496 	int cap, lower, upper;
1497 	int cap_permille;
1498 
1499 	cap = di->bat_cap.user_mah;
1500 
1501 	cap_permille = ab8500_fg_convert_mah_to_permille(di,
1502 		di->bat_cap.user_mah);
1503 
1504 	lower = di->bat_cap.permille - di->bm->fg_params->user_cap_limit * 10;
1505 	upper = di->bat_cap.permille + di->bm->fg_params->user_cap_limit * 10;
1506 
1507 	if (lower < 0)
1508 		lower = 0;
1509 	/* 1000 is permille, -> 100 percent */
1510 	if (upper > 1000)
1511 		upper = 1000;
1512 
1513 	dev_dbg(di->dev, "Capacity limits:"
1514 		" (Lower: %d User: %d Upper: %d) [user: %d, was: %d]\n",
1515 		lower, cap_permille, upper, cap, di->bat_cap.mah);
1516 
1517 	/* If within limits, use the saved capacity and exit estimation...*/
1518 	if (cap_permille > lower && cap_permille < upper) {
1519 		dev_dbg(di->dev, "OK! Using users cap %d uAh now\n", cap);
1520 		force_capacity(di);
1521 		return true;
1522 	}
1523 	dev_dbg(di->dev, "Capacity from user out of limits, ignoring");
1524 	return false;
1525 }
1526 
1527 /**
1528  * ab8500_fg_algorithm_discharging() - FG algorithm for when discharging
1529  * @di:		pointer to the ab8500_fg structure
1530  *
1531  * Battery capacity calculation state machine for when we're discharging
1532  */
1533 static void ab8500_fg_algorithm_discharging(struct ab8500_fg *di)
1534 {
1535 	int sleep_time;
1536 
1537 	/* If we change to charge mode we should start with init */
1538 	if (di->charge_state != AB8500_FG_CHARGE_INIT)
1539 		ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
1540 
1541 	switch (di->discharge_state) {
1542 	case AB8500_FG_DISCHARGE_INIT:
1543 		/* We use the FG IRQ to work on */
1544 		di->init_cnt = 0;
1545 		di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
1546 		ab8500_fg_coulomb_counter(di, true);
1547 		ab8500_fg_discharge_state_to(di,
1548 			AB8500_FG_DISCHARGE_INITMEASURING);
1549 
1550 		fallthrough;
1551 	case AB8500_FG_DISCHARGE_INITMEASURING:
1552 		/*
1553 		 * Discard a number of samples during startup.
1554 		 * After that, use compensated voltage for a few
1555 		 * samples to get an initial capacity.
1556 		 * Then go to READOUT
1557 		 */
1558 		sleep_time = di->bm->fg_params->init_timer;
1559 
1560 		/* Discard the first [x] seconds */
1561 		if (di->init_cnt > di->bm->fg_params->init_discard_time) {
1562 			ab8500_fg_calc_cap_discharge_voltage(di);
1563 
1564 			ab8500_fg_check_capacity_limits(di, true);
1565 		}
1566 
1567 		di->init_cnt += sleep_time;
1568 		if (di->init_cnt > di->bm->fg_params->init_total_time)
1569 			ab8500_fg_discharge_state_to(di,
1570 				AB8500_FG_DISCHARGE_READOUT_INIT);
1571 
1572 		break;
1573 
1574 	case AB8500_FG_DISCHARGE_INIT_RECOVERY:
1575 		di->recovery_cnt = 0;
1576 		di->recovery_needed = true;
1577 		ab8500_fg_discharge_state_to(di,
1578 			AB8500_FG_DISCHARGE_RECOVERY);
1579 
1580 		fallthrough;
1581 
1582 	case AB8500_FG_DISCHARGE_RECOVERY:
1583 		sleep_time = di->bm->fg_params->recovery_sleep_timer;
1584 
1585 		/*
1586 		 * We should check the power consumption
1587 		 * If low, go to READOUT (after x min) or
1588 		 * RECOVERY_SLEEP if time left.
1589 		 * If high, go to READOUT
1590 		 */
1591 		di->inst_curr_ua = ab8500_fg_inst_curr_blocking(di);
1592 
1593 		if (ab8500_fg_is_low_curr(di, di->inst_curr_ua)) {
1594 			if (di->recovery_cnt >
1595 				di->bm->fg_params->recovery_total_time) {
1596 				di->fg_samples = SEC_TO_SAMPLE(
1597 					di->bm->fg_params->accu_high_curr);
1598 				ab8500_fg_coulomb_counter(di, true);
1599 				ab8500_fg_discharge_state_to(di,
1600 					AB8500_FG_DISCHARGE_READOUT);
1601 				di->recovery_needed = false;
1602 			} else {
1603 				queue_delayed_work(di->fg_wq,
1604 					&di->fg_periodic_work,
1605 					sleep_time * HZ);
1606 			}
1607 			di->recovery_cnt += sleep_time;
1608 		} else {
1609 			di->fg_samples = SEC_TO_SAMPLE(
1610 				di->bm->fg_params->accu_high_curr);
1611 			ab8500_fg_coulomb_counter(di, true);
1612 			ab8500_fg_discharge_state_to(di,
1613 				AB8500_FG_DISCHARGE_READOUT);
1614 		}
1615 		break;
1616 
1617 	case AB8500_FG_DISCHARGE_READOUT_INIT:
1618 		di->fg_samples = SEC_TO_SAMPLE(
1619 			di->bm->fg_params->accu_high_curr);
1620 		ab8500_fg_coulomb_counter(di, true);
1621 		ab8500_fg_discharge_state_to(di,
1622 				AB8500_FG_DISCHARGE_READOUT);
1623 		break;
1624 
1625 	case AB8500_FG_DISCHARGE_READOUT:
1626 		di->inst_curr_ua = ab8500_fg_inst_curr_blocking(di);
1627 
1628 		if (ab8500_fg_is_low_curr(di, di->inst_curr_ua)) {
1629 			/* Detect mode change */
1630 			if (di->high_curr_mode) {
1631 				di->high_curr_mode = false;
1632 				di->high_curr_cnt = 0;
1633 			}
1634 
1635 			if (di->recovery_needed) {
1636 				ab8500_fg_discharge_state_to(di,
1637 					AB8500_FG_DISCHARGE_INIT_RECOVERY);
1638 
1639 				queue_delayed_work(di->fg_wq,
1640 					&di->fg_periodic_work, 0);
1641 
1642 				break;
1643 			}
1644 
1645 			ab8500_fg_calc_cap_discharge_voltage(di);
1646 		} else {
1647 			mutex_lock(&di->cc_lock);
1648 			if (!di->flags.conv_done) {
1649 				/* Wasn't the CC IRQ that got us here */
1650 				mutex_unlock(&di->cc_lock);
1651 				dev_dbg(di->dev, "%s CC conv not done\n",
1652 					__func__);
1653 
1654 				break;
1655 			}
1656 			di->flags.conv_done = false;
1657 			mutex_unlock(&di->cc_lock);
1658 
1659 			/* Detect mode change */
1660 			if (!di->high_curr_mode) {
1661 				di->high_curr_mode = true;
1662 				di->high_curr_cnt = 0;
1663 			}
1664 
1665 			di->high_curr_cnt +=
1666 				di->bm->fg_params->accu_high_curr;
1667 			if (di->high_curr_cnt >
1668 				di->bm->fg_params->high_curr_time)
1669 				di->recovery_needed = true;
1670 
1671 			ab8500_fg_calc_cap_discharge_fg(di);
1672 		}
1673 
1674 		ab8500_fg_check_capacity_limits(di, false);
1675 
1676 		break;
1677 
1678 	case AB8500_FG_DISCHARGE_WAKEUP:
1679 		ab8500_fg_calc_cap_discharge_voltage(di);
1680 
1681 		di->fg_samples = SEC_TO_SAMPLE(
1682 			di->bm->fg_params->accu_high_curr);
1683 		ab8500_fg_coulomb_counter(di, true);
1684 		ab8500_fg_discharge_state_to(di,
1685 				AB8500_FG_DISCHARGE_READOUT);
1686 
1687 		ab8500_fg_check_capacity_limits(di, false);
1688 
1689 		break;
1690 
1691 	default:
1692 		break;
1693 	}
1694 }
1695 
1696 /**
1697  * ab8500_fg_algorithm_calibrate() - Internal columb counter offset calibration
1698  * @di:		pointer to the ab8500_fg structure
1699  *
1700  */
1701 static void ab8500_fg_algorithm_calibrate(struct ab8500_fg *di)
1702 {
1703 	int ret;
1704 
1705 	switch (di->calib_state) {
1706 	case AB8500_FG_CALIB_INIT:
1707 		dev_dbg(di->dev, "Calibration ongoing...\n");
1708 
1709 		ret = abx500_mask_and_set_register_interruptible(di->dev,
1710 			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1711 			CC_INT_CAL_N_AVG_MASK, CC_INT_CAL_SAMPLES_8);
1712 		if (ret < 0)
1713 			goto err;
1714 
1715 		ret = abx500_mask_and_set_register_interruptible(di->dev,
1716 			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1717 			CC_INTAVGOFFSET_ENA, CC_INTAVGOFFSET_ENA);
1718 		if (ret < 0)
1719 			goto err;
1720 		di->calib_state = AB8500_FG_CALIB_WAIT;
1721 		break;
1722 	case AB8500_FG_CALIB_END:
1723 		ret = abx500_mask_and_set_register_interruptible(di->dev,
1724 			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1725 			CC_MUXOFFSET, CC_MUXOFFSET);
1726 		if (ret < 0)
1727 			goto err;
1728 		di->flags.calibrate = false;
1729 		dev_dbg(di->dev, "Calibration done...\n");
1730 		queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1731 		break;
1732 	case AB8500_FG_CALIB_WAIT:
1733 		dev_dbg(di->dev, "Calibration WFI\n");
1734 		break;
1735 	default:
1736 		break;
1737 	}
1738 	return;
1739 err:
1740 	/* Something went wrong, don't calibrate then */
1741 	dev_err(di->dev, "failed to calibrate the CC\n");
1742 	di->flags.calibrate = false;
1743 	di->calib_state = AB8500_FG_CALIB_INIT;
1744 	queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1745 }
1746 
1747 /**
1748  * ab8500_fg_algorithm() - Entry point for the FG algorithm
1749  * @di:		pointer to the ab8500_fg structure
1750  *
1751  * Entry point for the battery capacity calculation state machine
1752  */
1753 static void ab8500_fg_algorithm(struct ab8500_fg *di)
1754 {
1755 	if (di->flags.calibrate)
1756 		ab8500_fg_algorithm_calibrate(di);
1757 	else {
1758 		if (di->flags.charging)
1759 			ab8500_fg_algorithm_charging(di);
1760 		else
1761 			ab8500_fg_algorithm_discharging(di);
1762 	}
1763 
1764 	dev_dbg(di->dev, "[FG_DATA] %d %d %d %d %d %d %d %d %d %d "
1765 		"%d %d %d %d %d %d %d\n",
1766 		di->bat_cap.max_mah_design,
1767 		di->bat_cap.max_mah,
1768 		di->bat_cap.mah,
1769 		di->bat_cap.permille,
1770 		di->bat_cap.level,
1771 		di->bat_cap.prev_mah,
1772 		di->bat_cap.prev_percent,
1773 		di->bat_cap.prev_level,
1774 		di->vbat_uv,
1775 		di->inst_curr_ua,
1776 		di->avg_curr_ua,
1777 		di->accu_charge,
1778 		di->flags.charging,
1779 		di->charge_state,
1780 		di->discharge_state,
1781 		di->high_curr_mode,
1782 		di->recovery_needed);
1783 }
1784 
1785 /**
1786  * ab8500_fg_periodic_work() - Run the FG state machine periodically
1787  * @work:	pointer to the work_struct structure
1788  *
1789  * Work queue function for periodic work
1790  */
1791 static void ab8500_fg_periodic_work(struct work_struct *work)
1792 {
1793 	struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1794 		fg_periodic_work.work);
1795 
1796 	if (di->init_capacity) {
1797 		/* Get an initial capacity calculation */
1798 		ab8500_fg_calc_cap_discharge_voltage(di);
1799 		ab8500_fg_check_capacity_limits(di, true);
1800 		di->init_capacity = false;
1801 
1802 		queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1803 	} else if (di->flags.user_cap) {
1804 		if (check_sysfs_capacity(di)) {
1805 			ab8500_fg_check_capacity_limits(di, true);
1806 			if (di->flags.charging)
1807 				ab8500_fg_charge_state_to(di,
1808 					AB8500_FG_CHARGE_INIT);
1809 			else
1810 				ab8500_fg_discharge_state_to(di,
1811 					AB8500_FG_DISCHARGE_READOUT_INIT);
1812 		}
1813 		di->flags.user_cap = false;
1814 		queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1815 	} else
1816 		ab8500_fg_algorithm(di);
1817 
1818 }
1819 
1820 /**
1821  * ab8500_fg_check_hw_failure_work() - Check OVV_BAT condition
1822  * @work:	pointer to the work_struct structure
1823  *
1824  * Work queue function for checking the OVV_BAT condition
1825  */
1826 static void ab8500_fg_check_hw_failure_work(struct work_struct *work)
1827 {
1828 	int ret;
1829 	u8 reg_value;
1830 
1831 	struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1832 		fg_check_hw_failure_work.work);
1833 
1834 	/*
1835 	 * If we have had a battery over-voltage situation,
1836 	 * check ovv-bit to see if it should be reset.
1837 	 */
1838 	ret = abx500_get_register_interruptible(di->dev,
1839 		AB8500_CHARGER, AB8500_CH_STAT_REG,
1840 		&reg_value);
1841 	if (ret < 0) {
1842 		dev_err(di->dev, "%s ab8500 read failed\n", __func__);
1843 		return;
1844 	}
1845 	if ((reg_value & BATT_OVV) == BATT_OVV) {
1846 		if (!di->flags.bat_ovv) {
1847 			dev_dbg(di->dev, "Battery OVV\n");
1848 			di->flags.bat_ovv = true;
1849 			power_supply_changed(di->fg_psy);
1850 		}
1851 		/* Not yet recovered from ovv, reschedule this test */
1852 		queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work,
1853 				   HZ);
1854 		} else {
1855 			dev_dbg(di->dev, "Battery recovered from OVV\n");
1856 			di->flags.bat_ovv = false;
1857 			power_supply_changed(di->fg_psy);
1858 	}
1859 }
1860 
1861 /**
1862  * ab8500_fg_low_bat_work() - Check LOW_BAT condition
1863  * @work:	pointer to the work_struct structure
1864  *
1865  * Work queue function for checking the LOW_BAT condition
1866  */
1867 static void ab8500_fg_low_bat_work(struct work_struct *work)
1868 {
1869 	int vbat_uv;
1870 
1871 	struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1872 		fg_low_bat_work.work);
1873 
1874 	vbat_uv = ab8500_fg_bat_voltage(di);
1875 
1876 	/* Check if LOW_BAT still fulfilled */
1877 	if (vbat_uv < di->bm->fg_params->lowbat_threshold_uv) {
1878 		/* Is it time to shut down? */
1879 		if (di->low_bat_cnt < 1) {
1880 			di->flags.low_bat = true;
1881 			dev_warn(di->dev, "Shut down pending...\n");
1882 		} else {
1883 			/*
1884 			* Else we need to re-schedule this check to be able to detect
1885 			* if the voltage increases again during charging or
1886 			* due to decreasing load.
1887 			*/
1888 			di->low_bat_cnt--;
1889 			dev_warn(di->dev, "Battery voltage still LOW\n");
1890 			queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
1891 				round_jiffies(LOW_BAT_CHECK_INTERVAL));
1892 		}
1893 	} else {
1894 		di->flags.low_bat_delay = false;
1895 		di->low_bat_cnt = 10;
1896 		dev_warn(di->dev, "Battery voltage OK again\n");
1897 	}
1898 
1899 	/* This is needed to dispatch LOW_BAT */
1900 	ab8500_fg_check_capacity_limits(di, false);
1901 }
1902 
1903 /**
1904  * ab8500_fg_battok_calc - calculate the bit pattern corresponding
1905  * to the target voltage.
1906  * @di:       pointer to the ab8500_fg structure
1907  * @target:   target voltage
1908  *
1909  * Returns bit pattern closest to the target voltage
1910  * valid return values are 0-14. (0-BATT_OK_MAX_NR_INCREMENTS)
1911  */
1912 
1913 static int ab8500_fg_battok_calc(struct ab8500_fg *di, int target)
1914 {
1915 	if (target > BATT_OK_MIN +
1916 		(BATT_OK_INCREMENT * BATT_OK_MAX_NR_INCREMENTS))
1917 		return BATT_OK_MAX_NR_INCREMENTS;
1918 	if (target < BATT_OK_MIN)
1919 		return 0;
1920 	return (target - BATT_OK_MIN) / BATT_OK_INCREMENT;
1921 }
1922 
1923 /**
1924  * ab8500_fg_battok_init_hw_register - init battok levels
1925  * @di:       pointer to the ab8500_fg structure
1926  *
1927  */
1928 
1929 static int ab8500_fg_battok_init_hw_register(struct ab8500_fg *di)
1930 {
1931 	int selected;
1932 	int sel0;
1933 	int sel1;
1934 	int cbp_sel0;
1935 	int cbp_sel1;
1936 	int ret;
1937 	int new_val;
1938 
1939 	sel0 = di->bm->fg_params->battok_falling_th_sel0;
1940 	sel1 = di->bm->fg_params->battok_raising_th_sel1;
1941 
1942 	cbp_sel0 = ab8500_fg_battok_calc(di, sel0);
1943 	cbp_sel1 = ab8500_fg_battok_calc(di, sel1);
1944 
1945 	selected = BATT_OK_MIN + cbp_sel0 * BATT_OK_INCREMENT;
1946 
1947 	if (selected != sel0)
1948 		dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1949 			sel0, selected, cbp_sel0);
1950 
1951 	selected = BATT_OK_MIN + cbp_sel1 * BATT_OK_INCREMENT;
1952 
1953 	if (selected != sel1)
1954 		dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1955 			sel1, selected, cbp_sel1);
1956 
1957 	new_val = cbp_sel0 | (cbp_sel1 << 4);
1958 
1959 	dev_dbg(di->dev, "using: %x %d %d\n", new_val, cbp_sel0, cbp_sel1);
1960 	ret = abx500_set_register_interruptible(di->dev, AB8500_SYS_CTRL2_BLOCK,
1961 		AB8500_BATT_OK_REG, new_val);
1962 	return ret;
1963 }
1964 
1965 /**
1966  * ab8500_fg_instant_work() - Run the FG state machine instantly
1967  * @work:	pointer to the work_struct structure
1968  *
1969  * Work queue function for instant work
1970  */
1971 static void ab8500_fg_instant_work(struct work_struct *work)
1972 {
1973 	struct ab8500_fg *di = container_of(work, struct ab8500_fg, fg_work);
1974 
1975 	ab8500_fg_algorithm(di);
1976 }
1977 
1978 /**
1979  * ab8500_fg_cc_data_end_handler() - end of data conversion isr.
1980  * @irq:       interrupt number
1981  * @_di:       pointer to the ab8500_fg structure
1982  *
1983  * Returns IRQ status(IRQ_HANDLED)
1984  */
1985 static irqreturn_t ab8500_fg_cc_data_end_handler(int irq, void *_di)
1986 {
1987 	struct ab8500_fg *di = _di;
1988 	if (!di->nbr_cceoc_irq_cnt) {
1989 		di->nbr_cceoc_irq_cnt++;
1990 		complete(&di->ab8500_fg_started);
1991 	} else {
1992 		di->nbr_cceoc_irq_cnt = 0;
1993 		complete(&di->ab8500_fg_complete);
1994 	}
1995 	return IRQ_HANDLED;
1996 }
1997 
1998 /**
1999  * ab8500_fg_cc_int_calib_handler () - end of calibration isr.
2000  * @irq:       interrupt number
2001  * @_di:       pointer to the ab8500_fg structure
2002  *
2003  * Returns IRQ status(IRQ_HANDLED)
2004  */
2005 static irqreturn_t ab8500_fg_cc_int_calib_handler(int irq, void *_di)
2006 {
2007 	struct ab8500_fg *di = _di;
2008 	di->calib_state = AB8500_FG_CALIB_END;
2009 	queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2010 	return IRQ_HANDLED;
2011 }
2012 
2013 /**
2014  * ab8500_fg_cc_convend_handler() - isr to get battery avg current.
2015  * @irq:       interrupt number
2016  * @_di:       pointer to the ab8500_fg structure
2017  *
2018  * Returns IRQ status(IRQ_HANDLED)
2019  */
2020 static irqreturn_t ab8500_fg_cc_convend_handler(int irq, void *_di)
2021 {
2022 	struct ab8500_fg *di = _di;
2023 
2024 	queue_work(di->fg_wq, &di->fg_acc_cur_work);
2025 
2026 	return IRQ_HANDLED;
2027 }
2028 
2029 /**
2030  * ab8500_fg_batt_ovv_handler() - Battery OVV occured
2031  * @irq:       interrupt number
2032  * @_di:       pointer to the ab8500_fg structure
2033  *
2034  * Returns IRQ status(IRQ_HANDLED)
2035  */
2036 static irqreturn_t ab8500_fg_batt_ovv_handler(int irq, void *_di)
2037 {
2038 	struct ab8500_fg *di = _di;
2039 
2040 	dev_dbg(di->dev, "Battery OVV\n");
2041 
2042 	/* Schedule a new HW failure check */
2043 	queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work, 0);
2044 
2045 	return IRQ_HANDLED;
2046 }
2047 
2048 /**
2049  * ab8500_fg_lowbatf_handler() - Battery voltage is below LOW threshold
2050  * @irq:       interrupt number
2051  * @_di:       pointer to the ab8500_fg structure
2052  *
2053  * Returns IRQ status(IRQ_HANDLED)
2054  */
2055 static irqreturn_t ab8500_fg_lowbatf_handler(int irq, void *_di)
2056 {
2057 	struct ab8500_fg *di = _di;
2058 
2059 	/* Initiate handling in ab8500_fg_low_bat_work() if not already initiated. */
2060 	if (!di->flags.low_bat_delay) {
2061 		dev_warn(di->dev, "Battery voltage is below LOW threshold\n");
2062 		di->flags.low_bat_delay = true;
2063 		/*
2064 		 * Start a timer to check LOW_BAT again after some time
2065 		 * This is done to avoid shutdown on single voltage dips
2066 		 */
2067 		queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
2068 			round_jiffies(LOW_BAT_CHECK_INTERVAL));
2069 	}
2070 	return IRQ_HANDLED;
2071 }
2072 
2073 /**
2074  * ab8500_fg_get_property() - get the fg properties
2075  * @psy:	pointer to the power_supply structure
2076  * @psp:	pointer to the power_supply_property structure
2077  * @val:	pointer to the power_supply_propval union
2078  *
2079  * This function gets called when an application tries to get the
2080  * fg properties by reading the sysfs files.
2081  * voltage_now:		battery voltage
2082  * current_now:		battery instant current
2083  * current_avg:		battery average current
2084  * charge_full_design:	capacity where battery is considered full
2085  * charge_now:		battery capacity in nAh
2086  * capacity:		capacity in percent
2087  * capacity_level:	capacity level
2088  *
2089  * Returns error code in case of failure else 0 on success
2090  */
2091 static int ab8500_fg_get_property(struct power_supply *psy,
2092 	enum power_supply_property psp,
2093 	union power_supply_propval *val)
2094 {
2095 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2096 
2097 	/*
2098 	 * If battery is identified as unknown and charging of unknown
2099 	 * batteries is disabled, we always report 100% capacity and
2100 	 * capacity level UNKNOWN, since we can't calculate
2101 	 * remaining capacity
2102 	 */
2103 
2104 	switch (psp) {
2105 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
2106 		if (di->flags.bat_ovv)
2107 			val->intval = BATT_OVV_VALUE;
2108 		else
2109 			val->intval = di->vbat_uv;
2110 		break;
2111 	case POWER_SUPPLY_PROP_CURRENT_NOW:
2112 		val->intval = di->inst_curr_ua;
2113 		break;
2114 	case POWER_SUPPLY_PROP_CURRENT_AVG:
2115 		val->intval = di->avg_curr_ua;
2116 		break;
2117 	case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
2118 		val->intval = ab8500_fg_convert_mah_to_uwh(di,
2119 				di->bat_cap.max_mah_design);
2120 		break;
2121 	case POWER_SUPPLY_PROP_ENERGY_FULL:
2122 		val->intval = ab8500_fg_convert_mah_to_uwh(di,
2123 				di->bat_cap.max_mah);
2124 		break;
2125 	case POWER_SUPPLY_PROP_ENERGY_NOW:
2126 		if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2127 				di->flags.batt_id_received)
2128 			val->intval = ab8500_fg_convert_mah_to_uwh(di,
2129 					di->bat_cap.max_mah);
2130 		else
2131 			val->intval = ab8500_fg_convert_mah_to_uwh(di,
2132 					di->bat_cap.prev_mah);
2133 		break;
2134 	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
2135 		val->intval = di->bat_cap.max_mah_design;
2136 		break;
2137 	case POWER_SUPPLY_PROP_CHARGE_FULL:
2138 		val->intval = di->bat_cap.max_mah;
2139 		break;
2140 	case POWER_SUPPLY_PROP_CHARGE_NOW:
2141 		if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2142 				di->flags.batt_id_received)
2143 			val->intval = di->bat_cap.max_mah;
2144 		else
2145 			val->intval = di->bat_cap.prev_mah;
2146 		break;
2147 	case POWER_SUPPLY_PROP_CAPACITY:
2148 		if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2149 				di->flags.batt_id_received)
2150 			val->intval = 100;
2151 		else
2152 			val->intval = di->bat_cap.prev_percent;
2153 		break;
2154 	case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
2155 		if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2156 				di->flags.batt_id_received)
2157 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
2158 		else
2159 			val->intval = di->bat_cap.prev_level;
2160 		break;
2161 	default:
2162 		return -EINVAL;
2163 	}
2164 	return 0;
2165 }
2166 
2167 static int ab8500_fg_get_ext_psy_data(struct device *dev, void *data)
2168 {
2169 	struct power_supply *psy;
2170 	struct power_supply *ext = dev_get_drvdata(dev);
2171 	const char **supplicants = (const char **)ext->supplied_to;
2172 	struct ab8500_fg *di;
2173 	struct power_supply_battery_info *bi;
2174 	union power_supply_propval ret;
2175 	int j;
2176 
2177 	psy = (struct power_supply *)data;
2178 	di = power_supply_get_drvdata(psy);
2179 	bi = di->bm->bi;
2180 
2181 	/*
2182 	 * For all psy where the name of your driver
2183 	 * appears in any supplied_to
2184 	 */
2185 	j = match_string(supplicants, ext->num_supplicants, psy->desc->name);
2186 	if (j < 0)
2187 		return 0;
2188 
2189 	/* Go through all properties for the psy */
2190 	for (j = 0; j < ext->desc->num_properties; j++) {
2191 		enum power_supply_property prop;
2192 		prop = ext->desc->properties[j];
2193 
2194 		if (power_supply_get_property(ext, prop, &ret))
2195 			continue;
2196 
2197 		switch (prop) {
2198 		case POWER_SUPPLY_PROP_STATUS:
2199 			switch (ext->desc->type) {
2200 			case POWER_SUPPLY_TYPE_BATTERY:
2201 				switch (ret.intval) {
2202 				case POWER_SUPPLY_STATUS_UNKNOWN:
2203 				case POWER_SUPPLY_STATUS_DISCHARGING:
2204 				case POWER_SUPPLY_STATUS_NOT_CHARGING:
2205 					if (!di->flags.charging)
2206 						break;
2207 					di->flags.charging = false;
2208 					di->flags.fully_charged = false;
2209 					if (di->bm->capacity_scaling)
2210 						ab8500_fg_update_cap_scalers(di);
2211 					queue_work(di->fg_wq, &di->fg_work);
2212 					break;
2213 				case POWER_SUPPLY_STATUS_FULL:
2214 					if (di->flags.fully_charged)
2215 						break;
2216 					di->flags.fully_charged = true;
2217 					di->flags.force_full = true;
2218 					/* Save current capacity as maximum */
2219 					di->bat_cap.max_mah = di->bat_cap.mah;
2220 					queue_work(di->fg_wq, &di->fg_work);
2221 					break;
2222 				case POWER_SUPPLY_STATUS_CHARGING:
2223 					if (di->flags.charging &&
2224 						!di->flags.fully_charged)
2225 						break;
2226 					di->flags.charging = true;
2227 					di->flags.fully_charged = false;
2228 					if (di->bm->capacity_scaling)
2229 						ab8500_fg_update_cap_scalers(di);
2230 					queue_work(di->fg_wq, &di->fg_work);
2231 					break;
2232 				}
2233 				break;
2234 			default:
2235 				break;
2236 			}
2237 			break;
2238 		case POWER_SUPPLY_PROP_TECHNOLOGY:
2239 			switch (ext->desc->type) {
2240 			case POWER_SUPPLY_TYPE_BATTERY:
2241 				if (!di->flags.batt_id_received &&
2242 				    (bi && (bi->technology !=
2243 					    POWER_SUPPLY_TECHNOLOGY_UNKNOWN))) {
2244 					const struct ab8500_battery_type *b;
2245 
2246 					b = di->bm->bat_type;
2247 
2248 					di->flags.batt_id_received = true;
2249 
2250 					di->bat_cap.max_mah_design =
2251 						di->bm->bi->charge_full_design_uah;
2252 
2253 					di->bat_cap.max_mah =
2254 						di->bat_cap.max_mah_design;
2255 
2256 					di->vbat_nom_uv =
2257 						di->bm->bi->voltage_max_design_uv;
2258 				}
2259 
2260 				if (ret.intval)
2261 					di->flags.batt_unknown = false;
2262 				else
2263 					di->flags.batt_unknown = true;
2264 				break;
2265 			default:
2266 				break;
2267 			}
2268 			break;
2269 		case POWER_SUPPLY_PROP_TEMP:
2270 			switch (ext->desc->type) {
2271 			case POWER_SUPPLY_TYPE_BATTERY:
2272 				if (di->flags.batt_id_received)
2273 					di->bat_temp = ret.intval;
2274 				break;
2275 			default:
2276 				break;
2277 			}
2278 			break;
2279 		default:
2280 			break;
2281 		}
2282 	}
2283 	return 0;
2284 }
2285 
2286 /**
2287  * ab8500_fg_init_hw_registers() - Set up FG related registers
2288  * @di:		pointer to the ab8500_fg structure
2289  *
2290  * Set up battery OVV, low battery voltage registers
2291  */
2292 static int ab8500_fg_init_hw_registers(struct ab8500_fg *di)
2293 {
2294 	int ret;
2295 
2296 	/*
2297 	 * Set VBAT OVV (overvoltage) threshold to 4.75V (typ) this is what
2298 	 * the hardware supports, nothing else can be configured in hardware.
2299 	 * See this as an "outer limit" where the charger will certainly
2300 	 * shut down. Other (lower) overvoltage levels need to be implemented
2301 	 * in software.
2302 	 */
2303 	ret = abx500_mask_and_set_register_interruptible(di->dev,
2304 		AB8500_CHARGER,
2305 		AB8500_BATT_OVV,
2306 		BATT_OVV_TH_4P75,
2307 		BATT_OVV_TH_4P75);
2308 	if (ret) {
2309 		dev_err(di->dev, "failed to set BATT_OVV\n");
2310 		goto out;
2311 	}
2312 
2313 	/* Enable VBAT OVV detection */
2314 	ret = abx500_mask_and_set_register_interruptible(di->dev,
2315 		AB8500_CHARGER,
2316 		AB8500_BATT_OVV,
2317 		BATT_OVV_ENA,
2318 		BATT_OVV_ENA);
2319 	if (ret) {
2320 		dev_err(di->dev, "failed to enable BATT_OVV\n");
2321 		goto out;
2322 	}
2323 
2324 	/* Low Battery Voltage */
2325 	ret = abx500_set_register_interruptible(di->dev,
2326 		AB8500_SYS_CTRL2_BLOCK,
2327 		AB8500_LOW_BAT_REG,
2328 		ab8500_volt_to_regval(
2329 			di->bm->fg_params->lowbat_threshold_uv) << 1 |
2330 		LOW_BAT_ENABLE);
2331 	if (ret) {
2332 		dev_err(di->dev, "%s write failed\n", __func__);
2333 		goto out;
2334 	}
2335 
2336 	/* Battery OK threshold */
2337 	ret = ab8500_fg_battok_init_hw_register(di);
2338 	if (ret) {
2339 		dev_err(di->dev, "BattOk init write failed.\n");
2340 		goto out;
2341 	}
2342 
2343 	if (is_ab8505(di->parent)) {
2344 		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2345 			AB8505_RTC_PCUT_MAX_TIME_REG, di->bm->fg_params->pcut_max_time);
2346 
2347 		if (ret) {
2348 			dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_MAX_TIME_REG\n", __func__);
2349 			goto out;
2350 		}
2351 
2352 		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2353 			AB8505_RTC_PCUT_FLAG_TIME_REG, di->bm->fg_params->pcut_flag_time);
2354 
2355 		if (ret) {
2356 			dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_FLAG_TIME_REG\n", __func__);
2357 			goto out;
2358 		}
2359 
2360 		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2361 			AB8505_RTC_PCUT_RESTART_REG, di->bm->fg_params->pcut_max_restart);
2362 
2363 		if (ret) {
2364 			dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_RESTART_REG\n", __func__);
2365 			goto out;
2366 		}
2367 
2368 		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2369 			AB8505_RTC_PCUT_DEBOUNCE_REG, di->bm->fg_params->pcut_debounce_time);
2370 
2371 		if (ret) {
2372 			dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_DEBOUNCE_REG\n", __func__);
2373 			goto out;
2374 		}
2375 
2376 		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2377 			AB8505_RTC_PCUT_CTL_STATUS_REG, di->bm->fg_params->pcut_enable);
2378 
2379 		if (ret) {
2380 			dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_CTL_STATUS_REG\n", __func__);
2381 			goto out;
2382 		}
2383 	}
2384 out:
2385 	return ret;
2386 }
2387 
2388 /**
2389  * ab8500_fg_external_power_changed() - callback for power supply changes
2390  * @psy:       pointer to the structure power_supply
2391  *
2392  * This function is the entry point of the pointer external_power_changed
2393  * of the structure power_supply.
2394  * This function gets executed when there is a change in any external power
2395  * supply that this driver needs to be notified of.
2396  */
2397 static void ab8500_fg_external_power_changed(struct power_supply *psy)
2398 {
2399 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2400 
2401 	class_for_each_device(power_supply_class, NULL,
2402 		di->fg_psy, ab8500_fg_get_ext_psy_data);
2403 }
2404 
2405 /**
2406  * ab8500_fg_reinit_work() - work to reset the FG algorithm
2407  * @work:	pointer to the work_struct structure
2408  *
2409  * Used to reset the current battery capacity to be able to
2410  * retrigger a new voltage base capacity calculation. For
2411  * test and verification purpose.
2412  */
2413 static void ab8500_fg_reinit_work(struct work_struct *work)
2414 {
2415 	struct ab8500_fg *di = container_of(work, struct ab8500_fg,
2416 		fg_reinit_work.work);
2417 
2418 	if (!di->flags.calibrate) {
2419 		dev_dbg(di->dev, "Resetting FG state machine to init.\n");
2420 		ab8500_fg_clear_cap_samples(di);
2421 		ab8500_fg_calc_cap_discharge_voltage(di);
2422 		ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
2423 		ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
2424 		queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2425 
2426 	} else {
2427 		dev_err(di->dev, "Residual offset calibration ongoing "
2428 			"retrying..\n");
2429 		/* Wait one second until next try*/
2430 		queue_delayed_work(di->fg_wq, &di->fg_reinit_work,
2431 			round_jiffies(1));
2432 	}
2433 }
2434 
2435 /* Exposure to the sysfs interface */
2436 
2437 struct ab8500_fg_sysfs_entry {
2438 	struct attribute attr;
2439 	ssize_t (*show)(struct ab8500_fg *, char *);
2440 	ssize_t (*store)(struct ab8500_fg *, const char *, size_t);
2441 };
2442 
2443 static ssize_t charge_full_show(struct ab8500_fg *di, char *buf)
2444 {
2445 	return sprintf(buf, "%d\n", di->bat_cap.max_mah);
2446 }
2447 
2448 static ssize_t charge_full_store(struct ab8500_fg *di, const char *buf,
2449 				 size_t count)
2450 {
2451 	unsigned long charge_full;
2452 	int ret;
2453 
2454 	ret = kstrtoul(buf, 10, &charge_full);
2455 	if (ret)
2456 		return ret;
2457 
2458 	di->bat_cap.max_mah = (int) charge_full;
2459 	return count;
2460 }
2461 
2462 static ssize_t charge_now_show(struct ab8500_fg *di, char *buf)
2463 {
2464 	return sprintf(buf, "%d\n", di->bat_cap.prev_mah);
2465 }
2466 
2467 static ssize_t charge_now_store(struct ab8500_fg *di, const char *buf,
2468 				 size_t count)
2469 {
2470 	unsigned long charge_now;
2471 	int ret;
2472 
2473 	ret = kstrtoul(buf, 10, &charge_now);
2474 	if (ret)
2475 		return ret;
2476 
2477 	di->bat_cap.user_mah = (int) charge_now;
2478 	di->flags.user_cap = true;
2479 	queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2480 	return count;
2481 }
2482 
2483 static struct ab8500_fg_sysfs_entry charge_full_attr =
2484 	__ATTR(charge_full, 0644, charge_full_show, charge_full_store);
2485 
2486 static struct ab8500_fg_sysfs_entry charge_now_attr =
2487 	__ATTR(charge_now, 0644, charge_now_show, charge_now_store);
2488 
2489 static ssize_t
2490 ab8500_fg_show(struct kobject *kobj, struct attribute *attr, char *buf)
2491 {
2492 	struct ab8500_fg_sysfs_entry *entry;
2493 	struct ab8500_fg *di;
2494 
2495 	entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2496 	di = container_of(kobj, struct ab8500_fg, fg_kobject);
2497 
2498 	if (!entry->show)
2499 		return -EIO;
2500 
2501 	return entry->show(di, buf);
2502 }
2503 static ssize_t
2504 ab8500_fg_store(struct kobject *kobj, struct attribute *attr, const char *buf,
2505 		size_t count)
2506 {
2507 	struct ab8500_fg_sysfs_entry *entry;
2508 	struct ab8500_fg *di;
2509 
2510 	entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2511 	di = container_of(kobj, struct ab8500_fg, fg_kobject);
2512 
2513 	if (!entry->store)
2514 		return -EIO;
2515 
2516 	return entry->store(di, buf, count);
2517 }
2518 
2519 static const struct sysfs_ops ab8500_fg_sysfs_ops = {
2520 	.show = ab8500_fg_show,
2521 	.store = ab8500_fg_store,
2522 };
2523 
2524 static struct attribute *ab8500_fg_attrs[] = {
2525 	&charge_full_attr.attr,
2526 	&charge_now_attr.attr,
2527 	NULL,
2528 };
2529 
2530 static struct kobj_type ab8500_fg_ktype = {
2531 	.sysfs_ops = &ab8500_fg_sysfs_ops,
2532 	.default_attrs = ab8500_fg_attrs,
2533 };
2534 
2535 /**
2536  * ab8500_fg_sysfs_exit() - de-init of sysfs entry
2537  * @di:                pointer to the struct ab8500_chargalg
2538  *
2539  * This function removes the entry in sysfs.
2540  */
2541 static void ab8500_fg_sysfs_exit(struct ab8500_fg *di)
2542 {
2543 	kobject_del(&di->fg_kobject);
2544 }
2545 
2546 /**
2547  * ab8500_fg_sysfs_init() - init of sysfs entry
2548  * @di:                pointer to the struct ab8500_chargalg
2549  *
2550  * This function adds an entry in sysfs.
2551  * Returns error code in case of failure else 0(on success)
2552  */
2553 static int ab8500_fg_sysfs_init(struct ab8500_fg *di)
2554 {
2555 	int ret = 0;
2556 
2557 	ret = kobject_init_and_add(&di->fg_kobject,
2558 		&ab8500_fg_ktype,
2559 		NULL, "battery");
2560 	if (ret < 0) {
2561 		kobject_put(&di->fg_kobject);
2562 		dev_err(di->dev, "failed to create sysfs entry\n");
2563 	}
2564 
2565 	return ret;
2566 }
2567 
2568 static ssize_t ab8505_powercut_flagtime_read(struct device *dev,
2569 			     struct device_attribute *attr,
2570 			     char *buf)
2571 {
2572 	int ret;
2573 	u8 reg_value;
2574 	struct power_supply *psy = dev_get_drvdata(dev);
2575 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2576 
2577 	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2578 		AB8505_RTC_PCUT_FLAG_TIME_REG, &reg_value);
2579 
2580 	if (ret < 0) {
2581 		dev_err(dev, "Failed to read AB8505_RTC_PCUT_FLAG_TIME_REG\n");
2582 		goto fail;
2583 	}
2584 
2585 	return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7F));
2586 
2587 fail:
2588 	return ret;
2589 }
2590 
2591 static ssize_t ab8505_powercut_flagtime_write(struct device *dev,
2592 				  struct device_attribute *attr,
2593 				  const char *buf, size_t count)
2594 {
2595 	int ret;
2596 	int reg_value;
2597 	struct power_supply *psy = dev_get_drvdata(dev);
2598 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2599 
2600 	if (kstrtoint(buf, 10, &reg_value))
2601 		goto fail;
2602 
2603 	if (reg_value > 0x7F) {
2604 		dev_err(dev, "Incorrect parameter, echo 0 (1.98s) - 127 (15.625ms) for flagtime\n");
2605 		goto fail;
2606 	}
2607 
2608 	ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2609 		AB8505_RTC_PCUT_FLAG_TIME_REG, (u8)reg_value);
2610 
2611 	if (ret < 0)
2612 		dev_err(dev, "Failed to set AB8505_RTC_PCUT_FLAG_TIME_REG\n");
2613 
2614 fail:
2615 	return count;
2616 }
2617 
2618 static ssize_t ab8505_powercut_maxtime_read(struct device *dev,
2619 			     struct device_attribute *attr,
2620 			     char *buf)
2621 {
2622 	int ret;
2623 	u8 reg_value;
2624 	struct power_supply *psy = dev_get_drvdata(dev);
2625 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2626 
2627 	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2628 		AB8505_RTC_PCUT_MAX_TIME_REG, &reg_value);
2629 
2630 	if (ret < 0) {
2631 		dev_err(dev, "Failed to read AB8505_RTC_PCUT_MAX_TIME_REG\n");
2632 		goto fail;
2633 	}
2634 
2635 	return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7F));
2636 
2637 fail:
2638 	return ret;
2639 
2640 }
2641 
2642 static ssize_t ab8505_powercut_maxtime_write(struct device *dev,
2643 				  struct device_attribute *attr,
2644 				  const char *buf, size_t count)
2645 {
2646 	int ret;
2647 	int reg_value;
2648 	struct power_supply *psy = dev_get_drvdata(dev);
2649 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2650 
2651 	if (kstrtoint(buf, 10, &reg_value))
2652 		goto fail;
2653 
2654 	if (reg_value > 0x7F) {
2655 		dev_err(dev, "Incorrect parameter, echo 0 (0.0s) - 127 (1.98s) for maxtime\n");
2656 		goto fail;
2657 	}
2658 
2659 	ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2660 		AB8505_RTC_PCUT_MAX_TIME_REG, (u8)reg_value);
2661 
2662 	if (ret < 0)
2663 		dev_err(dev, "Failed to set AB8505_RTC_PCUT_MAX_TIME_REG\n");
2664 
2665 fail:
2666 	return count;
2667 }
2668 
2669 static ssize_t ab8505_powercut_restart_read(struct device *dev,
2670 			     struct device_attribute *attr,
2671 			     char *buf)
2672 {
2673 	int ret;
2674 	u8 reg_value;
2675 	struct power_supply *psy = dev_get_drvdata(dev);
2676 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2677 
2678 	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2679 		AB8505_RTC_PCUT_RESTART_REG, &reg_value);
2680 
2681 	if (ret < 0) {
2682 		dev_err(dev, "Failed to read AB8505_RTC_PCUT_RESTART_REG\n");
2683 		goto fail;
2684 	}
2685 
2686 	return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0xF));
2687 
2688 fail:
2689 	return ret;
2690 }
2691 
2692 static ssize_t ab8505_powercut_restart_write(struct device *dev,
2693 					     struct device_attribute *attr,
2694 					     const char *buf, size_t count)
2695 {
2696 	int ret;
2697 	int reg_value;
2698 	struct power_supply *psy = dev_get_drvdata(dev);
2699 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2700 
2701 	if (kstrtoint(buf, 10, &reg_value))
2702 		goto fail;
2703 
2704 	if (reg_value > 0xF) {
2705 		dev_err(dev, "Incorrect parameter, echo 0 - 15 for number of restart\n");
2706 		goto fail;
2707 	}
2708 
2709 	ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2710 						AB8505_RTC_PCUT_RESTART_REG, (u8)reg_value);
2711 
2712 	if (ret < 0)
2713 		dev_err(dev, "Failed to set AB8505_RTC_PCUT_RESTART_REG\n");
2714 
2715 fail:
2716 	return count;
2717 
2718 }
2719 
2720 static ssize_t ab8505_powercut_timer_read(struct device *dev,
2721 					  struct device_attribute *attr,
2722 					  char *buf)
2723 {
2724 	int ret;
2725 	u8 reg_value;
2726 	struct power_supply *psy = dev_get_drvdata(dev);
2727 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2728 
2729 	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2730 						AB8505_RTC_PCUT_TIME_REG, &reg_value);
2731 
2732 	if (ret < 0) {
2733 		dev_err(dev, "Failed to read AB8505_RTC_PCUT_TIME_REG\n");
2734 		goto fail;
2735 	}
2736 
2737 	return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7F));
2738 
2739 fail:
2740 	return ret;
2741 }
2742 
2743 static ssize_t ab8505_powercut_restart_counter_read(struct device *dev,
2744 						    struct device_attribute *attr,
2745 						    char *buf)
2746 {
2747 	int ret;
2748 	u8 reg_value;
2749 	struct power_supply *psy = dev_get_drvdata(dev);
2750 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2751 
2752 	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2753 						AB8505_RTC_PCUT_RESTART_REG, &reg_value);
2754 
2755 	if (ret < 0) {
2756 		dev_err(dev, "Failed to read AB8505_RTC_PCUT_RESTART_REG\n");
2757 		goto fail;
2758 	}
2759 
2760 	return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0xF0) >> 4);
2761 
2762 fail:
2763 	return ret;
2764 }
2765 
2766 static ssize_t ab8505_powercut_read(struct device *dev,
2767 				    struct device_attribute *attr,
2768 				    char *buf)
2769 {
2770 	int ret;
2771 	u8 reg_value;
2772 	struct power_supply *psy = dev_get_drvdata(dev);
2773 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2774 
2775 	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2776 						AB8505_RTC_PCUT_CTL_STATUS_REG, &reg_value);
2777 
2778 	if (ret < 0)
2779 		goto fail;
2780 
2781 	return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x1));
2782 
2783 fail:
2784 	return ret;
2785 }
2786 
2787 static ssize_t ab8505_powercut_write(struct device *dev,
2788 				     struct device_attribute *attr,
2789 				     const char *buf, size_t count)
2790 {
2791 	int ret;
2792 	int reg_value;
2793 	struct power_supply *psy = dev_get_drvdata(dev);
2794 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2795 
2796 	if (kstrtoint(buf, 10, &reg_value))
2797 		goto fail;
2798 
2799 	if (reg_value > 0x1) {
2800 		dev_err(dev, "Incorrect parameter, echo 0/1 to disable/enable Pcut feature\n");
2801 		goto fail;
2802 	}
2803 
2804 	ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2805 						AB8505_RTC_PCUT_CTL_STATUS_REG, (u8)reg_value);
2806 
2807 	if (ret < 0)
2808 		dev_err(dev, "Failed to set AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2809 
2810 fail:
2811 	return count;
2812 }
2813 
2814 static ssize_t ab8505_powercut_flag_read(struct device *dev,
2815 					 struct device_attribute *attr,
2816 					 char *buf)
2817 {
2818 
2819 	int ret;
2820 	u8 reg_value;
2821 	struct power_supply *psy = dev_get_drvdata(dev);
2822 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2823 
2824 	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2825 						AB8505_RTC_PCUT_CTL_STATUS_REG,  &reg_value);
2826 
2827 	if (ret < 0) {
2828 		dev_err(dev, "Failed to read AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2829 		goto fail;
2830 	}
2831 
2832 	return scnprintf(buf, PAGE_SIZE, "%d\n", ((reg_value & 0x10) >> 4));
2833 
2834 fail:
2835 	return ret;
2836 }
2837 
2838 static ssize_t ab8505_powercut_debounce_read(struct device *dev,
2839 					     struct device_attribute *attr,
2840 					     char *buf)
2841 {
2842 	int ret;
2843 	u8 reg_value;
2844 	struct power_supply *psy = dev_get_drvdata(dev);
2845 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2846 
2847 	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2848 						AB8505_RTC_PCUT_DEBOUNCE_REG,  &reg_value);
2849 
2850 	if (ret < 0) {
2851 		dev_err(dev, "Failed to read AB8505_RTC_PCUT_DEBOUNCE_REG\n");
2852 		goto fail;
2853 	}
2854 
2855 	return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7));
2856 
2857 fail:
2858 	return ret;
2859 }
2860 
2861 static ssize_t ab8505_powercut_debounce_write(struct device *dev,
2862 					      struct device_attribute *attr,
2863 					      const char *buf, size_t count)
2864 {
2865 	int ret;
2866 	int reg_value;
2867 	struct power_supply *psy = dev_get_drvdata(dev);
2868 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2869 
2870 	if (kstrtoint(buf, 10, &reg_value))
2871 		goto fail;
2872 
2873 	if (reg_value > 0x7) {
2874 		dev_err(dev, "Incorrect parameter, echo 0 to 7 for debounce setting\n");
2875 		goto fail;
2876 	}
2877 
2878 	ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2879 						AB8505_RTC_PCUT_DEBOUNCE_REG, (u8)reg_value);
2880 
2881 	if (ret < 0)
2882 		dev_err(dev, "Failed to set AB8505_RTC_PCUT_DEBOUNCE_REG\n");
2883 
2884 fail:
2885 	return count;
2886 }
2887 
2888 static ssize_t ab8505_powercut_enable_status_read(struct device *dev,
2889 						  struct device_attribute *attr,
2890 						  char *buf)
2891 {
2892 	int ret;
2893 	u8 reg_value;
2894 	struct power_supply *psy = dev_get_drvdata(dev);
2895 	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2896 
2897 	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2898 						AB8505_RTC_PCUT_CTL_STATUS_REG, &reg_value);
2899 
2900 	if (ret < 0) {
2901 		dev_err(dev, "Failed to read AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2902 		goto fail;
2903 	}
2904 
2905 	return scnprintf(buf, PAGE_SIZE, "%d\n", ((reg_value & 0x20) >> 5));
2906 
2907 fail:
2908 	return ret;
2909 }
2910 
2911 static struct device_attribute ab8505_fg_sysfs_psy_attrs[] = {
2912 	__ATTR(powercut_flagtime, (S_IRUGO | S_IWUSR | S_IWGRP),
2913 		ab8505_powercut_flagtime_read, ab8505_powercut_flagtime_write),
2914 	__ATTR(powercut_maxtime, (S_IRUGO | S_IWUSR | S_IWGRP),
2915 		ab8505_powercut_maxtime_read, ab8505_powercut_maxtime_write),
2916 	__ATTR(powercut_restart_max, (S_IRUGO | S_IWUSR | S_IWGRP),
2917 		ab8505_powercut_restart_read, ab8505_powercut_restart_write),
2918 	__ATTR(powercut_timer, S_IRUGO, ab8505_powercut_timer_read, NULL),
2919 	__ATTR(powercut_restart_counter, S_IRUGO,
2920 		ab8505_powercut_restart_counter_read, NULL),
2921 	__ATTR(powercut_enable, (S_IRUGO | S_IWUSR | S_IWGRP),
2922 		ab8505_powercut_read, ab8505_powercut_write),
2923 	__ATTR(powercut_flag, S_IRUGO, ab8505_powercut_flag_read, NULL),
2924 	__ATTR(powercut_debounce_time, (S_IRUGO | S_IWUSR | S_IWGRP),
2925 		ab8505_powercut_debounce_read, ab8505_powercut_debounce_write),
2926 	__ATTR(powercut_enable_status, S_IRUGO,
2927 		ab8505_powercut_enable_status_read, NULL),
2928 };
2929 
2930 static int ab8500_fg_sysfs_psy_create_attrs(struct ab8500_fg *di)
2931 {
2932 	unsigned int i;
2933 
2934 	if (is_ab8505(di->parent)) {
2935 		for (i = 0; i < ARRAY_SIZE(ab8505_fg_sysfs_psy_attrs); i++)
2936 			if (device_create_file(&di->fg_psy->dev,
2937 					       &ab8505_fg_sysfs_psy_attrs[i]))
2938 				goto sysfs_psy_create_attrs_failed_ab8505;
2939 	}
2940 	return 0;
2941 sysfs_psy_create_attrs_failed_ab8505:
2942 	dev_err(&di->fg_psy->dev, "Failed creating sysfs psy attrs for ab8505.\n");
2943 	while (i--)
2944 		device_remove_file(&di->fg_psy->dev,
2945 				   &ab8505_fg_sysfs_psy_attrs[i]);
2946 
2947 	return -EIO;
2948 }
2949 
2950 static void ab8500_fg_sysfs_psy_remove_attrs(struct ab8500_fg *di)
2951 {
2952 	unsigned int i;
2953 
2954 	if (is_ab8505(di->parent)) {
2955 		for (i = 0; i < ARRAY_SIZE(ab8505_fg_sysfs_psy_attrs); i++)
2956 			(void)device_remove_file(&di->fg_psy->dev,
2957 						 &ab8505_fg_sysfs_psy_attrs[i]);
2958 	}
2959 }
2960 
2961 /* Exposure to the sysfs interface <<END>> */
2962 
2963 static int __maybe_unused ab8500_fg_resume(struct device *dev)
2964 {
2965 	struct ab8500_fg *di = dev_get_drvdata(dev);
2966 
2967 	/*
2968 	 * Change state if we're not charging. If we're charging we will wake
2969 	 * up on the FG IRQ
2970 	 */
2971 	if (!di->flags.charging) {
2972 		ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_WAKEUP);
2973 		queue_work(di->fg_wq, &di->fg_work);
2974 	}
2975 
2976 	return 0;
2977 }
2978 
2979 static int __maybe_unused ab8500_fg_suspend(struct device *dev)
2980 {
2981 	struct ab8500_fg *di = dev_get_drvdata(dev);
2982 
2983 	flush_delayed_work(&di->fg_periodic_work);
2984 	flush_work(&di->fg_work);
2985 	flush_work(&di->fg_acc_cur_work);
2986 	flush_delayed_work(&di->fg_reinit_work);
2987 	flush_delayed_work(&di->fg_low_bat_work);
2988 	flush_delayed_work(&di->fg_check_hw_failure_work);
2989 
2990 	/*
2991 	 * If the FG is enabled we will disable it before going to suspend
2992 	 * only if we're not charging
2993 	 */
2994 	if (di->flags.fg_enabled && !di->flags.charging)
2995 		ab8500_fg_coulomb_counter(di, false);
2996 
2997 	return 0;
2998 }
2999 
3000 /* ab8500 fg driver interrupts and their respective isr */
3001 static struct ab8500_fg_interrupts ab8500_fg_irq[] = {
3002 	{"NCONV_ACCU", ab8500_fg_cc_convend_handler},
3003 	{"BATT_OVV", ab8500_fg_batt_ovv_handler},
3004 	{"LOW_BAT_F", ab8500_fg_lowbatf_handler},
3005 	{"CC_INT_CALIB", ab8500_fg_cc_int_calib_handler},
3006 	{"CCEOC", ab8500_fg_cc_data_end_handler},
3007 };
3008 
3009 static char *supply_interface[] = {
3010 	"ab8500_chargalg",
3011 	"ab8500_usb",
3012 };
3013 
3014 static const struct power_supply_desc ab8500_fg_desc = {
3015 	.name			= "ab8500_fg",
3016 	.type			= POWER_SUPPLY_TYPE_BATTERY,
3017 	.properties		= ab8500_fg_props,
3018 	.num_properties		= ARRAY_SIZE(ab8500_fg_props),
3019 	.get_property		= ab8500_fg_get_property,
3020 	.external_power_changed	= ab8500_fg_external_power_changed,
3021 };
3022 
3023 static int ab8500_fg_bind(struct device *dev, struct device *master,
3024 			  void *data)
3025 {
3026 	struct ab8500_fg *di = dev_get_drvdata(dev);
3027 
3028 	/* Create a work queue for running the FG algorithm */
3029 	di->fg_wq = alloc_ordered_workqueue("ab8500_fg_wq", WQ_MEM_RECLAIM);
3030 	if (di->fg_wq == NULL) {
3031 		dev_err(dev, "failed to create work queue\n");
3032 		return -ENOMEM;
3033 	}
3034 
3035 	di->bat_cap.max_mah_design = di->bm->bi->charge_full_design_uah;
3036 	di->bat_cap.max_mah = di->bat_cap.max_mah_design;
3037 	di->vbat_nom_uv = di->bm->bi->voltage_max_design_uv;
3038 
3039 	/* Start the coulomb counter */
3040 	ab8500_fg_coulomb_counter(di, true);
3041 	/* Run the FG algorithm */
3042 	queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
3043 
3044 	return 0;
3045 }
3046 
3047 static void ab8500_fg_unbind(struct device *dev, struct device *master,
3048 			     void *data)
3049 {
3050 	struct ab8500_fg *di = dev_get_drvdata(dev);
3051 	int ret;
3052 
3053 	/* Disable coulomb counter */
3054 	ret = ab8500_fg_coulomb_counter(di, false);
3055 	if (ret)
3056 		dev_err(dev, "failed to disable coulomb counter\n");
3057 
3058 	destroy_workqueue(di->fg_wq);
3059 	flush_scheduled_work();
3060 }
3061 
3062 static const struct component_ops ab8500_fg_component_ops = {
3063 	.bind = ab8500_fg_bind,
3064 	.unbind = ab8500_fg_unbind,
3065 };
3066 
3067 static int ab8500_fg_probe(struct platform_device *pdev)
3068 {
3069 	struct device *dev = &pdev->dev;
3070 	struct power_supply_config psy_cfg = {};
3071 	struct ab8500_fg *di;
3072 	int i, irq;
3073 	int ret = 0;
3074 
3075 	di = devm_kzalloc(dev, sizeof(*di), GFP_KERNEL);
3076 	if (!di)
3077 		return -ENOMEM;
3078 
3079 	di->bm = &ab8500_bm_data;
3080 
3081 	mutex_init(&di->cc_lock);
3082 
3083 	/* get parent data */
3084 	di->dev = dev;
3085 	di->parent = dev_get_drvdata(pdev->dev.parent);
3086 
3087 	di->main_bat_v = devm_iio_channel_get(dev, "main_bat_v");
3088 	if (IS_ERR(di->main_bat_v)) {
3089 		ret = dev_err_probe(dev, PTR_ERR(di->main_bat_v),
3090 				    "failed to get main battery ADC channel\n");
3091 		return ret;
3092 	}
3093 
3094 	psy_cfg.supplied_to = supply_interface;
3095 	psy_cfg.num_supplicants = ARRAY_SIZE(supply_interface);
3096 	psy_cfg.drv_data = di;
3097 
3098 	di->init_capacity = true;
3099 
3100 	ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
3101 	ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
3102 
3103 	/* Init work for running the fg algorithm instantly */
3104 	INIT_WORK(&di->fg_work, ab8500_fg_instant_work);
3105 
3106 	/* Init work for getting the battery accumulated current */
3107 	INIT_WORK(&di->fg_acc_cur_work, ab8500_fg_acc_cur_work);
3108 
3109 	/* Init work for reinitialising the fg algorithm */
3110 	INIT_DEFERRABLE_WORK(&di->fg_reinit_work,
3111 		ab8500_fg_reinit_work);
3112 
3113 	/* Work delayed Queue to run the state machine */
3114 	INIT_DEFERRABLE_WORK(&di->fg_periodic_work,
3115 		ab8500_fg_periodic_work);
3116 
3117 	/* Work to check low battery condition */
3118 	INIT_DEFERRABLE_WORK(&di->fg_low_bat_work,
3119 		ab8500_fg_low_bat_work);
3120 
3121 	/* Init work for HW failure check */
3122 	INIT_DEFERRABLE_WORK(&di->fg_check_hw_failure_work,
3123 		ab8500_fg_check_hw_failure_work);
3124 
3125 	/* Reset battery low voltage flag */
3126 	di->flags.low_bat = false;
3127 
3128 	/* Initialize low battery counter */
3129 	di->low_bat_cnt = 10;
3130 
3131 	/* Initialize OVV, and other registers */
3132 	ret = ab8500_fg_init_hw_registers(di);
3133 	if (ret) {
3134 		dev_err(dev, "failed to initialize registers\n");
3135 		return ret;
3136 	}
3137 
3138 	/* Consider battery unknown until we're informed otherwise */
3139 	di->flags.batt_unknown = true;
3140 	di->flags.batt_id_received = false;
3141 
3142 	/* Register FG power supply class */
3143 	di->fg_psy = devm_power_supply_register(dev, &ab8500_fg_desc, &psy_cfg);
3144 	if (IS_ERR(di->fg_psy)) {
3145 		dev_err(dev, "failed to register FG psy\n");
3146 		return PTR_ERR(di->fg_psy);
3147 	}
3148 
3149 	di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
3150 
3151 	/*
3152 	 * Initialize completion used to notify completion and start
3153 	 * of inst current
3154 	 */
3155 	init_completion(&di->ab8500_fg_started);
3156 	init_completion(&di->ab8500_fg_complete);
3157 
3158 	/* Register primary interrupt handlers */
3159 	for (i = 0; i < ARRAY_SIZE(ab8500_fg_irq); i++) {
3160 		irq = platform_get_irq_byname(pdev, ab8500_fg_irq[i].name);
3161 		if (irq < 0)
3162 			return irq;
3163 
3164 		ret = devm_request_threaded_irq(dev, irq, NULL,
3165 				  ab8500_fg_irq[i].isr,
3166 				  IRQF_SHARED | IRQF_NO_SUSPEND | IRQF_ONESHOT,
3167 				  ab8500_fg_irq[i].name, di);
3168 
3169 		if (ret != 0) {
3170 			dev_err(dev, "failed to request %s IRQ %d: %d\n",
3171 				ab8500_fg_irq[i].name, irq, ret);
3172 			return ret;
3173 		}
3174 		dev_dbg(dev, "Requested %s IRQ %d: %d\n",
3175 			ab8500_fg_irq[i].name, irq, ret);
3176 	}
3177 
3178 	di->irq = platform_get_irq_byname(pdev, "CCEOC");
3179 	disable_irq(di->irq);
3180 	di->nbr_cceoc_irq_cnt = 0;
3181 
3182 	platform_set_drvdata(pdev, di);
3183 
3184 	ret = ab8500_fg_sysfs_init(di);
3185 	if (ret) {
3186 		dev_err(dev, "failed to create sysfs entry\n");
3187 		return ret;
3188 	}
3189 
3190 	ret = ab8500_fg_sysfs_psy_create_attrs(di);
3191 	if (ret) {
3192 		dev_err(dev, "failed to create FG psy\n");
3193 		ab8500_fg_sysfs_exit(di);
3194 		return ret;
3195 	}
3196 
3197 	/* Calibrate the fg first time */
3198 	di->flags.calibrate = true;
3199 	di->calib_state = AB8500_FG_CALIB_INIT;
3200 
3201 	/* Use room temp as default value until we get an update from driver. */
3202 	di->bat_temp = 210;
3203 
3204 	list_add_tail(&di->node, &ab8500_fg_list);
3205 
3206 	return component_add(dev, &ab8500_fg_component_ops);
3207 }
3208 
3209 static int ab8500_fg_remove(struct platform_device *pdev)
3210 {
3211 	int ret = 0;
3212 	struct ab8500_fg *di = platform_get_drvdata(pdev);
3213 
3214 	component_del(&pdev->dev, &ab8500_fg_component_ops);
3215 	list_del(&di->node);
3216 	ab8500_fg_sysfs_exit(di);
3217 	ab8500_fg_sysfs_psy_remove_attrs(di);
3218 
3219 	return ret;
3220 }
3221 
3222 static SIMPLE_DEV_PM_OPS(ab8500_fg_pm_ops, ab8500_fg_suspend, ab8500_fg_resume);
3223 
3224 static const struct of_device_id ab8500_fg_match[] = {
3225 	{ .compatible = "stericsson,ab8500-fg", },
3226 	{ },
3227 };
3228 MODULE_DEVICE_TABLE(of, ab8500_fg_match);
3229 
3230 struct platform_driver ab8500_fg_driver = {
3231 	.probe = ab8500_fg_probe,
3232 	.remove = ab8500_fg_remove,
3233 	.driver = {
3234 		.name = "ab8500-fg",
3235 		.of_match_table = ab8500_fg_match,
3236 		.pm = &ab8500_fg_pm_ops,
3237 	},
3238 };
3239 MODULE_LICENSE("GPL v2");
3240 MODULE_AUTHOR("Johan Palsson, Karl Komierowski");
3241 MODULE_ALIAS("platform:ab8500-fg");
3242 MODULE_DESCRIPTION("AB8500 Fuel Gauge driver");
3243