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