2 * Copyright (C) ST-Ericsson AB 2012
4 * Main and Back-up battery management driver.
6 * Note: Backup battery management is required in case of Li-Ion battery and not
7 * for capacitive battery. HREF boards have capacitive battery and hence backup
8 * battery management is not used and the supported code is available in this
11 * License Terms: GNU General Public License v2
13 * Johan Palsson <johan.palsson@stericsson.com>
14 * Karl Komierowski <karl.komierowski@stericsson.com>
15 * Arun R Murthy <arun.murthy@stericsson.com>
18 #include <linux/init.h>
19 #include <linux/module.h>
20 #include <linux/device.h>
21 #include <linux/interrupt.h>
22 #include <linux/platform_device.h>
23 #include <linux/power_supply.h>
24 #include <linux/kobject.h>
25 #include <linux/slab.h>
26 #include <linux/delay.h>
27 #include <linux/time.h>
29 #include <linux/completion.h>
30 #include <linux/mfd/core.h>
31 #include <linux/mfd/abx500.h>
32 #include <linux/mfd/abx500/ab8500.h>
33 #include <linux/mfd/abx500/ab8500-bm.h>
34 #include <linux/mfd/abx500/ab8500-gpadc.h>
36 #define MILLI_TO_MICRO 1000
37 #define FG_LSB_IN_MA 1627
38 #define QLSB_NANO_AMP_HOURS_X10 1129
39 #define INS_CURR_TIMEOUT (3 * HZ)
41 #define SEC_TO_SAMPLE(S) (S * 4)
43 #define NBR_AVG_SAMPLES 20
45 #define LOW_BAT_CHECK_INTERVAL (2 * HZ)
47 #define VALID_CAPACITY_SEC (45 * 60) /* 45 minutes */
48 #define BATT_OK_MIN 2360 /* mV */
49 #define BATT_OK_INCREMENT 50 /* mV */
50 #define BATT_OK_MAX_NR_INCREMENTS 0xE
55 #define interpolate(x, x1, y1, x2, y2) \
56 ((y1) + ((((y2) - (y1)) * ((x) - (x1))) / ((x2) - (x1))));
58 #define to_ab8500_fg_device_info(x) container_of((x), \
59 struct ab8500_fg, fg_psy);
62 * struct ab8500_fg_interrupts - ab8500 fg interupts
63 * @name: name of the interrupt
64 * @isr function pointer to the isr
66 struct ab8500_fg_interrupts {
68 irqreturn_t (*isr)(int irq, void *data);
71 enum ab8500_fg_discharge_state {
72 AB8500_FG_DISCHARGE_INIT,
73 AB8500_FG_DISCHARGE_INITMEASURING,
74 AB8500_FG_DISCHARGE_INIT_RECOVERY,
75 AB8500_FG_DISCHARGE_RECOVERY,
76 AB8500_FG_DISCHARGE_READOUT_INIT,
77 AB8500_FG_DISCHARGE_READOUT,
78 AB8500_FG_DISCHARGE_WAKEUP,
81 static char *discharge_state[] = {
83 "DISCHARGE_INITMEASURING",
84 "DISCHARGE_INIT_RECOVERY",
86 "DISCHARGE_READOUT_INIT",
91 enum ab8500_fg_charge_state {
92 AB8500_FG_CHARGE_INIT,
93 AB8500_FG_CHARGE_READOUT,
96 static char *charge_state[] = {
101 enum ab8500_fg_calibration_state {
102 AB8500_FG_CALIB_INIT,
103 AB8500_FG_CALIB_WAIT,
107 struct ab8500_fg_avg_cap {
109 int samples[NBR_AVG_SAMPLES];
110 __kernel_time_t time_stamps[NBR_AVG_SAMPLES];
116 struct ab8500_fg_cap_scaling {
119 int disable_cap_level;
123 struct ab8500_fg_battery_capacity {
133 struct ab8500_fg_cap_scaling cap_scale;
136 struct ab8500_fg_flags {
148 bool batt_id_received;
151 struct inst_curr_result_list {
152 struct list_head list;
157 * struct ab8500_fg - ab8500 FG device information
158 * @dev: Pointer to the structure device
159 * @node: a list of AB8500 FGs, hence prepared for reentrance
160 * @irq holds the CCEOC interrupt number
161 * @vbat: Battery voltage in mV
162 * @vbat_nom: Nominal battery voltage in mV
163 * @inst_curr: Instantenous battery current in mA
164 * @avg_curr: Average battery current in mA
165 * @bat_temp battery temperature
166 * @fg_samples: Number of samples used in the FG accumulation
167 * @accu_charge: Accumulated charge from the last conversion
168 * @recovery_cnt: Counter for recovery mode
169 * @high_curr_cnt: Counter for high current mode
170 * @init_cnt: Counter for init mode
171 * @nbr_cceoc_irq_cnt Counter for number of CCEOC irqs received since enabled
172 * @recovery_needed: Indicate if recovery is needed
173 * @high_curr_mode: Indicate if we're in high current mode
174 * @init_capacity: Indicate if initial capacity measuring should be done
175 * @turn_off_fg: True if fg was off before current measurement
176 * @calib_state State during offset calibration
177 * @discharge_state: Current discharge state
178 * @charge_state: Current charge state
179 * @ab8500_fg_started Completion struct used for the instant current start
180 * @ab8500_fg_complete Completion struct used for the instant current reading
181 * @flags: Structure for information about events triggered
182 * @bat_cap: Structure for battery capacity specific parameters
183 * @avg_cap: Average capacity filter
184 * @parent: Pointer to the struct ab8500
185 * @gpadc: Pointer to the struct gpadc
186 * @bm: Platform specific battery management information
187 * @fg_psy: Structure that holds the FG specific battery properties
188 * @fg_wq: Work queue for running the FG algorithm
189 * @fg_periodic_work: Work to run the FG algorithm periodically
190 * @fg_low_bat_work: Work to check low bat condition
191 * @fg_reinit_work Work used to reset and reinitialise the FG algorithm
192 * @fg_work: Work to run the FG algorithm instantly
193 * @fg_acc_cur_work: Work to read the FG accumulator
194 * @fg_check_hw_failure_work: Work for checking HW state
195 * @cc_lock: Mutex for locking the CC
196 * @fg_kobject: Structure of type kobject
200 struct list_head node;
212 int nbr_cceoc_irq_cnt;
213 bool recovery_needed;
217 enum ab8500_fg_calibration_state calib_state;
218 enum ab8500_fg_discharge_state discharge_state;
219 enum ab8500_fg_charge_state charge_state;
220 struct completion ab8500_fg_started;
221 struct completion ab8500_fg_complete;
222 struct ab8500_fg_flags flags;
223 struct ab8500_fg_battery_capacity bat_cap;
224 struct ab8500_fg_avg_cap avg_cap;
225 struct ab8500 *parent;
226 struct ab8500_gpadc *gpadc;
227 struct abx500_bm_data *bm;
228 struct power_supply fg_psy;
229 struct workqueue_struct *fg_wq;
230 struct delayed_work fg_periodic_work;
231 struct delayed_work fg_low_bat_work;
232 struct delayed_work fg_reinit_work;
233 struct work_struct fg_work;
234 struct work_struct fg_acc_cur_work;
235 struct delayed_work fg_check_hw_failure_work;
236 struct mutex cc_lock;
237 struct kobject fg_kobject;
239 static LIST_HEAD(ab8500_fg_list);
242 * ab8500_fg_get() - returns a reference to the primary AB8500 fuel gauge
243 * (i.e. the first fuel gauge in the instance list)
245 struct ab8500_fg *ab8500_fg_get(void)
247 struct ab8500_fg *fg;
249 if (list_empty(&ab8500_fg_list))
252 fg = list_first_entry(&ab8500_fg_list, struct ab8500_fg, node);
256 /* Main battery properties */
257 static enum power_supply_property ab8500_fg_props[] = {
258 POWER_SUPPLY_PROP_VOLTAGE_NOW,
259 POWER_SUPPLY_PROP_CURRENT_NOW,
260 POWER_SUPPLY_PROP_CURRENT_AVG,
261 POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
262 POWER_SUPPLY_PROP_ENERGY_FULL,
263 POWER_SUPPLY_PROP_ENERGY_NOW,
264 POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
265 POWER_SUPPLY_PROP_CHARGE_FULL,
266 POWER_SUPPLY_PROP_CHARGE_NOW,
267 POWER_SUPPLY_PROP_CAPACITY,
268 POWER_SUPPLY_PROP_CAPACITY_LEVEL,
272 * This array maps the raw hex value to lowbat voltage used by the AB8500
273 * Values taken from the UM0836
275 static int ab8500_fg_lowbat_voltage_map[] = {
342 static u8 ab8500_volt_to_regval(int voltage)
346 if (voltage < ab8500_fg_lowbat_voltage_map[0])
349 for (i = 0; i < ARRAY_SIZE(ab8500_fg_lowbat_voltage_map); i++) {
350 if (voltage < ab8500_fg_lowbat_voltage_map[i])
354 /* If not captured above, return index of last element */
355 return (u8) ARRAY_SIZE(ab8500_fg_lowbat_voltage_map) - 1;
359 * ab8500_fg_is_low_curr() - Low or high current mode
360 * @di: pointer to the ab8500_fg structure
361 * @curr: the current to base or our decision on
363 * Low current mode if the current consumption is below a certain threshold
365 static int ab8500_fg_is_low_curr(struct ab8500_fg *di, int curr)
368 * We want to know if we're in low current mode
370 if (curr > -di->bm->fg_params->high_curr_threshold)
377 * ab8500_fg_add_cap_sample() - Add capacity to average filter
378 * @di: pointer to the ab8500_fg structure
379 * @sample: the capacity in mAh to add to the filter
381 * A capacity is added to the filter and a new mean capacity is calculated and
384 static int ab8500_fg_add_cap_sample(struct ab8500_fg *di, int sample)
387 struct ab8500_fg_avg_cap *avg = &di->avg_cap;
392 avg->sum += sample - avg->samples[avg->pos];
393 avg->samples[avg->pos] = sample;
394 avg->time_stamps[avg->pos] = ts.tv_sec;
397 if (avg->pos == NBR_AVG_SAMPLES)
400 if (avg->nbr_samples < NBR_AVG_SAMPLES)
404 * Check the time stamp for each sample. If too old,
405 * replace with latest sample
407 } while (ts.tv_sec - VALID_CAPACITY_SEC > avg->time_stamps[avg->pos]);
409 avg->avg = avg->sum / avg->nbr_samples;
415 * ab8500_fg_clear_cap_samples() - Clear average filter
416 * @di: pointer to the ab8500_fg structure
418 * The capacity filter is is reset to zero.
420 static void ab8500_fg_clear_cap_samples(struct ab8500_fg *di)
423 struct ab8500_fg_avg_cap *avg = &di->avg_cap;
426 avg->nbr_samples = 0;
430 for (i = 0; i < NBR_AVG_SAMPLES; i++) {
432 avg->time_stamps[i] = 0;
437 * ab8500_fg_fill_cap_sample() - Fill average filter
438 * @di: pointer to the ab8500_fg structure
439 * @sample: the capacity in mAh to fill the filter with
441 * The capacity filter is filled with a capacity in mAh
443 static void ab8500_fg_fill_cap_sample(struct ab8500_fg *di, int sample)
447 struct ab8500_fg_avg_cap *avg = &di->avg_cap;
451 for (i = 0; i < NBR_AVG_SAMPLES; i++) {
452 avg->samples[i] = sample;
453 avg->time_stamps[i] = ts.tv_sec;
457 avg->nbr_samples = NBR_AVG_SAMPLES;
458 avg->sum = sample * NBR_AVG_SAMPLES;
463 * ab8500_fg_coulomb_counter() - enable coulomb counter
464 * @di: pointer to the ab8500_fg structure
465 * @enable: enable/disable
467 * Enable/Disable coulomb counter.
468 * On failure returns negative value.
470 static int ab8500_fg_coulomb_counter(struct ab8500_fg *di, bool enable)
473 mutex_lock(&di->cc_lock);
475 /* To be able to reprogram the number of samples, we have to
476 * first stop the CC and then enable it again */
477 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
478 AB8500_RTC_CC_CONF_REG, 0x00);
482 /* Program the samples */
483 ret = abx500_set_register_interruptible(di->dev,
484 AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
490 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
491 AB8500_RTC_CC_CONF_REG,
492 (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
496 di->flags.fg_enabled = true;
498 /* Clear any pending read requests */
499 ret = abx500_mask_and_set_register_interruptible(di->dev,
500 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
501 (RESET_ACCU | READ_REQ), 0);
505 ret = abx500_set_register_interruptible(di->dev,
506 AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU_CTRL, 0);
511 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
512 AB8500_RTC_CC_CONF_REG, 0);
516 di->flags.fg_enabled = false;
519 dev_dbg(di->dev, " CC enabled: %d Samples: %d\n",
520 enable, di->fg_samples);
522 mutex_unlock(&di->cc_lock);
526 dev_err(di->dev, "%s Enabling coulomb counter failed\n", __func__);
527 mutex_unlock(&di->cc_lock);
532 * ab8500_fg_inst_curr_start() - start battery instantaneous current
533 * @di: pointer to the ab8500_fg structure
535 * Returns 0 or error code
536 * Note: This is part "one" and has to be called before
537 * ab8500_fg_inst_curr_finalize()
539 int ab8500_fg_inst_curr_start(struct ab8500_fg *di)
544 mutex_lock(&di->cc_lock);
546 di->nbr_cceoc_irq_cnt = 0;
547 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
548 AB8500_RTC_CC_CONF_REG, ®_val);
552 if (!(reg_val & CC_PWR_UP_ENA)) {
553 dev_dbg(di->dev, "%s Enable FG\n", __func__);
554 di->turn_off_fg = true;
556 /* Program the samples */
557 ret = abx500_set_register_interruptible(di->dev,
558 AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
564 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
565 AB8500_RTC_CC_CONF_REG,
566 (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
570 di->turn_off_fg = false;
574 INIT_COMPLETION(di->ab8500_fg_started);
575 INIT_COMPLETION(di->ab8500_fg_complete);
578 /* Note: cc_lock is still locked */
581 mutex_unlock(&di->cc_lock);
586 * ab8500_fg_inst_curr_started() - check if fg conversion has started
587 * @di: pointer to the ab8500_fg structure
589 * Returns 1 if conversion started, 0 if still waiting
591 int ab8500_fg_inst_curr_started(struct ab8500_fg *di)
593 return completion_done(&di->ab8500_fg_started);
597 * ab8500_fg_inst_curr_done() - check if fg conversion is done
598 * @di: pointer to the ab8500_fg structure
600 * Returns 1 if conversion done, 0 if still waiting
602 int ab8500_fg_inst_curr_done(struct ab8500_fg *di)
604 return completion_done(&di->ab8500_fg_complete);
608 * ab8500_fg_inst_curr_finalize() - battery instantaneous current
609 * @di: pointer to the ab8500_fg structure
610 * @res: battery instantenous current(on success)
612 * Returns 0 or an error code
613 * Note: This is part "two" and has to be called at earliest 250 ms
614 * after ab8500_fg_inst_curr_start()
616 int ab8500_fg_inst_curr_finalize(struct ab8500_fg *di, int *res)
623 if (!completion_done(&di->ab8500_fg_complete)) {
624 timeout = wait_for_completion_timeout(
625 &di->ab8500_fg_complete,
627 dev_dbg(di->dev, "Finalize time: %d ms\n",
628 ((INS_CURR_TIMEOUT - timeout) * 1000) / HZ);
631 disable_irq(di->irq);
632 di->nbr_cceoc_irq_cnt = 0;
633 dev_err(di->dev, "completion timed out [%d]\n",
639 disable_irq(di->irq);
640 di->nbr_cceoc_irq_cnt = 0;
642 ret = abx500_mask_and_set_register_interruptible(di->dev,
643 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
646 /* 100uS between read request and read is needed */
647 usleep_range(100, 100);
649 /* Read CC Sample conversion value Low and high */
650 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
651 AB8500_GASG_CC_SMPL_CNVL_REG, &low);
655 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
656 AB8500_GASG_CC_SMPL_CNVH_REG, &high);
661 * negative value for Discharging
662 * convert 2's compliment into decimal
665 val = (low | (high << 8) | 0xFFFFE000);
667 val = (low | (high << 8));
670 * Convert to unit value in mA
671 * Full scale input voltage is
672 * 66.660mV => LSB = 66.660mV/(4096*res) = 1.627mA
673 * Given a 250ms conversion cycle time the LSB corresponds
674 * to 112.9 nAh. Convert to current by dividing by the conversion
675 * time in hours (250ms = 1 / (3600 * 4)h)
676 * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
678 val = (val * QLSB_NANO_AMP_HOURS_X10 * 36 * 4) /
679 (1000 * di->bm->fg_res);
681 if (di->turn_off_fg) {
682 dev_dbg(di->dev, "%s Disable FG\n", __func__);
684 /* Clear any pending read requests */
685 ret = abx500_set_register_interruptible(di->dev,
686 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG, 0);
691 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
692 AB8500_RTC_CC_CONF_REG, 0);
696 mutex_unlock(&di->cc_lock);
701 mutex_unlock(&di->cc_lock);
706 * ab8500_fg_inst_curr_blocking() - battery instantaneous current
707 * @di: pointer to the ab8500_fg structure
708 * @res: battery instantenous current(on success)
710 * Returns 0 else error code
712 int ab8500_fg_inst_curr_blocking(struct ab8500_fg *di)
718 ret = ab8500_fg_inst_curr_start(di);
720 dev_err(di->dev, "Failed to initialize fg_inst\n");
724 /* Wait for CC to actually start */
725 if (!completion_done(&di->ab8500_fg_started)) {
726 timeout = wait_for_completion_timeout(
727 &di->ab8500_fg_started,
729 dev_dbg(di->dev, "Start time: %d ms\n",
730 ((INS_CURR_TIMEOUT - timeout) * 1000) / HZ);
733 dev_err(di->dev, "completion timed out [%d]\n",
739 ret = ab8500_fg_inst_curr_finalize(di, &res);
741 dev_err(di->dev, "Failed to finalize fg_inst\n");
745 dev_dbg(di->dev, "%s instant current: %d", __func__, res);
748 disable_irq(di->irq);
749 mutex_unlock(&di->cc_lock);
754 * ab8500_fg_acc_cur_work() - average battery current
755 * @work: pointer to the work_struct structure
757 * Updated the average battery current obtained from the
760 static void ab8500_fg_acc_cur_work(struct work_struct *work)
766 struct ab8500_fg *di = container_of(work,
767 struct ab8500_fg, fg_acc_cur_work);
769 mutex_lock(&di->cc_lock);
770 ret = abx500_set_register_interruptible(di->dev, AB8500_GAS_GAUGE,
771 AB8500_GASG_CC_NCOV_ACCU_CTRL, RD_NCONV_ACCU_REQ);
775 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
776 AB8500_GASG_CC_NCOV_ACCU_LOW, &low);
780 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
781 AB8500_GASG_CC_NCOV_ACCU_MED, &med);
785 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
786 AB8500_GASG_CC_NCOV_ACCU_HIGH, &high);
790 /* Check for sign bit in case of negative value, 2's compliment */
792 val = (low | (med << 8) | (high << 16) | 0xFFE00000);
794 val = (low | (med << 8) | (high << 16));
798 * Given a 250ms conversion cycle time the LSB corresponds
800 * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
802 di->accu_charge = (val * QLSB_NANO_AMP_HOURS_X10) /
803 (100 * di->bm->fg_res);
806 * Convert to unit value in mA
807 * Full scale input voltage is
808 * 66.660mV => LSB = 66.660mV/(4096*res) = 1.627mA
809 * Given a 250ms conversion cycle time the LSB corresponds
810 * to 112.9 nAh. Convert to current by dividing by the conversion
811 * time in hours (= samples / (3600 * 4)h)
812 * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
814 di->avg_curr = (val * QLSB_NANO_AMP_HOURS_X10 * 36) /
815 (1000 * di->bm->fg_res * (di->fg_samples / 4));
817 di->flags.conv_done = true;
819 mutex_unlock(&di->cc_lock);
821 queue_work(di->fg_wq, &di->fg_work);
826 "Failed to read or write gas gauge registers\n");
827 mutex_unlock(&di->cc_lock);
828 queue_work(di->fg_wq, &di->fg_work);
832 * ab8500_fg_bat_voltage() - get battery voltage
833 * @di: pointer to the ab8500_fg structure
835 * Returns battery voltage(on success) else error code
837 static int ab8500_fg_bat_voltage(struct ab8500_fg *di)
842 vbat = ab8500_gpadc_convert(di->gpadc, MAIN_BAT_V);
845 "%s gpadc conversion failed, using previous value\n",
855 * ab8500_fg_volt_to_capacity() - Voltage based capacity
856 * @di: pointer to the ab8500_fg structure
857 * @voltage: The voltage to convert to a capacity
859 * Returns battery capacity in per mille based on voltage
861 static int ab8500_fg_volt_to_capacity(struct ab8500_fg *di, int voltage)
864 struct abx500_v_to_cap *tbl;
867 tbl = di->bm->bat_type[di->bm->batt_id].v_to_cap_tbl,
868 tbl_size = di->bm->bat_type[di->bm->batt_id].n_v_cap_tbl_elements;
870 for (i = 0; i < tbl_size; ++i) {
871 if (voltage > tbl[i].voltage)
875 if ((i > 0) && (i < tbl_size)) {
876 cap = interpolate(voltage,
878 tbl[i].capacity * 10,
880 tbl[i-1].capacity * 10);
887 dev_dbg(di->dev, "%s Vbat: %d, Cap: %d per mille",
888 __func__, voltage, cap);
894 * ab8500_fg_uncomp_volt_to_capacity() - Uncompensated voltage based capacity
895 * @di: pointer to the ab8500_fg structure
897 * Returns battery capacity based on battery voltage that is not compensated
898 * for the voltage drop due to the load
900 static int ab8500_fg_uncomp_volt_to_capacity(struct ab8500_fg *di)
902 di->vbat = ab8500_fg_bat_voltage(di);
903 return ab8500_fg_volt_to_capacity(di, di->vbat);
907 * ab8500_fg_battery_resistance() - Returns the battery inner resistance
908 * @di: pointer to the ab8500_fg structure
910 * Returns battery inner resistance added with the fuel gauge resistor value
911 * to get the total resistance in the whole link from gnd to bat+ node.
913 static int ab8500_fg_battery_resistance(struct ab8500_fg *di)
916 struct batres_vs_temp *tbl;
919 tbl = di->bm->bat_type[di->bm->batt_id].batres_tbl;
920 tbl_size = di->bm->bat_type[di->bm->batt_id].n_batres_tbl_elements;
922 for (i = 0; i < tbl_size; ++i) {
923 if (di->bat_temp / 10 > tbl[i].temp)
927 if ((i > 0) && (i < tbl_size)) {
928 resist = interpolate(di->bat_temp / 10,
934 resist = tbl[0].resist;
936 resist = tbl[tbl_size - 1].resist;
939 dev_dbg(di->dev, "%s Temp: %d battery internal resistance: %d"
940 " fg resistance %d, total: %d (mOhm)\n",
941 __func__, di->bat_temp, resist, di->bm->fg_res / 10,
942 (di->bm->fg_res / 10) + resist);
944 /* fg_res variable is in 0.1mOhm */
945 resist += di->bm->fg_res / 10;
951 * ab8500_fg_load_comp_volt_to_capacity() - Load compensated voltage based capacity
952 * @di: pointer to the ab8500_fg structure
954 * Returns battery capacity based on battery voltage that is load compensated
955 * for the voltage drop
957 static int ab8500_fg_load_comp_volt_to_capacity(struct ab8500_fg *di)
963 ab8500_fg_inst_curr_start(di);
966 vbat += ab8500_fg_bat_voltage(di);
968 usleep_range(5000, 6000);
969 } while (!ab8500_fg_inst_curr_done(di));
971 ab8500_fg_inst_curr_finalize(di, &di->inst_curr);
974 res = ab8500_fg_battery_resistance(di);
976 /* Use Ohms law to get the load compensated voltage */
977 vbat_comp = di->vbat - (di->inst_curr * res) / 1000;
979 dev_dbg(di->dev, "%s Measured Vbat: %dmV,Compensated Vbat %dmV, "
980 "R: %dmOhm, Current: %dmA Vbat Samples: %d\n",
981 __func__, di->vbat, vbat_comp, res, di->inst_curr, i);
983 return ab8500_fg_volt_to_capacity(di, vbat_comp);
987 * ab8500_fg_convert_mah_to_permille() - Capacity in mAh to permille
988 * @di: pointer to the ab8500_fg structure
989 * @cap_mah: capacity in mAh
991 * Converts capacity in mAh to capacity in permille
993 static int ab8500_fg_convert_mah_to_permille(struct ab8500_fg *di, int cap_mah)
995 return (cap_mah * 1000) / di->bat_cap.max_mah_design;
999 * ab8500_fg_convert_permille_to_mah() - Capacity in permille to mAh
1000 * @di: pointer to the ab8500_fg structure
1001 * @cap_pm: capacity in permille
1003 * Converts capacity in permille to capacity in mAh
1005 static int ab8500_fg_convert_permille_to_mah(struct ab8500_fg *di, int cap_pm)
1007 return cap_pm * di->bat_cap.max_mah_design / 1000;
1011 * ab8500_fg_convert_mah_to_uwh() - Capacity in mAh to uWh
1012 * @di: pointer to the ab8500_fg structure
1013 * @cap_mah: capacity in mAh
1015 * Converts capacity in mAh to capacity in uWh
1017 static int ab8500_fg_convert_mah_to_uwh(struct ab8500_fg *di, int cap_mah)
1022 div_res = ((u64) cap_mah) * ((u64) di->vbat_nom);
1023 div_rem = do_div(div_res, 1000);
1025 /* Make sure to round upwards if necessary */
1026 if (div_rem >= 1000 / 2)
1029 return (int) div_res;
1033 * ab8500_fg_calc_cap_charging() - Calculate remaining capacity while charging
1034 * @di: pointer to the ab8500_fg structure
1036 * Return the capacity in mAh based on previous calculated capcity and the FG
1037 * accumulator register value. The filter is filled with this capacity
1039 static int ab8500_fg_calc_cap_charging(struct ab8500_fg *di)
1041 dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1046 /* Capacity should not be less than 0 */
1047 if (di->bat_cap.mah + di->accu_charge > 0)
1048 di->bat_cap.mah += di->accu_charge;
1050 di->bat_cap.mah = 0;
1052 * We force capacity to 100% once when the algorithm
1053 * reports that it's full.
1055 if (di->bat_cap.mah >= di->bat_cap.max_mah_design ||
1056 di->flags.force_full) {
1057 di->bat_cap.mah = di->bat_cap.max_mah_design;
1060 ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1061 di->bat_cap.permille =
1062 ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1064 /* We need to update battery voltage and inst current when charging */
1065 di->vbat = ab8500_fg_bat_voltage(di);
1066 di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1068 return di->bat_cap.mah;
1072 * ab8500_fg_calc_cap_discharge_voltage() - Capacity in discharge with voltage
1073 * @di: pointer to the ab8500_fg structure
1074 * @comp: if voltage should be load compensated before capacity calc
1076 * Return the capacity in mAh based on the battery voltage. The voltage can
1077 * either be load compensated or not. This value is added to the filter and a
1078 * new mean value is calculated and returned.
1080 static int ab8500_fg_calc_cap_discharge_voltage(struct ab8500_fg *di, bool comp)
1085 permille = ab8500_fg_load_comp_volt_to_capacity(di);
1087 permille = ab8500_fg_uncomp_volt_to_capacity(di);
1089 mah = ab8500_fg_convert_permille_to_mah(di, permille);
1091 di->bat_cap.mah = ab8500_fg_add_cap_sample(di, mah);
1092 di->bat_cap.permille =
1093 ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1095 return di->bat_cap.mah;
1099 * ab8500_fg_calc_cap_discharge_fg() - Capacity in discharge with FG
1100 * @di: pointer to the ab8500_fg structure
1102 * Return the capacity in mAh based on previous calculated capcity and the FG
1103 * accumulator register value. This value is added to the filter and a
1104 * new mean value is calculated and returned.
1106 static int ab8500_fg_calc_cap_discharge_fg(struct ab8500_fg *di)
1108 int permille_volt, permille;
1110 dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1115 /* Capacity should not be less than 0 */
1116 if (di->bat_cap.mah + di->accu_charge > 0)
1117 di->bat_cap.mah += di->accu_charge;
1119 di->bat_cap.mah = 0;
1121 if (di->bat_cap.mah >= di->bat_cap.max_mah_design)
1122 di->bat_cap.mah = di->bat_cap.max_mah_design;
1125 * Check against voltage based capacity. It can not be lower
1126 * than what the uncompensated voltage says
1128 permille = ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1129 permille_volt = ab8500_fg_uncomp_volt_to_capacity(di);
1131 if (permille < permille_volt) {
1132 di->bat_cap.permille = permille_volt;
1133 di->bat_cap.mah = ab8500_fg_convert_permille_to_mah(di,
1134 di->bat_cap.permille);
1136 dev_dbg(di->dev, "%s voltage based: perm %d perm_volt %d\n",
1141 ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1143 ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1144 di->bat_cap.permille =
1145 ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1148 return di->bat_cap.mah;
1152 * ab8500_fg_capacity_level() - Get the battery capacity level
1153 * @di: pointer to the ab8500_fg structure
1155 * Get the battery capacity level based on the capacity in percent
1157 static int ab8500_fg_capacity_level(struct ab8500_fg *di)
1161 percent = di->bat_cap.permille / 10;
1163 if (percent <= di->bm->cap_levels->critical ||
1165 ret = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1166 else if (percent <= di->bm->cap_levels->low)
1167 ret = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1168 else if (percent <= di->bm->cap_levels->normal)
1169 ret = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1170 else if (percent <= di->bm->cap_levels->high)
1171 ret = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
1173 ret = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1179 * ab8500_fg_calculate_scaled_capacity() - Capacity scaling
1180 * @di: pointer to the ab8500_fg structure
1182 * Calculates the capacity to be shown to upper layers. Scales the capacity
1183 * to have 100% as a reference from the actual capacity upon removal of charger
1184 * when charging is in maintenance mode.
1186 static int ab8500_fg_calculate_scaled_capacity(struct ab8500_fg *di)
1188 struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1189 int capacity = di->bat_cap.prev_percent;
1195 * As long as we are in fully charge mode scale the capacity
1198 if (di->flags.fully_charged) {
1199 cs->cap_to_scale[0] = 100;
1200 cs->cap_to_scale[1] =
1201 max(capacity, di->bm->fg_params->maint_thres);
1202 dev_dbg(di->dev, "Scale cap with %d/%d\n",
1203 cs->cap_to_scale[0], cs->cap_to_scale[1]);
1206 /* Calculates the scaled capacity. */
1207 if ((cs->cap_to_scale[0] != cs->cap_to_scale[1])
1208 && (cs->cap_to_scale[1] > 0))
1210 DIV_ROUND_CLOSEST(di->bat_cap.prev_percent *
1211 cs->cap_to_scale[0],
1212 cs->cap_to_scale[1]));
1214 if (di->flags.charging) {
1215 if (capacity < cs->disable_cap_level) {
1216 cs->disable_cap_level = capacity;
1217 dev_dbg(di->dev, "Cap to stop scale lowered %d%%\n",
1218 cs->disable_cap_level);
1219 } else if (!di->flags.fully_charged) {
1220 if (di->bat_cap.prev_percent >=
1221 cs->disable_cap_level) {
1222 dev_dbg(di->dev, "Disabling scaled capacity\n");
1224 capacity = di->bat_cap.prev_percent;
1227 "Waiting in cap to level %d%%\n",
1228 cs->disable_cap_level);
1229 capacity = cs->disable_cap_level;
1238 * ab8500_fg_update_cap_scalers() - Capacity scaling
1239 * @di: pointer to the ab8500_fg structure
1241 * To be called when state change from charge<->discharge to update
1242 * the capacity scalers.
1244 static void ab8500_fg_update_cap_scalers(struct ab8500_fg *di)
1246 struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1250 if (di->flags.charging) {
1251 di->bat_cap.cap_scale.disable_cap_level =
1252 di->bat_cap.cap_scale.scaled_cap;
1253 dev_dbg(di->dev, "Cap to stop scale at charge %d%%\n",
1254 di->bat_cap.cap_scale.disable_cap_level);
1256 if (cs->scaled_cap != 100) {
1257 cs->cap_to_scale[0] = cs->scaled_cap;
1258 cs->cap_to_scale[1] = di->bat_cap.prev_percent;
1260 cs->cap_to_scale[0] = 100;
1261 cs->cap_to_scale[1] =
1262 max(di->bat_cap.prev_percent,
1263 di->bm->fg_params->maint_thres);
1266 dev_dbg(di->dev, "Cap to scale at discharge %d/%d\n",
1267 cs->cap_to_scale[0], cs->cap_to_scale[1]);
1272 * ab8500_fg_check_capacity_limits() - Check if capacity has changed
1273 * @di: pointer to the ab8500_fg structure
1274 * @init: capacity is allowed to go up in init mode
1276 * Check if capacity or capacity limit has changed and notify the system
1277 * about it using the power_supply framework
1279 static void ab8500_fg_check_capacity_limits(struct ab8500_fg *di, bool init)
1281 bool changed = false;
1283 di->bat_cap.level = ab8500_fg_capacity_level(di);
1285 if (di->bat_cap.level != di->bat_cap.prev_level) {
1287 * We do not allow reported capacity level to go up
1288 * unless we're charging or if we're in init
1290 if (!(!di->flags.charging && di->bat_cap.level >
1291 di->bat_cap.prev_level) || init) {
1292 dev_dbg(di->dev, "level changed from %d to %d\n",
1293 di->bat_cap.prev_level,
1295 di->bat_cap.prev_level = di->bat_cap.level;
1298 dev_dbg(di->dev, "level not allowed to go up "
1299 "since no charger is connected: %d to %d\n",
1300 di->bat_cap.prev_level,
1306 * If we have received the LOW_BAT IRQ, set capacity to 0 to initiate
1309 if (di->flags.low_bat) {
1310 dev_dbg(di->dev, "Battery low, set capacity to 0\n");
1311 di->bat_cap.prev_percent = 0;
1312 di->bat_cap.permille = 0;
1313 di->bat_cap.prev_mah = 0;
1314 di->bat_cap.mah = 0;
1316 } else if (di->flags.fully_charged) {
1318 * We report 100% if algorithm reported fully charged
1319 * and show 100% during maintenance charging (scaling).
1321 if (di->flags.force_full) {
1322 di->bat_cap.prev_percent = di->bat_cap.permille / 10;
1323 di->bat_cap.prev_mah = di->bat_cap.mah;
1327 if (!di->bat_cap.cap_scale.enable &&
1328 di->bm->capacity_scaling) {
1329 di->bat_cap.cap_scale.enable = true;
1330 di->bat_cap.cap_scale.cap_to_scale[0] = 100;
1331 di->bat_cap.cap_scale.cap_to_scale[1] =
1332 di->bat_cap.prev_percent;
1333 di->bat_cap.cap_scale.disable_cap_level = 100;
1335 } else if ( di->bat_cap.prev_percent !=
1336 (di->bat_cap.permille) / 10) {
1338 "battery reported full "
1339 "but capacity dropping: %d\n",
1340 di->bat_cap.permille / 10);
1341 di->bat_cap.prev_percent = di->bat_cap.permille / 10;
1342 di->bat_cap.prev_mah = di->bat_cap.mah;
1346 } else if (di->bat_cap.prev_percent != di->bat_cap.permille / 10) {
1347 if (di->bat_cap.permille / 10 == 0) {
1349 * We will not report 0% unless we've got
1350 * the LOW_BAT IRQ, no matter what the FG
1353 di->bat_cap.prev_percent = 1;
1354 di->bat_cap.permille = 1;
1355 di->bat_cap.prev_mah = 1;
1356 di->bat_cap.mah = 1;
1359 } else if (!(!di->flags.charging &&
1360 (di->bat_cap.permille / 10) >
1361 di->bat_cap.prev_percent) || init) {
1363 * We do not allow reported capacity to go up
1364 * unless we're charging or if we're in init
1367 "capacity changed from %d to %d (%d)\n",
1368 di->bat_cap.prev_percent,
1369 di->bat_cap.permille / 10,
1370 di->bat_cap.permille);
1371 di->bat_cap.prev_percent = di->bat_cap.permille / 10;
1372 di->bat_cap.prev_mah = di->bat_cap.mah;
1376 dev_dbg(di->dev, "capacity not allowed to go up since "
1377 "no charger is connected: %d to %d (%d)\n",
1378 di->bat_cap.prev_percent,
1379 di->bat_cap.permille / 10,
1380 di->bat_cap.permille);
1385 if (di->bm->capacity_scaling) {
1386 di->bat_cap.cap_scale.scaled_cap =
1387 ab8500_fg_calculate_scaled_capacity(di);
1389 dev_info(di->dev, "capacity=%d (%d)\n",
1390 di->bat_cap.prev_percent,
1391 di->bat_cap.cap_scale.scaled_cap);
1393 power_supply_changed(&di->fg_psy);
1394 if (di->flags.fully_charged && di->flags.force_full) {
1395 dev_dbg(di->dev, "Battery full, notifying.\n");
1396 di->flags.force_full = false;
1397 sysfs_notify(&di->fg_kobject, NULL, "charge_full");
1399 sysfs_notify(&di->fg_kobject, NULL, "charge_now");
1403 static void ab8500_fg_charge_state_to(struct ab8500_fg *di,
1404 enum ab8500_fg_charge_state new_state)
1406 dev_dbg(di->dev, "Charge state from %d [%s] to %d [%s]\n",
1408 charge_state[di->charge_state],
1410 charge_state[new_state]);
1412 di->charge_state = new_state;
1415 static void ab8500_fg_discharge_state_to(struct ab8500_fg *di,
1416 enum ab8500_fg_discharge_state new_state)
1418 dev_dbg(di->dev, "Disharge state from %d [%s] to %d [%s]\n",
1419 di->discharge_state,
1420 discharge_state[di->discharge_state],
1422 discharge_state[new_state]);
1424 di->discharge_state = new_state;
1428 * ab8500_fg_algorithm_charging() - FG algorithm for when charging
1429 * @di: pointer to the ab8500_fg structure
1431 * Battery capacity calculation state machine for when we're charging
1433 static void ab8500_fg_algorithm_charging(struct ab8500_fg *di)
1436 * If we change to discharge mode
1437 * we should start with recovery
1439 if (di->discharge_state != AB8500_FG_DISCHARGE_INIT_RECOVERY)
1440 ab8500_fg_discharge_state_to(di,
1441 AB8500_FG_DISCHARGE_INIT_RECOVERY);
1443 switch (di->charge_state) {
1444 case AB8500_FG_CHARGE_INIT:
1445 di->fg_samples = SEC_TO_SAMPLE(
1446 di->bm->fg_params->accu_charging);
1448 ab8500_fg_coulomb_counter(di, true);
1449 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_READOUT);
1453 case AB8500_FG_CHARGE_READOUT:
1455 * Read the FG and calculate the new capacity
1457 mutex_lock(&di->cc_lock);
1458 if (!di->flags.conv_done && !di->flags.force_full) {
1459 /* Wasn't the CC IRQ that got us here */
1460 mutex_unlock(&di->cc_lock);
1461 dev_dbg(di->dev, "%s CC conv not done\n",
1466 di->flags.conv_done = false;
1467 mutex_unlock(&di->cc_lock);
1469 ab8500_fg_calc_cap_charging(di);
1477 /* Check capacity limits */
1478 ab8500_fg_check_capacity_limits(di, false);
1481 static void force_capacity(struct ab8500_fg *di)
1485 ab8500_fg_clear_cap_samples(di);
1486 cap = di->bat_cap.user_mah;
1487 if (cap > di->bat_cap.max_mah_design) {
1488 dev_dbg(di->dev, "Remaining cap %d can't be bigger than total"
1489 " %d\n", cap, di->bat_cap.max_mah_design);
1490 cap = di->bat_cap.max_mah_design;
1492 ab8500_fg_fill_cap_sample(di, di->bat_cap.user_mah);
1493 di->bat_cap.permille = ab8500_fg_convert_mah_to_permille(di, cap);
1494 di->bat_cap.mah = cap;
1495 ab8500_fg_check_capacity_limits(di, true);
1498 static bool check_sysfs_capacity(struct ab8500_fg *di)
1500 int cap, lower, upper;
1503 cap = di->bat_cap.user_mah;
1505 cap_permille = ab8500_fg_convert_mah_to_permille(di,
1506 di->bat_cap.user_mah);
1508 lower = di->bat_cap.permille - di->bm->fg_params->user_cap_limit * 10;
1509 upper = di->bat_cap.permille + di->bm->fg_params->user_cap_limit * 10;
1513 /* 1000 is permille, -> 100 percent */
1517 dev_dbg(di->dev, "Capacity limits:"
1518 " (Lower: %d User: %d Upper: %d) [user: %d, was: %d]\n",
1519 lower, cap_permille, upper, cap, di->bat_cap.mah);
1521 /* If within limits, use the saved capacity and exit estimation...*/
1522 if (cap_permille > lower && cap_permille < upper) {
1523 dev_dbg(di->dev, "OK! Using users cap %d uAh now\n", cap);
1527 dev_dbg(di->dev, "Capacity from user out of limits, ignoring");
1532 * ab8500_fg_algorithm_discharging() - FG algorithm for when discharging
1533 * @di: pointer to the ab8500_fg structure
1535 * Battery capacity calculation state machine for when we're discharging
1537 static void ab8500_fg_algorithm_discharging(struct ab8500_fg *di)
1541 /* If we change to charge mode we should start with init */
1542 if (di->charge_state != AB8500_FG_CHARGE_INIT)
1543 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
1545 switch (di->discharge_state) {
1546 case AB8500_FG_DISCHARGE_INIT:
1547 /* We use the FG IRQ to work on */
1549 di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
1550 ab8500_fg_coulomb_counter(di, true);
1551 ab8500_fg_discharge_state_to(di,
1552 AB8500_FG_DISCHARGE_INITMEASURING);
1554 /* Intentional fallthrough */
1555 case AB8500_FG_DISCHARGE_INITMEASURING:
1557 * Discard a number of samples during startup.
1558 * After that, use compensated voltage for a few
1559 * samples to get an initial capacity.
1560 * Then go to READOUT
1562 sleep_time = di->bm->fg_params->init_timer;
1564 /* Discard the first [x] seconds */
1565 if (di->init_cnt > di->bm->fg_params->init_discard_time) {
1566 ab8500_fg_calc_cap_discharge_voltage(di, true);
1568 ab8500_fg_check_capacity_limits(di, true);
1571 di->init_cnt += sleep_time;
1572 if (di->init_cnt > di->bm->fg_params->init_total_time)
1573 ab8500_fg_discharge_state_to(di,
1574 AB8500_FG_DISCHARGE_READOUT_INIT);
1578 case AB8500_FG_DISCHARGE_INIT_RECOVERY:
1579 di->recovery_cnt = 0;
1580 di->recovery_needed = true;
1581 ab8500_fg_discharge_state_to(di,
1582 AB8500_FG_DISCHARGE_RECOVERY);
1584 /* Intentional fallthrough */
1586 case AB8500_FG_DISCHARGE_RECOVERY:
1587 sleep_time = di->bm->fg_params->recovery_sleep_timer;
1590 * We should check the power consumption
1591 * If low, go to READOUT (after x min) or
1592 * RECOVERY_SLEEP if time left.
1593 * If high, go to READOUT
1595 di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1597 if (ab8500_fg_is_low_curr(di, di->inst_curr)) {
1598 if (di->recovery_cnt >
1599 di->bm->fg_params->recovery_total_time) {
1600 di->fg_samples = SEC_TO_SAMPLE(
1601 di->bm->fg_params->accu_high_curr);
1602 ab8500_fg_coulomb_counter(di, true);
1603 ab8500_fg_discharge_state_to(di,
1604 AB8500_FG_DISCHARGE_READOUT);
1605 di->recovery_needed = false;
1607 queue_delayed_work(di->fg_wq,
1608 &di->fg_periodic_work,
1611 di->recovery_cnt += sleep_time;
1613 di->fg_samples = SEC_TO_SAMPLE(
1614 di->bm->fg_params->accu_high_curr);
1615 ab8500_fg_coulomb_counter(di, true);
1616 ab8500_fg_discharge_state_to(di,
1617 AB8500_FG_DISCHARGE_READOUT);
1621 case AB8500_FG_DISCHARGE_READOUT_INIT:
1622 di->fg_samples = SEC_TO_SAMPLE(
1623 di->bm->fg_params->accu_high_curr);
1624 ab8500_fg_coulomb_counter(di, true);
1625 ab8500_fg_discharge_state_to(di,
1626 AB8500_FG_DISCHARGE_READOUT);
1629 case AB8500_FG_DISCHARGE_READOUT:
1630 di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1632 if (ab8500_fg_is_low_curr(di, di->inst_curr)) {
1633 /* Detect mode change */
1634 if (di->high_curr_mode) {
1635 di->high_curr_mode = false;
1636 di->high_curr_cnt = 0;
1639 if (di->recovery_needed) {
1640 ab8500_fg_discharge_state_to(di,
1641 AB8500_FG_DISCHARGE_RECOVERY);
1643 queue_delayed_work(di->fg_wq,
1644 &di->fg_periodic_work, 0);
1649 ab8500_fg_calc_cap_discharge_voltage(di, true);
1651 mutex_lock(&di->cc_lock);
1652 if (!di->flags.conv_done) {
1653 /* Wasn't the CC IRQ that got us here */
1654 mutex_unlock(&di->cc_lock);
1655 dev_dbg(di->dev, "%s CC conv not done\n",
1660 di->flags.conv_done = false;
1661 mutex_unlock(&di->cc_lock);
1663 /* Detect mode change */
1664 if (!di->high_curr_mode) {
1665 di->high_curr_mode = true;
1666 di->high_curr_cnt = 0;
1669 di->high_curr_cnt +=
1670 di->bm->fg_params->accu_high_curr;
1671 if (di->high_curr_cnt >
1672 di->bm->fg_params->high_curr_time)
1673 di->recovery_needed = true;
1675 ab8500_fg_calc_cap_discharge_fg(di);
1678 ab8500_fg_check_capacity_limits(di, false);
1682 case AB8500_FG_DISCHARGE_WAKEUP:
1683 ab8500_fg_coulomb_counter(di, true);
1684 ab8500_fg_calc_cap_discharge_voltage(di, true);
1686 di->fg_samples = SEC_TO_SAMPLE(
1687 di->bm->fg_params->accu_high_curr);
1688 ab8500_fg_coulomb_counter(di, true);
1689 ab8500_fg_discharge_state_to(di,
1690 AB8500_FG_DISCHARGE_READOUT);
1692 ab8500_fg_check_capacity_limits(di, false);
1702 * ab8500_fg_algorithm_calibrate() - Internal columb counter offset calibration
1703 * @di: pointer to the ab8500_fg structure
1706 static void ab8500_fg_algorithm_calibrate(struct ab8500_fg *di)
1710 switch (di->calib_state) {
1711 case AB8500_FG_CALIB_INIT:
1712 dev_dbg(di->dev, "Calibration ongoing...\n");
1714 ret = abx500_mask_and_set_register_interruptible(di->dev,
1715 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1716 CC_INT_CAL_N_AVG_MASK, CC_INT_CAL_SAMPLES_8);
1720 ret = abx500_mask_and_set_register_interruptible(di->dev,
1721 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1722 CC_INTAVGOFFSET_ENA, CC_INTAVGOFFSET_ENA);
1725 di->calib_state = AB8500_FG_CALIB_WAIT;
1727 case AB8500_FG_CALIB_END:
1728 ret = abx500_mask_and_set_register_interruptible(di->dev,
1729 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1730 CC_MUXOFFSET, CC_MUXOFFSET);
1733 di->flags.calibrate = false;
1734 dev_dbg(di->dev, "Calibration done...\n");
1735 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1737 case AB8500_FG_CALIB_WAIT:
1738 dev_dbg(di->dev, "Calibration WFI\n");
1744 /* Something went wrong, don't calibrate then */
1745 dev_err(di->dev, "failed to calibrate the CC\n");
1746 di->flags.calibrate = false;
1747 di->calib_state = AB8500_FG_CALIB_INIT;
1748 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1752 * ab8500_fg_algorithm() - Entry point for the FG algorithm
1753 * @di: pointer to the ab8500_fg structure
1755 * Entry point for the battery capacity calculation state machine
1757 static void ab8500_fg_algorithm(struct ab8500_fg *di)
1759 if (di->flags.calibrate)
1760 ab8500_fg_algorithm_calibrate(di);
1762 if (di->flags.charging)
1763 ab8500_fg_algorithm_charging(di);
1765 ab8500_fg_algorithm_discharging(di);
1768 dev_dbg(di->dev, "[FG_DATA] %d %d %d %d %d %d %d %d %d "
1769 "%d %d %d %d %d %d %d\n",
1770 di->bat_cap.max_mah_design,
1772 di->bat_cap.permille,
1774 di->bat_cap.prev_mah,
1775 di->bat_cap.prev_percent,
1776 di->bat_cap.prev_level,
1783 di->discharge_state,
1785 di->recovery_needed);
1789 * ab8500_fg_periodic_work() - Run the FG state machine periodically
1790 * @work: pointer to the work_struct structure
1792 * Work queue function for periodic work
1794 static void ab8500_fg_periodic_work(struct work_struct *work)
1796 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1797 fg_periodic_work.work);
1799 if (di->init_capacity) {
1800 /* Get an initial capacity calculation */
1801 ab8500_fg_calc_cap_discharge_voltage(di, true);
1802 ab8500_fg_check_capacity_limits(di, true);
1803 di->init_capacity = false;
1805 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1806 } else if (di->flags.user_cap) {
1807 if (check_sysfs_capacity(di)) {
1808 ab8500_fg_check_capacity_limits(di, true);
1809 if (di->flags.charging)
1810 ab8500_fg_charge_state_to(di,
1811 AB8500_FG_CHARGE_INIT);
1813 ab8500_fg_discharge_state_to(di,
1814 AB8500_FG_DISCHARGE_READOUT_INIT);
1816 di->flags.user_cap = false;
1817 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1819 ab8500_fg_algorithm(di);
1824 * ab8500_fg_check_hw_failure_work() - Check OVV_BAT condition
1825 * @work: pointer to the work_struct structure
1827 * Work queue function for checking the OVV_BAT condition
1829 static void ab8500_fg_check_hw_failure_work(struct work_struct *work)
1834 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1835 fg_check_hw_failure_work.work);
1838 * If we have had a battery over-voltage situation,
1839 * check ovv-bit to see if it should be reset.
1841 if (di->flags.bat_ovv) {
1842 ret = abx500_get_register_interruptible(di->dev,
1843 AB8500_CHARGER, AB8500_CH_STAT_REG,
1846 dev_err(di->dev, "%s ab8500 read failed\n", __func__);
1849 if ((reg_value & BATT_OVV) != BATT_OVV) {
1850 dev_dbg(di->dev, "Battery recovered from OVV\n");
1851 di->flags.bat_ovv = false;
1852 power_supply_changed(&di->fg_psy);
1856 /* Not yet recovered from ovv, reschedule this test */
1857 queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work,
1863 * ab8500_fg_low_bat_work() - Check LOW_BAT condition
1864 * @work: pointer to the work_struct structure
1866 * Work queue function for checking the LOW_BAT condition
1868 static void ab8500_fg_low_bat_work(struct work_struct *work)
1872 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1873 fg_low_bat_work.work);
1875 vbat = ab8500_fg_bat_voltage(di);
1877 /* Check if LOW_BAT still fulfilled */
1878 if (vbat < di->bm->fg_params->lowbat_threshold) {
1879 di->flags.low_bat = true;
1880 dev_warn(di->dev, "Battery voltage still LOW\n");
1883 * We need to re-schedule this check to be able to detect
1884 * if the voltage increases again during charging
1886 queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
1887 round_jiffies(LOW_BAT_CHECK_INTERVAL));
1889 di->flags.low_bat = false;
1890 dev_warn(di->dev, "Battery voltage OK again\n");
1893 /* This is needed to dispatch LOW_BAT */
1894 ab8500_fg_check_capacity_limits(di, false);
1896 /* Set this flag to check if LOW_BAT IRQ still occurs */
1897 di->flags.low_bat_delay = false;
1901 * ab8500_fg_battok_calc - calculate the bit pattern corresponding
1902 * to the target voltage.
1903 * @di: pointer to the ab8500_fg structure
1904 * @target target voltage
1906 * Returns bit pattern closest to the target voltage
1907 * valid return values are 0-14. (0-BATT_OK_MAX_NR_INCREMENTS)
1910 static int ab8500_fg_battok_calc(struct ab8500_fg *di, int target)
1912 if (target > BATT_OK_MIN +
1913 (BATT_OK_INCREMENT * BATT_OK_MAX_NR_INCREMENTS))
1914 return BATT_OK_MAX_NR_INCREMENTS;
1915 if (target < BATT_OK_MIN)
1917 return (target - BATT_OK_MIN) / BATT_OK_INCREMENT;
1921 * ab8500_fg_battok_init_hw_register - init battok levels
1922 * @di: pointer to the ab8500_fg structure
1926 static int ab8500_fg_battok_init_hw_register(struct ab8500_fg *di)
1936 sel0 = di->bm->fg_params->battok_falling_th_sel0;
1937 sel1 = di->bm->fg_params->battok_raising_th_sel1;
1939 cbp_sel0 = ab8500_fg_battok_calc(di, sel0);
1940 cbp_sel1 = ab8500_fg_battok_calc(di, sel1);
1942 selected = BATT_OK_MIN + cbp_sel0 * BATT_OK_INCREMENT;
1944 if (selected != sel0)
1945 dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1946 sel0, selected, cbp_sel0);
1948 selected = BATT_OK_MIN + cbp_sel1 * BATT_OK_INCREMENT;
1950 if (selected != sel1)
1951 dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1952 sel1, selected, cbp_sel1);
1954 new_val = cbp_sel0 | (cbp_sel1 << 4);
1956 dev_dbg(di->dev, "using: %x %d %d\n", new_val, cbp_sel0, cbp_sel1);
1957 ret = abx500_set_register_interruptible(di->dev, AB8500_SYS_CTRL2_BLOCK,
1958 AB8500_BATT_OK_REG, new_val);
1963 * ab8500_fg_instant_work() - Run the FG state machine instantly
1964 * @work: pointer to the work_struct structure
1966 * Work queue function for instant work
1968 static void ab8500_fg_instant_work(struct work_struct *work)
1970 struct ab8500_fg *di = container_of(work, struct ab8500_fg, fg_work);
1972 ab8500_fg_algorithm(di);
1976 * ab8500_fg_cc_data_end_handler() - isr to get battery avg current.
1977 * @irq: interrupt number
1978 * @_di: pointer to the ab8500_fg structure
1980 * Returns IRQ status(IRQ_HANDLED)
1982 static irqreturn_t ab8500_fg_cc_data_end_handler(int irq, void *_di)
1984 struct ab8500_fg *di = _di;
1985 if (!di->nbr_cceoc_irq_cnt) {
1986 di->nbr_cceoc_irq_cnt++;
1987 complete(&di->ab8500_fg_started);
1989 di->nbr_cceoc_irq_cnt = 0;
1990 complete(&di->ab8500_fg_complete);
1996 * ab8500_fg_cc_convend_handler() - isr to get battery avg current.
1997 * @irq: interrupt number
1998 * @_di: pointer to the ab8500_fg structure
2000 * Returns IRQ status(IRQ_HANDLED)
2002 static irqreturn_t ab8500_fg_cc_int_calib_handler(int irq, void *_di)
2004 struct ab8500_fg *di = _di;
2005 di->calib_state = AB8500_FG_CALIB_END;
2006 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2011 * ab8500_fg_cc_convend_handler() - isr to get battery avg current.
2012 * @irq: interrupt number
2013 * @_di: pointer to the ab8500_fg structure
2015 * Returns IRQ status(IRQ_HANDLED)
2017 static irqreturn_t ab8500_fg_cc_convend_handler(int irq, void *_di)
2019 struct ab8500_fg *di = _di;
2021 queue_work(di->fg_wq, &di->fg_acc_cur_work);
2027 * ab8500_fg_batt_ovv_handler() - Battery OVV occured
2028 * @irq: interrupt number
2029 * @_di: pointer to the ab8500_fg structure
2031 * Returns IRQ status(IRQ_HANDLED)
2033 static irqreturn_t ab8500_fg_batt_ovv_handler(int irq, void *_di)
2035 struct ab8500_fg *di = _di;
2037 dev_dbg(di->dev, "Battery OVV\n");
2038 di->flags.bat_ovv = true;
2039 power_supply_changed(&di->fg_psy);
2041 /* Schedule a new HW failure check */
2042 queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work, 0);
2048 * ab8500_fg_lowbatf_handler() - Battery voltage is below LOW threshold
2049 * @irq: interrupt number
2050 * @_di: pointer to the ab8500_fg structure
2052 * Returns IRQ status(IRQ_HANDLED)
2054 static irqreturn_t ab8500_fg_lowbatf_handler(int irq, void *_di)
2056 struct ab8500_fg *di = _di;
2058 if (!di->flags.low_bat_delay) {
2059 dev_warn(di->dev, "Battery voltage is below LOW threshold\n");
2060 di->flags.low_bat_delay = true;
2062 * Start a timer to check LOW_BAT again after some time
2063 * This is done to avoid shutdown on single voltage dips
2065 queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
2066 round_jiffies(LOW_BAT_CHECK_INTERVAL));
2072 * ab8500_fg_get_property() - get the fg properties
2073 * @psy: pointer to the power_supply structure
2074 * @psp: pointer to the power_supply_property structure
2075 * @val: pointer to the power_supply_propval union
2077 * This function gets called when an application tries to get the
2078 * fg properties by reading the sysfs files.
2079 * voltage_now: battery voltage
2080 * current_now: battery instant current
2081 * current_avg: battery average current
2082 * charge_full_design: capacity where battery is considered full
2083 * charge_now: battery capacity in nAh
2084 * capacity: capacity in percent
2085 * capacity_level: capacity level
2087 * Returns error code in case of failure else 0 on success
2089 static int ab8500_fg_get_property(struct power_supply *psy,
2090 enum power_supply_property psp,
2091 union power_supply_propval *val)
2093 struct ab8500_fg *di;
2095 di = to_ab8500_fg_device_info(psy);
2098 * If battery is identified as unknown and charging of unknown
2099 * batteries is disabled, we always report 100% capacity and
2100 * capacity level UNKNOWN, since we can't calculate
2101 * remaining capacity
2105 case POWER_SUPPLY_PROP_VOLTAGE_NOW:
2106 if (di->flags.bat_ovv)
2107 val->intval = BATT_OVV_VALUE * 1000;
2109 val->intval = di->vbat * 1000;
2111 case POWER_SUPPLY_PROP_CURRENT_NOW:
2112 val->intval = di->inst_curr * 1000;
2114 case POWER_SUPPLY_PROP_CURRENT_AVG:
2115 val->intval = di->avg_curr * 1000;
2117 case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
2118 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2119 di->bat_cap.max_mah_design);
2121 case POWER_SUPPLY_PROP_ENERGY_FULL:
2122 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2123 di->bat_cap.max_mah);
2125 case POWER_SUPPLY_PROP_ENERGY_NOW:
2126 if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2127 di->flags.batt_id_received)
2128 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2129 di->bat_cap.max_mah);
2131 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2132 di->bat_cap.prev_mah);
2134 case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
2135 val->intval = di->bat_cap.max_mah_design;
2137 case POWER_SUPPLY_PROP_CHARGE_FULL:
2138 val->intval = di->bat_cap.max_mah;
2140 case POWER_SUPPLY_PROP_CHARGE_NOW:
2141 if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2142 di->flags.batt_id_received)
2143 val->intval = di->bat_cap.max_mah;
2145 val->intval = di->bat_cap.prev_mah;
2147 case POWER_SUPPLY_PROP_CAPACITY:
2148 if (di->bm->capacity_scaling)
2149 val->intval = di->bat_cap.cap_scale.scaled_cap;
2150 else if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2151 di->flags.batt_id_received)
2154 val->intval = di->bat_cap.prev_percent;
2156 case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
2157 if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2158 di->flags.batt_id_received)
2159 val->intval = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
2161 val->intval = di->bat_cap.prev_level;
2169 static int ab8500_fg_get_ext_psy_data(struct device *dev, void *data)
2171 struct power_supply *psy;
2172 struct power_supply *ext;
2173 struct ab8500_fg *di;
2174 union power_supply_propval ret;
2176 bool psy_found = false;
2178 psy = (struct power_supply *)data;
2179 ext = dev_get_drvdata(dev);
2180 di = to_ab8500_fg_device_info(psy);
2183 * For all psy where the name of your driver
2184 * appears in any supplied_to
2186 for (i = 0; i < ext->num_supplicants; i++) {
2187 if (!strcmp(ext->supplied_to[i], psy->name))
2194 /* Go through all properties for the psy */
2195 for (j = 0; j < ext->num_properties; j++) {
2196 enum power_supply_property prop;
2197 prop = ext->properties[j];
2199 if (ext->get_property(ext, prop, &ret))
2203 case POWER_SUPPLY_PROP_STATUS:
2204 switch (ext->type) {
2205 case POWER_SUPPLY_TYPE_BATTERY:
2206 switch (ret.intval) {
2207 case POWER_SUPPLY_STATUS_UNKNOWN:
2208 case POWER_SUPPLY_STATUS_DISCHARGING:
2209 case POWER_SUPPLY_STATUS_NOT_CHARGING:
2210 if (!di->flags.charging)
2212 di->flags.charging = false;
2213 di->flags.fully_charged = false;
2214 if (di->bm->capacity_scaling)
2215 ab8500_fg_update_cap_scalers(di);
2216 queue_work(di->fg_wq, &di->fg_work);
2218 case POWER_SUPPLY_STATUS_FULL:
2219 if (di->flags.fully_charged)
2221 di->flags.fully_charged = true;
2222 di->flags.force_full = true;
2223 /* Save current capacity as maximum */
2224 di->bat_cap.max_mah = di->bat_cap.mah;
2225 queue_work(di->fg_wq, &di->fg_work);
2227 case POWER_SUPPLY_STATUS_CHARGING:
2228 if (di->flags.charging &&
2229 !di->flags.fully_charged)
2231 di->flags.charging = true;
2232 di->flags.fully_charged = false;
2233 if (di->bm->capacity_scaling)
2234 ab8500_fg_update_cap_scalers(di);
2235 queue_work(di->fg_wq, &di->fg_work);
2242 case POWER_SUPPLY_PROP_TECHNOLOGY:
2243 switch (ext->type) {
2244 case POWER_SUPPLY_TYPE_BATTERY:
2245 if (!di->flags.batt_id_received) {
2246 const struct abx500_battery_type *b;
2248 b = &(di->bm->bat_type[di->bm->batt_id]);
2250 di->flags.batt_id_received = true;
2252 di->bat_cap.max_mah_design =
2254 b->charge_full_design;
2256 di->bat_cap.max_mah =
2257 di->bat_cap.max_mah_design;
2259 di->vbat_nom = b->nominal_voltage;
2263 di->flags.batt_unknown = false;
2265 di->flags.batt_unknown = true;
2271 case POWER_SUPPLY_PROP_TEMP:
2272 switch (ext->type) {
2273 case POWER_SUPPLY_TYPE_BATTERY:
2274 if (di->flags.batt_id_received)
2275 di->bat_temp = ret.intval;
2289 * ab8500_fg_init_hw_registers() - Set up FG related registers
2290 * @di: pointer to the ab8500_fg structure
2292 * Set up battery OVV, low battery voltage registers
2294 static int ab8500_fg_init_hw_registers(struct ab8500_fg *di)
2298 /* Set VBAT OVV threshold */
2299 ret = abx500_mask_and_set_register_interruptible(di->dev,
2305 dev_err(di->dev, "failed to set BATT_OVV\n");
2309 /* Enable VBAT OVV detection */
2310 ret = abx500_mask_and_set_register_interruptible(di->dev,
2316 dev_err(di->dev, "failed to enable BATT_OVV\n");
2320 /* Low Battery Voltage */
2321 ret = abx500_set_register_interruptible(di->dev,
2322 AB8500_SYS_CTRL2_BLOCK,
2324 ab8500_volt_to_regval(
2325 di->bm->fg_params->lowbat_threshold) << 1 |
2328 dev_err(di->dev, "%s write failed\n", __func__);
2332 /* Battery OK threshold */
2333 ret = ab8500_fg_battok_init_hw_register(di);
2335 dev_err(di->dev, "BattOk init write failed.\n");
2343 * ab8500_fg_external_power_changed() - callback for power supply changes
2344 * @psy: pointer to the structure power_supply
2346 * This function is the entry point of the pointer external_power_changed
2347 * of the structure power_supply.
2348 * This function gets executed when there is a change in any external power
2349 * supply that this driver needs to be notified of.
2351 static void ab8500_fg_external_power_changed(struct power_supply *psy)
2353 struct ab8500_fg *di = to_ab8500_fg_device_info(psy);
2355 class_for_each_device(power_supply_class, NULL,
2356 &di->fg_psy, ab8500_fg_get_ext_psy_data);
2360 * abab8500_fg_reinit_work() - work to reset the FG algorithm
2361 * @work: pointer to the work_struct structure
2363 * Used to reset the current battery capacity to be able to
2364 * retrigger a new voltage base capacity calculation. For
2365 * test and verification purpose.
2367 static void ab8500_fg_reinit_work(struct work_struct *work)
2369 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
2370 fg_reinit_work.work);
2372 if (di->flags.calibrate == false) {
2373 dev_dbg(di->dev, "Resetting FG state machine to init.\n");
2374 ab8500_fg_clear_cap_samples(di);
2375 ab8500_fg_calc_cap_discharge_voltage(di, true);
2376 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
2377 ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
2378 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2381 dev_err(di->dev, "Residual offset calibration ongoing "
2383 /* Wait one second until next try*/
2384 queue_delayed_work(di->fg_wq, &di->fg_reinit_work,
2390 * ab8500_fg_reinit() - forces FG algorithm to reinitialize with current values
2392 * This function can be used to force the FG algorithm to recalculate a new
2393 * voltage based battery capacity.
2395 void ab8500_fg_reinit(void)
2397 struct ab8500_fg *di = ab8500_fg_get();
2398 /* User won't be notified if a null pointer returned. */
2400 queue_delayed_work(di->fg_wq, &di->fg_reinit_work, 0);
2403 /* Exposure to the sysfs interface */
2405 struct ab8500_fg_sysfs_entry {
2406 struct attribute attr;
2407 ssize_t (*show)(struct ab8500_fg *, char *);
2408 ssize_t (*store)(struct ab8500_fg *, const char *, size_t);
2411 static ssize_t charge_full_show(struct ab8500_fg *di, char *buf)
2413 return sprintf(buf, "%d\n", di->bat_cap.max_mah);
2416 static ssize_t charge_full_store(struct ab8500_fg *di, const char *buf,
2419 unsigned long charge_full;
2420 ssize_t ret = -EINVAL;
2422 ret = strict_strtoul(buf, 10, &charge_full);
2424 dev_dbg(di->dev, "Ret %zd charge_full %lu", ret, charge_full);
2427 di->bat_cap.max_mah = (int) charge_full;
2433 static ssize_t charge_now_show(struct ab8500_fg *di, char *buf)
2435 return sprintf(buf, "%d\n", di->bat_cap.prev_mah);
2438 static ssize_t charge_now_store(struct ab8500_fg *di, const char *buf,
2441 unsigned long charge_now;
2444 ret = strict_strtoul(buf, 10, &charge_now);
2446 dev_dbg(di->dev, "Ret %zd charge_now %lu was %d",
2447 ret, charge_now, di->bat_cap.prev_mah);
2450 di->bat_cap.user_mah = (int) charge_now;
2451 di->flags.user_cap = true;
2453 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2458 static struct ab8500_fg_sysfs_entry charge_full_attr =
2459 __ATTR(charge_full, 0644, charge_full_show, charge_full_store);
2461 static struct ab8500_fg_sysfs_entry charge_now_attr =
2462 __ATTR(charge_now, 0644, charge_now_show, charge_now_store);
2465 ab8500_fg_show(struct kobject *kobj, struct attribute *attr, char *buf)
2467 struct ab8500_fg_sysfs_entry *entry;
2468 struct ab8500_fg *di;
2470 entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2471 di = container_of(kobj, struct ab8500_fg, fg_kobject);
2476 return entry->show(di, buf);
2479 ab8500_fg_store(struct kobject *kobj, struct attribute *attr, const char *buf,
2482 struct ab8500_fg_sysfs_entry *entry;
2483 struct ab8500_fg *di;
2485 entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2486 di = container_of(kobj, struct ab8500_fg, fg_kobject);
2491 return entry->store(di, buf, count);
2494 static const struct sysfs_ops ab8500_fg_sysfs_ops = {
2495 .show = ab8500_fg_show,
2496 .store = ab8500_fg_store,
2499 static struct attribute *ab8500_fg_attrs[] = {
2500 &charge_full_attr.attr,
2501 &charge_now_attr.attr,
2505 static struct kobj_type ab8500_fg_ktype = {
2506 .sysfs_ops = &ab8500_fg_sysfs_ops,
2507 .default_attrs = ab8500_fg_attrs,
2511 * ab8500_chargalg_sysfs_exit() - de-init of sysfs entry
2512 * @di: pointer to the struct ab8500_chargalg
2514 * This function removes the entry in sysfs.
2516 static void ab8500_fg_sysfs_exit(struct ab8500_fg *di)
2518 kobject_del(&di->fg_kobject);
2522 * ab8500_chargalg_sysfs_init() - init of sysfs entry
2523 * @di: pointer to the struct ab8500_chargalg
2525 * This function adds an entry in sysfs.
2526 * Returns error code in case of failure else 0(on success)
2528 static int ab8500_fg_sysfs_init(struct ab8500_fg *di)
2532 ret = kobject_init_and_add(&di->fg_kobject,
2536 dev_err(di->dev, "failed to create sysfs entry\n");
2540 /* Exposure to the sysfs interface <<END>> */
2542 #if defined(CONFIG_PM)
2543 static int ab8500_fg_resume(struct platform_device *pdev)
2545 struct ab8500_fg *di = platform_get_drvdata(pdev);
2548 * Change state if we're not charging. If we're charging we will wake
2551 if (!di->flags.charging) {
2552 ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_WAKEUP);
2553 queue_work(di->fg_wq, &di->fg_work);
2559 static int ab8500_fg_suspend(struct platform_device *pdev,
2562 struct ab8500_fg *di = platform_get_drvdata(pdev);
2564 flush_delayed_work(&di->fg_periodic_work);
2567 * If the FG is enabled we will disable it before going to suspend
2568 * only if we're not charging
2570 if (di->flags.fg_enabled && !di->flags.charging)
2571 ab8500_fg_coulomb_counter(di, false);
2576 #define ab8500_fg_suspend NULL
2577 #define ab8500_fg_resume NULL
2580 static int ab8500_fg_remove(struct platform_device *pdev)
2583 struct ab8500_fg *di = platform_get_drvdata(pdev);
2585 list_del(&di->node);
2587 /* Disable coulomb counter */
2588 ret = ab8500_fg_coulomb_counter(di, false);
2590 dev_err(di->dev, "failed to disable coulomb counter\n");
2592 destroy_workqueue(di->fg_wq);
2593 ab8500_fg_sysfs_exit(di);
2595 flush_scheduled_work();
2596 power_supply_unregister(&di->fg_psy);
2597 platform_set_drvdata(pdev, NULL);
2601 /* ab8500 fg driver interrupts and their respective isr */
2602 static struct ab8500_fg_interrupts ab8500_fg_irq[] = {
2603 {"NCONV_ACCU", ab8500_fg_cc_convend_handler},
2604 {"BATT_OVV", ab8500_fg_batt_ovv_handler},
2605 {"LOW_BAT_F", ab8500_fg_lowbatf_handler},
2606 {"CC_INT_CALIB", ab8500_fg_cc_int_calib_handler},
2607 {"CCEOC", ab8500_fg_cc_data_end_handler},
2610 static char *supply_interface[] = {
2615 static int ab8500_fg_probe(struct platform_device *pdev)
2617 struct device_node *np = pdev->dev.of_node;
2618 struct abx500_bm_data *plat = pdev->dev.platform_data;
2619 struct ab8500_fg *di;
2623 di = devm_kzalloc(&pdev->dev, sizeof(*di), GFP_KERNEL);
2625 dev_err(&pdev->dev, "%s no mem for ab8500_fg\n", __func__);
2630 dev_err(&pdev->dev, "no battery management data supplied\n");
2636 ret = ab8500_bm_of_probe(&pdev->dev, np, di->bm);
2638 dev_err(&pdev->dev, "failed to get battery information\n");
2643 mutex_init(&di->cc_lock);
2645 /* get parent data */
2646 di->dev = &pdev->dev;
2647 di->parent = dev_get_drvdata(pdev->dev.parent);
2648 di->gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
2650 di->fg_psy.name = "ab8500_fg";
2651 di->fg_psy.type = POWER_SUPPLY_TYPE_BATTERY;
2652 di->fg_psy.properties = ab8500_fg_props;
2653 di->fg_psy.num_properties = ARRAY_SIZE(ab8500_fg_props);
2654 di->fg_psy.get_property = ab8500_fg_get_property;
2655 di->fg_psy.supplied_to = supply_interface;
2656 di->fg_psy.num_supplicants = ARRAY_SIZE(supply_interface),
2657 di->fg_psy.external_power_changed = ab8500_fg_external_power_changed;
2659 di->bat_cap.max_mah_design = MILLI_TO_MICRO *
2660 di->bm->bat_type[di->bm->batt_id].charge_full_design;
2662 di->bat_cap.max_mah = di->bat_cap.max_mah_design;
2664 di->vbat_nom = di->bm->bat_type[di->bm->batt_id].nominal_voltage;
2666 di->init_capacity = true;
2668 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
2669 ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
2671 /* Create a work queue for running the FG algorithm */
2672 di->fg_wq = create_singlethread_workqueue("ab8500_fg_wq");
2673 if (di->fg_wq == NULL) {
2674 dev_err(di->dev, "failed to create work queue\n");
2678 /* Init work for running the fg algorithm instantly */
2679 INIT_WORK(&di->fg_work, ab8500_fg_instant_work);
2681 /* Init work for getting the battery accumulated current */
2682 INIT_WORK(&di->fg_acc_cur_work, ab8500_fg_acc_cur_work);
2684 /* Init work for reinitialising the fg algorithm */
2685 INIT_DEFERRABLE_WORK(&di->fg_reinit_work,
2686 ab8500_fg_reinit_work);
2688 /* Work delayed Queue to run the state machine */
2689 INIT_DEFERRABLE_WORK(&di->fg_periodic_work,
2690 ab8500_fg_periodic_work);
2692 /* Work to check low battery condition */
2693 INIT_DEFERRABLE_WORK(&di->fg_low_bat_work,
2694 ab8500_fg_low_bat_work);
2696 /* Init work for HW failure check */
2697 INIT_DEFERRABLE_WORK(&di->fg_check_hw_failure_work,
2698 ab8500_fg_check_hw_failure_work);
2700 /* Initialize OVV, and other registers */
2701 ret = ab8500_fg_init_hw_registers(di);
2703 dev_err(di->dev, "failed to initialize registers\n");
2704 goto free_inst_curr_wq;
2707 /* Consider battery unknown until we're informed otherwise */
2708 di->flags.batt_unknown = true;
2709 di->flags.batt_id_received = false;
2711 /* Register FG power supply class */
2712 ret = power_supply_register(di->dev, &di->fg_psy);
2714 dev_err(di->dev, "failed to register FG psy\n");
2715 goto free_inst_curr_wq;
2718 di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
2719 ab8500_fg_coulomb_counter(di, true);
2722 * Initialize completion used to notify completion and start
2725 init_completion(&di->ab8500_fg_started);
2726 init_completion(&di->ab8500_fg_complete);
2728 /* Register interrupts */
2729 for (i = 0; i < ARRAY_SIZE(ab8500_fg_irq); i++) {
2730 irq = platform_get_irq_byname(pdev, ab8500_fg_irq[i].name);
2731 ret = request_threaded_irq(irq, NULL, ab8500_fg_irq[i].isr,
2732 IRQF_SHARED | IRQF_NO_SUSPEND,
2733 ab8500_fg_irq[i].name, di);
2736 dev_err(di->dev, "failed to request %s IRQ %d: %d\n"
2737 , ab8500_fg_irq[i].name, irq, ret);
2740 dev_dbg(di->dev, "Requested %s IRQ %d: %d\n",
2741 ab8500_fg_irq[i].name, irq, ret);
2743 di->irq = platform_get_irq_byname(pdev, "CCEOC");
2744 disable_irq(di->irq);
2745 di->nbr_cceoc_irq_cnt = 0;
2747 platform_set_drvdata(pdev, di);
2749 ret = ab8500_fg_sysfs_init(di);
2751 dev_err(di->dev, "failed to create sysfs entry\n");
2755 /* Calibrate the fg first time */
2756 di->flags.calibrate = true;
2757 di->calib_state = AB8500_FG_CALIB_INIT;
2759 /* Use room temp as default value until we get an update from driver. */
2762 /* Run the FG algorithm */
2763 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2765 list_add_tail(&di->node, &ab8500_fg_list);
2770 power_supply_unregister(&di->fg_psy);
2772 /* We also have to free all successfully registered irqs */
2773 for (i = i - 1; i >= 0; i--) {
2774 irq = platform_get_irq_byname(pdev, ab8500_fg_irq[i].name);
2778 destroy_workqueue(di->fg_wq);
2782 static const struct of_device_id ab8500_fg_match[] = {
2783 { .compatible = "stericsson,ab8500-fg", },
2787 static struct platform_driver ab8500_fg_driver = {
2788 .probe = ab8500_fg_probe,
2789 .remove = ab8500_fg_remove,
2790 .suspend = ab8500_fg_suspend,
2791 .resume = ab8500_fg_resume,
2793 .name = "ab8500-fg",
2794 .owner = THIS_MODULE,
2795 .of_match_table = ab8500_fg_match,
2799 static int __init ab8500_fg_init(void)
2801 return platform_driver_register(&ab8500_fg_driver);
2804 static void __exit ab8500_fg_exit(void)
2806 platform_driver_unregister(&ab8500_fg_driver);
2809 subsys_initcall_sync(ab8500_fg_init);
2810 module_exit(ab8500_fg_exit);
2812 MODULE_LICENSE("GPL v2");
2813 MODULE_AUTHOR("Johan Palsson, Karl Komierowski");
2814 MODULE_ALIAS("platform:ab8500-fg");
2815 MODULE_DESCRIPTION("AB8500 Fuel Gauge driver");