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>
35 #include <linux/kernel.h>
37 #define MILLI_TO_MICRO 1000
38 #define FG_LSB_IN_MA 1627
39 #define QLSB_NANO_AMP_HOURS_X10 1129
40 #define INS_CURR_TIMEOUT (3 * HZ)
42 #define SEC_TO_SAMPLE(S) (S * 4)
44 #define NBR_AVG_SAMPLES 20
46 #define LOW_BAT_CHECK_INTERVAL (HZ / 16) /* 62.5 ms */
48 #define VALID_CAPACITY_SEC (45 * 60) /* 45 minutes */
49 #define BATT_OK_MIN 2360 /* mV */
50 #define BATT_OK_INCREMENT 50 /* mV */
51 #define BATT_OK_MAX_NR_INCREMENTS 0xE
56 #define interpolate(x, x1, y1, x2, y2) \
57 ((y1) + ((((y2) - (y1)) * ((x) - (x1))) / ((x2) - (x1))));
59 #define to_ab8500_fg_device_info(x) container_of((x), \
60 struct ab8500_fg, fg_psy);
63 * struct ab8500_fg_interrupts - ab8500 fg interupts
64 * @name: name of the interrupt
65 * @isr function pointer to the isr
67 struct ab8500_fg_interrupts {
69 irqreturn_t (*isr)(int irq, void *data);
72 enum ab8500_fg_discharge_state {
73 AB8500_FG_DISCHARGE_INIT,
74 AB8500_FG_DISCHARGE_INITMEASURING,
75 AB8500_FG_DISCHARGE_INIT_RECOVERY,
76 AB8500_FG_DISCHARGE_RECOVERY,
77 AB8500_FG_DISCHARGE_READOUT_INIT,
78 AB8500_FG_DISCHARGE_READOUT,
79 AB8500_FG_DISCHARGE_WAKEUP,
82 static char *discharge_state[] = {
84 "DISCHARGE_INITMEASURING",
85 "DISCHARGE_INIT_RECOVERY",
87 "DISCHARGE_READOUT_INIT",
92 enum ab8500_fg_charge_state {
93 AB8500_FG_CHARGE_INIT,
94 AB8500_FG_CHARGE_READOUT,
97 static char *charge_state[] = {
102 enum ab8500_fg_calibration_state {
103 AB8500_FG_CALIB_INIT,
104 AB8500_FG_CALIB_WAIT,
108 struct ab8500_fg_avg_cap {
110 int samples[NBR_AVG_SAMPLES];
111 __kernel_time_t time_stamps[NBR_AVG_SAMPLES];
117 struct ab8500_fg_cap_scaling {
120 int disable_cap_level;
124 struct ab8500_fg_battery_capacity {
134 struct ab8500_fg_cap_scaling cap_scale;
137 struct ab8500_fg_flags {
149 bool batt_id_received;
152 struct inst_curr_result_list {
153 struct list_head list;
158 * struct ab8500_fg - ab8500 FG device information
159 * @dev: Pointer to the structure device
160 * @node: a list of AB8500 FGs, hence prepared for reentrance
161 * @irq holds the CCEOC interrupt number
162 * @vbat: Battery voltage in mV
163 * @vbat_nom: Nominal battery voltage in mV
164 * @inst_curr: Instantenous battery current in mA
165 * @avg_curr: Average battery current in mA
166 * @bat_temp battery temperature
167 * @fg_samples: Number of samples used in the FG accumulation
168 * @accu_charge: Accumulated charge from the last conversion
169 * @recovery_cnt: Counter for recovery mode
170 * @high_curr_cnt: Counter for high current mode
171 * @init_cnt: Counter for init mode
172 * @low_bat_cnt Counter for number of consecutive low battery measures
173 * @nbr_cceoc_irq_cnt Counter for number of CCEOC irqs received since enabled
174 * @recovery_needed: Indicate if recovery is needed
175 * @high_curr_mode: Indicate if we're in high current mode
176 * @init_capacity: Indicate if initial capacity measuring should be done
177 * @turn_off_fg: True if fg was off before current measurement
178 * @calib_state State during offset calibration
179 * @discharge_state: Current discharge state
180 * @charge_state: Current charge state
181 * @ab8500_fg_started Completion struct used for the instant current start
182 * @ab8500_fg_complete Completion struct used for the instant current reading
183 * @flags: Structure for information about events triggered
184 * @bat_cap: Structure for battery capacity specific parameters
185 * @avg_cap: Average capacity filter
186 * @parent: Pointer to the struct ab8500
187 * @gpadc: Pointer to the struct gpadc
188 * @bm: Platform specific battery management information
189 * @fg_psy: Structure that holds the FG specific battery properties
190 * @fg_wq: Work queue for running the FG algorithm
191 * @fg_periodic_work: Work to run the FG algorithm periodically
192 * @fg_low_bat_work: Work to check low bat condition
193 * @fg_reinit_work Work used to reset and reinitialise the FG algorithm
194 * @fg_work: Work to run the FG algorithm instantly
195 * @fg_acc_cur_work: Work to read the FG accumulator
196 * @fg_check_hw_failure_work: Work for checking HW state
197 * @cc_lock: Mutex for locking the CC
198 * @fg_kobject: Structure of type kobject
202 struct list_head node;
215 int nbr_cceoc_irq_cnt;
216 bool recovery_needed;
220 enum ab8500_fg_calibration_state calib_state;
221 enum ab8500_fg_discharge_state discharge_state;
222 enum ab8500_fg_charge_state charge_state;
223 struct completion ab8500_fg_started;
224 struct completion ab8500_fg_complete;
225 struct ab8500_fg_flags flags;
226 struct ab8500_fg_battery_capacity bat_cap;
227 struct ab8500_fg_avg_cap avg_cap;
228 struct ab8500 *parent;
229 struct ab8500_gpadc *gpadc;
230 struct abx500_bm_data *bm;
231 struct power_supply fg_psy;
232 struct workqueue_struct *fg_wq;
233 struct delayed_work fg_periodic_work;
234 struct delayed_work fg_low_bat_work;
235 struct delayed_work fg_reinit_work;
236 struct work_struct fg_work;
237 struct work_struct fg_acc_cur_work;
238 struct delayed_work fg_check_hw_failure_work;
239 struct mutex cc_lock;
240 struct kobject fg_kobject;
242 static LIST_HEAD(ab8500_fg_list);
245 * ab8500_fg_get() - returns a reference to the primary AB8500 fuel gauge
246 * (i.e. the first fuel gauge in the instance list)
248 struct ab8500_fg *ab8500_fg_get(void)
250 struct ab8500_fg *fg;
252 if (list_empty(&ab8500_fg_list))
255 fg = list_first_entry(&ab8500_fg_list, struct ab8500_fg, node);
259 /* Main battery properties */
260 static enum power_supply_property ab8500_fg_props[] = {
261 POWER_SUPPLY_PROP_VOLTAGE_NOW,
262 POWER_SUPPLY_PROP_CURRENT_NOW,
263 POWER_SUPPLY_PROP_CURRENT_AVG,
264 POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
265 POWER_SUPPLY_PROP_ENERGY_FULL,
266 POWER_SUPPLY_PROP_ENERGY_NOW,
267 POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
268 POWER_SUPPLY_PROP_CHARGE_FULL,
269 POWER_SUPPLY_PROP_CHARGE_NOW,
270 POWER_SUPPLY_PROP_CAPACITY,
271 POWER_SUPPLY_PROP_CAPACITY_LEVEL,
275 * This array maps the raw hex value to lowbat voltage used by the AB8500
276 * Values taken from the UM0836
278 static int ab8500_fg_lowbat_voltage_map[] = {
345 static u8 ab8500_volt_to_regval(int voltage)
349 if (voltage < ab8500_fg_lowbat_voltage_map[0])
352 for (i = 0; i < ARRAY_SIZE(ab8500_fg_lowbat_voltage_map); i++) {
353 if (voltage < ab8500_fg_lowbat_voltage_map[i])
357 /* If not captured above, return index of last element */
358 return (u8) ARRAY_SIZE(ab8500_fg_lowbat_voltage_map) - 1;
362 * ab8500_fg_is_low_curr() - Low or high current mode
363 * @di: pointer to the ab8500_fg structure
364 * @curr: the current to base or our decision on
366 * Low current mode if the current consumption is below a certain threshold
368 static int ab8500_fg_is_low_curr(struct ab8500_fg *di, int curr)
371 * We want to know if we're in low current mode
373 if (curr > -di->bm->fg_params->high_curr_threshold)
380 * ab8500_fg_add_cap_sample() - Add capacity to average filter
381 * @di: pointer to the ab8500_fg structure
382 * @sample: the capacity in mAh to add to the filter
384 * A capacity is added to the filter and a new mean capacity is calculated and
387 static int ab8500_fg_add_cap_sample(struct ab8500_fg *di, int sample)
390 struct ab8500_fg_avg_cap *avg = &di->avg_cap;
395 avg->sum += sample - avg->samples[avg->pos];
396 avg->samples[avg->pos] = sample;
397 avg->time_stamps[avg->pos] = ts.tv_sec;
400 if (avg->pos == NBR_AVG_SAMPLES)
403 if (avg->nbr_samples < NBR_AVG_SAMPLES)
407 * Check the time stamp for each sample. If too old,
408 * replace with latest sample
410 } while (ts.tv_sec - VALID_CAPACITY_SEC > avg->time_stamps[avg->pos]);
412 avg->avg = avg->sum / avg->nbr_samples;
418 * ab8500_fg_clear_cap_samples() - Clear average filter
419 * @di: pointer to the ab8500_fg structure
421 * The capacity filter is is reset to zero.
423 static void ab8500_fg_clear_cap_samples(struct ab8500_fg *di)
426 struct ab8500_fg_avg_cap *avg = &di->avg_cap;
429 avg->nbr_samples = 0;
433 for (i = 0; i < NBR_AVG_SAMPLES; i++) {
435 avg->time_stamps[i] = 0;
440 * ab8500_fg_fill_cap_sample() - Fill average filter
441 * @di: pointer to the ab8500_fg structure
442 * @sample: the capacity in mAh to fill the filter with
444 * The capacity filter is filled with a capacity in mAh
446 static void ab8500_fg_fill_cap_sample(struct ab8500_fg *di, int sample)
450 struct ab8500_fg_avg_cap *avg = &di->avg_cap;
454 for (i = 0; i < NBR_AVG_SAMPLES; i++) {
455 avg->samples[i] = sample;
456 avg->time_stamps[i] = ts.tv_sec;
460 avg->nbr_samples = NBR_AVG_SAMPLES;
461 avg->sum = sample * NBR_AVG_SAMPLES;
466 * ab8500_fg_coulomb_counter() - enable coulomb counter
467 * @di: pointer to the ab8500_fg structure
468 * @enable: enable/disable
470 * Enable/Disable coulomb counter.
471 * On failure returns negative value.
473 static int ab8500_fg_coulomb_counter(struct ab8500_fg *di, bool enable)
476 mutex_lock(&di->cc_lock);
478 /* To be able to reprogram the number of samples, we have to
479 * first stop the CC and then enable it again */
480 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
481 AB8500_RTC_CC_CONF_REG, 0x00);
485 /* Program the samples */
486 ret = abx500_set_register_interruptible(di->dev,
487 AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
493 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
494 AB8500_RTC_CC_CONF_REG,
495 (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
499 di->flags.fg_enabled = true;
501 /* Clear any pending read requests */
502 ret = abx500_mask_and_set_register_interruptible(di->dev,
503 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
504 (RESET_ACCU | READ_REQ), 0);
508 ret = abx500_set_register_interruptible(di->dev,
509 AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU_CTRL, 0);
514 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
515 AB8500_RTC_CC_CONF_REG, 0);
519 di->flags.fg_enabled = false;
522 dev_dbg(di->dev, " CC enabled: %d Samples: %d\n",
523 enable, di->fg_samples);
525 mutex_unlock(&di->cc_lock);
529 dev_err(di->dev, "%s Enabling coulomb counter failed\n", __func__);
530 mutex_unlock(&di->cc_lock);
535 * ab8500_fg_inst_curr_start() - start battery instantaneous current
536 * @di: pointer to the ab8500_fg structure
538 * Returns 0 or error code
539 * Note: This is part "one" and has to be called before
540 * ab8500_fg_inst_curr_finalize()
542 int ab8500_fg_inst_curr_start(struct ab8500_fg *di)
547 mutex_lock(&di->cc_lock);
549 di->nbr_cceoc_irq_cnt = 0;
550 ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
551 AB8500_RTC_CC_CONF_REG, ®_val);
555 if (!(reg_val & CC_PWR_UP_ENA)) {
556 dev_dbg(di->dev, "%s Enable FG\n", __func__);
557 di->turn_off_fg = true;
559 /* Program the samples */
560 ret = abx500_set_register_interruptible(di->dev,
561 AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
567 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
568 AB8500_RTC_CC_CONF_REG,
569 (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
573 di->turn_off_fg = false;
577 INIT_COMPLETION(di->ab8500_fg_started);
578 INIT_COMPLETION(di->ab8500_fg_complete);
581 /* Note: cc_lock is still locked */
584 mutex_unlock(&di->cc_lock);
589 * ab8500_fg_inst_curr_started() - check if fg conversion has started
590 * @di: pointer to the ab8500_fg structure
592 * Returns 1 if conversion started, 0 if still waiting
594 int ab8500_fg_inst_curr_started(struct ab8500_fg *di)
596 return completion_done(&di->ab8500_fg_started);
600 * ab8500_fg_inst_curr_done() - check if fg conversion is done
601 * @di: pointer to the ab8500_fg structure
603 * Returns 1 if conversion done, 0 if still waiting
605 int ab8500_fg_inst_curr_done(struct ab8500_fg *di)
607 return completion_done(&di->ab8500_fg_complete);
611 * ab8500_fg_inst_curr_finalize() - battery instantaneous current
612 * @di: pointer to the ab8500_fg structure
613 * @res: battery instantenous current(on success)
615 * Returns 0 or an error code
616 * Note: This is part "two" and has to be called at earliest 250 ms
617 * after ab8500_fg_inst_curr_start()
619 int ab8500_fg_inst_curr_finalize(struct ab8500_fg *di, int *res)
626 if (!completion_done(&di->ab8500_fg_complete)) {
627 timeout = wait_for_completion_timeout(
628 &di->ab8500_fg_complete,
630 dev_dbg(di->dev, "Finalize time: %d ms\n",
631 ((INS_CURR_TIMEOUT - timeout) * 1000) / HZ);
634 disable_irq(di->irq);
635 di->nbr_cceoc_irq_cnt = 0;
636 dev_err(di->dev, "completion timed out [%d]\n",
642 disable_irq(di->irq);
643 di->nbr_cceoc_irq_cnt = 0;
645 ret = abx500_mask_and_set_register_interruptible(di->dev,
646 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
649 /* 100uS between read request and read is needed */
650 usleep_range(100, 100);
652 /* Read CC Sample conversion value Low and high */
653 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
654 AB8500_GASG_CC_SMPL_CNVL_REG, &low);
658 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
659 AB8500_GASG_CC_SMPL_CNVH_REG, &high);
664 * negative value for Discharging
665 * convert 2's compliment into decimal
668 val = (low | (high << 8) | 0xFFFFE000);
670 val = (low | (high << 8));
673 * Convert to unit value in mA
674 * Full scale input voltage is
675 * 66.660mV => LSB = 66.660mV/(4096*res) = 1.627mA
676 * Given a 250ms conversion cycle time the LSB corresponds
677 * to 112.9 nAh. Convert to current by dividing by the conversion
678 * time in hours (250ms = 1 / (3600 * 4)h)
679 * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
681 val = (val * QLSB_NANO_AMP_HOURS_X10 * 36 * 4) /
682 (1000 * di->bm->fg_res);
684 if (di->turn_off_fg) {
685 dev_dbg(di->dev, "%s Disable FG\n", __func__);
687 /* Clear any pending read requests */
688 ret = abx500_set_register_interruptible(di->dev,
689 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG, 0);
694 ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
695 AB8500_RTC_CC_CONF_REG, 0);
699 mutex_unlock(&di->cc_lock);
704 mutex_unlock(&di->cc_lock);
709 * ab8500_fg_inst_curr_blocking() - battery instantaneous current
710 * @di: pointer to the ab8500_fg structure
711 * @res: battery instantenous current(on success)
713 * Returns 0 else error code
715 int ab8500_fg_inst_curr_blocking(struct ab8500_fg *di)
721 ret = ab8500_fg_inst_curr_start(di);
723 dev_err(di->dev, "Failed to initialize fg_inst\n");
727 /* Wait for CC to actually start */
728 if (!completion_done(&di->ab8500_fg_started)) {
729 timeout = wait_for_completion_timeout(
730 &di->ab8500_fg_started,
732 dev_dbg(di->dev, "Start time: %d ms\n",
733 ((INS_CURR_TIMEOUT - timeout) * 1000) / HZ);
736 dev_err(di->dev, "completion timed out [%d]\n",
742 ret = ab8500_fg_inst_curr_finalize(di, &res);
744 dev_err(di->dev, "Failed to finalize fg_inst\n");
748 dev_dbg(di->dev, "%s instant current: %d", __func__, res);
751 disable_irq(di->irq);
752 mutex_unlock(&di->cc_lock);
757 * ab8500_fg_acc_cur_work() - average battery current
758 * @work: pointer to the work_struct structure
760 * Updated the average battery current obtained from the
763 static void ab8500_fg_acc_cur_work(struct work_struct *work)
769 struct ab8500_fg *di = container_of(work,
770 struct ab8500_fg, fg_acc_cur_work);
772 mutex_lock(&di->cc_lock);
773 ret = abx500_set_register_interruptible(di->dev, AB8500_GAS_GAUGE,
774 AB8500_GASG_CC_NCOV_ACCU_CTRL, RD_NCONV_ACCU_REQ);
778 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
779 AB8500_GASG_CC_NCOV_ACCU_LOW, &low);
783 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
784 AB8500_GASG_CC_NCOV_ACCU_MED, &med);
788 ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
789 AB8500_GASG_CC_NCOV_ACCU_HIGH, &high);
793 /* Check for sign bit in case of negative value, 2's compliment */
795 val = (low | (med << 8) | (high << 16) | 0xFFE00000);
797 val = (low | (med << 8) | (high << 16));
801 * Given a 250ms conversion cycle time the LSB corresponds
803 * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
805 di->accu_charge = (val * QLSB_NANO_AMP_HOURS_X10) /
806 (100 * di->bm->fg_res);
809 * Convert to unit value in mA
810 * by dividing by the conversion
811 * time in hours (= samples / (3600 * 4)h)
812 * and multiply with 1000
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);
823 dev_dbg(di->dev, "fg_res: %d, fg_samples: %d, gasg: %d, accu_charge: %d \n",
824 di->bm->fg_res, di->fg_samples, val, di->accu_charge);
828 "Failed to read or write gas gauge registers\n");
829 mutex_unlock(&di->cc_lock);
830 queue_work(di->fg_wq, &di->fg_work);
834 * ab8500_fg_bat_voltage() - get battery voltage
835 * @di: pointer to the ab8500_fg structure
837 * Returns battery voltage(on success) else error code
839 static int ab8500_fg_bat_voltage(struct ab8500_fg *di)
844 vbat = ab8500_gpadc_convert(di->gpadc, MAIN_BAT_V);
847 "%s gpadc conversion failed, using previous value\n",
857 * ab8500_fg_volt_to_capacity() - Voltage based capacity
858 * @di: pointer to the ab8500_fg structure
859 * @voltage: The voltage to convert to a capacity
861 * Returns battery capacity in per mille based on voltage
863 static int ab8500_fg_volt_to_capacity(struct ab8500_fg *di, int voltage)
866 struct abx500_v_to_cap *tbl;
869 tbl = di->bm->bat_type[di->bm->batt_id].v_to_cap_tbl,
870 tbl_size = di->bm->bat_type[di->bm->batt_id].n_v_cap_tbl_elements;
872 for (i = 0; i < tbl_size; ++i) {
873 if (voltage > tbl[i].voltage)
877 if ((i > 0) && (i < tbl_size)) {
878 cap = interpolate(voltage,
880 tbl[i].capacity * 10,
882 tbl[i-1].capacity * 10);
889 dev_dbg(di->dev, "%s Vbat: %d, Cap: %d per mille",
890 __func__, voltage, cap);
896 * ab8500_fg_uncomp_volt_to_capacity() - Uncompensated voltage based capacity
897 * @di: pointer to the ab8500_fg structure
899 * Returns battery capacity based on battery voltage that is not compensated
900 * for the voltage drop due to the load
902 static int ab8500_fg_uncomp_volt_to_capacity(struct ab8500_fg *di)
904 di->vbat = ab8500_fg_bat_voltage(di);
905 return ab8500_fg_volt_to_capacity(di, di->vbat);
909 * ab8500_fg_battery_resistance() - Returns the battery inner resistance
910 * @di: pointer to the ab8500_fg structure
912 * Returns battery inner resistance added with the fuel gauge resistor value
913 * to get the total resistance in the whole link from gnd to bat+ node.
915 static int ab8500_fg_battery_resistance(struct ab8500_fg *di)
918 struct batres_vs_temp *tbl;
921 tbl = di->bm->bat_type[di->bm->batt_id].batres_tbl;
922 tbl_size = di->bm->bat_type[di->bm->batt_id].n_batres_tbl_elements;
924 for (i = 0; i < tbl_size; ++i) {
925 if (di->bat_temp / 10 > tbl[i].temp)
929 if ((i > 0) && (i < tbl_size)) {
930 resist = interpolate(di->bat_temp / 10,
936 resist = tbl[0].resist;
938 resist = tbl[tbl_size - 1].resist;
941 dev_dbg(di->dev, "%s Temp: %d battery internal resistance: %d"
942 " fg resistance %d, total: %d (mOhm)\n",
943 __func__, di->bat_temp, resist, di->bm->fg_res / 10,
944 (di->bm->fg_res / 10) + resist);
946 /* fg_res variable is in 0.1mOhm */
947 resist += di->bm->fg_res / 10;
953 * ab8500_fg_load_comp_volt_to_capacity() - Load compensated voltage based capacity
954 * @di: pointer to the ab8500_fg structure
956 * Returns battery capacity based on battery voltage that is load compensated
957 * for the voltage drop
959 static int ab8500_fg_load_comp_volt_to_capacity(struct ab8500_fg *di)
965 ab8500_fg_inst_curr_start(di);
968 vbat += ab8500_fg_bat_voltage(di);
970 usleep_range(5000, 6000);
971 } while (!ab8500_fg_inst_curr_done(di));
973 ab8500_fg_inst_curr_finalize(di, &di->inst_curr);
976 res = ab8500_fg_battery_resistance(di);
978 /* Use Ohms law to get the load compensated voltage */
979 vbat_comp = di->vbat - (di->inst_curr * res) / 1000;
981 dev_dbg(di->dev, "%s Measured Vbat: %dmV,Compensated Vbat %dmV, "
982 "R: %dmOhm, Current: %dmA Vbat Samples: %d\n",
983 __func__, di->vbat, vbat_comp, res, di->inst_curr, i);
985 return ab8500_fg_volt_to_capacity(di, vbat_comp);
989 * ab8500_fg_convert_mah_to_permille() - Capacity in mAh to permille
990 * @di: pointer to the ab8500_fg structure
991 * @cap_mah: capacity in mAh
993 * Converts capacity in mAh to capacity in permille
995 static int ab8500_fg_convert_mah_to_permille(struct ab8500_fg *di, int cap_mah)
997 return (cap_mah * 1000) / di->bat_cap.max_mah_design;
1001 * ab8500_fg_convert_permille_to_mah() - Capacity in permille to mAh
1002 * @di: pointer to the ab8500_fg structure
1003 * @cap_pm: capacity in permille
1005 * Converts capacity in permille to capacity in mAh
1007 static int ab8500_fg_convert_permille_to_mah(struct ab8500_fg *di, int cap_pm)
1009 return cap_pm * di->bat_cap.max_mah_design / 1000;
1013 * ab8500_fg_convert_mah_to_uwh() - Capacity in mAh to uWh
1014 * @di: pointer to the ab8500_fg structure
1015 * @cap_mah: capacity in mAh
1017 * Converts capacity in mAh to capacity in uWh
1019 static int ab8500_fg_convert_mah_to_uwh(struct ab8500_fg *di, int cap_mah)
1024 div_res = ((u64) cap_mah) * ((u64) di->vbat_nom);
1025 div_rem = do_div(div_res, 1000);
1027 /* Make sure to round upwards if necessary */
1028 if (div_rem >= 1000 / 2)
1031 return (int) div_res;
1035 * ab8500_fg_calc_cap_charging() - Calculate remaining capacity while charging
1036 * @di: pointer to the ab8500_fg structure
1038 * Return the capacity in mAh based on previous calculated capcity and the FG
1039 * accumulator register value. The filter is filled with this capacity
1041 static int ab8500_fg_calc_cap_charging(struct ab8500_fg *di)
1043 dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1048 /* Capacity should not be less than 0 */
1049 if (di->bat_cap.mah + di->accu_charge > 0)
1050 di->bat_cap.mah += di->accu_charge;
1052 di->bat_cap.mah = 0;
1054 * We force capacity to 100% once when the algorithm
1055 * reports that it's full.
1057 if (di->bat_cap.mah >= di->bat_cap.max_mah_design ||
1058 di->flags.force_full) {
1059 di->bat_cap.mah = di->bat_cap.max_mah_design;
1062 ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1063 di->bat_cap.permille =
1064 ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1066 /* We need to update battery voltage and inst current when charging */
1067 di->vbat = ab8500_fg_bat_voltage(di);
1068 di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1070 return di->bat_cap.mah;
1074 * ab8500_fg_calc_cap_discharge_voltage() - Capacity in discharge with voltage
1075 * @di: pointer to the ab8500_fg structure
1076 * @comp: if voltage should be load compensated before capacity calc
1078 * Return the capacity in mAh based on the battery voltage. The voltage can
1079 * either be load compensated or not. This value is added to the filter and a
1080 * new mean value is calculated and returned.
1082 static int ab8500_fg_calc_cap_discharge_voltage(struct ab8500_fg *di, bool comp)
1087 permille = ab8500_fg_load_comp_volt_to_capacity(di);
1089 permille = ab8500_fg_uncomp_volt_to_capacity(di);
1091 mah = ab8500_fg_convert_permille_to_mah(di, permille);
1093 di->bat_cap.mah = ab8500_fg_add_cap_sample(di, mah);
1094 di->bat_cap.permille =
1095 ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1097 return di->bat_cap.mah;
1101 * ab8500_fg_calc_cap_discharge_fg() - Capacity in discharge with FG
1102 * @di: pointer to the ab8500_fg structure
1104 * Return the capacity in mAh based on previous calculated capcity and the FG
1105 * accumulator register value. This value is added to the filter and a
1106 * new mean value is calculated and returned.
1108 static int ab8500_fg_calc_cap_discharge_fg(struct ab8500_fg *di)
1110 int permille_volt, permille;
1112 dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1117 /* Capacity should not be less than 0 */
1118 if (di->bat_cap.mah + di->accu_charge > 0)
1119 di->bat_cap.mah += di->accu_charge;
1121 di->bat_cap.mah = 0;
1123 if (di->bat_cap.mah >= di->bat_cap.max_mah_design)
1124 di->bat_cap.mah = di->bat_cap.max_mah_design;
1127 * Check against voltage based capacity. It can not be lower
1128 * than what the uncompensated voltage says
1130 permille = ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1131 permille_volt = ab8500_fg_uncomp_volt_to_capacity(di);
1133 if (permille < permille_volt) {
1134 di->bat_cap.permille = permille_volt;
1135 di->bat_cap.mah = ab8500_fg_convert_permille_to_mah(di,
1136 di->bat_cap.permille);
1138 dev_dbg(di->dev, "%s voltage based: perm %d perm_volt %d\n",
1143 ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1145 ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1146 di->bat_cap.permille =
1147 ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1150 return di->bat_cap.mah;
1154 * ab8500_fg_capacity_level() - Get the battery capacity level
1155 * @di: pointer to the ab8500_fg structure
1157 * Get the battery capacity level based on the capacity in percent
1159 static int ab8500_fg_capacity_level(struct ab8500_fg *di)
1163 percent = DIV_ROUND_CLOSEST(di->bat_cap.permille, 10);
1165 if (percent <= di->bm->cap_levels->critical ||
1167 ret = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1168 else if (percent <= di->bm->cap_levels->low)
1169 ret = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1170 else if (percent <= di->bm->cap_levels->normal)
1171 ret = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1172 else if (percent <= di->bm->cap_levels->high)
1173 ret = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
1175 ret = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1181 * ab8500_fg_calculate_scaled_capacity() - Capacity scaling
1182 * @di: pointer to the ab8500_fg structure
1184 * Calculates the capacity to be shown to upper layers. Scales the capacity
1185 * to have 100% as a reference from the actual capacity upon removal of charger
1186 * when charging is in maintenance mode.
1188 static int ab8500_fg_calculate_scaled_capacity(struct ab8500_fg *di)
1190 struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1191 int capacity = di->bat_cap.prev_percent;
1197 * As long as we are in fully charge mode scale the capacity
1200 if (di->flags.fully_charged) {
1201 cs->cap_to_scale[0] = 100;
1202 cs->cap_to_scale[1] =
1203 max(capacity, di->bm->fg_params->maint_thres);
1204 dev_dbg(di->dev, "Scale cap with %d/%d\n",
1205 cs->cap_to_scale[0], cs->cap_to_scale[1]);
1208 /* Calculates the scaled capacity. */
1209 if ((cs->cap_to_scale[0] != cs->cap_to_scale[1])
1210 && (cs->cap_to_scale[1] > 0))
1212 DIV_ROUND_CLOSEST(di->bat_cap.prev_percent *
1213 cs->cap_to_scale[0],
1214 cs->cap_to_scale[1]));
1216 if (di->flags.charging) {
1217 if (capacity < cs->disable_cap_level) {
1218 cs->disable_cap_level = capacity;
1219 dev_dbg(di->dev, "Cap to stop scale lowered %d%%\n",
1220 cs->disable_cap_level);
1221 } else if (!di->flags.fully_charged) {
1222 if (di->bat_cap.prev_percent >=
1223 cs->disable_cap_level) {
1224 dev_dbg(di->dev, "Disabling scaled capacity\n");
1226 capacity = di->bat_cap.prev_percent;
1229 "Waiting in cap to level %d%%\n",
1230 cs->disable_cap_level);
1231 capacity = cs->disable_cap_level;
1240 * ab8500_fg_update_cap_scalers() - Capacity scaling
1241 * @di: pointer to the ab8500_fg structure
1243 * To be called when state change from charge<->discharge to update
1244 * the capacity scalers.
1246 static void ab8500_fg_update_cap_scalers(struct ab8500_fg *di)
1248 struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1252 if (di->flags.charging) {
1253 di->bat_cap.cap_scale.disable_cap_level =
1254 di->bat_cap.cap_scale.scaled_cap;
1255 dev_dbg(di->dev, "Cap to stop scale at charge %d%%\n",
1256 di->bat_cap.cap_scale.disable_cap_level);
1258 if (cs->scaled_cap != 100) {
1259 cs->cap_to_scale[0] = cs->scaled_cap;
1260 cs->cap_to_scale[1] = di->bat_cap.prev_percent;
1262 cs->cap_to_scale[0] = 100;
1263 cs->cap_to_scale[1] =
1264 max(di->bat_cap.prev_percent,
1265 di->bm->fg_params->maint_thres);
1268 dev_dbg(di->dev, "Cap to scale at discharge %d/%d\n",
1269 cs->cap_to_scale[0], cs->cap_to_scale[1]);
1274 * ab8500_fg_check_capacity_limits() - Check if capacity has changed
1275 * @di: pointer to the ab8500_fg structure
1276 * @init: capacity is allowed to go up in init mode
1278 * Check if capacity or capacity limit has changed and notify the system
1279 * about it using the power_supply framework
1281 static void ab8500_fg_check_capacity_limits(struct ab8500_fg *di, bool init)
1283 bool changed = false;
1284 int percent = DIV_ROUND_CLOSEST(di->bat_cap.permille, 10);
1286 di->bat_cap.level = ab8500_fg_capacity_level(di);
1288 if (di->bat_cap.level != di->bat_cap.prev_level) {
1290 * We do not allow reported capacity level to go up
1291 * unless we're charging or if we're in init
1293 if (!(!di->flags.charging && di->bat_cap.level >
1294 di->bat_cap.prev_level) || init) {
1295 dev_dbg(di->dev, "level changed from %d to %d\n",
1296 di->bat_cap.prev_level,
1298 di->bat_cap.prev_level = di->bat_cap.level;
1301 dev_dbg(di->dev, "level not allowed to go up "
1302 "since no charger is connected: %d to %d\n",
1303 di->bat_cap.prev_level,
1309 * If we have received the LOW_BAT IRQ, set capacity to 0 to initiate
1312 if (di->flags.low_bat) {
1313 dev_dbg(di->dev, "Battery low, set capacity to 0\n");
1314 di->bat_cap.prev_percent = 0;
1315 di->bat_cap.permille = 0;
1317 di->bat_cap.prev_mah = 0;
1318 di->bat_cap.mah = 0;
1320 } else if (di->flags.fully_charged) {
1322 * We report 100% if algorithm reported fully charged
1323 * and show 100% during maintenance charging (scaling).
1325 if (di->flags.force_full) {
1326 di->bat_cap.prev_percent = percent;
1327 di->bat_cap.prev_mah = di->bat_cap.mah;
1331 if (!di->bat_cap.cap_scale.enable &&
1332 di->bm->capacity_scaling) {
1333 di->bat_cap.cap_scale.enable = true;
1334 di->bat_cap.cap_scale.cap_to_scale[0] = 100;
1335 di->bat_cap.cap_scale.cap_to_scale[1] =
1336 di->bat_cap.prev_percent;
1337 di->bat_cap.cap_scale.disable_cap_level = 100;
1339 } else if (di->bat_cap.prev_percent != percent) {
1341 "battery reported full "
1342 "but capacity dropping: %d\n",
1344 di->bat_cap.prev_percent = percent;
1345 di->bat_cap.prev_mah = di->bat_cap.mah;
1349 } else if (di->bat_cap.prev_percent != percent) {
1352 * We will not report 0% unless we've got
1353 * the LOW_BAT IRQ, no matter what the FG
1356 di->bat_cap.prev_percent = 1;
1357 di->bat_cap.permille = 1;
1358 di->bat_cap.prev_mah = 1;
1359 di->bat_cap.mah = 1;
1363 } else if (!(!di->flags.charging &&
1364 percent > di->bat_cap.prev_percent) || init) {
1366 * We do not allow reported capacity to go up
1367 * unless we're charging or if we're in init
1370 "capacity changed from %d to %d (%d)\n",
1371 di->bat_cap.prev_percent,
1373 di->bat_cap.permille);
1374 di->bat_cap.prev_percent = percent;
1375 di->bat_cap.prev_mah = di->bat_cap.mah;
1379 dev_dbg(di->dev, "capacity not allowed to go up since "
1380 "no charger is connected: %d to %d (%d)\n",
1381 di->bat_cap.prev_percent,
1383 di->bat_cap.permille);
1388 if (di->bm->capacity_scaling) {
1389 di->bat_cap.cap_scale.scaled_cap =
1390 ab8500_fg_calculate_scaled_capacity(di);
1392 dev_info(di->dev, "capacity=%d (%d)\n",
1393 di->bat_cap.prev_percent,
1394 di->bat_cap.cap_scale.scaled_cap);
1396 power_supply_changed(&di->fg_psy);
1397 if (di->flags.fully_charged && di->flags.force_full) {
1398 dev_dbg(di->dev, "Battery full, notifying.\n");
1399 di->flags.force_full = false;
1400 sysfs_notify(&di->fg_kobject, NULL, "charge_full");
1402 sysfs_notify(&di->fg_kobject, NULL, "charge_now");
1406 static void ab8500_fg_charge_state_to(struct ab8500_fg *di,
1407 enum ab8500_fg_charge_state new_state)
1409 dev_dbg(di->dev, "Charge state from %d [%s] to %d [%s]\n",
1411 charge_state[di->charge_state],
1413 charge_state[new_state]);
1415 di->charge_state = new_state;
1418 static void ab8500_fg_discharge_state_to(struct ab8500_fg *di,
1419 enum ab8500_fg_discharge_state new_state)
1421 dev_dbg(di->dev, "Disharge state from %d [%s] to %d [%s]\n",
1422 di->discharge_state,
1423 discharge_state[di->discharge_state],
1425 discharge_state[new_state]);
1427 di->discharge_state = new_state;
1431 * ab8500_fg_algorithm_charging() - FG algorithm for when charging
1432 * @di: pointer to the ab8500_fg structure
1434 * Battery capacity calculation state machine for when we're charging
1436 static void ab8500_fg_algorithm_charging(struct ab8500_fg *di)
1439 * If we change to discharge mode
1440 * we should start with recovery
1442 if (di->discharge_state != AB8500_FG_DISCHARGE_INIT_RECOVERY)
1443 ab8500_fg_discharge_state_to(di,
1444 AB8500_FG_DISCHARGE_INIT_RECOVERY);
1446 switch (di->charge_state) {
1447 case AB8500_FG_CHARGE_INIT:
1448 di->fg_samples = SEC_TO_SAMPLE(
1449 di->bm->fg_params->accu_charging);
1451 ab8500_fg_coulomb_counter(di, true);
1452 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_READOUT);
1456 case AB8500_FG_CHARGE_READOUT:
1458 * Read the FG and calculate the new capacity
1460 mutex_lock(&di->cc_lock);
1461 if (!di->flags.conv_done && !di->flags.force_full) {
1462 /* Wasn't the CC IRQ that got us here */
1463 mutex_unlock(&di->cc_lock);
1464 dev_dbg(di->dev, "%s CC conv not done\n",
1469 di->flags.conv_done = false;
1470 mutex_unlock(&di->cc_lock);
1472 ab8500_fg_calc_cap_charging(di);
1480 /* Check capacity limits */
1481 ab8500_fg_check_capacity_limits(di, false);
1484 static void force_capacity(struct ab8500_fg *di)
1488 ab8500_fg_clear_cap_samples(di);
1489 cap = di->bat_cap.user_mah;
1490 if (cap > di->bat_cap.max_mah_design) {
1491 dev_dbg(di->dev, "Remaining cap %d can't be bigger than total"
1492 " %d\n", cap, di->bat_cap.max_mah_design);
1493 cap = di->bat_cap.max_mah_design;
1495 ab8500_fg_fill_cap_sample(di, di->bat_cap.user_mah);
1496 di->bat_cap.permille = ab8500_fg_convert_mah_to_permille(di, cap);
1497 di->bat_cap.mah = cap;
1498 ab8500_fg_check_capacity_limits(di, true);
1501 static bool check_sysfs_capacity(struct ab8500_fg *di)
1503 int cap, lower, upper;
1506 cap = di->bat_cap.user_mah;
1508 cap_permille = ab8500_fg_convert_mah_to_permille(di,
1509 di->bat_cap.user_mah);
1511 lower = di->bat_cap.permille - di->bm->fg_params->user_cap_limit * 10;
1512 upper = di->bat_cap.permille + di->bm->fg_params->user_cap_limit * 10;
1516 /* 1000 is permille, -> 100 percent */
1520 dev_dbg(di->dev, "Capacity limits:"
1521 " (Lower: %d User: %d Upper: %d) [user: %d, was: %d]\n",
1522 lower, cap_permille, upper, cap, di->bat_cap.mah);
1524 /* If within limits, use the saved capacity and exit estimation...*/
1525 if (cap_permille > lower && cap_permille < upper) {
1526 dev_dbg(di->dev, "OK! Using users cap %d uAh now\n", cap);
1530 dev_dbg(di->dev, "Capacity from user out of limits, ignoring");
1535 * ab8500_fg_algorithm_discharging() - FG algorithm for when discharging
1536 * @di: pointer to the ab8500_fg structure
1538 * Battery capacity calculation state machine for when we're discharging
1540 static void ab8500_fg_algorithm_discharging(struct ab8500_fg *di)
1544 /* If we change to charge mode we should start with init */
1545 if (di->charge_state != AB8500_FG_CHARGE_INIT)
1546 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
1548 switch (di->discharge_state) {
1549 case AB8500_FG_DISCHARGE_INIT:
1550 /* We use the FG IRQ to work on */
1552 di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
1553 ab8500_fg_coulomb_counter(di, true);
1554 ab8500_fg_discharge_state_to(di,
1555 AB8500_FG_DISCHARGE_INITMEASURING);
1557 /* Intentional fallthrough */
1558 case AB8500_FG_DISCHARGE_INITMEASURING:
1560 * Discard a number of samples during startup.
1561 * After that, use compensated voltage for a few
1562 * samples to get an initial capacity.
1563 * Then go to READOUT
1565 sleep_time = di->bm->fg_params->init_timer;
1567 /* Discard the first [x] seconds */
1568 if (di->init_cnt > di->bm->fg_params->init_discard_time) {
1569 ab8500_fg_calc_cap_discharge_voltage(di, true);
1571 ab8500_fg_check_capacity_limits(di, true);
1574 di->init_cnt += sleep_time;
1575 if (di->init_cnt > di->bm->fg_params->init_total_time)
1576 ab8500_fg_discharge_state_to(di,
1577 AB8500_FG_DISCHARGE_READOUT_INIT);
1581 case AB8500_FG_DISCHARGE_INIT_RECOVERY:
1582 di->recovery_cnt = 0;
1583 di->recovery_needed = true;
1584 ab8500_fg_discharge_state_to(di,
1585 AB8500_FG_DISCHARGE_RECOVERY);
1587 /* Intentional fallthrough */
1589 case AB8500_FG_DISCHARGE_RECOVERY:
1590 sleep_time = di->bm->fg_params->recovery_sleep_timer;
1593 * We should check the power consumption
1594 * If low, go to READOUT (after x min) or
1595 * RECOVERY_SLEEP if time left.
1596 * If high, go to READOUT
1598 di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1600 if (ab8500_fg_is_low_curr(di, di->inst_curr)) {
1601 if (di->recovery_cnt >
1602 di->bm->fg_params->recovery_total_time) {
1603 di->fg_samples = SEC_TO_SAMPLE(
1604 di->bm->fg_params->accu_high_curr);
1605 ab8500_fg_coulomb_counter(di, true);
1606 ab8500_fg_discharge_state_to(di,
1607 AB8500_FG_DISCHARGE_READOUT);
1608 di->recovery_needed = false;
1610 queue_delayed_work(di->fg_wq,
1611 &di->fg_periodic_work,
1614 di->recovery_cnt += sleep_time;
1616 di->fg_samples = SEC_TO_SAMPLE(
1617 di->bm->fg_params->accu_high_curr);
1618 ab8500_fg_coulomb_counter(di, true);
1619 ab8500_fg_discharge_state_to(di,
1620 AB8500_FG_DISCHARGE_READOUT);
1624 case AB8500_FG_DISCHARGE_READOUT_INIT:
1625 di->fg_samples = SEC_TO_SAMPLE(
1626 di->bm->fg_params->accu_high_curr);
1627 ab8500_fg_coulomb_counter(di, true);
1628 ab8500_fg_discharge_state_to(di,
1629 AB8500_FG_DISCHARGE_READOUT);
1632 case AB8500_FG_DISCHARGE_READOUT:
1633 di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1635 if (ab8500_fg_is_low_curr(di, di->inst_curr)) {
1636 /* Detect mode change */
1637 if (di->high_curr_mode) {
1638 di->high_curr_mode = false;
1639 di->high_curr_cnt = 0;
1642 if (di->recovery_needed) {
1643 ab8500_fg_discharge_state_to(di,
1644 AB8500_FG_DISCHARGE_INIT_RECOVERY);
1646 queue_delayed_work(di->fg_wq,
1647 &di->fg_periodic_work, 0);
1652 ab8500_fg_calc_cap_discharge_voltage(di, true);
1654 mutex_lock(&di->cc_lock);
1655 if (!di->flags.conv_done) {
1656 /* Wasn't the CC IRQ that got us here */
1657 mutex_unlock(&di->cc_lock);
1658 dev_dbg(di->dev, "%s CC conv not done\n",
1663 di->flags.conv_done = false;
1664 mutex_unlock(&di->cc_lock);
1666 /* Detect mode change */
1667 if (!di->high_curr_mode) {
1668 di->high_curr_mode = true;
1669 di->high_curr_cnt = 0;
1672 di->high_curr_cnt +=
1673 di->bm->fg_params->accu_high_curr;
1674 if (di->high_curr_cnt >
1675 di->bm->fg_params->high_curr_time)
1676 di->recovery_needed = true;
1678 ab8500_fg_calc_cap_discharge_fg(di);
1681 ab8500_fg_check_capacity_limits(di, false);
1685 case AB8500_FG_DISCHARGE_WAKEUP:
1686 ab8500_fg_coulomb_counter(di, true);
1687 ab8500_fg_calc_cap_discharge_voltage(di, true);
1689 di->fg_samples = SEC_TO_SAMPLE(
1690 di->bm->fg_params->accu_high_curr);
1691 ab8500_fg_coulomb_counter(di, true);
1692 ab8500_fg_discharge_state_to(di,
1693 AB8500_FG_DISCHARGE_READOUT);
1695 ab8500_fg_check_capacity_limits(di, false);
1705 * ab8500_fg_algorithm_calibrate() - Internal columb counter offset calibration
1706 * @di: pointer to the ab8500_fg structure
1709 static void ab8500_fg_algorithm_calibrate(struct ab8500_fg *di)
1713 switch (di->calib_state) {
1714 case AB8500_FG_CALIB_INIT:
1715 dev_dbg(di->dev, "Calibration ongoing...\n");
1717 ret = abx500_mask_and_set_register_interruptible(di->dev,
1718 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1719 CC_INT_CAL_N_AVG_MASK, CC_INT_CAL_SAMPLES_8);
1723 ret = abx500_mask_and_set_register_interruptible(di->dev,
1724 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1725 CC_INTAVGOFFSET_ENA, CC_INTAVGOFFSET_ENA);
1728 di->calib_state = AB8500_FG_CALIB_WAIT;
1730 case AB8500_FG_CALIB_END:
1731 ret = abx500_mask_and_set_register_interruptible(di->dev,
1732 AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1733 CC_MUXOFFSET, CC_MUXOFFSET);
1736 di->flags.calibrate = false;
1737 dev_dbg(di->dev, "Calibration done...\n");
1738 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1740 case AB8500_FG_CALIB_WAIT:
1741 dev_dbg(di->dev, "Calibration WFI\n");
1747 /* Something went wrong, don't calibrate then */
1748 dev_err(di->dev, "failed to calibrate the CC\n");
1749 di->flags.calibrate = false;
1750 di->calib_state = AB8500_FG_CALIB_INIT;
1751 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1755 * ab8500_fg_algorithm() - Entry point for the FG algorithm
1756 * @di: pointer to the ab8500_fg structure
1758 * Entry point for the battery capacity calculation state machine
1760 static void ab8500_fg_algorithm(struct ab8500_fg *di)
1762 if (di->flags.calibrate)
1763 ab8500_fg_algorithm_calibrate(di);
1765 if (di->flags.charging)
1766 ab8500_fg_algorithm_charging(di);
1768 ab8500_fg_algorithm_discharging(di);
1771 dev_dbg(di->dev, "[FG_DATA] %d %d %d %d %d %d %d %d %d "
1772 "%d %d %d %d %d %d %d\n",
1773 di->bat_cap.max_mah_design,
1775 di->bat_cap.permille,
1777 di->bat_cap.prev_mah,
1778 di->bat_cap.prev_percent,
1779 di->bat_cap.prev_level,
1786 di->discharge_state,
1788 di->recovery_needed);
1792 * ab8500_fg_periodic_work() - Run the FG state machine periodically
1793 * @work: pointer to the work_struct structure
1795 * Work queue function for periodic work
1797 static void ab8500_fg_periodic_work(struct work_struct *work)
1799 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1800 fg_periodic_work.work);
1802 if (di->init_capacity) {
1803 /* Get an initial capacity calculation */
1804 ab8500_fg_calc_cap_discharge_voltage(di, true);
1805 ab8500_fg_check_capacity_limits(di, true);
1806 di->init_capacity = false;
1808 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1809 } else if (di->flags.user_cap) {
1810 if (check_sysfs_capacity(di)) {
1811 ab8500_fg_check_capacity_limits(di, true);
1812 if (di->flags.charging)
1813 ab8500_fg_charge_state_to(di,
1814 AB8500_FG_CHARGE_INIT);
1816 ab8500_fg_discharge_state_to(di,
1817 AB8500_FG_DISCHARGE_READOUT_INIT);
1819 di->flags.user_cap = false;
1820 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1822 ab8500_fg_algorithm(di);
1827 * ab8500_fg_check_hw_failure_work() - Check OVV_BAT condition
1828 * @work: pointer to the work_struct structure
1830 * Work queue function for checking the OVV_BAT condition
1832 static void ab8500_fg_check_hw_failure_work(struct work_struct *work)
1837 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1838 fg_check_hw_failure_work.work);
1841 * If we have had a battery over-voltage situation,
1842 * check ovv-bit to see if it should be reset.
1844 ret = abx500_get_register_interruptible(di->dev,
1845 AB8500_CHARGER, AB8500_CH_STAT_REG,
1848 dev_err(di->dev, "%s ab8500 read failed\n", __func__);
1851 if ((reg_value & BATT_OVV) == BATT_OVV) {
1852 if (!di->flags.bat_ovv) {
1853 dev_dbg(di->dev, "Battery OVV\n");
1854 di->flags.bat_ovv = true;
1855 power_supply_changed(&di->fg_psy);
1857 /* Not yet recovered from ovv, reschedule this test */
1858 queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work,
1861 dev_dbg(di->dev, "Battery recovered from OVV\n");
1862 di->flags.bat_ovv = false;
1863 power_supply_changed(&di->fg_psy);
1868 * ab8500_fg_low_bat_work() - Check LOW_BAT condition
1869 * @work: pointer to the work_struct structure
1871 * Work queue function for checking the LOW_BAT condition
1873 static void ab8500_fg_low_bat_work(struct work_struct *work)
1877 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1878 fg_low_bat_work.work);
1880 vbat = ab8500_fg_bat_voltage(di);
1882 /* Check if LOW_BAT still fulfilled */
1883 if (vbat < di->bm->fg_params->lowbat_threshold) {
1884 /* Is it time to shut down? */
1885 if (di->low_bat_cnt < 1) {
1886 di->flags.low_bat = true;
1887 dev_warn(di->dev, "Shut down pending...\n");
1890 * Else we need to re-schedule this check to be able to detect
1891 * if the voltage increases again during charging or
1892 * due to decreasing load.
1895 dev_warn(di->dev, "Battery voltage still LOW\n");
1896 queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
1897 round_jiffies(LOW_BAT_CHECK_INTERVAL));
1900 di->flags.low_bat_delay = false;
1901 di->low_bat_cnt = 10;
1902 dev_warn(di->dev, "Battery voltage OK again\n");
1905 /* This is needed to dispatch LOW_BAT */
1906 ab8500_fg_check_capacity_limits(di, false);
1910 * ab8500_fg_battok_calc - calculate the bit pattern corresponding
1911 * to the target voltage.
1912 * @di: pointer to the ab8500_fg structure
1913 * @target target voltage
1915 * Returns bit pattern closest to the target voltage
1916 * valid return values are 0-14. (0-BATT_OK_MAX_NR_INCREMENTS)
1919 static int ab8500_fg_battok_calc(struct ab8500_fg *di, int target)
1921 if (target > BATT_OK_MIN +
1922 (BATT_OK_INCREMENT * BATT_OK_MAX_NR_INCREMENTS))
1923 return BATT_OK_MAX_NR_INCREMENTS;
1924 if (target < BATT_OK_MIN)
1926 return (target - BATT_OK_MIN) / BATT_OK_INCREMENT;
1930 * ab8500_fg_battok_init_hw_register - init battok levels
1931 * @di: pointer to the ab8500_fg structure
1935 static int ab8500_fg_battok_init_hw_register(struct ab8500_fg *di)
1945 sel0 = di->bm->fg_params->battok_falling_th_sel0;
1946 sel1 = di->bm->fg_params->battok_raising_th_sel1;
1948 cbp_sel0 = ab8500_fg_battok_calc(di, sel0);
1949 cbp_sel1 = ab8500_fg_battok_calc(di, sel1);
1951 selected = BATT_OK_MIN + cbp_sel0 * BATT_OK_INCREMENT;
1953 if (selected != sel0)
1954 dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1955 sel0, selected, cbp_sel0);
1957 selected = BATT_OK_MIN + cbp_sel1 * BATT_OK_INCREMENT;
1959 if (selected != sel1)
1960 dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1961 sel1, selected, cbp_sel1);
1963 new_val = cbp_sel0 | (cbp_sel1 << 4);
1965 dev_dbg(di->dev, "using: %x %d %d\n", new_val, cbp_sel0, cbp_sel1);
1966 ret = abx500_set_register_interruptible(di->dev, AB8500_SYS_CTRL2_BLOCK,
1967 AB8500_BATT_OK_REG, new_val);
1972 * ab8500_fg_instant_work() - Run the FG state machine instantly
1973 * @work: pointer to the work_struct structure
1975 * Work queue function for instant work
1977 static void ab8500_fg_instant_work(struct work_struct *work)
1979 struct ab8500_fg *di = container_of(work, struct ab8500_fg, fg_work);
1981 ab8500_fg_algorithm(di);
1985 * ab8500_fg_cc_data_end_handler() - isr to get battery avg current.
1986 * @irq: interrupt number
1987 * @_di: pointer to the ab8500_fg structure
1989 * Returns IRQ status(IRQ_HANDLED)
1991 static irqreturn_t ab8500_fg_cc_data_end_handler(int irq, void *_di)
1993 struct ab8500_fg *di = _di;
1994 if (!di->nbr_cceoc_irq_cnt) {
1995 di->nbr_cceoc_irq_cnt++;
1996 complete(&di->ab8500_fg_started);
1998 di->nbr_cceoc_irq_cnt = 0;
1999 complete(&di->ab8500_fg_complete);
2005 * ab8500_fg_cc_convend_handler() - isr to get battery avg current.
2006 * @irq: interrupt number
2007 * @_di: pointer to the ab8500_fg structure
2009 * Returns IRQ status(IRQ_HANDLED)
2011 static irqreturn_t ab8500_fg_cc_int_calib_handler(int irq, void *_di)
2013 struct ab8500_fg *di = _di;
2014 di->calib_state = AB8500_FG_CALIB_END;
2015 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2020 * ab8500_fg_cc_convend_handler() - isr to get battery avg current.
2021 * @irq: interrupt number
2022 * @_di: pointer to the ab8500_fg structure
2024 * Returns IRQ status(IRQ_HANDLED)
2026 static irqreturn_t ab8500_fg_cc_convend_handler(int irq, void *_di)
2028 struct ab8500_fg *di = _di;
2030 queue_work(di->fg_wq, &di->fg_acc_cur_work);
2036 * ab8500_fg_batt_ovv_handler() - Battery OVV occured
2037 * @irq: interrupt number
2038 * @_di: pointer to the ab8500_fg structure
2040 * Returns IRQ status(IRQ_HANDLED)
2042 static irqreturn_t ab8500_fg_batt_ovv_handler(int irq, void *_di)
2044 struct ab8500_fg *di = _di;
2046 dev_dbg(di->dev, "Battery OVV\n");
2048 /* Schedule a new HW failure check */
2049 queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work, 0);
2055 * ab8500_fg_lowbatf_handler() - Battery voltage is below LOW threshold
2056 * @irq: interrupt number
2057 * @_di: pointer to the ab8500_fg structure
2059 * Returns IRQ status(IRQ_HANDLED)
2061 static irqreturn_t ab8500_fg_lowbatf_handler(int irq, void *_di)
2063 struct ab8500_fg *di = _di;
2065 /* Initiate handling in ab8500_fg_low_bat_work() if not already initiated. */
2066 if (!di->flags.low_bat_delay) {
2067 dev_warn(di->dev, "Battery voltage is below LOW threshold\n");
2068 di->flags.low_bat_delay = true;
2070 * Start a timer to check LOW_BAT again after some time
2071 * This is done to avoid shutdown on single voltage dips
2073 queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
2074 round_jiffies(LOW_BAT_CHECK_INTERVAL));
2080 * ab8500_fg_get_property() - get the fg properties
2081 * @psy: pointer to the power_supply structure
2082 * @psp: pointer to the power_supply_property structure
2083 * @val: pointer to the power_supply_propval union
2085 * This function gets called when an application tries to get the
2086 * fg properties by reading the sysfs files.
2087 * voltage_now: battery voltage
2088 * current_now: battery instant current
2089 * current_avg: battery average current
2090 * charge_full_design: capacity where battery is considered full
2091 * charge_now: battery capacity in nAh
2092 * capacity: capacity in percent
2093 * capacity_level: capacity level
2095 * Returns error code in case of failure else 0 on success
2097 static int ab8500_fg_get_property(struct power_supply *psy,
2098 enum power_supply_property psp,
2099 union power_supply_propval *val)
2101 struct ab8500_fg *di;
2103 di = to_ab8500_fg_device_info(psy);
2106 * If battery is identified as unknown and charging of unknown
2107 * batteries is disabled, we always report 100% capacity and
2108 * capacity level UNKNOWN, since we can't calculate
2109 * remaining capacity
2113 case POWER_SUPPLY_PROP_VOLTAGE_NOW:
2114 if (di->flags.bat_ovv)
2115 val->intval = BATT_OVV_VALUE * 1000;
2117 val->intval = di->vbat * 1000;
2119 case POWER_SUPPLY_PROP_CURRENT_NOW:
2120 val->intval = di->inst_curr * 1000;
2122 case POWER_SUPPLY_PROP_CURRENT_AVG:
2123 val->intval = di->avg_curr * 1000;
2125 case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
2126 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2127 di->bat_cap.max_mah_design);
2129 case POWER_SUPPLY_PROP_ENERGY_FULL:
2130 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2131 di->bat_cap.max_mah);
2133 case POWER_SUPPLY_PROP_ENERGY_NOW:
2134 if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2135 di->flags.batt_id_received)
2136 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2137 di->bat_cap.max_mah);
2139 val->intval = ab8500_fg_convert_mah_to_uwh(di,
2140 di->bat_cap.prev_mah);
2142 case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
2143 val->intval = di->bat_cap.max_mah_design;
2145 case POWER_SUPPLY_PROP_CHARGE_FULL:
2146 val->intval = di->bat_cap.max_mah;
2148 case POWER_SUPPLY_PROP_CHARGE_NOW:
2149 if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2150 di->flags.batt_id_received)
2151 val->intval = di->bat_cap.max_mah;
2153 val->intval = di->bat_cap.prev_mah;
2155 case POWER_SUPPLY_PROP_CAPACITY:
2156 if (di->bm->capacity_scaling)
2157 val->intval = di->bat_cap.cap_scale.scaled_cap;
2158 else if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2159 di->flags.batt_id_received)
2162 val->intval = di->bat_cap.prev_percent;
2164 case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
2165 if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2166 di->flags.batt_id_received)
2167 val->intval = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
2169 val->intval = di->bat_cap.prev_level;
2177 static int ab8500_fg_get_ext_psy_data(struct device *dev, void *data)
2179 struct power_supply *psy;
2180 struct power_supply *ext;
2181 struct ab8500_fg *di;
2182 union power_supply_propval ret;
2184 bool psy_found = false;
2186 psy = (struct power_supply *)data;
2187 ext = dev_get_drvdata(dev);
2188 di = to_ab8500_fg_device_info(psy);
2191 * For all psy where the name of your driver
2192 * appears in any supplied_to
2194 for (i = 0; i < ext->num_supplicants; i++) {
2195 if (!strcmp(ext->supplied_to[i], psy->name))
2202 /* Go through all properties for the psy */
2203 for (j = 0; j < ext->num_properties; j++) {
2204 enum power_supply_property prop;
2205 prop = ext->properties[j];
2207 if (ext->get_property(ext, prop, &ret))
2211 case POWER_SUPPLY_PROP_STATUS:
2212 switch (ext->type) {
2213 case POWER_SUPPLY_TYPE_BATTERY:
2214 switch (ret.intval) {
2215 case POWER_SUPPLY_STATUS_UNKNOWN:
2216 case POWER_SUPPLY_STATUS_DISCHARGING:
2217 case POWER_SUPPLY_STATUS_NOT_CHARGING:
2218 if (!di->flags.charging)
2220 di->flags.charging = false;
2221 di->flags.fully_charged = false;
2222 if (di->bm->capacity_scaling)
2223 ab8500_fg_update_cap_scalers(di);
2224 queue_work(di->fg_wq, &di->fg_work);
2226 case POWER_SUPPLY_STATUS_FULL:
2227 if (di->flags.fully_charged)
2229 di->flags.fully_charged = true;
2230 di->flags.force_full = true;
2231 /* Save current capacity as maximum */
2232 di->bat_cap.max_mah = di->bat_cap.mah;
2233 queue_work(di->fg_wq, &di->fg_work);
2235 case POWER_SUPPLY_STATUS_CHARGING:
2236 if (di->flags.charging &&
2237 !di->flags.fully_charged)
2239 di->flags.charging = true;
2240 di->flags.fully_charged = false;
2241 if (di->bm->capacity_scaling)
2242 ab8500_fg_update_cap_scalers(di);
2243 queue_work(di->fg_wq, &di->fg_work);
2250 case POWER_SUPPLY_PROP_TECHNOLOGY:
2251 switch (ext->type) {
2252 case POWER_SUPPLY_TYPE_BATTERY:
2253 if (!di->flags.batt_id_received &&
2254 di->bm->batt_id != BATTERY_UNKNOWN) {
2255 const struct abx500_battery_type *b;
2257 b = &(di->bm->bat_type[di->bm->batt_id]);
2259 di->flags.batt_id_received = true;
2261 di->bat_cap.max_mah_design =
2263 b->charge_full_design;
2265 di->bat_cap.max_mah =
2266 di->bat_cap.max_mah_design;
2268 di->vbat_nom = b->nominal_voltage;
2272 di->flags.batt_unknown = false;
2274 di->flags.batt_unknown = true;
2280 case POWER_SUPPLY_PROP_TEMP:
2281 switch (ext->type) {
2282 case POWER_SUPPLY_TYPE_BATTERY:
2283 if (di->flags.batt_id_received)
2284 di->bat_temp = ret.intval;
2298 * ab8500_fg_init_hw_registers() - Set up FG related registers
2299 * @di: pointer to the ab8500_fg structure
2301 * Set up battery OVV, low battery voltage registers
2303 static int ab8500_fg_init_hw_registers(struct ab8500_fg *di)
2307 /* Set VBAT OVV threshold */
2308 ret = abx500_mask_and_set_register_interruptible(di->dev,
2314 dev_err(di->dev, "failed to set BATT_OVV\n");
2318 /* Enable VBAT OVV detection */
2319 ret = abx500_mask_and_set_register_interruptible(di->dev,
2325 dev_err(di->dev, "failed to enable BATT_OVV\n");
2329 /* Low Battery Voltage */
2330 ret = abx500_set_register_interruptible(di->dev,
2331 AB8500_SYS_CTRL2_BLOCK,
2333 ab8500_volt_to_regval(
2334 di->bm->fg_params->lowbat_threshold) << 1 |
2337 dev_err(di->dev, "%s write failed\n", __func__);
2341 /* Battery OK threshold */
2342 ret = ab8500_fg_battok_init_hw_register(di);
2344 dev_err(di->dev, "BattOk init write failed.\n");
2352 * ab8500_fg_external_power_changed() - callback for power supply changes
2353 * @psy: pointer to the structure power_supply
2355 * This function is the entry point of the pointer external_power_changed
2356 * of the structure power_supply.
2357 * This function gets executed when there is a change in any external power
2358 * supply that this driver needs to be notified of.
2360 static void ab8500_fg_external_power_changed(struct power_supply *psy)
2362 struct ab8500_fg *di = to_ab8500_fg_device_info(psy);
2364 class_for_each_device(power_supply_class, NULL,
2365 &di->fg_psy, ab8500_fg_get_ext_psy_data);
2369 * abab8500_fg_reinit_work() - work to reset the FG algorithm
2370 * @work: pointer to the work_struct structure
2372 * Used to reset the current battery capacity to be able to
2373 * retrigger a new voltage base capacity calculation. For
2374 * test and verification purpose.
2376 static void ab8500_fg_reinit_work(struct work_struct *work)
2378 struct ab8500_fg *di = container_of(work, struct ab8500_fg,
2379 fg_reinit_work.work);
2381 if (di->flags.calibrate == false) {
2382 dev_dbg(di->dev, "Resetting FG state machine to init.\n");
2383 ab8500_fg_clear_cap_samples(di);
2384 ab8500_fg_calc_cap_discharge_voltage(di, true);
2385 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
2386 ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
2387 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2390 dev_err(di->dev, "Residual offset calibration ongoing "
2392 /* Wait one second until next try*/
2393 queue_delayed_work(di->fg_wq, &di->fg_reinit_work,
2399 * ab8500_fg_reinit() - forces FG algorithm to reinitialize with current values
2401 * This function can be used to force the FG algorithm to recalculate a new
2402 * voltage based battery capacity.
2404 void ab8500_fg_reinit(void)
2406 struct ab8500_fg *di = ab8500_fg_get();
2407 /* User won't be notified if a null pointer returned. */
2409 queue_delayed_work(di->fg_wq, &di->fg_reinit_work, 0);
2412 /* Exposure to the sysfs interface */
2414 struct ab8500_fg_sysfs_entry {
2415 struct attribute attr;
2416 ssize_t (*show)(struct ab8500_fg *, char *);
2417 ssize_t (*store)(struct ab8500_fg *, const char *, size_t);
2420 static ssize_t charge_full_show(struct ab8500_fg *di, char *buf)
2422 return sprintf(buf, "%d\n", di->bat_cap.max_mah);
2425 static ssize_t charge_full_store(struct ab8500_fg *di, const char *buf,
2428 unsigned long charge_full;
2429 ssize_t ret = -EINVAL;
2431 ret = strict_strtoul(buf, 10, &charge_full);
2433 dev_dbg(di->dev, "Ret %zd charge_full %lu", ret, charge_full);
2436 di->bat_cap.max_mah = (int) charge_full;
2442 static ssize_t charge_now_show(struct ab8500_fg *di, char *buf)
2444 return sprintf(buf, "%d\n", di->bat_cap.prev_mah);
2447 static ssize_t charge_now_store(struct ab8500_fg *di, const char *buf,
2450 unsigned long charge_now;
2453 ret = strict_strtoul(buf, 10, &charge_now);
2455 dev_dbg(di->dev, "Ret %zd charge_now %lu was %d",
2456 ret, charge_now, di->bat_cap.prev_mah);
2459 di->bat_cap.user_mah = (int) charge_now;
2460 di->flags.user_cap = true;
2462 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2467 static struct ab8500_fg_sysfs_entry charge_full_attr =
2468 __ATTR(charge_full, 0644, charge_full_show, charge_full_store);
2470 static struct ab8500_fg_sysfs_entry charge_now_attr =
2471 __ATTR(charge_now, 0644, charge_now_show, charge_now_store);
2474 ab8500_fg_show(struct kobject *kobj, struct attribute *attr, char *buf)
2476 struct ab8500_fg_sysfs_entry *entry;
2477 struct ab8500_fg *di;
2479 entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2480 di = container_of(kobj, struct ab8500_fg, fg_kobject);
2485 return entry->show(di, buf);
2488 ab8500_fg_store(struct kobject *kobj, struct attribute *attr, const char *buf,
2491 struct ab8500_fg_sysfs_entry *entry;
2492 struct ab8500_fg *di;
2494 entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2495 di = container_of(kobj, struct ab8500_fg, fg_kobject);
2500 return entry->store(di, buf, count);
2503 static const struct sysfs_ops ab8500_fg_sysfs_ops = {
2504 .show = ab8500_fg_show,
2505 .store = ab8500_fg_store,
2508 static struct attribute *ab8500_fg_attrs[] = {
2509 &charge_full_attr.attr,
2510 &charge_now_attr.attr,
2514 static struct kobj_type ab8500_fg_ktype = {
2515 .sysfs_ops = &ab8500_fg_sysfs_ops,
2516 .default_attrs = ab8500_fg_attrs,
2520 * ab8500_chargalg_sysfs_exit() - de-init of sysfs entry
2521 * @di: pointer to the struct ab8500_chargalg
2523 * This function removes the entry in sysfs.
2525 static void ab8500_fg_sysfs_exit(struct ab8500_fg *di)
2527 kobject_del(&di->fg_kobject);
2531 * ab8500_chargalg_sysfs_init() - init of sysfs entry
2532 * @di: pointer to the struct ab8500_chargalg
2534 * This function adds an entry in sysfs.
2535 * Returns error code in case of failure else 0(on success)
2537 static int ab8500_fg_sysfs_init(struct ab8500_fg *di)
2541 ret = kobject_init_and_add(&di->fg_kobject,
2545 dev_err(di->dev, "failed to create sysfs entry\n");
2549 /* Exposure to the sysfs interface <<END>> */
2551 #if defined(CONFIG_PM)
2552 static int ab8500_fg_resume(struct platform_device *pdev)
2554 struct ab8500_fg *di = platform_get_drvdata(pdev);
2557 * Change state if we're not charging. If we're charging we will wake
2560 if (!di->flags.charging) {
2561 ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_WAKEUP);
2562 queue_work(di->fg_wq, &di->fg_work);
2568 static int ab8500_fg_suspend(struct platform_device *pdev,
2571 struct ab8500_fg *di = platform_get_drvdata(pdev);
2573 flush_delayed_work(&di->fg_periodic_work);
2574 flush_work(&di->fg_work);
2575 flush_work(&di->fg_acc_cur_work);
2576 flush_delayed_work(&di->fg_reinit_work);
2577 flush_delayed_work(&di->fg_low_bat_work);
2578 flush_delayed_work(&di->fg_check_hw_failure_work);
2581 * If the FG is enabled we will disable it before going to suspend
2582 * only if we're not charging
2584 if (di->flags.fg_enabled && !di->flags.charging)
2585 ab8500_fg_coulomb_counter(di, false);
2590 #define ab8500_fg_suspend NULL
2591 #define ab8500_fg_resume NULL
2594 static int ab8500_fg_remove(struct platform_device *pdev)
2597 struct ab8500_fg *di = platform_get_drvdata(pdev);
2599 list_del(&di->node);
2601 /* Disable coulomb counter */
2602 ret = ab8500_fg_coulomb_counter(di, false);
2604 dev_err(di->dev, "failed to disable coulomb counter\n");
2606 destroy_workqueue(di->fg_wq);
2607 ab8500_fg_sysfs_exit(di);
2609 flush_scheduled_work();
2610 power_supply_unregister(&di->fg_psy);
2611 platform_set_drvdata(pdev, NULL);
2615 /* ab8500 fg driver interrupts and their respective isr */
2616 static struct ab8500_fg_interrupts ab8500_fg_irq[] = {
2617 {"NCONV_ACCU", ab8500_fg_cc_convend_handler},
2618 {"BATT_OVV", ab8500_fg_batt_ovv_handler},
2619 {"LOW_BAT_F", ab8500_fg_lowbatf_handler},
2620 {"CC_INT_CALIB", ab8500_fg_cc_int_calib_handler},
2621 {"CCEOC", ab8500_fg_cc_data_end_handler},
2624 static char *supply_interface[] = {
2629 static int ab8500_fg_probe(struct platform_device *pdev)
2631 struct device_node *np = pdev->dev.of_node;
2632 struct abx500_bm_data *plat = pdev->dev.platform_data;
2633 struct ab8500_fg *di;
2637 di = devm_kzalloc(&pdev->dev, sizeof(*di), GFP_KERNEL);
2639 dev_err(&pdev->dev, "%s no mem for ab8500_fg\n", __func__);
2644 dev_err(&pdev->dev, "no battery management data supplied\n");
2650 ret = ab8500_bm_of_probe(&pdev->dev, np, di->bm);
2652 dev_err(&pdev->dev, "failed to get battery information\n");
2657 mutex_init(&di->cc_lock);
2659 /* get parent data */
2660 di->dev = &pdev->dev;
2661 di->parent = dev_get_drvdata(pdev->dev.parent);
2662 di->gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
2664 di->fg_psy.name = "ab8500_fg";
2665 di->fg_psy.type = POWER_SUPPLY_TYPE_BATTERY;
2666 di->fg_psy.properties = ab8500_fg_props;
2667 di->fg_psy.num_properties = ARRAY_SIZE(ab8500_fg_props);
2668 di->fg_psy.get_property = ab8500_fg_get_property;
2669 di->fg_psy.supplied_to = supply_interface;
2670 di->fg_psy.num_supplicants = ARRAY_SIZE(supply_interface),
2671 di->fg_psy.external_power_changed = ab8500_fg_external_power_changed;
2673 di->bat_cap.max_mah_design = MILLI_TO_MICRO *
2674 di->bm->bat_type[di->bm->batt_id].charge_full_design;
2676 di->bat_cap.max_mah = di->bat_cap.max_mah_design;
2678 di->vbat_nom = di->bm->bat_type[di->bm->batt_id].nominal_voltage;
2680 di->init_capacity = true;
2682 ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
2683 ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
2685 /* Create a work queue for running the FG algorithm */
2686 di->fg_wq = create_singlethread_workqueue("ab8500_fg_wq");
2687 if (di->fg_wq == NULL) {
2688 dev_err(di->dev, "failed to create work queue\n");
2692 /* Init work for running the fg algorithm instantly */
2693 INIT_WORK(&di->fg_work, ab8500_fg_instant_work);
2695 /* Init work for getting the battery accumulated current */
2696 INIT_WORK(&di->fg_acc_cur_work, ab8500_fg_acc_cur_work);
2698 /* Init work for reinitialising the fg algorithm */
2699 INIT_DEFERRABLE_WORK(&di->fg_reinit_work,
2700 ab8500_fg_reinit_work);
2702 /* Work delayed Queue to run the state machine */
2703 INIT_DEFERRABLE_WORK(&di->fg_periodic_work,
2704 ab8500_fg_periodic_work);
2706 /* Work to check low battery condition */
2707 INIT_DEFERRABLE_WORK(&di->fg_low_bat_work,
2708 ab8500_fg_low_bat_work);
2710 /* Init work for HW failure check */
2711 INIT_DEFERRABLE_WORK(&di->fg_check_hw_failure_work,
2712 ab8500_fg_check_hw_failure_work);
2714 /* Reset battery low voltage flag */
2715 di->flags.low_bat = false;
2717 /* Initialize low battery counter */
2718 di->low_bat_cnt = 10;
2720 /* Initialize OVV, and other registers */
2721 ret = ab8500_fg_init_hw_registers(di);
2723 dev_err(di->dev, "failed to initialize registers\n");
2724 goto free_inst_curr_wq;
2727 /* Consider battery unknown until we're informed otherwise */
2728 di->flags.batt_unknown = true;
2729 di->flags.batt_id_received = false;
2731 /* Register FG power supply class */
2732 ret = power_supply_register(di->dev, &di->fg_psy);
2734 dev_err(di->dev, "failed to register FG psy\n");
2735 goto free_inst_curr_wq;
2738 di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
2739 ab8500_fg_coulomb_counter(di, true);
2742 * Initialize completion used to notify completion and start
2745 init_completion(&di->ab8500_fg_started);
2746 init_completion(&di->ab8500_fg_complete);
2748 /* Register interrupts */
2749 for (i = 0; i < ARRAY_SIZE(ab8500_fg_irq); i++) {
2750 irq = platform_get_irq_byname(pdev, ab8500_fg_irq[i].name);
2751 ret = request_threaded_irq(irq, NULL, ab8500_fg_irq[i].isr,
2752 IRQF_SHARED | IRQF_NO_SUSPEND,
2753 ab8500_fg_irq[i].name, di);
2756 dev_err(di->dev, "failed to request %s IRQ %d: %d\n"
2757 , ab8500_fg_irq[i].name, irq, ret);
2760 dev_dbg(di->dev, "Requested %s IRQ %d: %d\n",
2761 ab8500_fg_irq[i].name, irq, ret);
2763 di->irq = platform_get_irq_byname(pdev, "CCEOC");
2764 disable_irq(di->irq);
2765 di->nbr_cceoc_irq_cnt = 0;
2767 platform_set_drvdata(pdev, di);
2769 ret = ab8500_fg_sysfs_init(di);
2771 dev_err(di->dev, "failed to create sysfs entry\n");
2775 /* Calibrate the fg first time */
2776 di->flags.calibrate = true;
2777 di->calib_state = AB8500_FG_CALIB_INIT;
2779 /* Use room temp as default value until we get an update from driver. */
2782 /* Run the FG algorithm */
2783 queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2785 list_add_tail(&di->node, &ab8500_fg_list);
2790 power_supply_unregister(&di->fg_psy);
2792 /* We also have to free all successfully registered irqs */
2793 for (i = i - 1; i >= 0; i--) {
2794 irq = platform_get_irq_byname(pdev, ab8500_fg_irq[i].name);
2798 destroy_workqueue(di->fg_wq);
2802 static const struct of_device_id ab8500_fg_match[] = {
2803 { .compatible = "stericsson,ab8500-fg", },
2807 static struct platform_driver ab8500_fg_driver = {
2808 .probe = ab8500_fg_probe,
2809 .remove = ab8500_fg_remove,
2810 .suspend = ab8500_fg_suspend,
2811 .resume = ab8500_fg_resume,
2813 .name = "ab8500-fg",
2814 .owner = THIS_MODULE,
2815 .of_match_table = ab8500_fg_match,
2819 static int __init ab8500_fg_init(void)
2821 return platform_driver_register(&ab8500_fg_driver);
2824 static void __exit ab8500_fg_exit(void)
2826 platform_driver_unregister(&ab8500_fg_driver);
2829 subsys_initcall_sync(ab8500_fg_init);
2830 module_exit(ab8500_fg_exit);
2832 MODULE_LICENSE("GPL v2");
2833 MODULE_AUTHOR("Johan Palsson, Karl Komierowski");
2834 MODULE_ALIAS("platform:ab8500-fg");
2835 MODULE_DESCRIPTION("AB8500 Fuel Gauge driver");