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