1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) ST-Ericsson AB 2012
5 * Main and Back-up battery management driver.
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
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/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>
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>
39 #include "ab8500-bm.h"
41 #define FG_LSB_IN_MA 1627
42 #define QLSB_NANO_AMP_HOURS_X10 1071
43 #define INS_CURR_TIMEOUT (3 * HZ)
45 #define SEC_TO_SAMPLE(S) (S * 4)
47 #define NBR_AVG_SAMPLES 20
49 #define LOW_BAT_CHECK_INTERVAL (HZ / 16) /* 62.5 ms */
51 #define VALID_CAPACITY_SEC (45 * 60) /* 45 minutes */
52 #define BATT_OK_MIN 2360 /* mV */
53 #define BATT_OK_INCREMENT 50 /* mV */
54 #define BATT_OK_MAX_NR_INCREMENTS 0xE
60 * struct ab8500_fg_interrupts - ab8500 fg interrupts
61 * @name: name of the interrupt
62 * @isr function pointer to the isr
64 struct ab8500_fg_interrupts {
66 irqreturn_t (*isr)(int irq, void *data);
69 enum ab8500_fg_discharge_state {
70 AB8500_FG_DISCHARGE_INIT,
71 AB8500_FG_DISCHARGE_INITMEASURING,
72 AB8500_FG_DISCHARGE_INIT_RECOVERY,
73 AB8500_FG_DISCHARGE_RECOVERY,
74 AB8500_FG_DISCHARGE_READOUT_INIT,
75 AB8500_FG_DISCHARGE_READOUT,
76 AB8500_FG_DISCHARGE_WAKEUP,
79 static char *discharge_state[] = {
81 "DISCHARGE_INITMEASURING",
82 "DISCHARGE_INIT_RECOVERY",
84 "DISCHARGE_READOUT_INIT",
89 enum ab8500_fg_charge_state {
90 AB8500_FG_CHARGE_INIT,
91 AB8500_FG_CHARGE_READOUT,
94 static char *charge_state[] = {
99 enum ab8500_fg_calibration_state {
100 AB8500_FG_CALIB_INIT,
101 AB8500_FG_CALIB_WAIT,
105 struct ab8500_fg_avg_cap {
107 int samples[NBR_AVG_SAMPLES];
108 time64_t time_stamps[NBR_AVG_SAMPLES];
114 struct ab8500_fg_cap_scaling {
117 int disable_cap_level;
121 struct ab8500_fg_battery_capacity {
131 struct ab8500_fg_cap_scaling cap_scale;
134 struct ab8500_fg_flags {
146 bool batt_id_received;
149 struct inst_curr_result_list {
150 struct list_head list;
155 * struct ab8500_fg - ab8500 FG device information
156 * @dev: Pointer to the structure device
157 * @node: a list of AB8500 FGs, hence prepared for reentrance
158 * @irq holds the CCEOC interrupt number
159 * @vbat: Battery voltage in mV
160 * @vbat_nom_uv: Nominal battery voltage in uV
161 * @inst_curr: Instantenous battery current in mA
162 * @avg_curr: Average battery current in mA
163 * @bat_temp battery temperature
164 * @fg_samples: Number of samples used in the FG accumulation
165 * @accu_charge: Accumulated charge from the last conversion
166 * @recovery_cnt: Counter for recovery mode
167 * @high_curr_cnt: Counter for high current mode
168 * @init_cnt: Counter for init mode
169 * @low_bat_cnt Counter for number of consecutive low battery measures
170 * @nbr_cceoc_irq_cnt Counter for number of CCEOC irqs received since enabled
171 * @recovery_needed: Indicate if recovery is needed
172 * @high_curr_mode: Indicate if we're in high current mode
173 * @init_capacity: Indicate if initial capacity measuring should be done
174 * @turn_off_fg: True if fg was off before current measurement
175 * @calib_state State during offset calibration
176 * @discharge_state: Current discharge state
177 * @charge_state: Current charge state
178 * @ab8500_fg_started Completion struct used for the instant current start
179 * @ab8500_fg_complete Completion struct used for the instant current reading
180 * @flags: Structure for information about events triggered
181 * @bat_cap: Structure for battery capacity specific parameters
182 * @avg_cap: Average capacity filter
183 * @parent: Pointer to the struct ab8500
184 * @main_bat_v: ADC channel for the main battery voltage
185 * @bm: Platform specific battery management information
186 * @fg_psy: Structure that holds the FG specific battery properties
187 * @fg_wq: Work queue for running the FG algorithm
188 * @fg_periodic_work: Work to run the FG algorithm periodically
189 * @fg_low_bat_work: Work to check low bat condition
190 * @fg_reinit_work Work used to reset and reinitialise the FG algorithm
191 * @fg_work: Work to run the FG algorithm instantly
192 * @fg_acc_cur_work: Work to read the FG accumulator
193 * @fg_check_hw_failure_work: Work for checking HW state
194 * @cc_lock: Mutex for locking the CC
195 * @fg_kobject: Structure of type kobject
199 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 iio_channel *main_bat_v;
227 struct ab8500_bm_data *bm;
228 struct power_supply *fg_psy;
229 struct workqueue_struct *fg_wq;
230 struct delayed_work fg_periodic_work;
231 struct delayed_work fg_low_bat_work;
232 struct delayed_work fg_reinit_work;
233 struct work_struct fg_work;
234 struct work_struct fg_acc_cur_work;
235 struct delayed_work fg_check_hw_failure_work;
236 struct mutex cc_lock;
237 struct kobject fg_kobject;
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 return list_first_entry_or_null(&ab8500_fg_list, struct ab8500_fg,
251 /* Main battery properties */
252 static enum power_supply_property ab8500_fg_props[] = {
253 POWER_SUPPLY_PROP_VOLTAGE_NOW,
254 POWER_SUPPLY_PROP_CURRENT_NOW,
255 POWER_SUPPLY_PROP_CURRENT_AVG,
256 POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
257 POWER_SUPPLY_PROP_ENERGY_FULL,
258 POWER_SUPPLY_PROP_ENERGY_NOW,
259 POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
260 POWER_SUPPLY_PROP_CHARGE_FULL,
261 POWER_SUPPLY_PROP_CHARGE_NOW,
262 POWER_SUPPLY_PROP_CAPACITY,
263 POWER_SUPPLY_PROP_CAPACITY_LEVEL,
267 * This array maps the raw hex value to lowbat voltage used by the AB8500
268 * Values taken from the UM0836
270 static int ab8500_fg_lowbat_voltage_map[] = {
337 static u8 ab8500_volt_to_regval(int voltage)
341 if (voltage < ab8500_fg_lowbat_voltage_map[0])
344 for (i = 0; i < ARRAY_SIZE(ab8500_fg_lowbat_voltage_map); i++) {
345 if (voltage < ab8500_fg_lowbat_voltage_map[i])
349 /* If not captured above, return index of last element */
350 return (u8) ARRAY_SIZE(ab8500_fg_lowbat_voltage_map) - 1;
354 * ab8500_fg_is_low_curr() - Low or high current mode
355 * @di: pointer to the ab8500_fg structure
356 * @curr: the current to base or our decision on
358 * Low current mode if the current consumption is below a certain threshold
360 static int ab8500_fg_is_low_curr(struct ab8500_fg *di, int curr)
363 * We want to know if we're in low current mode
365 if (curr > -di->bm->fg_params->high_curr_threshold)
372 * ab8500_fg_add_cap_sample() - Add capacity to average filter
373 * @di: pointer to the ab8500_fg structure
374 * @sample: the capacity in mAh to add to the filter
376 * A capacity is added to the filter and a new mean capacity is calculated and
379 static int ab8500_fg_add_cap_sample(struct ab8500_fg *di, int sample)
381 time64_t now = ktime_get_boottime_seconds();
382 struct ab8500_fg_avg_cap *avg = &di->avg_cap;
385 avg->sum += sample - avg->samples[avg->pos];
386 avg->samples[avg->pos] = sample;
387 avg->time_stamps[avg->pos] = now;
390 if (avg->pos == NBR_AVG_SAMPLES)
393 if (avg->nbr_samples < NBR_AVG_SAMPLES)
397 * Check the time stamp for each sample. If too old,
398 * replace with latest sample
400 } while (now - VALID_CAPACITY_SEC > avg->time_stamps[avg->pos]);
402 avg->avg = avg->sum / avg->nbr_samples;
408 * ab8500_fg_clear_cap_samples() - Clear average filter
409 * @di: pointer to the ab8500_fg structure
411 * The capacity filter is is reset to zero.
413 static void ab8500_fg_clear_cap_samples(struct ab8500_fg *di)
416 struct ab8500_fg_avg_cap *avg = &di->avg_cap;
419 avg->nbr_samples = 0;
423 for (i = 0; i < NBR_AVG_SAMPLES; i++) {
425 avg->time_stamps[i] = 0;
430 * ab8500_fg_fill_cap_sample() - Fill average filter
431 * @di: pointer to the ab8500_fg structure
432 * @sample: the capacity in mAh to fill the filter with
434 * The capacity filter is filled with a capacity in mAh
436 static void ab8500_fg_fill_cap_sample(struct ab8500_fg *di, int sample)
440 struct ab8500_fg_avg_cap *avg = &di->avg_cap;
442 now = ktime_get_boottime_seconds();
444 for (i = 0; i < NBR_AVG_SAMPLES; i++) {
445 avg->samples[i] = sample;
446 avg->time_stamps[i] = now;
450 avg->nbr_samples = NBR_AVG_SAMPLES;
451 avg->sum = sample * NBR_AVG_SAMPLES;
456 * ab8500_fg_coulomb_counter() - enable coulomb counter
457 * @di: pointer to the ab8500_fg structure
458 * @enable: enable/disable
460 * Enable/Disable coulomb counter.
461 * On failure returns negative value.
463 static int ab8500_fg_coulomb_counter(struct ab8500_fg *di, bool enable)
466 mutex_lock(&di->cc_lock);
468 /* To be able to reprogram the number of samples, we have to
469 * first stop the CC and then enable it again */
470 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
471 AB8500_RTC_CC_CONF_REG, 0x00);
475 /* Program the samples */
476 ret = abx500_set_register_interruptible(di->dev,
477 AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
483 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
484 AB8500_RTC_CC_CONF_REG,
485 (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
489 di->flags.fg_enabled = true;
491 /* Clear any pending read requests */
492 ret = abx500_mask_and_set_register_interruptible(di->dev,
493 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
494 (RESET_ACCU | READ_REQ), 0);
498 ret = abx500_set_register_interruptible(di->dev,
499 AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU_CTRL, 0);
504 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
505 AB8500_RTC_CC_CONF_REG, 0);
509 di->flags.fg_enabled = false;
512 dev_dbg(di->dev, " CC enabled: %d Samples: %d\n",
513 enable, di->fg_samples);
515 mutex_unlock(&di->cc_lock);
519 dev_err(di->dev, "%s Enabling coulomb counter failed\n", __func__);
520 mutex_unlock(&di->cc_lock);
525 * ab8500_fg_inst_curr_start() - start battery instantaneous current
526 * @di: pointer to the ab8500_fg structure
528 * Returns 0 or error code
529 * Note: This is part "one" and has to be called before
530 * ab8500_fg_inst_curr_finalize()
532 int ab8500_fg_inst_curr_start(struct ab8500_fg *di)
537 mutex_lock(&di->cc_lock);
539 di->nbr_cceoc_irq_cnt = 0;
540 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
541 AB8500_RTC_CC_CONF_REG, ®_val);
545 if (!(reg_val & CC_PWR_UP_ENA)) {
546 dev_dbg(di->dev, "%s Enable FG\n", __func__);
547 di->turn_off_fg = true;
549 /* Program the samples */
550 ret = abx500_set_register_interruptible(di->dev,
551 AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
557 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
558 AB8500_RTC_CC_CONF_REG,
559 (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
563 di->turn_off_fg = false;
567 reinit_completion(&di->ab8500_fg_started);
568 reinit_completion(&di->ab8500_fg_complete);
571 /* Note: cc_lock is still locked */
574 mutex_unlock(&di->cc_lock);
579 * ab8500_fg_inst_curr_started() - check if fg conversion has started
580 * @di: pointer to the ab8500_fg structure
582 * Returns 1 if conversion started, 0 if still waiting
584 int ab8500_fg_inst_curr_started(struct ab8500_fg *di)
586 return completion_done(&di->ab8500_fg_started);
590 * ab8500_fg_inst_curr_done() - check if fg conversion is done
591 * @di: pointer to the ab8500_fg structure
593 * Returns 1 if conversion done, 0 if still waiting
595 int ab8500_fg_inst_curr_done(struct ab8500_fg *di)
597 return completion_done(&di->ab8500_fg_complete);
601 * ab8500_fg_inst_curr_finalize() - battery instantaneous current
602 * @di: pointer to the ab8500_fg structure
603 * @res: battery instantenous current(on success)
605 * Returns 0 or an error code
606 * Note: This is part "two" and has to be called at earliest 250 ms
607 * after ab8500_fg_inst_curr_start()
609 int ab8500_fg_inst_curr_finalize(struct ab8500_fg *di, int *res)
614 unsigned long timeout;
616 if (!completion_done(&di->ab8500_fg_complete)) {
617 timeout = wait_for_completion_timeout(
618 &di->ab8500_fg_complete,
620 dev_dbg(di->dev, "Finalize time: %d ms\n",
621 jiffies_to_msecs(INS_CURR_TIMEOUT - timeout));
624 disable_irq(di->irq);
625 di->nbr_cceoc_irq_cnt = 0;
626 dev_err(di->dev, "completion timed out [%d]\n",
632 disable_irq(di->irq);
633 di->nbr_cceoc_irq_cnt = 0;
635 ret = abx500_mask_and_set_register_interruptible(di->dev,
636 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
639 /* 100uS between read request and read is needed */
640 usleep_range(100, 100);
642 /* Read CC Sample conversion value Low and high */
643 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
644 AB8500_GASG_CC_SMPL_CNVL_REG, &low);
648 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
649 AB8500_GASG_CC_SMPL_CNVH_REG, &high);
654 * negative value for Discharging
655 * convert 2's complement into decimal
658 val = (low | (high << 8) | 0xFFFFE000);
660 val = (low | (high << 8));
663 * Convert to unit value in mA
664 * Full scale input voltage is
665 * 63.160mV => LSB = 63.160mV/(4096*res) = 1.542mA
666 * Given a 250ms conversion cycle time the LSB corresponds
667 * to 107.1 nAh. Convert to current by dividing by the conversion
668 * time in hours (250ms = 1 / (3600 * 4)h)
669 * 107.1nAh assumes 10mOhm, but fg_res is in 0.1mOhm
671 val = (val * QLSB_NANO_AMP_HOURS_X10 * 36 * 4) /
672 (1000 * di->bm->fg_res);
674 if (di->turn_off_fg) {
675 dev_dbg(di->dev, "%s Disable FG\n", __func__);
677 /* Clear any pending read requests */
678 ret = abx500_set_register_interruptible(di->dev,
679 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG, 0);
684 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
685 AB8500_RTC_CC_CONF_REG, 0);
689 mutex_unlock(&di->cc_lock);
694 mutex_unlock(&di->cc_lock);
699 * ab8500_fg_inst_curr_blocking() - battery instantaneous current
700 * @di: pointer to the ab8500_fg structure
701 * @res: battery instantenous current(on success)
703 * Returns 0 else error code
705 int ab8500_fg_inst_curr_blocking(struct ab8500_fg *di)
708 unsigned long timeout;
711 ret = ab8500_fg_inst_curr_start(di);
713 dev_err(di->dev, "Failed to initialize fg_inst\n");
717 /* Wait for CC to actually start */
718 if (!completion_done(&di->ab8500_fg_started)) {
719 timeout = wait_for_completion_timeout(
720 &di->ab8500_fg_started,
722 dev_dbg(di->dev, "Start time: %d ms\n",
723 jiffies_to_msecs(INS_CURR_TIMEOUT - timeout));
726 dev_err(di->dev, "completion timed out [%d]\n",
732 ret = ab8500_fg_inst_curr_finalize(di, &res);
734 dev_err(di->dev, "Failed to finalize fg_inst\n");
738 dev_dbg(di->dev, "%s instant current: %d", __func__, res);
741 disable_irq(di->irq);
742 mutex_unlock(&di->cc_lock);
747 * ab8500_fg_acc_cur_work() - average battery current
748 * @work: pointer to the work_struct structure
750 * Updated the average battery current obtained from the
753 static void ab8500_fg_acc_cur_work(struct work_struct *work)
759 struct ab8500_fg *di = container_of(work,
760 struct ab8500_fg, fg_acc_cur_work);
762 mutex_lock(&di->cc_lock);
763 ret = abx500_set_register_interruptible(di->dev, AB8500_GAS_GAUGE,
764 AB8500_GASG_CC_NCOV_ACCU_CTRL, RD_NCONV_ACCU_REQ);
768 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
769 AB8500_GASG_CC_NCOV_ACCU_LOW, &low);
773 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
774 AB8500_GASG_CC_NCOV_ACCU_MED, &med);
778 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
779 AB8500_GASG_CC_NCOV_ACCU_HIGH, &high);
783 /* Check for sign bit in case of negative value, 2's complement */
785 val = (low | (med << 8) | (high << 16) | 0xFFE00000);
787 val = (low | (med << 8) | (high << 16));
791 * Given a 250ms conversion cycle time the LSB corresponds
793 * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
795 di->accu_charge = (val * QLSB_NANO_AMP_HOURS_X10) /
796 (100 * di->bm->fg_res);
799 * Convert to unit value in mA
800 * by dividing by the conversion
801 * time in hours (= samples / (3600 * 4)h)
802 * and multiply with 1000
804 di->avg_curr = (val * QLSB_NANO_AMP_HOURS_X10 * 36) /
805 (1000 * di->bm->fg_res * (di->fg_samples / 4));
807 di->flags.conv_done = true;
809 mutex_unlock(&di->cc_lock);
811 queue_work(di->fg_wq, &di->fg_work);
813 dev_dbg(di->dev, "fg_res: %d, fg_samples: %d, gasg: %d, accu_charge: %d \n",
814 di->bm->fg_res, di->fg_samples, val, di->accu_charge);
818 "Failed to read or write gas gauge registers\n");
819 mutex_unlock(&di->cc_lock);
820 queue_work(di->fg_wq, &di->fg_work);
824 * ab8500_fg_bat_voltage() - get battery voltage
825 * @di: pointer to the ab8500_fg structure
827 * Returns battery voltage(on success) else error code
829 static int ab8500_fg_bat_voltage(struct ab8500_fg *di)
834 ret = iio_read_channel_processed(di->main_bat_v, &vbat);
837 "%s ADC conversion failed, using previous value\n",
847 * ab8500_fg_volt_to_capacity() - Voltage based capacity
848 * @di: pointer to the ab8500_fg structure
849 * @voltage: The voltage to convert to a capacity
851 * Returns battery capacity in per mille based on voltage
853 static int ab8500_fg_volt_to_capacity(struct ab8500_fg *di, int voltage)
856 const struct ab8500_v_to_cap *tbl;
859 tbl = di->bm->bat_type->v_to_cap_tbl;
860 tbl_size = di->bm->bat_type->n_v_cap_tbl_elements;
862 for (i = 0; i < tbl_size; ++i) {
863 if (voltage > tbl[i].voltage)
867 if ((i > 0) && (i < tbl_size)) {
868 cap = fixp_linear_interpolate(
870 tbl[i].capacity * 10,
872 tbl[i-1].capacity * 10,
880 dev_dbg(di->dev, "%s Vbat: %d, Cap: %d per mille",
881 __func__, voltage, cap);
887 * ab8500_fg_uncomp_volt_to_capacity() - Uncompensated voltage based capacity
888 * @di: pointer to the ab8500_fg structure
890 * Returns battery capacity based on battery voltage that is not compensated
891 * for the voltage drop due to the load
893 static int ab8500_fg_uncomp_volt_to_capacity(struct ab8500_fg *di)
895 di->vbat = ab8500_fg_bat_voltage(di);
896 return ab8500_fg_volt_to_capacity(di, di->vbat);
900 * ab8500_fg_battery_resistance() - Returns the battery inner resistance
901 * @di: pointer to the ab8500_fg structure
903 * Returns battery inner resistance added with the fuel gauge resistor value
904 * to get the total resistance in the whole link from gnd to bat+ node.
906 static int ab8500_fg_battery_resistance(struct ab8500_fg *di)
909 const struct batres_vs_temp *tbl;
912 tbl = di->bm->bat_type->batres_tbl;
913 tbl_size = di->bm->bat_type->n_batres_tbl_elements;
915 for (i = 0; i < tbl_size; ++i) {
916 if (di->bat_temp / 10 > tbl[i].temp)
920 if ((i > 0) && (i < tbl_size)) {
921 resist = fixp_linear_interpolate(
928 resist = tbl[0].resist;
930 resist = tbl[tbl_size - 1].resist;
933 dev_dbg(di->dev, "%s Temp: %d battery internal resistance: %d"
934 " fg resistance %d, total: %d (mOhm)\n",
935 __func__, di->bat_temp, resist, di->bm->fg_res / 10,
936 (di->bm->fg_res / 10) + resist);
938 /* fg_res variable is in 0.1mOhm */
939 resist += di->bm->fg_res / 10;
945 * ab8500_fg_load_comp_volt_to_capacity() - Load compensated voltage based capacity
946 * @di: pointer to the ab8500_fg structure
948 * Returns battery capacity based on battery voltage that is load compensated
949 * for the voltage drop
951 static int ab8500_fg_load_comp_volt_to_capacity(struct ab8500_fg *di)
957 ab8500_fg_inst_curr_start(di);
960 vbat += ab8500_fg_bat_voltage(di);
962 usleep_range(5000, 6000);
963 } while (!ab8500_fg_inst_curr_done(di));
965 ab8500_fg_inst_curr_finalize(di, &di->inst_curr);
968 res = ab8500_fg_battery_resistance(di);
970 /* Use Ohms law to get the load compensated voltage */
971 vbat_comp = di->vbat - (di->inst_curr * res) / 1000;
973 dev_dbg(di->dev, "%s Measured Vbat: %dmV,Compensated Vbat %dmV, "
974 "R: %dmOhm, Current: %dmA Vbat Samples: %d\n",
975 __func__, di->vbat, vbat_comp, res, di->inst_curr, i);
977 return ab8500_fg_volt_to_capacity(di, vbat_comp);
981 * ab8500_fg_convert_mah_to_permille() - Capacity in mAh to permille
982 * @di: pointer to the ab8500_fg structure
983 * @cap_mah: capacity in mAh
985 * Converts capacity in mAh to capacity in permille
987 static int ab8500_fg_convert_mah_to_permille(struct ab8500_fg *di, int cap_mah)
989 return (cap_mah * 1000) / di->bat_cap.max_mah_design;
993 * ab8500_fg_convert_permille_to_mah() - Capacity in permille to mAh
994 * @di: pointer to the ab8500_fg structure
995 * @cap_pm: capacity in permille
997 * Converts capacity in permille to capacity in mAh
999 static int ab8500_fg_convert_permille_to_mah(struct ab8500_fg *di, int cap_pm)
1001 return cap_pm * di->bat_cap.max_mah_design / 1000;
1005 * ab8500_fg_convert_mah_to_uwh() - Capacity in mAh to uWh
1006 * @di: pointer to the ab8500_fg structure
1007 * @cap_mah: capacity in mAh
1009 * Converts capacity in mAh to capacity in uWh
1011 static int ab8500_fg_convert_mah_to_uwh(struct ab8500_fg *di, int cap_mah)
1017 * Capacity is in milli ampere hours (10^-3)Ah
1018 * Nominal voltage is in microvolts (10^-6)V
1019 * divide by 1000000 after multiplication to get to mWh
1021 div_res = ((u64) cap_mah) * ((u64) di->vbat_nom_uv);
1022 div_rem = do_div(div_res, 1000000);
1024 /* Make sure to round upwards if necessary */
1025 if (div_rem >= 1000000 / 2)
1028 return (int) div_res;
1032 * ab8500_fg_calc_cap_charging() - Calculate remaining capacity while charging
1033 * @di: pointer to the ab8500_fg structure
1035 * Return the capacity in mAh based on previous calculated capcity and the FG
1036 * accumulator register value. The filter is filled with this capacity
1038 static int ab8500_fg_calc_cap_charging(struct ab8500_fg *di)
1040 dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1045 /* Capacity should not be less than 0 */
1046 if (di->bat_cap.mah + di->accu_charge > 0)
1047 di->bat_cap.mah += di->accu_charge;
1049 di->bat_cap.mah = 0;
1051 * We force capacity to 100% once when the algorithm
1052 * reports that it's full.
1054 if (di->bat_cap.mah >= di->bat_cap.max_mah_design ||
1055 di->flags.force_full) {
1056 di->bat_cap.mah = di->bat_cap.max_mah_design;
1059 ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1060 di->bat_cap.permille =
1061 ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1063 /* We need to update battery voltage and inst current when charging */
1064 di->vbat = ab8500_fg_bat_voltage(di);
1065 di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1067 return di->bat_cap.mah;
1071 * ab8500_fg_calc_cap_discharge_voltage() - Capacity in discharge with voltage
1072 * @di: pointer to the ab8500_fg structure
1073 * @comp: if voltage should be load compensated before capacity calc
1075 * Return the capacity in mAh based on the battery voltage. The voltage can
1076 * either be load compensated or not. This value is added to the filter and a
1077 * new mean value is calculated and returned.
1079 static int ab8500_fg_calc_cap_discharge_voltage(struct ab8500_fg *di, bool comp)
1084 permille = ab8500_fg_load_comp_volt_to_capacity(di);
1086 permille = ab8500_fg_uncomp_volt_to_capacity(di);
1088 mah = ab8500_fg_convert_permille_to_mah(di, permille);
1090 di->bat_cap.mah = ab8500_fg_add_cap_sample(di, mah);
1091 di->bat_cap.permille =
1092 ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1094 return di->bat_cap.mah;
1098 * ab8500_fg_calc_cap_discharge_fg() - Capacity in discharge with FG
1099 * @di: pointer to the ab8500_fg structure
1101 * Return the capacity in mAh based on previous calculated capcity and the FG
1102 * accumulator register value. This value is added to the filter and a
1103 * new mean value is calculated and returned.
1105 static int ab8500_fg_calc_cap_discharge_fg(struct ab8500_fg *di)
1107 int permille_volt, permille;
1109 dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1114 /* Capacity should not be less than 0 */
1115 if (di->bat_cap.mah + di->accu_charge > 0)
1116 di->bat_cap.mah += di->accu_charge;
1118 di->bat_cap.mah = 0;
1120 if (di->bat_cap.mah >= di->bat_cap.max_mah_design)
1121 di->bat_cap.mah = di->bat_cap.max_mah_design;
1124 * Check against voltage based capacity. It can not be lower
1125 * than what the uncompensated voltage says
1127 permille = ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1128 permille_volt = ab8500_fg_uncomp_volt_to_capacity(di);
1130 if (permille < permille_volt) {
1131 di->bat_cap.permille = permille_volt;
1132 di->bat_cap.mah = ab8500_fg_convert_permille_to_mah(di,
1133 di->bat_cap.permille);
1135 dev_dbg(di->dev, "%s voltage based: perm %d perm_volt %d\n",
1140 ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1142 ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1143 di->bat_cap.permille =
1144 ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1147 return di->bat_cap.mah;
1151 * ab8500_fg_capacity_level() - Get the battery capacity level
1152 * @di: pointer to the ab8500_fg structure
1154 * Get the battery capacity level based on the capacity in percent
1156 static int ab8500_fg_capacity_level(struct ab8500_fg *di)
1160 percent = DIV_ROUND_CLOSEST(di->bat_cap.permille, 10);
1162 if (percent <= di->bm->cap_levels->critical ||
1164 ret = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1165 else if (percent <= di->bm->cap_levels->low)
1166 ret = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1167 else if (percent <= di->bm->cap_levels->normal)
1168 ret = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1169 else if (percent <= di->bm->cap_levels->high)
1170 ret = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
1172 ret = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1178 * ab8500_fg_calculate_scaled_capacity() - Capacity scaling
1179 * @di: pointer to the ab8500_fg structure
1181 * Calculates the capacity to be shown to upper layers. Scales the capacity
1182 * to have 100% as a reference from the actual capacity upon removal of charger
1183 * when charging is in maintenance mode.
1185 static int ab8500_fg_calculate_scaled_capacity(struct ab8500_fg *di)
1187 struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1188 int capacity = di->bat_cap.prev_percent;
1194 * As long as we are in fully charge mode scale the capacity
1197 if (di->flags.fully_charged) {
1198 cs->cap_to_scale[0] = 100;
1199 cs->cap_to_scale[1] =
1200 max(capacity, di->bm->fg_params->maint_thres);
1201 dev_dbg(di->dev, "Scale cap with %d/%d\n",
1202 cs->cap_to_scale[0], cs->cap_to_scale[1]);
1205 /* Calculates the scaled capacity. */
1206 if ((cs->cap_to_scale[0] != cs->cap_to_scale[1])
1207 && (cs->cap_to_scale[1] > 0))
1209 DIV_ROUND_CLOSEST(di->bat_cap.prev_percent *
1210 cs->cap_to_scale[0],
1211 cs->cap_to_scale[1]));
1213 if (di->flags.charging) {
1214 if (capacity < cs->disable_cap_level) {
1215 cs->disable_cap_level = capacity;
1216 dev_dbg(di->dev, "Cap to stop scale lowered %d%%\n",
1217 cs->disable_cap_level);
1218 } else if (!di->flags.fully_charged) {
1219 if (di->bat_cap.prev_percent >=
1220 cs->disable_cap_level) {
1221 dev_dbg(di->dev, "Disabling scaled capacity\n");
1223 capacity = di->bat_cap.prev_percent;
1226 "Waiting in cap to level %d%%\n",
1227 cs->disable_cap_level);
1228 capacity = cs->disable_cap_level;
1237 * ab8500_fg_update_cap_scalers() - Capacity scaling
1238 * @di: pointer to the ab8500_fg structure
1240 * To be called when state change from charge<->discharge to update
1241 * the capacity scalers.
1243 static void ab8500_fg_update_cap_scalers(struct ab8500_fg *di)
1245 struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1249 if (di->flags.charging) {
1250 di->bat_cap.cap_scale.disable_cap_level =
1251 di->bat_cap.cap_scale.scaled_cap;
1252 dev_dbg(di->dev, "Cap to stop scale at charge %d%%\n",
1253 di->bat_cap.cap_scale.disable_cap_level);
1255 if (cs->scaled_cap != 100) {
1256 cs->cap_to_scale[0] = cs->scaled_cap;
1257 cs->cap_to_scale[1] = di->bat_cap.prev_percent;
1259 cs->cap_to_scale[0] = 100;
1260 cs->cap_to_scale[1] =
1261 max(di->bat_cap.prev_percent,
1262 di->bm->fg_params->maint_thres);
1265 dev_dbg(di->dev, "Cap to scale at discharge %d/%d\n",
1266 cs->cap_to_scale[0], cs->cap_to_scale[1]);
1271 * ab8500_fg_check_capacity_limits() - Check if capacity has changed
1272 * @di: pointer to the ab8500_fg structure
1273 * @init: capacity is allowed to go up in init mode
1275 * Check if capacity or capacity limit has changed and notify the system
1276 * about it using the power_supply framework
1278 static void ab8500_fg_check_capacity_limits(struct ab8500_fg *di, bool init)
1280 bool changed = false;
1281 int percent = DIV_ROUND_CLOSEST(di->bat_cap.permille, 10);
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;
1314 di->bat_cap.prev_mah = 0;
1315 di->bat_cap.mah = 0;
1317 } else if (di->flags.fully_charged) {
1319 * We report 100% if algorithm reported fully charged
1320 * and show 100% during maintenance charging (scaling).
1322 if (di->flags.force_full) {
1323 di->bat_cap.prev_percent = percent;
1324 di->bat_cap.prev_mah = di->bat_cap.mah;
1328 if (!di->bat_cap.cap_scale.enable &&
1329 di->bm->capacity_scaling) {
1330 di->bat_cap.cap_scale.enable = true;
1331 di->bat_cap.cap_scale.cap_to_scale[0] = 100;
1332 di->bat_cap.cap_scale.cap_to_scale[1] =
1333 di->bat_cap.prev_percent;
1334 di->bat_cap.cap_scale.disable_cap_level = 100;
1336 } else if (di->bat_cap.prev_percent != percent) {
1338 "battery reported full "
1339 "but capacity dropping: %d\n",
1341 di->bat_cap.prev_percent = percent;
1342 di->bat_cap.prev_mah = di->bat_cap.mah;
1346 } else if (di->bat_cap.prev_percent != percent) {
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;
1357 } else if (!(!di->flags.charging &&
1358 percent > di->bat_cap.prev_percent) || init) {
1360 * We do not allow reported capacity to go up
1361 * unless we're charging or if we're in init
1364 "capacity changed from %d to %d (%d)\n",
1365 di->bat_cap.prev_percent,
1367 di->bat_cap.permille);
1368 di->bat_cap.prev_percent = percent;
1369 di->bat_cap.prev_mah = di->bat_cap.mah;
1373 dev_dbg(di->dev, "capacity not allowed to go up since "
1374 "no charger is connected: %d to %d (%d)\n",
1375 di->bat_cap.prev_percent,
1377 di->bat_cap.permille);
1382 if (di->bm->capacity_scaling) {
1383 di->bat_cap.cap_scale.scaled_cap =
1384 ab8500_fg_calculate_scaled_capacity(di);
1386 dev_info(di->dev, "capacity=%d (%d)\n",
1387 di->bat_cap.prev_percent,
1388 di->bat_cap.cap_scale.scaled_cap);
1390 power_supply_changed(di->fg_psy);
1391 if (di->flags.fully_charged && di->flags.force_full) {
1392 dev_dbg(di->dev, "Battery full, notifying.\n");
1393 di->flags.force_full = false;
1394 sysfs_notify(&di->fg_kobject, NULL, "charge_full");
1396 sysfs_notify(&di->fg_kobject, NULL, "charge_now");
1400 static void ab8500_fg_charge_state_to(struct ab8500_fg *di,
1401 enum ab8500_fg_charge_state new_state)
1403 dev_dbg(di->dev, "Charge state from %d [%s] to %d [%s]\n",
1405 charge_state[di->charge_state],
1407 charge_state[new_state]);
1409 di->charge_state = new_state;
1412 static void ab8500_fg_discharge_state_to(struct ab8500_fg *di,
1413 enum ab8500_fg_discharge_state new_state)
1415 dev_dbg(di->dev, "Discharge state from %d [%s] to %d [%s]\n",
1416 di->discharge_state,
1417 discharge_state[di->discharge_state],
1419 discharge_state[new_state]);
1421 di->discharge_state = new_state;
1425 * ab8500_fg_algorithm_charging() - FG algorithm for when charging
1426 * @di: pointer to the ab8500_fg structure
1428 * Battery capacity calculation state machine for when we're charging
1430 static void ab8500_fg_algorithm_charging(struct ab8500_fg *di)
1433 * If we change to discharge mode
1434 * we should start with recovery
1436 if (di->discharge_state != AB8500_FG_DISCHARGE_INIT_RECOVERY)
1437 ab8500_fg_discharge_state_to(di,
1438 AB8500_FG_DISCHARGE_INIT_RECOVERY);
1440 switch (di->charge_state) {
1441 case AB8500_FG_CHARGE_INIT:
1442 di->fg_samples = SEC_TO_SAMPLE(
1443 di->bm->fg_params->accu_charging);
1445 ab8500_fg_coulomb_counter(di, true);
1446 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_READOUT);
1450 case AB8500_FG_CHARGE_READOUT:
1452 * Read the FG and calculate the new capacity
1454 mutex_lock(&di->cc_lock);
1455 if (!di->flags.conv_done && !di->flags.force_full) {
1456 /* Wasn't the CC IRQ that got us here */
1457 mutex_unlock(&di->cc_lock);
1458 dev_dbg(di->dev, "%s CC conv not done\n",
1463 di->flags.conv_done = false;
1464 mutex_unlock(&di->cc_lock);
1466 ab8500_fg_calc_cap_charging(di);
1474 /* Check capacity limits */
1475 ab8500_fg_check_capacity_limits(di, false);
1478 static void force_capacity(struct ab8500_fg *di)
1482 ab8500_fg_clear_cap_samples(di);
1483 cap = di->bat_cap.user_mah;
1484 if (cap > di->bat_cap.max_mah_design) {
1485 dev_dbg(di->dev, "Remaining cap %d can't be bigger than total"
1486 " %d\n", cap, di->bat_cap.max_mah_design);
1487 cap = di->bat_cap.max_mah_design;
1489 ab8500_fg_fill_cap_sample(di, di->bat_cap.user_mah);
1490 di->bat_cap.permille = ab8500_fg_convert_mah_to_permille(di, cap);
1491 di->bat_cap.mah = cap;
1492 ab8500_fg_check_capacity_limits(di, true);
1495 static bool check_sysfs_capacity(struct ab8500_fg *di)
1497 int cap, lower, upper;
1500 cap = di->bat_cap.user_mah;
1502 cap_permille = ab8500_fg_convert_mah_to_permille(di,
1503 di->bat_cap.user_mah);
1505 lower = di->bat_cap.permille - di->bm->fg_params->user_cap_limit * 10;
1506 upper = di->bat_cap.permille + di->bm->fg_params->user_cap_limit * 10;
1510 /* 1000 is permille, -> 100 percent */
1514 dev_dbg(di->dev, "Capacity limits:"
1515 " (Lower: %d User: %d Upper: %d) [user: %d, was: %d]\n",
1516 lower, cap_permille, upper, cap, di->bat_cap.mah);
1518 /* If within limits, use the saved capacity and exit estimation...*/
1519 if (cap_permille > lower && cap_permille < upper) {
1520 dev_dbg(di->dev, "OK! Using users cap %d uAh now\n", cap);
1524 dev_dbg(di->dev, "Capacity from user out of limits, ignoring");
1529 * ab8500_fg_algorithm_discharging() - FG algorithm for when discharging
1530 * @di: pointer to the ab8500_fg structure
1532 * Battery capacity calculation state machine for when we're discharging
1534 static void ab8500_fg_algorithm_discharging(struct ab8500_fg *di)
1538 /* If we change to charge mode we should start with init */
1539 if (di->charge_state != AB8500_FG_CHARGE_INIT)
1540 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
1542 switch (di->discharge_state) {
1543 case AB8500_FG_DISCHARGE_INIT:
1544 /* We use the FG IRQ to work on */
1546 di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
1547 ab8500_fg_coulomb_counter(di, true);
1548 ab8500_fg_discharge_state_to(di,
1549 AB8500_FG_DISCHARGE_INITMEASURING);
1552 case AB8500_FG_DISCHARGE_INITMEASURING:
1554 * Discard a number of samples during startup.
1555 * After that, use compensated voltage for a few
1556 * samples to get an initial capacity.
1557 * Then go to READOUT
1559 sleep_time = di->bm->fg_params->init_timer;
1561 /* Discard the first [x] seconds */
1562 if (di->init_cnt > di->bm->fg_params->init_discard_time) {
1563 ab8500_fg_calc_cap_discharge_voltage(di, true);
1565 ab8500_fg_check_capacity_limits(di, true);
1568 di->init_cnt += sleep_time;
1569 if (di->init_cnt > di->bm->fg_params->init_total_time)
1570 ab8500_fg_discharge_state_to(di,
1571 AB8500_FG_DISCHARGE_READOUT_INIT);
1575 case AB8500_FG_DISCHARGE_INIT_RECOVERY:
1576 di->recovery_cnt = 0;
1577 di->recovery_needed = true;
1578 ab8500_fg_discharge_state_to(di,
1579 AB8500_FG_DISCHARGE_RECOVERY);
1583 case AB8500_FG_DISCHARGE_RECOVERY:
1584 sleep_time = di->bm->fg_params->recovery_sleep_timer;
1587 * We should check the power consumption
1588 * If low, go to READOUT (after x min) or
1589 * RECOVERY_SLEEP if time left.
1590 * If high, go to READOUT
1592 di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1594 if (ab8500_fg_is_low_curr(di, di->inst_curr)) {
1595 if (di->recovery_cnt >
1596 di->bm->fg_params->recovery_total_time) {
1597 di->fg_samples = SEC_TO_SAMPLE(
1598 di->bm->fg_params->accu_high_curr);
1599 ab8500_fg_coulomb_counter(di, true);
1600 ab8500_fg_discharge_state_to(di,
1601 AB8500_FG_DISCHARGE_READOUT);
1602 di->recovery_needed = false;
1604 queue_delayed_work(di->fg_wq,
1605 &di->fg_periodic_work,
1608 di->recovery_cnt += sleep_time;
1610 di->fg_samples = SEC_TO_SAMPLE(
1611 di->bm->fg_params->accu_high_curr);
1612 ab8500_fg_coulomb_counter(di, true);
1613 ab8500_fg_discharge_state_to(di,
1614 AB8500_FG_DISCHARGE_READOUT);
1618 case AB8500_FG_DISCHARGE_READOUT_INIT:
1619 di->fg_samples = SEC_TO_SAMPLE(
1620 di->bm->fg_params->accu_high_curr);
1621 ab8500_fg_coulomb_counter(di, true);
1622 ab8500_fg_discharge_state_to(di,
1623 AB8500_FG_DISCHARGE_READOUT);
1626 case AB8500_FG_DISCHARGE_READOUT:
1627 di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1629 if (ab8500_fg_is_low_curr(di, di->inst_curr)) {
1630 /* Detect mode change */
1631 if (di->high_curr_mode) {
1632 di->high_curr_mode = false;
1633 di->high_curr_cnt = 0;
1636 if (di->recovery_needed) {
1637 ab8500_fg_discharge_state_to(di,
1638 AB8500_FG_DISCHARGE_INIT_RECOVERY);
1640 queue_delayed_work(di->fg_wq,
1641 &di->fg_periodic_work, 0);
1646 ab8500_fg_calc_cap_discharge_voltage(di, true);
1648 mutex_lock(&di->cc_lock);
1649 if (!di->flags.conv_done) {
1650 /* Wasn't the CC IRQ that got us here */
1651 mutex_unlock(&di->cc_lock);
1652 dev_dbg(di->dev, "%s CC conv not done\n",
1657 di->flags.conv_done = false;
1658 mutex_unlock(&di->cc_lock);
1660 /* Detect mode change */
1661 if (!di->high_curr_mode) {
1662 di->high_curr_mode = true;
1663 di->high_curr_cnt = 0;
1666 di->high_curr_cnt +=
1667 di->bm->fg_params->accu_high_curr;
1668 if (di->high_curr_cnt >
1669 di->bm->fg_params->high_curr_time)
1670 di->recovery_needed = true;
1672 ab8500_fg_calc_cap_discharge_fg(di);
1675 ab8500_fg_check_capacity_limits(di, false);
1679 case AB8500_FG_DISCHARGE_WAKEUP:
1680 ab8500_fg_calc_cap_discharge_voltage(di, true);
1682 di->fg_samples = SEC_TO_SAMPLE(
1683 di->bm->fg_params->accu_high_curr);
1684 ab8500_fg_coulomb_counter(di, true);
1685 ab8500_fg_discharge_state_to(di,
1686 AB8500_FG_DISCHARGE_READOUT);
1688 ab8500_fg_check_capacity_limits(di, false);
1698 * ab8500_fg_algorithm_calibrate() - Internal columb counter offset calibration
1699 * @di: pointer to the ab8500_fg structure
1702 static void ab8500_fg_algorithm_calibrate(struct ab8500_fg *di)
1706 switch (di->calib_state) {
1707 case AB8500_FG_CALIB_INIT:
1708 dev_dbg(di->dev, "Calibration ongoing...\n");
1710 ret = abx500_mask_and_set_register_interruptible(di->dev,
1711 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1712 CC_INT_CAL_N_AVG_MASK, CC_INT_CAL_SAMPLES_8);
1716 ret = abx500_mask_and_set_register_interruptible(di->dev,
1717 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1718 CC_INTAVGOFFSET_ENA, CC_INTAVGOFFSET_ENA);
1721 di->calib_state = AB8500_FG_CALIB_WAIT;
1723 case AB8500_FG_CALIB_END:
1724 ret = abx500_mask_and_set_register_interruptible(di->dev,
1725 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1726 CC_MUXOFFSET, CC_MUXOFFSET);
1729 di->flags.calibrate = false;
1730 dev_dbg(di->dev, "Calibration done...\n");
1731 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1733 case AB8500_FG_CALIB_WAIT:
1734 dev_dbg(di->dev, "Calibration WFI\n");
1741 /* Something went wrong, don't calibrate then */
1742 dev_err(di->dev, "failed to calibrate the CC\n");
1743 di->flags.calibrate = false;
1744 di->calib_state = AB8500_FG_CALIB_INIT;
1745 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1749 * ab8500_fg_algorithm() - Entry point for the FG algorithm
1750 * @di: pointer to the ab8500_fg structure
1752 * Entry point for the battery capacity calculation state machine
1754 static void ab8500_fg_algorithm(struct ab8500_fg *di)
1756 if (di->flags.calibrate)
1757 ab8500_fg_algorithm_calibrate(di);
1759 if (di->flags.charging)
1760 ab8500_fg_algorithm_charging(di);
1762 ab8500_fg_algorithm_discharging(di);
1765 dev_dbg(di->dev, "[FG_DATA] %d %d %d %d %d %d %d %d %d %d "
1766 "%d %d %d %d %d %d %d\n",
1767 di->bat_cap.max_mah_design,
1768 di->bat_cap.max_mah,
1770 di->bat_cap.permille,
1772 di->bat_cap.prev_mah,
1773 di->bat_cap.prev_percent,
1774 di->bat_cap.prev_level,
1781 di->discharge_state,
1783 di->recovery_needed);
1787 * ab8500_fg_periodic_work() - Run the FG state machine periodically
1788 * @work: pointer to the work_struct structure
1790 * Work queue function for periodic work
1792 static void ab8500_fg_periodic_work(struct work_struct *work)
1794 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1795 fg_periodic_work.work);
1797 if (di->init_capacity) {
1798 /* Get an initial capacity calculation */
1799 ab8500_fg_calc_cap_discharge_voltage(di, true);
1800 ab8500_fg_check_capacity_limits(di, true);
1801 di->init_capacity = false;
1803 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1804 } else if (di->flags.user_cap) {
1805 if (check_sysfs_capacity(di)) {
1806 ab8500_fg_check_capacity_limits(di, true);
1807 if (di->flags.charging)
1808 ab8500_fg_charge_state_to(di,
1809 AB8500_FG_CHARGE_INIT);
1811 ab8500_fg_discharge_state_to(di,
1812 AB8500_FG_DISCHARGE_READOUT_INIT);
1814 di->flags.user_cap = false;
1815 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1817 ab8500_fg_algorithm(di);
1822 * ab8500_fg_check_hw_failure_work() - Check OVV_BAT condition
1823 * @work: pointer to the work_struct structure
1825 * Work queue function for checking the OVV_BAT condition
1827 static void ab8500_fg_check_hw_failure_work(struct work_struct *work)
1832 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1833 fg_check_hw_failure_work.work);
1836 * If we have had a battery over-voltage situation,
1837 * check ovv-bit to see if it should be reset.
1839 ret = abx500_get_register_interruptible(di->dev,
1840 AB8500_CHARGER, AB8500_CH_STAT_REG,
1843 dev_err(di->dev, "%s ab8500 read failed\n", __func__);
1846 if ((reg_value & BATT_OVV) == BATT_OVV) {
1847 if (!di->flags.bat_ovv) {
1848 dev_dbg(di->dev, "Battery OVV\n");
1849 di->flags.bat_ovv = true;
1850 power_supply_changed(di->fg_psy);
1852 /* Not yet recovered from ovv, reschedule this test */
1853 queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work,
1856 dev_dbg(di->dev, "Battery recovered from OVV\n");
1857 di->flags.bat_ovv = false;
1858 power_supply_changed(di->fg_psy);
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 /* Is it time to shut down? */
1880 if (di->low_bat_cnt < 1) {
1881 di->flags.low_bat = true;
1882 dev_warn(di->dev, "Shut down pending...\n");
1885 * Else we need to re-schedule this check to be able to detect
1886 * if the voltage increases again during charging or
1887 * due to decreasing load.
1890 dev_warn(di->dev, "Battery voltage still LOW\n");
1891 queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
1892 round_jiffies(LOW_BAT_CHECK_INTERVAL));
1895 di->flags.low_bat_delay = false;
1896 di->low_bat_cnt = 10;
1897 dev_warn(di->dev, "Battery voltage OK again\n");
1900 /* This is needed to dispatch LOW_BAT */
1901 ab8500_fg_check_capacity_limits(di, false);
1905 * ab8500_fg_battok_calc - calculate the bit pattern corresponding
1906 * to the target voltage.
1907 * @di: pointer to the ab8500_fg structure
1908 * @target: target voltage
1910 * Returns bit pattern closest to the target voltage
1911 * valid return values are 0-14. (0-BATT_OK_MAX_NR_INCREMENTS)
1914 static int ab8500_fg_battok_calc(struct ab8500_fg *di, int target)
1916 if (target > BATT_OK_MIN +
1917 (BATT_OK_INCREMENT * BATT_OK_MAX_NR_INCREMENTS))
1918 return BATT_OK_MAX_NR_INCREMENTS;
1919 if (target < BATT_OK_MIN)
1921 return (target - BATT_OK_MIN) / BATT_OK_INCREMENT;
1925 * ab8500_fg_battok_init_hw_register - init battok levels
1926 * @di: pointer to the ab8500_fg structure
1930 static int ab8500_fg_battok_init_hw_register(struct ab8500_fg *di)
1940 sel0 = di->bm->fg_params->battok_falling_th_sel0;
1941 sel1 = di->bm->fg_params->battok_raising_th_sel1;
1943 cbp_sel0 = ab8500_fg_battok_calc(di, sel0);
1944 cbp_sel1 = ab8500_fg_battok_calc(di, sel1);
1946 selected = BATT_OK_MIN + cbp_sel0 * BATT_OK_INCREMENT;
1948 if (selected != sel0)
1949 dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1950 sel0, selected, cbp_sel0);
1952 selected = BATT_OK_MIN + cbp_sel1 * BATT_OK_INCREMENT;
1954 if (selected != sel1)
1955 dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1956 sel1, selected, cbp_sel1);
1958 new_val = cbp_sel0 | (cbp_sel1 << 4);
1960 dev_dbg(di->dev, "using: %x %d %d\n", new_val, cbp_sel0, cbp_sel1);
1961 ret = abx500_set_register_interruptible(di->dev, AB8500_SYS_CTRL2_BLOCK,
1962 AB8500_BATT_OK_REG, new_val);
1967 * ab8500_fg_instant_work() - Run the FG state machine instantly
1968 * @work: pointer to the work_struct structure
1970 * Work queue function for instant work
1972 static void ab8500_fg_instant_work(struct work_struct *work)
1974 struct ab8500_fg *di = container_of(work, struct ab8500_fg, fg_work);
1976 ab8500_fg_algorithm(di);
1980 * ab8500_fg_cc_data_end_handler() - end of data conversion isr.
1981 * @irq: interrupt number
1982 * @_di: pointer to the ab8500_fg structure
1984 * Returns IRQ status(IRQ_HANDLED)
1986 static irqreturn_t ab8500_fg_cc_data_end_handler(int irq, void *_di)
1988 struct ab8500_fg *di = _di;
1989 if (!di->nbr_cceoc_irq_cnt) {
1990 di->nbr_cceoc_irq_cnt++;
1991 complete(&di->ab8500_fg_started);
1993 di->nbr_cceoc_irq_cnt = 0;
1994 complete(&di->ab8500_fg_complete);
2000 * ab8500_fg_cc_int_calib_handler () - end of calibration isr.
2001 * @irq: interrupt number
2002 * @_di: pointer to the ab8500_fg structure
2004 * Returns IRQ status(IRQ_HANDLED)
2006 static irqreturn_t ab8500_fg_cc_int_calib_handler(int irq, void *_di)
2008 struct ab8500_fg *di = _di;
2009 di->calib_state = AB8500_FG_CALIB_END;
2010 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2015 * ab8500_fg_cc_convend_handler() - isr to get battery avg current.
2016 * @irq: interrupt number
2017 * @_di: pointer to the ab8500_fg structure
2019 * Returns IRQ status(IRQ_HANDLED)
2021 static irqreturn_t ab8500_fg_cc_convend_handler(int irq, void *_di)
2023 struct ab8500_fg *di = _di;
2025 queue_work(di->fg_wq, &di->fg_acc_cur_work);
2031 * ab8500_fg_batt_ovv_handler() - Battery OVV occured
2032 * @irq: interrupt number
2033 * @_di: pointer to the ab8500_fg structure
2035 * Returns IRQ status(IRQ_HANDLED)
2037 static irqreturn_t ab8500_fg_batt_ovv_handler(int irq, void *_di)
2039 struct ab8500_fg *di = _di;
2041 dev_dbg(di->dev, "Battery OVV\n");
2043 /* Schedule a new HW failure check */
2044 queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work, 0);
2050 * ab8500_fg_lowbatf_handler() - Battery voltage is below LOW threshold
2051 * @irq: interrupt number
2052 * @_di: pointer to the ab8500_fg structure
2054 * Returns IRQ status(IRQ_HANDLED)
2056 static irqreturn_t ab8500_fg_lowbatf_handler(int irq, void *_di)
2058 struct ab8500_fg *di = _di;
2060 /* Initiate handling in ab8500_fg_low_bat_work() if not already initiated. */
2061 if (!di->flags.low_bat_delay) {
2062 dev_warn(di->dev, "Battery voltage is below LOW threshold\n");
2063 di->flags.low_bat_delay = true;
2065 * Start a timer to check LOW_BAT again after some time
2066 * This is done to avoid shutdown on single voltage dips
2068 queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
2069 round_jiffies(LOW_BAT_CHECK_INTERVAL));
2075 * ab8500_fg_get_property() - get the fg properties
2076 * @psy: pointer to the power_supply structure
2077 * @psp: pointer to the power_supply_property structure
2078 * @val: pointer to the power_supply_propval union
2080 * This function gets called when an application tries to get the
2081 * fg properties by reading the sysfs files.
2082 * voltage_now: battery voltage
2083 * current_now: battery instant current
2084 * current_avg: battery average current
2085 * charge_full_design: capacity where battery is considered full
2086 * charge_now: battery capacity in nAh
2087 * capacity: capacity in percent
2088 * capacity_level: capacity level
2090 * Returns error code in case of failure else 0 on success
2092 static int ab8500_fg_get_property(struct power_supply *psy,
2093 enum power_supply_property psp,
2094 union power_supply_propval *val)
2096 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2099 * If battery is identified as unknown and charging of unknown
2100 * batteries is disabled, we always report 100% capacity and
2101 * capacity level UNKNOWN, since we can't calculate
2102 * remaining capacity
2106 case POWER_SUPPLY_PROP_VOLTAGE_NOW:
2107 if (di->flags.bat_ovv)
2108 val->intval = BATT_OVV_VALUE * 1000;
2110 val->intval = di->vbat * 1000;
2112 case POWER_SUPPLY_PROP_CURRENT_NOW:
2113 val->intval = di->inst_curr * 1000;
2115 case POWER_SUPPLY_PROP_CURRENT_AVG:
2116 val->intval = di->avg_curr * 1000;
2118 case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
2119 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2120 di->bat_cap.max_mah_design);
2122 case POWER_SUPPLY_PROP_ENERGY_FULL:
2123 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2124 di->bat_cap.max_mah);
2126 case POWER_SUPPLY_PROP_ENERGY_NOW:
2127 if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2128 di->flags.batt_id_received)
2129 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2130 di->bat_cap.max_mah);
2132 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2133 di->bat_cap.prev_mah);
2135 case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
2136 val->intval = di->bat_cap.max_mah_design;
2138 case POWER_SUPPLY_PROP_CHARGE_FULL:
2139 val->intval = di->bat_cap.max_mah;
2141 case POWER_SUPPLY_PROP_CHARGE_NOW:
2142 if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2143 di->flags.batt_id_received)
2144 val->intval = di->bat_cap.max_mah;
2146 val->intval = di->bat_cap.prev_mah;
2148 case POWER_SUPPLY_PROP_CAPACITY:
2149 if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2150 di->flags.batt_id_received)
2153 val->intval = di->bat_cap.prev_percent;
2155 case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
2156 if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2157 di->flags.batt_id_received)
2158 val->intval = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
2160 val->intval = di->bat_cap.prev_level;
2168 static int ab8500_fg_get_ext_psy_data(struct device *dev, void *data)
2170 struct power_supply *psy;
2171 struct power_supply *ext = dev_get_drvdata(dev);
2172 const char **supplicants = (const char **)ext->supplied_to;
2173 struct ab8500_fg *di;
2174 union power_supply_propval ret;
2177 psy = (struct power_supply *)data;
2178 di = power_supply_get_drvdata(psy);
2181 * For all psy where the name of your driver
2182 * appears in any supplied_to
2184 j = match_string(supplicants, ext->num_supplicants, psy->desc->name);
2188 /* Go through all properties for the psy */
2189 for (j = 0; j < ext->desc->num_properties; j++) {
2190 enum power_supply_property prop;
2191 prop = ext->desc->properties[j];
2193 if (power_supply_get_property(ext, prop, &ret))
2197 case POWER_SUPPLY_PROP_STATUS:
2198 switch (ext->desc->type) {
2199 case POWER_SUPPLY_TYPE_BATTERY:
2200 switch (ret.intval) {
2201 case POWER_SUPPLY_STATUS_UNKNOWN:
2202 case POWER_SUPPLY_STATUS_DISCHARGING:
2203 case POWER_SUPPLY_STATUS_NOT_CHARGING:
2204 if (!di->flags.charging)
2206 di->flags.charging = false;
2207 di->flags.fully_charged = false;
2208 if (di->bm->capacity_scaling)
2209 ab8500_fg_update_cap_scalers(di);
2210 queue_work(di->fg_wq, &di->fg_work);
2212 case POWER_SUPPLY_STATUS_FULL:
2213 if (di->flags.fully_charged)
2215 di->flags.fully_charged = true;
2216 di->flags.force_full = true;
2217 /* Save current capacity as maximum */
2218 di->bat_cap.max_mah = di->bat_cap.mah;
2219 queue_work(di->fg_wq, &di->fg_work);
2221 case POWER_SUPPLY_STATUS_CHARGING:
2222 if (di->flags.charging &&
2223 !di->flags.fully_charged)
2225 di->flags.charging = true;
2226 di->flags.fully_charged = false;
2227 if (di->bm->capacity_scaling)
2228 ab8500_fg_update_cap_scalers(di);
2229 queue_work(di->fg_wq, &di->fg_work);
2237 case POWER_SUPPLY_PROP_TECHNOLOGY:
2238 switch (ext->desc->type) {
2239 case POWER_SUPPLY_TYPE_BATTERY:
2240 if (!di->flags.batt_id_received &&
2241 (di->bm->bi.technology !=
2242 POWER_SUPPLY_TECHNOLOGY_UNKNOWN)) {
2243 const struct ab8500_battery_type *b;
2245 b = di->bm->bat_type;
2247 di->flags.batt_id_received = true;
2249 di->bat_cap.max_mah_design =
2250 di->bm->bi.charge_full_design_uah;
2252 di->bat_cap.max_mah =
2253 di->bat_cap.max_mah_design;
2256 di->bm->bi.voltage_max_design_uv;
2260 di->flags.batt_unknown = false;
2262 di->flags.batt_unknown = true;
2268 case POWER_SUPPLY_PROP_TEMP:
2269 switch (ext->desc->type) {
2270 case POWER_SUPPLY_TYPE_BATTERY:
2271 if (di->flags.batt_id_received)
2272 di->bat_temp = ret.intval;
2286 * ab8500_fg_init_hw_registers() - Set up FG related registers
2287 * @di: pointer to the ab8500_fg structure
2289 * Set up battery OVV, low battery voltage registers
2291 static int ab8500_fg_init_hw_registers(struct ab8500_fg *di)
2295 /* Set VBAT OVV threshold */
2296 ret = abx500_mask_and_set_register_interruptible(di->dev,
2302 dev_err(di->dev, "failed to set BATT_OVV\n");
2306 /* Enable VBAT OVV detection */
2307 ret = abx500_mask_and_set_register_interruptible(di->dev,
2313 dev_err(di->dev, "failed to enable BATT_OVV\n");
2317 /* Low Battery Voltage */
2318 ret = abx500_set_register_interruptible(di->dev,
2319 AB8500_SYS_CTRL2_BLOCK,
2321 ab8500_volt_to_regval(
2322 di->bm->fg_params->lowbat_threshold) << 1 |
2325 dev_err(di->dev, "%s write failed\n", __func__);
2329 /* Battery OK threshold */
2330 ret = ab8500_fg_battok_init_hw_register(di);
2332 dev_err(di->dev, "BattOk init write failed.\n");
2336 if (is_ab8505(di->parent)) {
2337 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2338 AB8505_RTC_PCUT_MAX_TIME_REG, di->bm->fg_params->pcut_max_time);
2341 dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_MAX_TIME_REG\n", __func__);
2345 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2346 AB8505_RTC_PCUT_FLAG_TIME_REG, di->bm->fg_params->pcut_flag_time);
2349 dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_FLAG_TIME_REG\n", __func__);
2353 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2354 AB8505_RTC_PCUT_RESTART_REG, di->bm->fg_params->pcut_max_restart);
2357 dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_RESTART_REG\n", __func__);
2361 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2362 AB8505_RTC_PCUT_DEBOUNCE_REG, di->bm->fg_params->pcut_debounce_time);
2365 dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_DEBOUNCE_REG\n", __func__);
2369 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2370 AB8505_RTC_PCUT_CTL_STATUS_REG, di->bm->fg_params->pcut_enable);
2373 dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_CTL_STATUS_REG\n", __func__);
2382 * ab8500_fg_external_power_changed() - callback for power supply changes
2383 * @psy: pointer to the structure power_supply
2385 * This function is the entry point of the pointer external_power_changed
2386 * of the structure power_supply.
2387 * This function gets executed when there is a change in any external power
2388 * supply that this driver needs to be notified of.
2390 static void ab8500_fg_external_power_changed(struct power_supply *psy)
2392 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2394 class_for_each_device(power_supply_class, NULL,
2395 di->fg_psy, ab8500_fg_get_ext_psy_data);
2399 * ab8500_fg_reinit_work() - work to reset the FG algorithm
2400 * @work: pointer to the work_struct structure
2402 * Used to reset the current battery capacity to be able to
2403 * retrigger a new voltage base capacity calculation. For
2404 * test and verification purpose.
2406 static void ab8500_fg_reinit_work(struct work_struct *work)
2408 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
2409 fg_reinit_work.work);
2411 if (!di->flags.calibrate) {
2412 dev_dbg(di->dev, "Resetting FG state machine to init.\n");
2413 ab8500_fg_clear_cap_samples(di);
2414 ab8500_fg_calc_cap_discharge_voltage(di, true);
2415 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
2416 ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
2417 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2420 dev_err(di->dev, "Residual offset calibration ongoing "
2422 /* Wait one second until next try*/
2423 queue_delayed_work(di->fg_wq, &di->fg_reinit_work,
2428 /* Exposure to the sysfs interface */
2430 struct ab8500_fg_sysfs_entry {
2431 struct attribute attr;
2432 ssize_t (*show)(struct ab8500_fg *, char *);
2433 ssize_t (*store)(struct ab8500_fg *, const char *, size_t);
2436 static ssize_t charge_full_show(struct ab8500_fg *di, char *buf)
2438 return sprintf(buf, "%d\n", di->bat_cap.max_mah);
2441 static ssize_t charge_full_store(struct ab8500_fg *di, const char *buf,
2444 unsigned long charge_full;
2447 ret = kstrtoul(buf, 10, &charge_full);
2451 di->bat_cap.max_mah = (int) charge_full;
2455 static ssize_t charge_now_show(struct ab8500_fg *di, char *buf)
2457 return sprintf(buf, "%d\n", di->bat_cap.prev_mah);
2460 static ssize_t charge_now_store(struct ab8500_fg *di, const char *buf,
2463 unsigned long charge_now;
2466 ret = kstrtoul(buf, 10, &charge_now);
2470 di->bat_cap.user_mah = (int) charge_now;
2471 di->flags.user_cap = true;
2472 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2476 static struct ab8500_fg_sysfs_entry charge_full_attr =
2477 __ATTR(charge_full, 0644, charge_full_show, charge_full_store);
2479 static struct ab8500_fg_sysfs_entry charge_now_attr =
2480 __ATTR(charge_now, 0644, charge_now_show, charge_now_store);
2483 ab8500_fg_show(struct kobject *kobj, struct attribute *attr, char *buf)
2485 struct ab8500_fg_sysfs_entry *entry;
2486 struct ab8500_fg *di;
2488 entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2489 di = container_of(kobj, struct ab8500_fg, fg_kobject);
2494 return entry->show(di, buf);
2497 ab8500_fg_store(struct kobject *kobj, struct attribute *attr, const char *buf,
2500 struct ab8500_fg_sysfs_entry *entry;
2501 struct ab8500_fg *di;
2503 entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2504 di = container_of(kobj, struct ab8500_fg, fg_kobject);
2509 return entry->store(di, buf, count);
2512 static const struct sysfs_ops ab8500_fg_sysfs_ops = {
2513 .show = ab8500_fg_show,
2514 .store = ab8500_fg_store,
2517 static struct attribute *ab8500_fg_attrs[] = {
2518 &charge_full_attr.attr,
2519 &charge_now_attr.attr,
2523 static struct kobj_type ab8500_fg_ktype = {
2524 .sysfs_ops = &ab8500_fg_sysfs_ops,
2525 .default_attrs = ab8500_fg_attrs,
2529 * ab8500_fg_sysfs_exit() - de-init of sysfs entry
2530 * @di: pointer to the struct ab8500_chargalg
2532 * This function removes the entry in sysfs.
2534 static void ab8500_fg_sysfs_exit(struct ab8500_fg *di)
2536 kobject_del(&di->fg_kobject);
2540 * ab8500_fg_sysfs_init() - init of sysfs entry
2541 * @di: pointer to the struct ab8500_chargalg
2543 * This function adds an entry in sysfs.
2544 * Returns error code in case of failure else 0(on success)
2546 static int ab8500_fg_sysfs_init(struct ab8500_fg *di)
2550 ret = kobject_init_and_add(&di->fg_kobject,
2554 dev_err(di->dev, "failed to create sysfs entry\n");
2559 static ssize_t ab8505_powercut_flagtime_read(struct device *dev,
2560 struct device_attribute *attr,
2565 struct power_supply *psy = dev_get_drvdata(dev);
2566 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2568 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2569 AB8505_RTC_PCUT_FLAG_TIME_REG, ®_value);
2572 dev_err(dev, "Failed to read AB8505_RTC_PCUT_FLAG_TIME_REG\n");
2576 return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7F));
2582 static ssize_t ab8505_powercut_flagtime_write(struct device *dev,
2583 struct device_attribute *attr,
2584 const char *buf, size_t count)
2588 struct power_supply *psy = dev_get_drvdata(dev);
2589 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2591 if (kstrtoint(buf, 10, ®_value))
2594 if (reg_value > 0x7F) {
2595 dev_err(dev, "Incorrect parameter, echo 0 (1.98s) - 127 (15.625ms) for flagtime\n");
2599 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2600 AB8505_RTC_PCUT_FLAG_TIME_REG, (u8)reg_value);
2603 dev_err(dev, "Failed to set AB8505_RTC_PCUT_FLAG_TIME_REG\n");
2609 static ssize_t ab8505_powercut_maxtime_read(struct device *dev,
2610 struct device_attribute *attr,
2615 struct power_supply *psy = dev_get_drvdata(dev);
2616 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2618 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2619 AB8505_RTC_PCUT_MAX_TIME_REG, ®_value);
2622 dev_err(dev, "Failed to read AB8505_RTC_PCUT_MAX_TIME_REG\n");
2626 return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7F));
2633 static ssize_t ab8505_powercut_maxtime_write(struct device *dev,
2634 struct device_attribute *attr,
2635 const char *buf, size_t count)
2639 struct power_supply *psy = dev_get_drvdata(dev);
2640 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2642 if (kstrtoint(buf, 10, ®_value))
2645 if (reg_value > 0x7F) {
2646 dev_err(dev, "Incorrect parameter, echo 0 (0.0s) - 127 (1.98s) for maxtime\n");
2650 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2651 AB8505_RTC_PCUT_MAX_TIME_REG, (u8)reg_value);
2654 dev_err(dev, "Failed to set AB8505_RTC_PCUT_MAX_TIME_REG\n");
2660 static ssize_t ab8505_powercut_restart_read(struct device *dev,
2661 struct device_attribute *attr,
2666 struct power_supply *psy = dev_get_drvdata(dev);
2667 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2669 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2670 AB8505_RTC_PCUT_RESTART_REG, ®_value);
2673 dev_err(dev, "Failed to read AB8505_RTC_PCUT_RESTART_REG\n");
2677 return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0xF));
2683 static ssize_t ab8505_powercut_restart_write(struct device *dev,
2684 struct device_attribute *attr,
2685 const char *buf, size_t count)
2689 struct power_supply *psy = dev_get_drvdata(dev);
2690 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2692 if (kstrtoint(buf, 10, ®_value))
2695 if (reg_value > 0xF) {
2696 dev_err(dev, "Incorrect parameter, echo 0 - 15 for number of restart\n");
2700 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2701 AB8505_RTC_PCUT_RESTART_REG, (u8)reg_value);
2704 dev_err(dev, "Failed to set AB8505_RTC_PCUT_RESTART_REG\n");
2711 static ssize_t ab8505_powercut_timer_read(struct device *dev,
2712 struct device_attribute *attr,
2717 struct power_supply *psy = dev_get_drvdata(dev);
2718 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2720 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2721 AB8505_RTC_PCUT_TIME_REG, ®_value);
2724 dev_err(dev, "Failed to read AB8505_RTC_PCUT_TIME_REG\n");
2728 return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7F));
2734 static ssize_t ab8505_powercut_restart_counter_read(struct device *dev,
2735 struct device_attribute *attr,
2740 struct power_supply *psy = dev_get_drvdata(dev);
2741 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2743 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2744 AB8505_RTC_PCUT_RESTART_REG, ®_value);
2747 dev_err(dev, "Failed to read AB8505_RTC_PCUT_RESTART_REG\n");
2751 return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0xF0) >> 4);
2757 static ssize_t ab8505_powercut_read(struct device *dev,
2758 struct device_attribute *attr,
2763 struct power_supply *psy = dev_get_drvdata(dev);
2764 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2766 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2767 AB8505_RTC_PCUT_CTL_STATUS_REG, ®_value);
2772 return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x1));
2778 static ssize_t ab8505_powercut_write(struct device *dev,
2779 struct device_attribute *attr,
2780 const char *buf, size_t count)
2784 struct power_supply *psy = dev_get_drvdata(dev);
2785 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2787 if (kstrtoint(buf, 10, ®_value))
2790 if (reg_value > 0x1) {
2791 dev_err(dev, "Incorrect parameter, echo 0/1 to disable/enable Pcut feature\n");
2795 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2796 AB8505_RTC_PCUT_CTL_STATUS_REG, (u8)reg_value);
2799 dev_err(dev, "Failed to set AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2805 static ssize_t ab8505_powercut_flag_read(struct device *dev,
2806 struct device_attribute *attr,
2812 struct power_supply *psy = dev_get_drvdata(dev);
2813 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2815 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2816 AB8505_RTC_PCUT_CTL_STATUS_REG, ®_value);
2819 dev_err(dev, "Failed to read AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2823 return scnprintf(buf, PAGE_SIZE, "%d\n", ((reg_value & 0x10) >> 4));
2829 static ssize_t ab8505_powercut_debounce_read(struct device *dev,
2830 struct device_attribute *attr,
2835 struct power_supply *psy = dev_get_drvdata(dev);
2836 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2838 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2839 AB8505_RTC_PCUT_DEBOUNCE_REG, ®_value);
2842 dev_err(dev, "Failed to read AB8505_RTC_PCUT_DEBOUNCE_REG\n");
2846 return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7));
2852 static ssize_t ab8505_powercut_debounce_write(struct device *dev,
2853 struct device_attribute *attr,
2854 const char *buf, size_t count)
2858 struct power_supply *psy = dev_get_drvdata(dev);
2859 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2861 if (kstrtoint(buf, 10, ®_value))
2864 if (reg_value > 0x7) {
2865 dev_err(dev, "Incorrect parameter, echo 0 to 7 for debounce setting\n");
2869 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2870 AB8505_RTC_PCUT_DEBOUNCE_REG, (u8)reg_value);
2873 dev_err(dev, "Failed to set AB8505_RTC_PCUT_DEBOUNCE_REG\n");
2879 static ssize_t ab8505_powercut_enable_status_read(struct device *dev,
2880 struct device_attribute *attr,
2885 struct power_supply *psy = dev_get_drvdata(dev);
2886 struct ab8500_fg *di = power_supply_get_drvdata(psy);
2888 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2889 AB8505_RTC_PCUT_CTL_STATUS_REG, ®_value);
2892 dev_err(dev, "Failed to read AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2896 return scnprintf(buf, PAGE_SIZE, "%d\n", ((reg_value & 0x20) >> 5));
2902 static struct device_attribute ab8505_fg_sysfs_psy_attrs[] = {
2903 __ATTR(powercut_flagtime, (S_IRUGO | S_IWUSR | S_IWGRP),
2904 ab8505_powercut_flagtime_read, ab8505_powercut_flagtime_write),
2905 __ATTR(powercut_maxtime, (S_IRUGO | S_IWUSR | S_IWGRP),
2906 ab8505_powercut_maxtime_read, ab8505_powercut_maxtime_write),
2907 __ATTR(powercut_restart_max, (S_IRUGO | S_IWUSR | S_IWGRP),
2908 ab8505_powercut_restart_read, ab8505_powercut_restart_write),
2909 __ATTR(powercut_timer, S_IRUGO, ab8505_powercut_timer_read, NULL),
2910 __ATTR(powercut_restart_counter, S_IRUGO,
2911 ab8505_powercut_restart_counter_read, NULL),
2912 __ATTR(powercut_enable, (S_IRUGO | S_IWUSR | S_IWGRP),
2913 ab8505_powercut_read, ab8505_powercut_write),
2914 __ATTR(powercut_flag, S_IRUGO, ab8505_powercut_flag_read, NULL),
2915 __ATTR(powercut_debounce_time, (S_IRUGO | S_IWUSR | S_IWGRP),
2916 ab8505_powercut_debounce_read, ab8505_powercut_debounce_write),
2917 __ATTR(powercut_enable_status, S_IRUGO,
2918 ab8505_powercut_enable_status_read, NULL),
2921 static int ab8500_fg_sysfs_psy_create_attrs(struct ab8500_fg *di)
2925 if (is_ab8505(di->parent)) {
2926 for (i = 0; i < ARRAY_SIZE(ab8505_fg_sysfs_psy_attrs); i++)
2927 if (device_create_file(&di->fg_psy->dev,
2928 &ab8505_fg_sysfs_psy_attrs[i]))
2929 goto sysfs_psy_create_attrs_failed_ab8505;
2932 sysfs_psy_create_attrs_failed_ab8505:
2933 dev_err(&di->fg_psy->dev, "Failed creating sysfs psy attrs for ab8505.\n");
2935 device_remove_file(&di->fg_psy->dev,
2936 &ab8505_fg_sysfs_psy_attrs[i]);
2941 static void ab8500_fg_sysfs_psy_remove_attrs(struct ab8500_fg *di)
2945 if (is_ab8505(di->parent)) {
2946 for (i = 0; i < ARRAY_SIZE(ab8505_fg_sysfs_psy_attrs); i++)
2947 (void)device_remove_file(&di->fg_psy->dev,
2948 &ab8505_fg_sysfs_psy_attrs[i]);
2952 /* Exposure to the sysfs interface <<END>> */
2954 static int __maybe_unused ab8500_fg_resume(struct device *dev)
2956 struct ab8500_fg *di = dev_get_drvdata(dev);
2959 * Change state if we're not charging. If we're charging we will wake
2962 if (!di->flags.charging) {
2963 ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_WAKEUP);
2964 queue_work(di->fg_wq, &di->fg_work);
2970 static int __maybe_unused ab8500_fg_suspend(struct device *dev)
2972 struct ab8500_fg *di = dev_get_drvdata(dev);
2974 flush_delayed_work(&di->fg_periodic_work);
2975 flush_work(&di->fg_work);
2976 flush_work(&di->fg_acc_cur_work);
2977 flush_delayed_work(&di->fg_reinit_work);
2978 flush_delayed_work(&di->fg_low_bat_work);
2979 flush_delayed_work(&di->fg_check_hw_failure_work);
2982 * If the FG is enabled we will disable it before going to suspend
2983 * only if we're not charging
2985 if (di->flags.fg_enabled && !di->flags.charging)
2986 ab8500_fg_coulomb_counter(di, false);
2991 /* ab8500 fg driver interrupts and their respective isr */
2992 static struct ab8500_fg_interrupts ab8500_fg_irq[] = {
2993 {"NCONV_ACCU", ab8500_fg_cc_convend_handler},
2994 {"BATT_OVV", ab8500_fg_batt_ovv_handler},
2995 {"LOW_BAT_F", ab8500_fg_lowbatf_handler},
2996 {"CC_INT_CALIB", ab8500_fg_cc_int_calib_handler},
2997 {"CCEOC", ab8500_fg_cc_data_end_handler},
3000 static char *supply_interface[] = {
3005 static const struct power_supply_desc ab8500_fg_desc = {
3006 .name = "ab8500_fg",
3007 .type = POWER_SUPPLY_TYPE_BATTERY,
3008 .properties = ab8500_fg_props,
3009 .num_properties = ARRAY_SIZE(ab8500_fg_props),
3010 .get_property = ab8500_fg_get_property,
3011 .external_power_changed = ab8500_fg_external_power_changed,
3014 static int ab8500_fg_bind(struct device *dev, struct device *master,
3017 struct ab8500_fg *di = dev_get_drvdata(dev);
3019 /* Create a work queue for running the FG algorithm */
3020 di->fg_wq = alloc_ordered_workqueue("ab8500_fg_wq", WQ_MEM_RECLAIM);
3021 if (di->fg_wq == NULL) {
3022 dev_err(dev, "failed to create work queue\n");
3026 /* Start the coulomb counter */
3027 ab8500_fg_coulomb_counter(di, true);
3028 /* Run the FG algorithm */
3029 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
3034 static void ab8500_fg_unbind(struct device *dev, struct device *master,
3037 struct ab8500_fg *di = dev_get_drvdata(dev);
3040 /* Disable coulomb counter */
3041 ret = ab8500_fg_coulomb_counter(di, false);
3043 dev_err(dev, "failed to disable coulomb counter\n");
3045 destroy_workqueue(di->fg_wq);
3046 flush_scheduled_work();
3049 static const struct component_ops ab8500_fg_component_ops = {
3050 .bind = ab8500_fg_bind,
3051 .unbind = ab8500_fg_unbind,
3054 static int ab8500_fg_probe(struct platform_device *pdev)
3056 struct device *dev = &pdev->dev;
3057 struct power_supply_config psy_cfg = {};
3058 struct ab8500_fg *di;
3062 di = devm_kzalloc(dev, sizeof(*di), GFP_KERNEL);
3066 di->bm = &ab8500_bm_data;
3068 mutex_init(&di->cc_lock);
3070 /* get parent data */
3072 di->parent = dev_get_drvdata(pdev->dev.parent);
3074 di->main_bat_v = devm_iio_channel_get(dev, "main_bat_v");
3075 if (IS_ERR(di->main_bat_v)) {
3076 ret = dev_err_probe(dev, PTR_ERR(di->main_bat_v),
3077 "failed to get main battery ADC channel\n");
3081 psy_cfg.supplied_to = supply_interface;
3082 psy_cfg.num_supplicants = ARRAY_SIZE(supply_interface);
3083 psy_cfg.drv_data = di;
3085 di->bat_cap.max_mah_design = di->bm->bi.charge_full_design_uah;
3086 di->bat_cap.max_mah = di->bat_cap.max_mah_design;
3087 di->vbat_nom_uv = di->bm->bi.voltage_max_design_uv;
3089 di->init_capacity = true;
3091 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
3092 ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
3094 /* Init work for running the fg algorithm instantly */
3095 INIT_WORK(&di->fg_work, ab8500_fg_instant_work);
3097 /* Init work for getting the battery accumulated current */
3098 INIT_WORK(&di->fg_acc_cur_work, ab8500_fg_acc_cur_work);
3100 /* Init work for reinitialising the fg algorithm */
3101 INIT_DEFERRABLE_WORK(&di->fg_reinit_work,
3102 ab8500_fg_reinit_work);
3104 /* Work delayed Queue to run the state machine */
3105 INIT_DEFERRABLE_WORK(&di->fg_periodic_work,
3106 ab8500_fg_periodic_work);
3108 /* Work to check low battery condition */
3109 INIT_DEFERRABLE_WORK(&di->fg_low_bat_work,
3110 ab8500_fg_low_bat_work);
3112 /* Init work for HW failure check */
3113 INIT_DEFERRABLE_WORK(&di->fg_check_hw_failure_work,
3114 ab8500_fg_check_hw_failure_work);
3116 /* Reset battery low voltage flag */
3117 di->flags.low_bat = false;
3119 /* Initialize low battery counter */
3120 di->low_bat_cnt = 10;
3122 /* Initialize OVV, and other registers */
3123 ret = ab8500_fg_init_hw_registers(di);
3125 dev_err(dev, "failed to initialize registers\n");
3129 /* Consider battery unknown until we're informed otherwise */
3130 di->flags.batt_unknown = true;
3131 di->flags.batt_id_received = false;
3133 /* Register FG power supply class */
3134 di->fg_psy = devm_power_supply_register(dev, &ab8500_fg_desc, &psy_cfg);
3135 if (IS_ERR(di->fg_psy)) {
3136 dev_err(dev, "failed to register FG psy\n");
3137 return PTR_ERR(di->fg_psy);
3140 di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
3143 * Initialize completion used to notify completion and start
3146 init_completion(&di->ab8500_fg_started);
3147 init_completion(&di->ab8500_fg_complete);
3149 /* Register primary interrupt handlers */
3150 for (i = 0; i < ARRAY_SIZE(ab8500_fg_irq); i++) {
3151 irq = platform_get_irq_byname(pdev, ab8500_fg_irq[i].name);
3155 ret = devm_request_threaded_irq(dev, irq, NULL,
3156 ab8500_fg_irq[i].isr,
3157 IRQF_SHARED | IRQF_NO_SUSPEND | IRQF_ONESHOT,
3158 ab8500_fg_irq[i].name, di);
3161 dev_err(dev, "failed to request %s IRQ %d: %d\n",
3162 ab8500_fg_irq[i].name, irq, ret);
3165 dev_dbg(dev, "Requested %s IRQ %d: %d\n",
3166 ab8500_fg_irq[i].name, irq, ret);
3169 di->irq = platform_get_irq_byname(pdev, "CCEOC");
3170 disable_irq(di->irq);
3171 di->nbr_cceoc_irq_cnt = 0;
3173 platform_set_drvdata(pdev, di);
3175 ret = ab8500_fg_sysfs_init(di);
3177 dev_err(dev, "failed to create sysfs entry\n");
3181 ret = ab8500_fg_sysfs_psy_create_attrs(di);
3183 dev_err(dev, "failed to create FG psy\n");
3184 ab8500_fg_sysfs_exit(di);
3188 /* Calibrate the fg first time */
3189 di->flags.calibrate = true;
3190 di->calib_state = AB8500_FG_CALIB_INIT;
3192 /* Use room temp as default value until we get an update from driver. */
3195 list_add_tail(&di->node, &ab8500_fg_list);
3197 return component_add(dev, &ab8500_fg_component_ops);
3200 static int ab8500_fg_remove(struct platform_device *pdev)
3203 struct ab8500_fg *di = platform_get_drvdata(pdev);
3205 component_del(&pdev->dev, &ab8500_fg_component_ops);
3206 list_del(&di->node);
3207 ab8500_fg_sysfs_exit(di);
3208 ab8500_fg_sysfs_psy_remove_attrs(di);
3213 static SIMPLE_DEV_PM_OPS(ab8500_fg_pm_ops, ab8500_fg_suspend, ab8500_fg_resume);
3215 static const struct of_device_id ab8500_fg_match[] = {
3216 { .compatible = "stericsson,ab8500-fg", },
3219 MODULE_DEVICE_TABLE(of, ab8500_fg_match);
3221 struct platform_driver ab8500_fg_driver = {
3222 .probe = ab8500_fg_probe,
3223 .remove = ab8500_fg_remove,
3225 .name = "ab8500-fg",
3226 .of_match_table = ab8500_fg_match,
3227 .pm = &ab8500_fg_pm_ops,
3230 MODULE_LICENSE("GPL v2");
3231 MODULE_AUTHOR("Johan Palsson, Karl Komierowski");
3232 MODULE_ALIAS("platform:ab8500-fg");
3233 MODULE_DESCRIPTION("AB8500 Fuel Gauge driver");