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