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