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