Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Copyright (C) ST-Ericsson AB 2012
0004  *
0005  * Main and Back-up battery management driver.
0006  *
0007  * Note: Backup battery management is required in case of Li-Ion battery and not
0008  * for capacitive battery. HREF boards have capacitive battery and hence backup
0009  * battery management is not used and the supported code is available in this
0010  * driver.
0011  *
0012  * Author:
0013  *  Johan Palsson <johan.palsson@stericsson.com>
0014  *  Karl Komierowski <karl.komierowski@stericsson.com>
0015  *  Arun R Murthy <arun.murthy@stericsson.com>
0016  */
0017 
0018 #include <linux/init.h>
0019 #include <linux/module.h>
0020 #include <linux/component.h>
0021 #include <linux/device.h>
0022 #include <linux/interrupt.h>
0023 #include <linux/platform_device.h>
0024 #include <linux/power_supply.h>
0025 #include <linux/kobject.h>
0026 #include <linux/slab.h>
0027 #include <linux/delay.h>
0028 #include <linux/time.h>
0029 #include <linux/time64.h>
0030 #include <linux/of.h>
0031 #include <linux/completion.h>
0032 #include <linux/mfd/core.h>
0033 #include <linux/mfd/abx500.h>
0034 #include <linux/mfd/abx500/ab8500.h>
0035 #include <linux/iio/consumer.h>
0036 #include <linux/kernel.h>
0037 #include <linux/fixp-arith.h>
0038 
0039 #include "ab8500-bm.h"
0040 
0041 #define FG_LSB_IN_MA            1627
0042 #define QLSB_NANO_AMP_HOURS_X10     1071
0043 #define INS_CURR_TIMEOUT        (3 * HZ)
0044 
0045 #define SEC_TO_SAMPLE(S)        (S * 4)
0046 
0047 #define NBR_AVG_SAMPLES         20
0048 #define WAIT_FOR_INST_CURRENT_MAX   70
0049 /* Currents higher than -500mA (dissipating) will make compensation unstable */
0050 #define IGNORE_VBAT_HIGHCUR     -500000
0051 
0052 #define LOW_BAT_CHECK_INTERVAL      (HZ / 16) /* 62.5 ms */
0053 
0054 #define VALID_CAPACITY_SEC      (45 * 60) /* 45 minutes */
0055 #define BATT_OK_MIN         2360 /* mV */
0056 #define BATT_OK_INCREMENT       50 /* mV */
0057 #define BATT_OK_MAX_NR_INCREMENTS   0xE
0058 
0059 /* FG constants */
0060 #define BATT_OVV            0x01
0061 
0062 /**
0063  * struct ab8500_fg_interrupts - ab8500 fg interrupts
0064  * @name:   name of the interrupt
0065  * @isr     function pointer to the isr
0066  */
0067 struct ab8500_fg_interrupts {
0068     char *name;
0069     irqreturn_t (*isr)(int irq, void *data);
0070 };
0071 
0072 enum ab8500_fg_discharge_state {
0073     AB8500_FG_DISCHARGE_INIT,
0074     AB8500_FG_DISCHARGE_INITMEASURING,
0075     AB8500_FG_DISCHARGE_INIT_RECOVERY,
0076     AB8500_FG_DISCHARGE_RECOVERY,
0077     AB8500_FG_DISCHARGE_READOUT_INIT,
0078     AB8500_FG_DISCHARGE_READOUT,
0079     AB8500_FG_DISCHARGE_WAKEUP,
0080 };
0081 
0082 static char *discharge_state[] = {
0083     "DISCHARGE_INIT",
0084     "DISCHARGE_INITMEASURING",
0085     "DISCHARGE_INIT_RECOVERY",
0086     "DISCHARGE_RECOVERY",
0087     "DISCHARGE_READOUT_INIT",
0088     "DISCHARGE_READOUT",
0089     "DISCHARGE_WAKEUP",
0090 };
0091 
0092 enum ab8500_fg_charge_state {
0093     AB8500_FG_CHARGE_INIT,
0094     AB8500_FG_CHARGE_READOUT,
0095 };
0096 
0097 static char *charge_state[] = {
0098     "CHARGE_INIT",
0099     "CHARGE_READOUT",
0100 };
0101 
0102 enum ab8500_fg_calibration_state {
0103     AB8500_FG_CALIB_INIT,
0104     AB8500_FG_CALIB_WAIT,
0105     AB8500_FG_CALIB_END,
0106 };
0107 
0108 struct ab8500_fg_avg_cap {
0109     int avg;
0110     int samples[NBR_AVG_SAMPLES];
0111     time64_t time_stamps[NBR_AVG_SAMPLES];
0112     int pos;
0113     int nbr_samples;
0114     int sum;
0115 };
0116 
0117 struct ab8500_fg_cap_scaling {
0118     bool enable;
0119     int cap_to_scale[2];
0120     int disable_cap_level;
0121     int scaled_cap;
0122 };
0123 
0124 struct ab8500_fg_battery_capacity {
0125     int max_mah_design;
0126     int max_mah;
0127     int mah;
0128     int permille;
0129     int level;
0130     int prev_mah;
0131     int prev_percent;
0132     int prev_level;
0133     int user_mah;
0134     struct ab8500_fg_cap_scaling cap_scale;
0135 };
0136 
0137 struct ab8500_fg_flags {
0138     bool fg_enabled;
0139     bool conv_done;
0140     bool charging;
0141     bool fully_charged;
0142     bool force_full;
0143     bool low_bat_delay;
0144     bool low_bat;
0145     bool bat_ovv;
0146     bool batt_unknown;
0147     bool calibrate;
0148     bool user_cap;
0149     bool batt_id_received;
0150 };
0151 
0152 struct inst_curr_result_list {
0153     struct list_head list;
0154     int *result;
0155 };
0156 
0157 /**
0158  * struct ab8500_fg - ab8500 FG device information
0159  * @dev:        Pointer to the structure device
0160  * @node:       a list of AB8500 FGs, hence prepared for reentrance
0161  * @irq         holds the CCEOC interrupt number
0162  * @vbat_uv:        Battery voltage in uV
0163  * @vbat_nom_uv:    Nominal battery voltage in uV
0164  * @inst_curr_ua:   Instantenous battery current in uA
0165  * @avg_curr_ua:    Average battery current in uA
0166  * @bat_temp        battery temperature
0167  * @fg_samples:     Number of samples used in the FG accumulation
0168  * @accu_charge:    Accumulated charge from the last conversion
0169  * @recovery_cnt:   Counter for recovery mode
0170  * @high_curr_cnt:  Counter for high current mode
0171  * @init_cnt:       Counter for init mode
0172  * @low_bat_cnt     Counter for number of consecutive low battery measures
0173  * @nbr_cceoc_irq_cnt   Counter for number of CCEOC irqs received since enabled
0174  * @recovery_needed:    Indicate if recovery is needed
0175  * @high_curr_mode: Indicate if we're in high current mode
0176  * @init_capacity:  Indicate if initial capacity measuring should be done
0177  * @turn_off_fg:    True if fg was off before current measurement
0178  * @calib_state     State during offset calibration
0179  * @discharge_state:    Current discharge state
0180  * @charge_state:   Current charge state
0181  * @ab8500_fg_started   Completion struct used for the instant current start
0182  * @ab8500_fg_complete  Completion struct used for the instant current reading
0183  * @flags:      Structure for information about events triggered
0184  * @bat_cap:        Structure for battery capacity specific parameters
0185  * @avg_cap:        Average capacity filter
0186  * @parent:     Pointer to the struct ab8500
0187  * @main_bat_v:     ADC channel for the main battery voltage
0188  * @bm:             Platform specific battery management information
0189  * @fg_psy:     Structure that holds the FG specific battery properties
0190  * @fg_wq:      Work queue for running the FG algorithm
0191  * @fg_periodic_work:   Work to run the FG algorithm periodically
0192  * @fg_low_bat_work:    Work to check low bat condition
0193  * @fg_reinit_work  Work used to reset and reinitialise the FG algorithm
0194  * @fg_work:        Work to run the FG algorithm instantly
0195  * @fg_acc_cur_work:    Work to read the FG accumulator
0196  * @fg_check_hw_failure_work:   Work for checking HW state
0197  * @cc_lock:        Mutex for locking the CC
0198  * @fg_kobject:     Structure of type kobject
0199  */
0200 struct ab8500_fg {
0201     struct device *dev;
0202     struct list_head node;
0203     int irq;
0204     int vbat_uv;
0205     int vbat_nom_uv;
0206     int inst_curr_ua;
0207     int avg_curr_ua;
0208     int bat_temp;
0209     int fg_samples;
0210     int accu_charge;
0211     int recovery_cnt;
0212     int high_curr_cnt;
0213     int init_cnt;
0214     int low_bat_cnt;
0215     int nbr_cceoc_irq_cnt;
0216     u32 line_impedance_uohm;
0217     bool recovery_needed;
0218     bool high_curr_mode;
0219     bool init_capacity;
0220     bool turn_off_fg;
0221     enum ab8500_fg_calibration_state calib_state;
0222     enum ab8500_fg_discharge_state discharge_state;
0223     enum ab8500_fg_charge_state charge_state;
0224     struct completion ab8500_fg_started;
0225     struct completion ab8500_fg_complete;
0226     struct ab8500_fg_flags flags;
0227     struct ab8500_fg_battery_capacity bat_cap;
0228     struct ab8500_fg_avg_cap avg_cap;
0229     struct ab8500 *parent;
0230     struct iio_channel *main_bat_v;
0231     struct ab8500_bm_data *bm;
0232     struct power_supply *fg_psy;
0233     struct workqueue_struct *fg_wq;
0234     struct delayed_work fg_periodic_work;
0235     struct delayed_work fg_low_bat_work;
0236     struct delayed_work fg_reinit_work;
0237     struct work_struct fg_work;
0238     struct work_struct fg_acc_cur_work;
0239     struct delayed_work fg_check_hw_failure_work;
0240     struct mutex cc_lock;
0241     struct kobject fg_kobject;
0242 };
0243 static LIST_HEAD(ab8500_fg_list);
0244 
0245 /**
0246  * ab8500_fg_get() - returns a reference to the primary AB8500 fuel gauge
0247  * (i.e. the first fuel gauge in the instance list)
0248  */
0249 struct ab8500_fg *ab8500_fg_get(void)
0250 {
0251     return list_first_entry_or_null(&ab8500_fg_list, struct ab8500_fg,
0252                     node);
0253 }
0254 
0255 /* Main battery properties */
0256 static enum power_supply_property ab8500_fg_props[] = {
0257     POWER_SUPPLY_PROP_VOLTAGE_NOW,
0258     POWER_SUPPLY_PROP_CURRENT_NOW,
0259     POWER_SUPPLY_PROP_CURRENT_AVG,
0260     POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
0261     POWER_SUPPLY_PROP_ENERGY_FULL,
0262     POWER_SUPPLY_PROP_ENERGY_NOW,
0263     POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
0264     POWER_SUPPLY_PROP_CHARGE_FULL,
0265     POWER_SUPPLY_PROP_CHARGE_NOW,
0266     POWER_SUPPLY_PROP_CAPACITY,
0267     POWER_SUPPLY_PROP_CAPACITY_LEVEL,
0268 };
0269 
0270 /*
0271  * This array maps the raw hex value to lowbat voltage used by the AB8500
0272  * Values taken from the UM0836, in microvolts.
0273  */
0274 static int ab8500_fg_lowbat_voltage_map[] = {
0275     2300000,
0276     2325000,
0277     2350000,
0278     2375000,
0279     2400000,
0280     2425000,
0281     2450000,
0282     2475000,
0283     2500000,
0284     2525000,
0285     2550000,
0286     2575000,
0287     2600000,
0288     2625000,
0289     2650000,
0290     2675000,
0291     2700000,
0292     2725000,
0293     2750000,
0294     2775000,
0295     2800000,
0296     2825000,
0297     2850000,
0298     2875000,
0299     2900000,
0300     2925000,
0301     2950000,
0302     2975000,
0303     3000000,
0304     3025000,
0305     3050000,
0306     3075000,
0307     3100000,
0308     3125000,
0309     3150000,
0310     3175000,
0311     3200000,
0312     3225000,
0313     3250000,
0314     3275000,
0315     3300000,
0316     3325000,
0317     3350000,
0318     3375000,
0319     3400000,
0320     3425000,
0321     3450000,
0322     3475000,
0323     3500000,
0324     3525000,
0325     3550000,
0326     3575000,
0327     3600000,
0328     3625000,
0329     3650000,
0330     3675000,
0331     3700000,
0332     3725000,
0333     3750000,
0334     3775000,
0335     3800000,
0336     3825000,
0337     3850000,
0338     3850000,
0339 };
0340 
0341 static u8 ab8500_volt_to_regval(int voltage_uv)
0342 {
0343     int i;
0344 
0345     if (voltage_uv < ab8500_fg_lowbat_voltage_map[0])
0346         return 0;
0347 
0348     for (i = 0; i < ARRAY_SIZE(ab8500_fg_lowbat_voltage_map); i++) {
0349         if (voltage_uv < ab8500_fg_lowbat_voltage_map[i])
0350             return (u8) i - 1;
0351     }
0352 
0353     /* If not captured above, return index of last element */
0354     return (u8) ARRAY_SIZE(ab8500_fg_lowbat_voltage_map) - 1;
0355 }
0356 
0357 /**
0358  * ab8500_fg_is_low_curr() - Low or high current mode
0359  * @di:     pointer to the ab8500_fg structure
0360  * @curr_ua:    the current to base or our decision on in microampere
0361  *
0362  * Low current mode if the current consumption is below a certain threshold
0363  */
0364 static int ab8500_fg_is_low_curr(struct ab8500_fg *di, int curr_ua)
0365 {
0366     /*
0367      * We want to know if we're in low current mode
0368      */
0369     if (curr_ua > -di->bm->fg_params->high_curr_threshold_ua)
0370         return true;
0371     else
0372         return false;
0373 }
0374 
0375 /**
0376  * ab8500_fg_add_cap_sample() - Add capacity to average filter
0377  * @di:     pointer to the ab8500_fg structure
0378  * @sample: the capacity in mAh to add to the filter
0379  *
0380  * A capacity is added to the filter and a new mean capacity is calculated and
0381  * returned
0382  */
0383 static int ab8500_fg_add_cap_sample(struct ab8500_fg *di, int sample)
0384 {
0385     time64_t now = ktime_get_boottime_seconds();
0386     struct ab8500_fg_avg_cap *avg = &di->avg_cap;
0387 
0388     do {
0389         avg->sum += sample - avg->samples[avg->pos];
0390         avg->samples[avg->pos] = sample;
0391         avg->time_stamps[avg->pos] = now;
0392         avg->pos++;
0393 
0394         if (avg->pos == NBR_AVG_SAMPLES)
0395             avg->pos = 0;
0396 
0397         if (avg->nbr_samples < NBR_AVG_SAMPLES)
0398             avg->nbr_samples++;
0399 
0400         /*
0401          * Check the time stamp for each sample. If too old,
0402          * replace with latest sample
0403          */
0404     } while (now - VALID_CAPACITY_SEC > avg->time_stamps[avg->pos]);
0405 
0406     avg->avg = avg->sum / avg->nbr_samples;
0407 
0408     return avg->avg;
0409 }
0410 
0411 /**
0412  * ab8500_fg_clear_cap_samples() - Clear average filter
0413  * @di:     pointer to the ab8500_fg structure
0414  *
0415  * The capacity filter is reset to zero.
0416  */
0417 static void ab8500_fg_clear_cap_samples(struct ab8500_fg *di)
0418 {
0419     int i;
0420     struct ab8500_fg_avg_cap *avg = &di->avg_cap;
0421 
0422     avg->pos = 0;
0423     avg->nbr_samples = 0;
0424     avg->sum = 0;
0425     avg->avg = 0;
0426 
0427     for (i = 0; i < NBR_AVG_SAMPLES; i++) {
0428         avg->samples[i] = 0;
0429         avg->time_stamps[i] = 0;
0430     }
0431 }
0432 
0433 /**
0434  * ab8500_fg_fill_cap_sample() - Fill average filter
0435  * @di:     pointer to the ab8500_fg structure
0436  * @sample: the capacity in mAh to fill the filter with
0437  *
0438  * The capacity filter is filled with a capacity in mAh
0439  */
0440 static void ab8500_fg_fill_cap_sample(struct ab8500_fg *di, int sample)
0441 {
0442     int i;
0443     time64_t now;
0444     struct ab8500_fg_avg_cap *avg = &di->avg_cap;
0445 
0446     now = ktime_get_boottime_seconds();
0447 
0448     for (i = 0; i < NBR_AVG_SAMPLES; i++) {
0449         avg->samples[i] = sample;
0450         avg->time_stamps[i] = now;
0451     }
0452 
0453     avg->pos = 0;
0454     avg->nbr_samples = NBR_AVG_SAMPLES;
0455     avg->sum = sample * NBR_AVG_SAMPLES;
0456     avg->avg = sample;
0457 }
0458 
0459 /**
0460  * ab8500_fg_coulomb_counter() - enable coulomb counter
0461  * @di:     pointer to the ab8500_fg structure
0462  * @enable: enable/disable
0463  *
0464  * Enable/Disable coulomb counter.
0465  * On failure returns negative value.
0466  */
0467 static int ab8500_fg_coulomb_counter(struct ab8500_fg *di, bool enable)
0468 {
0469     int ret = 0;
0470     mutex_lock(&di->cc_lock);
0471     if (enable) {
0472         /* To be able to reprogram the number of samples, we have to
0473          * first stop the CC and then enable it again */
0474         ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
0475             AB8500_RTC_CC_CONF_REG, 0x00);
0476         if (ret)
0477             goto cc_err;
0478 
0479         /* Program the samples */
0480         ret = abx500_set_register_interruptible(di->dev,
0481             AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
0482             di->fg_samples);
0483         if (ret)
0484             goto cc_err;
0485 
0486         /* Start the CC */
0487         ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
0488             AB8500_RTC_CC_CONF_REG,
0489             (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
0490         if (ret)
0491             goto cc_err;
0492 
0493         di->flags.fg_enabled = true;
0494     } else {
0495         /* Clear any pending read requests */
0496         ret = abx500_mask_and_set_register_interruptible(di->dev,
0497             AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
0498             (RESET_ACCU | READ_REQ), 0);
0499         if (ret)
0500             goto cc_err;
0501 
0502         ret = abx500_set_register_interruptible(di->dev,
0503             AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU_CTRL, 0);
0504         if (ret)
0505             goto cc_err;
0506 
0507         /* Stop the CC */
0508         ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
0509             AB8500_RTC_CC_CONF_REG, 0);
0510         if (ret)
0511             goto cc_err;
0512 
0513         di->flags.fg_enabled = false;
0514 
0515     }
0516     dev_dbg(di->dev, " CC enabled: %d Samples: %d\n",
0517         enable, di->fg_samples);
0518 
0519     mutex_unlock(&di->cc_lock);
0520 
0521     return ret;
0522 cc_err:
0523     dev_err(di->dev, "%s Enabling coulomb counter failed\n", __func__);
0524     mutex_unlock(&di->cc_lock);
0525     return ret;
0526 }
0527 
0528 /**
0529  * ab8500_fg_inst_curr_start() - start battery instantaneous current
0530  * @di:         pointer to the ab8500_fg structure
0531  *
0532  * Returns 0 or error code
0533  * Note: This is part "one" and has to be called before
0534  * ab8500_fg_inst_curr_finalize()
0535  */
0536 int ab8500_fg_inst_curr_start(struct ab8500_fg *di)
0537 {
0538     u8 reg_val;
0539     int ret;
0540 
0541     mutex_lock(&di->cc_lock);
0542 
0543     di->nbr_cceoc_irq_cnt = 0;
0544     ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
0545         AB8500_RTC_CC_CONF_REG, &reg_val);
0546     if (ret < 0)
0547         goto fail;
0548 
0549     if (!(reg_val & CC_PWR_UP_ENA)) {
0550         dev_dbg(di->dev, "%s Enable FG\n", __func__);
0551         di->turn_off_fg = true;
0552 
0553         /* Program the samples */
0554         ret = abx500_set_register_interruptible(di->dev,
0555             AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
0556             SEC_TO_SAMPLE(10));
0557         if (ret)
0558             goto fail;
0559 
0560         /* Start the CC */
0561         ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
0562             AB8500_RTC_CC_CONF_REG,
0563             (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
0564         if (ret)
0565             goto fail;
0566     } else {
0567         di->turn_off_fg = false;
0568     }
0569 
0570     /* Return and WFI */
0571     reinit_completion(&di->ab8500_fg_started);
0572     reinit_completion(&di->ab8500_fg_complete);
0573     enable_irq(di->irq);
0574 
0575     /* Note: cc_lock is still locked */
0576     return 0;
0577 fail:
0578     mutex_unlock(&di->cc_lock);
0579     return ret;
0580 }
0581 
0582 /**
0583  * ab8500_fg_inst_curr_started() - check if fg conversion has started
0584  * @di:         pointer to the ab8500_fg structure
0585  *
0586  * Returns 1 if conversion started, 0 if still waiting
0587  */
0588 int ab8500_fg_inst_curr_started(struct ab8500_fg *di)
0589 {
0590     return completion_done(&di->ab8500_fg_started);
0591 }
0592 
0593 /**
0594  * ab8500_fg_inst_curr_done() - check if fg conversion is done
0595  * @di:         pointer to the ab8500_fg structure
0596  *
0597  * Returns 1 if conversion done, 0 if still waiting
0598  */
0599 int ab8500_fg_inst_curr_done(struct ab8500_fg *di)
0600 {
0601     return completion_done(&di->ab8500_fg_complete);
0602 }
0603 
0604 /**
0605  * ab8500_fg_inst_curr_finalize() - battery instantaneous current
0606  * @di:         pointer to the ab8500_fg structure
0607  * @curr_ua:    battery instantenous current in microampere (on success)
0608  *
0609  * Returns 0 or an error code
0610  * Note: This is part "two" and has to be called at earliest 250 ms
0611  * after ab8500_fg_inst_curr_start()
0612  */
0613 int ab8500_fg_inst_curr_finalize(struct ab8500_fg *di, int *curr_ua)
0614 {
0615     u8 low, high;
0616     int val;
0617     int ret;
0618     unsigned long timeout;
0619 
0620     if (!completion_done(&di->ab8500_fg_complete)) {
0621         timeout = wait_for_completion_timeout(
0622             &di->ab8500_fg_complete,
0623             INS_CURR_TIMEOUT);
0624         dev_dbg(di->dev, "Finalize time: %d ms\n",
0625             jiffies_to_msecs(INS_CURR_TIMEOUT - timeout));
0626         if (!timeout) {
0627             ret = -ETIME;
0628             disable_irq(di->irq);
0629             di->nbr_cceoc_irq_cnt = 0;
0630             dev_err(di->dev, "completion timed out [%d]\n",
0631                 __LINE__);
0632             goto fail;
0633         }
0634     }
0635 
0636     disable_irq(di->irq);
0637     di->nbr_cceoc_irq_cnt = 0;
0638 
0639     ret = abx500_mask_and_set_register_interruptible(di->dev,
0640             AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
0641             READ_REQ, READ_REQ);
0642 
0643     /* 100uS between read request and read is needed */
0644     usleep_range(100, 100);
0645 
0646     /* Read CC Sample conversion value Low and high */
0647     ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
0648         AB8500_GASG_CC_SMPL_CNVL_REG,  &low);
0649     if (ret < 0)
0650         goto fail;
0651 
0652     ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
0653         AB8500_GASG_CC_SMPL_CNVH_REG,  &high);
0654     if (ret < 0)
0655         goto fail;
0656 
0657     /*
0658      * negative value for Discharging
0659      * convert 2's complement into decimal
0660      */
0661     if (high & 0x10)
0662         val = (low | (high << 8) | 0xFFFFE000);
0663     else
0664         val = (low | (high << 8));
0665 
0666     /*
0667      * Convert to unit value in mA
0668      * Full scale input voltage is
0669      * 63.160mV => LSB = 63.160mV/(4096*res) = 1.542.000 uA
0670      * Given a 250ms conversion cycle time the LSB corresponds
0671      * to 107.1 nAh. Convert to current by dividing by the conversion
0672      * time in hours (250ms = 1 / (3600 * 4)h)
0673      * 107.1nAh assumes 10mOhm, but fg_res is in 0.1mOhm
0674      */
0675     val = (val * QLSB_NANO_AMP_HOURS_X10 * 36 * 4) / di->bm->fg_res;
0676 
0677     if (di->turn_off_fg) {
0678         dev_dbg(di->dev, "%s Disable FG\n", __func__);
0679 
0680         /* Clear any pending read requests */
0681         ret = abx500_set_register_interruptible(di->dev,
0682             AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG, 0);
0683         if (ret)
0684             goto fail;
0685 
0686         /* Stop the CC */
0687         ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
0688             AB8500_RTC_CC_CONF_REG, 0);
0689         if (ret)
0690             goto fail;
0691     }
0692     mutex_unlock(&di->cc_lock);
0693     *curr_ua = val;
0694 
0695     return 0;
0696 fail:
0697     mutex_unlock(&di->cc_lock);
0698     return ret;
0699 }
0700 
0701 /**
0702  * ab8500_fg_inst_curr_blocking() - battery instantaneous current
0703  * @di:         pointer to the ab8500_fg structure
0704  *
0705  * Returns battery instantenous current in microampere (on success)
0706  * else error code
0707  */
0708 int ab8500_fg_inst_curr_blocking(struct ab8500_fg *di)
0709 {
0710     int ret;
0711     unsigned long timeout;
0712     int curr_ua = 0;
0713 
0714     ret = ab8500_fg_inst_curr_start(di);
0715     if (ret) {
0716         dev_err(di->dev, "Failed to initialize fg_inst\n");
0717         return 0;
0718     }
0719 
0720     /* Wait for CC to actually start */
0721     if (!completion_done(&di->ab8500_fg_started)) {
0722         timeout = wait_for_completion_timeout(
0723             &di->ab8500_fg_started,
0724             INS_CURR_TIMEOUT);
0725         dev_dbg(di->dev, "Start time: %d ms\n",
0726             jiffies_to_msecs(INS_CURR_TIMEOUT - timeout));
0727         if (!timeout) {
0728             ret = -ETIME;
0729             dev_err(di->dev, "completion timed out [%d]\n",
0730                 __LINE__);
0731             goto fail;
0732         }
0733     }
0734 
0735     ret = ab8500_fg_inst_curr_finalize(di, &curr_ua);
0736     if (ret) {
0737         dev_err(di->dev, "Failed to finalize fg_inst\n");
0738         return 0;
0739     }
0740 
0741     dev_dbg(di->dev, "%s instant current: %d uA", __func__, curr_ua);
0742     return curr_ua;
0743 fail:
0744     disable_irq(di->irq);
0745     mutex_unlock(&di->cc_lock);
0746     return ret;
0747 }
0748 
0749 /**
0750  * ab8500_fg_acc_cur_work() - average battery current
0751  * @work:   pointer to the work_struct structure
0752  *
0753  * Updated the average battery current obtained from the
0754  * coulomb counter.
0755  */
0756 static void ab8500_fg_acc_cur_work(struct work_struct *work)
0757 {
0758     int val;
0759     int ret;
0760     u8 low, med, high;
0761 
0762     struct ab8500_fg *di = container_of(work,
0763         struct ab8500_fg, fg_acc_cur_work);
0764 
0765     mutex_lock(&di->cc_lock);
0766     ret = abx500_set_register_interruptible(di->dev, AB8500_GAS_GAUGE,
0767         AB8500_GASG_CC_NCOV_ACCU_CTRL, RD_NCONV_ACCU_REQ);
0768     if (ret)
0769         goto exit;
0770 
0771     ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
0772         AB8500_GASG_CC_NCOV_ACCU_LOW,  &low);
0773     if (ret < 0)
0774         goto exit;
0775 
0776     ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
0777         AB8500_GASG_CC_NCOV_ACCU_MED,  &med);
0778     if (ret < 0)
0779         goto exit;
0780 
0781     ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
0782         AB8500_GASG_CC_NCOV_ACCU_HIGH, &high);
0783     if (ret < 0)
0784         goto exit;
0785 
0786     /* Check for sign bit in case of negative value, 2's complement */
0787     if (high & 0x10)
0788         val = (low | (med << 8) | (high << 16) | 0xFFE00000);
0789     else
0790         val = (low | (med << 8) | (high << 16));
0791 
0792     /*
0793      * Convert to uAh
0794      * Given a 250ms conversion cycle time the LSB corresponds
0795      * to 112.9 nAh.
0796      * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
0797      */
0798     di->accu_charge = (val * QLSB_NANO_AMP_HOURS_X10) /
0799         (100 * di->bm->fg_res);
0800 
0801     /*
0802      * Convert to unit value in uA
0803      * by dividing by the conversion
0804      * time in hours (= samples / (3600 * 4)h)
0805      */
0806     di->avg_curr_ua = (val * QLSB_NANO_AMP_HOURS_X10 * 36) /
0807         (di->bm->fg_res * (di->fg_samples / 4));
0808 
0809     di->flags.conv_done = true;
0810 
0811     mutex_unlock(&di->cc_lock);
0812 
0813     queue_work(di->fg_wq, &di->fg_work);
0814 
0815     dev_dbg(di->dev, "fg_res: %d, fg_samples: %d, gasg: %d, accu_charge: %d \n",
0816                 di->bm->fg_res, di->fg_samples, val, di->accu_charge);
0817     return;
0818 exit:
0819     dev_err(di->dev,
0820         "Failed to read or write gas gauge registers\n");
0821     mutex_unlock(&di->cc_lock);
0822     queue_work(di->fg_wq, &di->fg_work);
0823 }
0824 
0825 /**
0826  * ab8500_fg_bat_voltage() - get battery voltage
0827  * @di:     pointer to the ab8500_fg structure
0828  *
0829  * Returns battery voltage in microvolts (on success) else error code
0830  */
0831 static int ab8500_fg_bat_voltage(struct ab8500_fg *di)
0832 {
0833     int vbat, ret;
0834     static int prev;
0835 
0836     ret = iio_read_channel_processed(di->main_bat_v, &vbat);
0837     if (ret < 0) {
0838         dev_err(di->dev,
0839             "%s ADC conversion failed, using previous value\n",
0840             __func__);
0841         return prev;
0842     }
0843 
0844     /* IIO returns millivolts but we want microvolts */
0845     vbat *= 1000;
0846     prev = vbat;
0847     return vbat;
0848 }
0849 
0850 /**
0851  * ab8500_fg_volt_to_capacity() - Voltage based capacity
0852  * @di:     pointer to the ab8500_fg structure
0853  * @voltage_uv: The voltage to convert to a capacity in microvolt
0854  *
0855  * Returns battery capacity in per mille based on voltage
0856  */
0857 static int ab8500_fg_volt_to_capacity(struct ab8500_fg *di, int voltage_uv)
0858 {
0859     struct power_supply_battery_info *bi = di->bm->bi;
0860 
0861     /* Multiply by 10 because the capacity is tracked in per mille */
0862     return power_supply_batinfo_ocv2cap(bi, voltage_uv, di->bat_temp) *  10;
0863 }
0864 
0865 /**
0866  * ab8500_fg_uncomp_volt_to_capacity() - Uncompensated voltage based capacity
0867  * @di:     pointer to the ab8500_fg structure
0868  *
0869  * Returns battery capacity based on battery voltage that is not compensated
0870  * for the voltage drop due to the load
0871  */
0872 static int ab8500_fg_uncomp_volt_to_capacity(struct ab8500_fg *di)
0873 {
0874     di->vbat_uv = ab8500_fg_bat_voltage(di);
0875     return ab8500_fg_volt_to_capacity(di, di->vbat_uv);
0876 }
0877 
0878 /**
0879  * ab8500_fg_battery_resistance() - Returns the battery inner resistance
0880  * @di:     pointer to the ab8500_fg structure
0881  * @vbat_uncomp_uv: Uncompensated VBAT voltage
0882  *
0883  * Returns battery inner resistance added with the fuel gauge resistor value
0884  * to get the total resistance in the whole link from gnd to bat+ node
0885  * in milliohm.
0886  */
0887 static int ab8500_fg_battery_resistance(struct ab8500_fg *di, int vbat_uncomp_uv)
0888 {
0889     struct power_supply_battery_info *bi = di->bm->bi;
0890     int resistance_percent = 0;
0891     int resistance;
0892 
0893     /*
0894      * Determine the resistance at this voltage. First try VBAT-to-Ri else
0895      * just infer it from the surrounding temperature, if nothing works just
0896      * use the internal resistance.
0897      */
0898     if (power_supply_supports_vbat2ri(bi)) {
0899         resistance = power_supply_vbat2ri(bi, vbat_uncomp_uv, di->flags.charging);
0900         /* Convert to milliohm */
0901         resistance = resistance / 1000;
0902     } else if (power_supply_supports_temp2ri(bi)) {
0903         resistance_percent = power_supply_temp2resist_simple(bi->resist_table,
0904                                      bi->resist_table_size,
0905                                      di->bat_temp / 10);
0906         /* Convert to milliohm */
0907         resistance = bi->factory_internal_resistance_uohm / 1000;
0908         resistance = resistance * resistance_percent / 100;
0909     } else {
0910         /* Last fallback */
0911         resistance = bi->factory_internal_resistance_uohm / 1000;
0912     }
0913 
0914     /* Compensate for line impedance */
0915     resistance += (di->line_impedance_uohm / 1000);
0916 
0917     dev_dbg(di->dev, "%s Temp: %d battery internal resistance: %d"
0918         " fg resistance %d, total: %d (mOhm)\n",
0919         __func__, di->bat_temp, resistance, di->bm->fg_res / 10,
0920         (di->bm->fg_res / 10) + resistance);
0921 
0922     /* fg_res variable is in 0.1mOhm */
0923     resistance += di->bm->fg_res / 10;
0924 
0925     return resistance;
0926 }
0927 
0928 /**
0929  * ab8500_load_comp_fg_bat_voltage() - get load compensated battery voltage
0930  * @di:     pointer to the ab8500_fg structure
0931  * @always: always return a voltage, also uncompensated
0932  *
0933  * Returns compensated battery voltage (on success) else error code.
0934  * If always is specified, we always return a voltage but it may be
0935  * uncompensated.
0936  */
0937 static int ab8500_load_comp_fg_bat_voltage(struct ab8500_fg *di, bool always)
0938 {
0939     int i = 0;
0940     int vbat_uv = 0;
0941     int rcomp;
0942 
0943     /* Average the instant current to get a stable current measurement */
0944     ab8500_fg_inst_curr_start(di);
0945 
0946     do {
0947         vbat_uv += ab8500_fg_bat_voltage(di);
0948         i++;
0949         usleep_range(5000, 6000);
0950     } while (!ab8500_fg_inst_curr_done(di) &&
0951          i <= WAIT_FOR_INST_CURRENT_MAX);
0952 
0953     if (i > WAIT_FOR_INST_CURRENT_MAX) {
0954         dev_err(di->dev,
0955             "TIMEOUT: return uncompensated measurement of VBAT\n");
0956         di->vbat_uv = vbat_uv / i;
0957         return di->vbat_uv;
0958     }
0959 
0960     ab8500_fg_inst_curr_finalize(di, &di->inst_curr_ua);
0961 
0962     /*
0963      * If there is too high current dissipation, the compensation cannot be
0964      * trusted so return an error unless we must return something here, as
0965      * enforced by the "always" parameter.
0966      */
0967     if (!always && di->inst_curr_ua < IGNORE_VBAT_HIGHCUR)
0968         return -EINVAL;
0969 
0970     vbat_uv = vbat_uv / i;
0971 
0972     /* Next we apply voltage compensation from internal resistance */
0973     rcomp = ab8500_fg_battery_resistance(di, vbat_uv);
0974     vbat_uv = vbat_uv - (di->inst_curr_ua * rcomp) / 1000;
0975 
0976     /* Always keep this state at latest measurement */
0977     di->vbat_uv = vbat_uv;
0978 
0979     return vbat_uv;
0980 }
0981 
0982 /**
0983  * ab8500_fg_load_comp_volt_to_capacity() - Load compensated voltage based capacity
0984  * @di:     pointer to the ab8500_fg structure
0985  *
0986  * Returns battery capacity based on battery voltage that is load compensated
0987  * for the voltage drop
0988  */
0989 static int ab8500_fg_load_comp_volt_to_capacity(struct ab8500_fg *di)
0990 {
0991     int vbat_comp_uv;
0992 
0993     vbat_comp_uv = ab8500_load_comp_fg_bat_voltage(di, true);
0994 
0995     return ab8500_fg_volt_to_capacity(di, vbat_comp_uv);
0996 }
0997 
0998 /**
0999  * ab8500_fg_convert_mah_to_permille() - Capacity in mAh to permille
1000  * @di:     pointer to the ab8500_fg structure
1001  * @cap_mah:    capacity in mAh
1002  *
1003  * Converts capacity in mAh to capacity in permille
1004  */
1005 static int ab8500_fg_convert_mah_to_permille(struct ab8500_fg *di, int cap_mah)
1006 {
1007     return (cap_mah * 1000) / di->bat_cap.max_mah_design;
1008 }
1009 
1010 /**
1011  * ab8500_fg_convert_permille_to_mah() - Capacity in permille to mAh
1012  * @di:     pointer to the ab8500_fg structure
1013  * @cap_pm: capacity in permille
1014  *
1015  * Converts capacity in permille to capacity in mAh
1016  */
1017 static int ab8500_fg_convert_permille_to_mah(struct ab8500_fg *di, int cap_pm)
1018 {
1019     return cap_pm * di->bat_cap.max_mah_design / 1000;
1020 }
1021 
1022 /**
1023  * ab8500_fg_convert_mah_to_uwh() - Capacity in mAh to uWh
1024  * @di:     pointer to the ab8500_fg structure
1025  * @cap_mah:    capacity in mAh
1026  *
1027  * Converts capacity in mAh to capacity in uWh
1028  */
1029 static int ab8500_fg_convert_mah_to_uwh(struct ab8500_fg *di, int cap_mah)
1030 {
1031     u64 div_res;
1032     u32 div_rem;
1033 
1034     /*
1035      * Capacity is in milli ampere hours (10^-3)Ah
1036      * Nominal voltage is in microvolts (10^-6)V
1037      * divide by 1000000 after multiplication to get to mWh
1038      */
1039     div_res = ((u64) cap_mah) * ((u64) di->vbat_nom_uv);
1040     div_rem = do_div(div_res, 1000000);
1041 
1042     /* Make sure to round upwards if necessary */
1043     if (div_rem >= 1000000 / 2)
1044         div_res++;
1045 
1046     return (int) div_res;
1047 }
1048 
1049 /**
1050  * ab8500_fg_calc_cap_charging() - Calculate remaining capacity while charging
1051  * @di:     pointer to the ab8500_fg structure
1052  *
1053  * Return the capacity in mAh based on previous calculated capcity and the FG
1054  * accumulator register value. The filter is filled with this capacity
1055  */
1056 static int ab8500_fg_calc_cap_charging(struct ab8500_fg *di)
1057 {
1058     dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1059         __func__,
1060         di->bat_cap.mah,
1061         di->accu_charge);
1062 
1063     /* Capacity should not be less than 0 */
1064     if (di->bat_cap.mah + di->accu_charge > 0)
1065         di->bat_cap.mah += di->accu_charge;
1066     else
1067         di->bat_cap.mah = 0;
1068     /*
1069      * We force capacity to 100% once when the algorithm
1070      * reports that it's full.
1071      */
1072     if (di->bat_cap.mah >= di->bat_cap.max_mah_design ||
1073         di->flags.force_full) {
1074         di->bat_cap.mah = di->bat_cap.max_mah_design;
1075     }
1076 
1077     ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1078     di->bat_cap.permille =
1079         ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1080 
1081     /* We need to update battery voltage and inst current when charging */
1082     di->vbat_uv = ab8500_fg_bat_voltage(di);
1083     di->inst_curr_ua = ab8500_fg_inst_curr_blocking(di);
1084 
1085     return di->bat_cap.mah;
1086 }
1087 
1088 /**
1089  * ab8500_fg_calc_cap_discharge_voltage() - Capacity in discharge with voltage
1090  * @di:     pointer to the ab8500_fg structure
1091  *
1092  * Return the capacity in mAh based on the load compensated battery voltage.
1093  * This value is added to the filter and a new mean value is calculated and
1094  * returned.
1095  */
1096 static int ab8500_fg_calc_cap_discharge_voltage(struct ab8500_fg *di)
1097 {
1098     int permille, mah;
1099 
1100     permille = ab8500_fg_load_comp_volt_to_capacity(di);
1101 
1102     mah = ab8500_fg_convert_permille_to_mah(di, permille);
1103 
1104     di->bat_cap.mah = ab8500_fg_add_cap_sample(di, mah);
1105     di->bat_cap.permille =
1106         ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1107 
1108     return di->bat_cap.mah;
1109 }
1110 
1111 /**
1112  * ab8500_fg_calc_cap_discharge_fg() - Capacity in discharge with FG
1113  * @di:     pointer to the ab8500_fg structure
1114  *
1115  * Return the capacity in mAh based on previous calculated capcity and the FG
1116  * accumulator register value. This value is added to the filter and a
1117  * new mean value is calculated and returned.
1118  */
1119 static int ab8500_fg_calc_cap_discharge_fg(struct ab8500_fg *di)
1120 {
1121     int permille_volt, permille;
1122 
1123     dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1124         __func__,
1125         di->bat_cap.mah,
1126         di->accu_charge);
1127 
1128     /* Capacity should not be less than 0 */
1129     if (di->bat_cap.mah + di->accu_charge > 0)
1130         di->bat_cap.mah += di->accu_charge;
1131     else
1132         di->bat_cap.mah = 0;
1133 
1134     if (di->bat_cap.mah >= di->bat_cap.max_mah_design)
1135         di->bat_cap.mah = di->bat_cap.max_mah_design;
1136 
1137     /*
1138      * Check against voltage based capacity. It can not be lower
1139      * than what the uncompensated voltage says
1140      */
1141     permille = ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1142     permille_volt = ab8500_fg_uncomp_volt_to_capacity(di);
1143 
1144     if (permille < permille_volt) {
1145         di->bat_cap.permille = permille_volt;
1146         di->bat_cap.mah = ab8500_fg_convert_permille_to_mah(di,
1147             di->bat_cap.permille);
1148 
1149         dev_dbg(di->dev, "%s voltage based: perm %d perm_volt %d\n",
1150             __func__,
1151             permille,
1152             permille_volt);
1153 
1154         ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1155     } else {
1156         ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1157         di->bat_cap.permille =
1158             ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1159     }
1160 
1161     return di->bat_cap.mah;
1162 }
1163 
1164 /**
1165  * ab8500_fg_capacity_level() - Get the battery capacity level
1166  * @di:     pointer to the ab8500_fg structure
1167  *
1168  * Get the battery capacity level based on the capacity in percent
1169  */
1170 static int ab8500_fg_capacity_level(struct ab8500_fg *di)
1171 {
1172     int ret, percent;
1173 
1174     percent = DIV_ROUND_CLOSEST(di->bat_cap.permille, 10);
1175 
1176     if (percent <= di->bm->cap_levels->critical ||
1177         di->flags.low_bat)
1178         ret = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1179     else if (percent <= di->bm->cap_levels->low)
1180         ret = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1181     else if (percent <= di->bm->cap_levels->normal)
1182         ret = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1183     else if (percent <= di->bm->cap_levels->high)
1184         ret = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
1185     else
1186         ret = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1187 
1188     return ret;
1189 }
1190 
1191 /**
1192  * ab8500_fg_calculate_scaled_capacity() - Capacity scaling
1193  * @di:     pointer to the ab8500_fg structure
1194  *
1195  * Calculates the capacity to be shown to upper layers. Scales the capacity
1196  * to have 100% as a reference from the actual capacity upon removal of charger
1197  * when charging is in maintenance mode.
1198  */
1199 static int ab8500_fg_calculate_scaled_capacity(struct ab8500_fg *di)
1200 {
1201     struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1202     int capacity = di->bat_cap.prev_percent;
1203 
1204     if (!cs->enable)
1205         return capacity;
1206 
1207     /*
1208      * As long as we are in fully charge mode scale the capacity
1209      * to show 100%.
1210      */
1211     if (di->flags.fully_charged) {
1212         cs->cap_to_scale[0] = 100;
1213         cs->cap_to_scale[1] =
1214             max(capacity, di->bm->fg_params->maint_thres);
1215         dev_dbg(di->dev, "Scale cap with %d/%d\n",
1216              cs->cap_to_scale[0], cs->cap_to_scale[1]);
1217     }
1218 
1219     /* Calculates the scaled capacity. */
1220     if ((cs->cap_to_scale[0] != cs->cap_to_scale[1])
1221                     && (cs->cap_to_scale[1] > 0))
1222         capacity = min(100,
1223                  DIV_ROUND_CLOSEST(di->bat_cap.prev_percent *
1224                          cs->cap_to_scale[0],
1225                          cs->cap_to_scale[1]));
1226 
1227     if (di->flags.charging) {
1228         if (capacity < cs->disable_cap_level) {
1229             cs->disable_cap_level = capacity;
1230             dev_dbg(di->dev, "Cap to stop scale lowered %d%%\n",
1231                 cs->disable_cap_level);
1232         } else if (!di->flags.fully_charged) {
1233             if (di->bat_cap.prev_percent >=
1234                 cs->disable_cap_level) {
1235                 dev_dbg(di->dev, "Disabling scaled capacity\n");
1236                 cs->enable = false;
1237                 capacity = di->bat_cap.prev_percent;
1238             } else {
1239                 dev_dbg(di->dev,
1240                     "Waiting in cap to level %d%%\n",
1241                     cs->disable_cap_level);
1242                 capacity = cs->disable_cap_level;
1243             }
1244         }
1245     }
1246 
1247     return capacity;
1248 }
1249 
1250 /**
1251  * ab8500_fg_update_cap_scalers() - Capacity scaling
1252  * @di:     pointer to the ab8500_fg structure
1253  *
1254  * To be called when state change from charge<->discharge to update
1255  * the capacity scalers.
1256  */
1257 static void ab8500_fg_update_cap_scalers(struct ab8500_fg *di)
1258 {
1259     struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1260 
1261     if (!cs->enable)
1262         return;
1263     if (di->flags.charging) {
1264         di->bat_cap.cap_scale.disable_cap_level =
1265             di->bat_cap.cap_scale.scaled_cap;
1266         dev_dbg(di->dev, "Cap to stop scale at charge %d%%\n",
1267                 di->bat_cap.cap_scale.disable_cap_level);
1268     } else {
1269         if (cs->scaled_cap != 100) {
1270             cs->cap_to_scale[0] = cs->scaled_cap;
1271             cs->cap_to_scale[1] = di->bat_cap.prev_percent;
1272         } else {
1273             cs->cap_to_scale[0] = 100;
1274             cs->cap_to_scale[1] =
1275                 max(di->bat_cap.prev_percent,
1276                     di->bm->fg_params->maint_thres);
1277         }
1278 
1279         dev_dbg(di->dev, "Cap to scale at discharge %d/%d\n",
1280                 cs->cap_to_scale[0], cs->cap_to_scale[1]);
1281     }
1282 }
1283 
1284 /**
1285  * ab8500_fg_check_capacity_limits() - Check if capacity has changed
1286  * @di:     pointer to the ab8500_fg structure
1287  * @init:   capacity is allowed to go up in init mode
1288  *
1289  * Check if capacity or capacity limit has changed and notify the system
1290  * about it using the power_supply framework
1291  */
1292 static void ab8500_fg_check_capacity_limits(struct ab8500_fg *di, bool init)
1293 {
1294     bool changed = false;
1295     int percent = DIV_ROUND_CLOSEST(di->bat_cap.permille, 10);
1296 
1297     di->bat_cap.level = ab8500_fg_capacity_level(di);
1298 
1299     if (di->bat_cap.level != di->bat_cap.prev_level) {
1300         /*
1301          * We do not allow reported capacity level to go up
1302          * unless we're charging or if we're in init
1303          */
1304         if (!(!di->flags.charging && di->bat_cap.level >
1305             di->bat_cap.prev_level) || init) {
1306             dev_dbg(di->dev, "level changed from %d to %d\n",
1307                 di->bat_cap.prev_level,
1308                 di->bat_cap.level);
1309             di->bat_cap.prev_level = di->bat_cap.level;
1310             changed = true;
1311         } else {
1312             dev_dbg(di->dev, "level not allowed to go up "
1313                 "since no charger is connected: %d to %d\n",
1314                 di->bat_cap.prev_level,
1315                 di->bat_cap.level);
1316         }
1317     }
1318 
1319     /*
1320      * If we have received the LOW_BAT IRQ, set capacity to 0 to initiate
1321      * shutdown
1322      */
1323     if (di->flags.low_bat) {
1324         dev_dbg(di->dev, "Battery low, set capacity to 0\n");
1325         di->bat_cap.prev_percent = 0;
1326         di->bat_cap.permille = 0;
1327         percent = 0;
1328         di->bat_cap.prev_mah = 0;
1329         di->bat_cap.mah = 0;
1330         changed = true;
1331     } else if (di->flags.fully_charged) {
1332         /*
1333          * We report 100% if algorithm reported fully charged
1334          * and show 100% during maintenance charging (scaling).
1335          */
1336         if (di->flags.force_full) {
1337             di->bat_cap.prev_percent = percent;
1338             di->bat_cap.prev_mah = di->bat_cap.mah;
1339 
1340             changed = true;
1341 
1342             if (!di->bat_cap.cap_scale.enable &&
1343                         di->bm->capacity_scaling) {
1344                 di->bat_cap.cap_scale.enable = true;
1345                 di->bat_cap.cap_scale.cap_to_scale[0] = 100;
1346                 di->bat_cap.cap_scale.cap_to_scale[1] =
1347                         di->bat_cap.prev_percent;
1348                 di->bat_cap.cap_scale.disable_cap_level = 100;
1349             }
1350         } else if (di->bat_cap.prev_percent != percent) {
1351             dev_dbg(di->dev,
1352                 "battery reported full "
1353                 "but capacity dropping: %d\n",
1354                 percent);
1355             di->bat_cap.prev_percent = percent;
1356             di->bat_cap.prev_mah = di->bat_cap.mah;
1357 
1358             changed = true;
1359         }
1360     } else if (di->bat_cap.prev_percent != percent) {
1361         if (percent == 0) {
1362             /*
1363              * We will not report 0% unless we've got
1364              * the LOW_BAT IRQ, no matter what the FG
1365              * algorithm says.
1366              */
1367             di->bat_cap.prev_percent = 1;
1368             percent = 1;
1369 
1370             changed = true;
1371         } else if (!(!di->flags.charging &&
1372             percent > di->bat_cap.prev_percent) || init) {
1373             /*
1374              * We do not allow reported capacity to go up
1375              * unless we're charging or if we're in init
1376              */
1377             dev_dbg(di->dev,
1378                 "capacity changed from %d to %d (%d)\n",
1379                 di->bat_cap.prev_percent,
1380                 percent,
1381                 di->bat_cap.permille);
1382             di->bat_cap.prev_percent = percent;
1383             di->bat_cap.prev_mah = di->bat_cap.mah;
1384 
1385             changed = true;
1386         } else {
1387             dev_dbg(di->dev, "capacity not allowed to go up since "
1388                 "no charger is connected: %d to %d (%d)\n",
1389                 di->bat_cap.prev_percent,
1390                 percent,
1391                 di->bat_cap.permille);
1392         }
1393     }
1394 
1395     if (changed) {
1396         if (di->bm->capacity_scaling) {
1397             di->bat_cap.cap_scale.scaled_cap =
1398                 ab8500_fg_calculate_scaled_capacity(di);
1399 
1400             dev_info(di->dev, "capacity=%d (%d)\n",
1401                 di->bat_cap.prev_percent,
1402                 di->bat_cap.cap_scale.scaled_cap);
1403         }
1404         power_supply_changed(di->fg_psy);
1405         if (di->flags.fully_charged && di->flags.force_full) {
1406             dev_dbg(di->dev, "Battery full, notifying.\n");
1407             di->flags.force_full = false;
1408             sysfs_notify(&di->fg_kobject, NULL, "charge_full");
1409         }
1410         sysfs_notify(&di->fg_kobject, NULL, "charge_now");
1411     }
1412 }
1413 
1414 static void ab8500_fg_charge_state_to(struct ab8500_fg *di,
1415     enum ab8500_fg_charge_state new_state)
1416 {
1417     dev_dbg(di->dev, "Charge state from %d [%s] to %d [%s]\n",
1418         di->charge_state,
1419         charge_state[di->charge_state],
1420         new_state,
1421         charge_state[new_state]);
1422 
1423     di->charge_state = new_state;
1424 }
1425 
1426 static void ab8500_fg_discharge_state_to(struct ab8500_fg *di,
1427     enum ab8500_fg_discharge_state new_state)
1428 {
1429     dev_dbg(di->dev, "Discharge state from %d [%s] to %d [%s]\n",
1430         di->discharge_state,
1431         discharge_state[di->discharge_state],
1432         new_state,
1433         discharge_state[new_state]);
1434 
1435     di->discharge_state = new_state;
1436 }
1437 
1438 /**
1439  * ab8500_fg_algorithm_charging() - FG algorithm for when charging
1440  * @di:     pointer to the ab8500_fg structure
1441  *
1442  * Battery capacity calculation state machine for when we're charging
1443  */
1444 static void ab8500_fg_algorithm_charging(struct ab8500_fg *di)
1445 {
1446     /*
1447      * If we change to discharge mode
1448      * we should start with recovery
1449      */
1450     if (di->discharge_state != AB8500_FG_DISCHARGE_INIT_RECOVERY)
1451         ab8500_fg_discharge_state_to(di,
1452             AB8500_FG_DISCHARGE_INIT_RECOVERY);
1453 
1454     switch (di->charge_state) {
1455     case AB8500_FG_CHARGE_INIT:
1456         di->fg_samples = SEC_TO_SAMPLE(
1457             di->bm->fg_params->accu_charging);
1458 
1459         ab8500_fg_coulomb_counter(di, true);
1460         ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_READOUT);
1461 
1462         break;
1463 
1464     case AB8500_FG_CHARGE_READOUT:
1465         /*
1466          * Read the FG and calculate the new capacity
1467          */
1468         mutex_lock(&di->cc_lock);
1469         if (!di->flags.conv_done && !di->flags.force_full) {
1470             /* Wasn't the CC IRQ that got us here */
1471             mutex_unlock(&di->cc_lock);
1472             dev_dbg(di->dev, "%s CC conv not done\n",
1473                 __func__);
1474 
1475             break;
1476         }
1477         di->flags.conv_done = false;
1478         mutex_unlock(&di->cc_lock);
1479 
1480         ab8500_fg_calc_cap_charging(di);
1481 
1482         break;
1483 
1484     default:
1485         break;
1486     }
1487 
1488     /* Check capacity limits */
1489     ab8500_fg_check_capacity_limits(di, false);
1490 }
1491 
1492 static void force_capacity(struct ab8500_fg *di)
1493 {
1494     int cap;
1495 
1496     ab8500_fg_clear_cap_samples(di);
1497     cap = di->bat_cap.user_mah;
1498     if (cap > di->bat_cap.max_mah_design) {
1499         dev_dbg(di->dev, "Remaining cap %d can't be bigger than total"
1500             " %d\n", cap, di->bat_cap.max_mah_design);
1501         cap = di->bat_cap.max_mah_design;
1502     }
1503     ab8500_fg_fill_cap_sample(di, di->bat_cap.user_mah);
1504     di->bat_cap.permille = ab8500_fg_convert_mah_to_permille(di, cap);
1505     di->bat_cap.mah = cap;
1506     ab8500_fg_check_capacity_limits(di, true);
1507 }
1508 
1509 static bool check_sysfs_capacity(struct ab8500_fg *di)
1510 {
1511     int cap, lower, upper;
1512     int cap_permille;
1513 
1514     cap = di->bat_cap.user_mah;
1515 
1516     cap_permille = ab8500_fg_convert_mah_to_permille(di,
1517         di->bat_cap.user_mah);
1518 
1519     lower = di->bat_cap.permille - di->bm->fg_params->user_cap_limit * 10;
1520     upper = di->bat_cap.permille + di->bm->fg_params->user_cap_limit * 10;
1521 
1522     if (lower < 0)
1523         lower = 0;
1524     /* 1000 is permille, -> 100 percent */
1525     if (upper > 1000)
1526         upper = 1000;
1527 
1528     dev_dbg(di->dev, "Capacity limits:"
1529         " (Lower: %d User: %d Upper: %d) [user: %d, was: %d]\n",
1530         lower, cap_permille, upper, cap, di->bat_cap.mah);
1531 
1532     /* If within limits, use the saved capacity and exit estimation...*/
1533     if (cap_permille > lower && cap_permille < upper) {
1534         dev_dbg(di->dev, "OK! Using users cap %d uAh now\n", cap);
1535         force_capacity(di);
1536         return true;
1537     }
1538     dev_dbg(di->dev, "Capacity from user out of limits, ignoring");
1539     return false;
1540 }
1541 
1542 /**
1543  * ab8500_fg_algorithm_discharging() - FG algorithm for when discharging
1544  * @di:     pointer to the ab8500_fg structure
1545  *
1546  * Battery capacity calculation state machine for when we're discharging
1547  */
1548 static void ab8500_fg_algorithm_discharging(struct ab8500_fg *di)
1549 {
1550     int sleep_time;
1551 
1552     /* If we change to charge mode we should start with init */
1553     if (di->charge_state != AB8500_FG_CHARGE_INIT)
1554         ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
1555 
1556     switch (di->discharge_state) {
1557     case AB8500_FG_DISCHARGE_INIT:
1558         /* We use the FG IRQ to work on */
1559         di->init_cnt = 0;
1560         di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
1561         ab8500_fg_coulomb_counter(di, true);
1562         ab8500_fg_discharge_state_to(di,
1563             AB8500_FG_DISCHARGE_INITMEASURING);
1564 
1565         fallthrough;
1566     case AB8500_FG_DISCHARGE_INITMEASURING:
1567         /*
1568          * Discard a number of samples during startup.
1569          * After that, use compensated voltage for a few
1570          * samples to get an initial capacity.
1571          * Then go to READOUT
1572          */
1573         sleep_time = di->bm->fg_params->init_timer;
1574 
1575         /* Discard the first [x] seconds */
1576         if (di->init_cnt > di->bm->fg_params->init_discard_time) {
1577             ab8500_fg_calc_cap_discharge_voltage(di);
1578 
1579             ab8500_fg_check_capacity_limits(di, true);
1580         }
1581 
1582         di->init_cnt += sleep_time;
1583         if (di->init_cnt > di->bm->fg_params->init_total_time)
1584             ab8500_fg_discharge_state_to(di,
1585                 AB8500_FG_DISCHARGE_READOUT_INIT);
1586 
1587         break;
1588 
1589     case AB8500_FG_DISCHARGE_INIT_RECOVERY:
1590         di->recovery_cnt = 0;
1591         di->recovery_needed = true;
1592         ab8500_fg_discharge_state_to(di,
1593             AB8500_FG_DISCHARGE_RECOVERY);
1594 
1595         fallthrough;
1596 
1597     case AB8500_FG_DISCHARGE_RECOVERY:
1598         sleep_time = di->bm->fg_params->recovery_sleep_timer;
1599 
1600         /*
1601          * We should check the power consumption
1602          * If low, go to READOUT (after x min) or
1603          * RECOVERY_SLEEP if time left.
1604          * If high, go to READOUT
1605          */
1606         di->inst_curr_ua = ab8500_fg_inst_curr_blocking(di);
1607 
1608         if (ab8500_fg_is_low_curr(di, di->inst_curr_ua)) {
1609             if (di->recovery_cnt >
1610                 di->bm->fg_params->recovery_total_time) {
1611                 di->fg_samples = SEC_TO_SAMPLE(
1612                     di->bm->fg_params->accu_high_curr);
1613                 ab8500_fg_coulomb_counter(di, true);
1614                 ab8500_fg_discharge_state_to(di,
1615                     AB8500_FG_DISCHARGE_READOUT);
1616                 di->recovery_needed = false;
1617             } else {
1618                 queue_delayed_work(di->fg_wq,
1619                     &di->fg_periodic_work,
1620                     sleep_time * HZ);
1621             }
1622             di->recovery_cnt += sleep_time;
1623         } else {
1624             di->fg_samples = SEC_TO_SAMPLE(
1625                 di->bm->fg_params->accu_high_curr);
1626             ab8500_fg_coulomb_counter(di, true);
1627             ab8500_fg_discharge_state_to(di,
1628                 AB8500_FG_DISCHARGE_READOUT);
1629         }
1630         break;
1631 
1632     case AB8500_FG_DISCHARGE_READOUT_INIT:
1633         di->fg_samples = SEC_TO_SAMPLE(
1634             di->bm->fg_params->accu_high_curr);
1635         ab8500_fg_coulomb_counter(di, true);
1636         ab8500_fg_discharge_state_to(di,
1637                 AB8500_FG_DISCHARGE_READOUT);
1638         break;
1639 
1640     case AB8500_FG_DISCHARGE_READOUT:
1641         di->inst_curr_ua = ab8500_fg_inst_curr_blocking(di);
1642 
1643         if (ab8500_fg_is_low_curr(di, di->inst_curr_ua)) {
1644             /* Detect mode change */
1645             if (di->high_curr_mode) {
1646                 di->high_curr_mode = false;
1647                 di->high_curr_cnt = 0;
1648             }
1649 
1650             if (di->recovery_needed) {
1651                 ab8500_fg_discharge_state_to(di,
1652                     AB8500_FG_DISCHARGE_INIT_RECOVERY);
1653 
1654                 queue_delayed_work(di->fg_wq,
1655                     &di->fg_periodic_work, 0);
1656 
1657                 break;
1658             }
1659 
1660             ab8500_fg_calc_cap_discharge_voltage(di);
1661         } else {
1662             mutex_lock(&di->cc_lock);
1663             if (!di->flags.conv_done) {
1664                 /* Wasn't the CC IRQ that got us here */
1665                 mutex_unlock(&di->cc_lock);
1666                 dev_dbg(di->dev, "%s CC conv not done\n",
1667                     __func__);
1668 
1669                 break;
1670             }
1671             di->flags.conv_done = false;
1672             mutex_unlock(&di->cc_lock);
1673 
1674             /* Detect mode change */
1675             if (!di->high_curr_mode) {
1676                 di->high_curr_mode = true;
1677                 di->high_curr_cnt = 0;
1678             }
1679 
1680             di->high_curr_cnt +=
1681                 di->bm->fg_params->accu_high_curr;
1682             if (di->high_curr_cnt >
1683                 di->bm->fg_params->high_curr_time)
1684                 di->recovery_needed = true;
1685 
1686             ab8500_fg_calc_cap_discharge_fg(di);
1687         }
1688 
1689         ab8500_fg_check_capacity_limits(di, false);
1690 
1691         break;
1692 
1693     case AB8500_FG_DISCHARGE_WAKEUP:
1694         ab8500_fg_calc_cap_discharge_voltage(di);
1695 
1696         di->fg_samples = SEC_TO_SAMPLE(
1697             di->bm->fg_params->accu_high_curr);
1698         ab8500_fg_coulomb_counter(di, true);
1699         ab8500_fg_discharge_state_to(di,
1700                 AB8500_FG_DISCHARGE_READOUT);
1701 
1702         ab8500_fg_check_capacity_limits(di, false);
1703 
1704         break;
1705 
1706     default:
1707         break;
1708     }
1709 }
1710 
1711 /**
1712  * ab8500_fg_algorithm_calibrate() - Internal columb counter offset calibration
1713  * @di:     pointer to the ab8500_fg structure
1714  *
1715  */
1716 static void ab8500_fg_algorithm_calibrate(struct ab8500_fg *di)
1717 {
1718     int ret;
1719 
1720     switch (di->calib_state) {
1721     case AB8500_FG_CALIB_INIT:
1722         dev_dbg(di->dev, "Calibration ongoing...\n");
1723 
1724         ret = abx500_mask_and_set_register_interruptible(di->dev,
1725             AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1726             CC_INT_CAL_N_AVG_MASK, CC_INT_CAL_SAMPLES_8);
1727         if (ret < 0)
1728             goto err;
1729 
1730         ret = abx500_mask_and_set_register_interruptible(di->dev,
1731             AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1732             CC_INTAVGOFFSET_ENA, CC_INTAVGOFFSET_ENA);
1733         if (ret < 0)
1734             goto err;
1735         di->calib_state = AB8500_FG_CALIB_WAIT;
1736         break;
1737     case AB8500_FG_CALIB_END:
1738         ret = abx500_mask_and_set_register_interruptible(di->dev,
1739             AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1740             CC_MUXOFFSET, CC_MUXOFFSET);
1741         if (ret < 0)
1742             goto err;
1743         di->flags.calibrate = false;
1744         dev_dbg(di->dev, "Calibration done...\n");
1745         queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1746         break;
1747     case AB8500_FG_CALIB_WAIT:
1748         dev_dbg(di->dev, "Calibration WFI\n");
1749         break;
1750     default:
1751         break;
1752     }
1753     return;
1754 err:
1755     /* Something went wrong, don't calibrate then */
1756     dev_err(di->dev, "failed to calibrate the CC\n");
1757     di->flags.calibrate = false;
1758     di->calib_state = AB8500_FG_CALIB_INIT;
1759     queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1760 }
1761 
1762 /**
1763  * ab8500_fg_algorithm() - Entry point for the FG algorithm
1764  * @di:     pointer to the ab8500_fg structure
1765  *
1766  * Entry point for the battery capacity calculation state machine
1767  */
1768 static void ab8500_fg_algorithm(struct ab8500_fg *di)
1769 {
1770     if (di->flags.calibrate)
1771         ab8500_fg_algorithm_calibrate(di);
1772     else {
1773         if (di->flags.charging)
1774             ab8500_fg_algorithm_charging(di);
1775         else
1776             ab8500_fg_algorithm_discharging(di);
1777     }
1778 
1779     dev_dbg(di->dev, "[FG_DATA] %d %d %d %d %d %d %d %d %d %d "
1780         "%d %d %d %d %d %d %d\n",
1781         di->bat_cap.max_mah_design,
1782         di->bat_cap.max_mah,
1783         di->bat_cap.mah,
1784         di->bat_cap.permille,
1785         di->bat_cap.level,
1786         di->bat_cap.prev_mah,
1787         di->bat_cap.prev_percent,
1788         di->bat_cap.prev_level,
1789         di->vbat_uv,
1790         di->inst_curr_ua,
1791         di->avg_curr_ua,
1792         di->accu_charge,
1793         di->flags.charging,
1794         di->charge_state,
1795         di->discharge_state,
1796         di->high_curr_mode,
1797         di->recovery_needed);
1798 }
1799 
1800 /**
1801  * ab8500_fg_periodic_work() - Run the FG state machine periodically
1802  * @work:   pointer to the work_struct structure
1803  *
1804  * Work queue function for periodic work
1805  */
1806 static void ab8500_fg_periodic_work(struct work_struct *work)
1807 {
1808     struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1809         fg_periodic_work.work);
1810 
1811     if (di->init_capacity) {
1812         /* Get an initial capacity calculation */
1813         ab8500_fg_calc_cap_discharge_voltage(di);
1814         ab8500_fg_check_capacity_limits(di, true);
1815         di->init_capacity = false;
1816 
1817         queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1818     } else if (di->flags.user_cap) {
1819         if (check_sysfs_capacity(di)) {
1820             ab8500_fg_check_capacity_limits(di, true);
1821             if (di->flags.charging)
1822                 ab8500_fg_charge_state_to(di,
1823                     AB8500_FG_CHARGE_INIT);
1824             else
1825                 ab8500_fg_discharge_state_to(di,
1826                     AB8500_FG_DISCHARGE_READOUT_INIT);
1827         }
1828         di->flags.user_cap = false;
1829         queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1830     } else
1831         ab8500_fg_algorithm(di);
1832 
1833 }
1834 
1835 /**
1836  * ab8500_fg_check_hw_failure_work() - Check OVV_BAT condition
1837  * @work:   pointer to the work_struct structure
1838  *
1839  * Work queue function for checking the OVV_BAT condition
1840  */
1841 static void ab8500_fg_check_hw_failure_work(struct work_struct *work)
1842 {
1843     int ret;
1844     u8 reg_value;
1845 
1846     struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1847         fg_check_hw_failure_work.work);
1848 
1849     /*
1850      * If we have had a battery over-voltage situation,
1851      * check ovv-bit to see if it should be reset.
1852      */
1853     ret = abx500_get_register_interruptible(di->dev,
1854         AB8500_CHARGER, AB8500_CH_STAT_REG,
1855         &reg_value);
1856     if (ret < 0) {
1857         dev_err(di->dev, "%s ab8500 read failed\n", __func__);
1858         return;
1859     }
1860     if ((reg_value & BATT_OVV) == BATT_OVV) {
1861         if (!di->flags.bat_ovv) {
1862             dev_dbg(di->dev, "Battery OVV\n");
1863             di->flags.bat_ovv = true;
1864             power_supply_changed(di->fg_psy);
1865         }
1866         /* Not yet recovered from ovv, reschedule this test */
1867         queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work,
1868                    HZ);
1869         } else {
1870             dev_dbg(di->dev, "Battery recovered from OVV\n");
1871             di->flags.bat_ovv = false;
1872             power_supply_changed(di->fg_psy);
1873     }
1874 }
1875 
1876 /**
1877  * ab8500_fg_low_bat_work() - Check LOW_BAT condition
1878  * @work:   pointer to the work_struct structure
1879  *
1880  * Work queue function for checking the LOW_BAT condition
1881  */
1882 static void ab8500_fg_low_bat_work(struct work_struct *work)
1883 {
1884     int vbat_uv;
1885 
1886     struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1887         fg_low_bat_work.work);
1888 
1889     vbat_uv = ab8500_fg_bat_voltage(di);
1890 
1891     /* Check if LOW_BAT still fulfilled */
1892     if (vbat_uv < di->bm->fg_params->lowbat_threshold_uv) {
1893         /* Is it time to shut down? */
1894         if (di->low_bat_cnt < 1) {
1895             di->flags.low_bat = true;
1896             dev_warn(di->dev, "Shut down pending...\n");
1897         } else {
1898             /*
1899             * Else we need to re-schedule this check to be able to detect
1900             * if the voltage increases again during charging or
1901             * due to decreasing load.
1902             */
1903             di->low_bat_cnt--;
1904             dev_warn(di->dev, "Battery voltage still LOW\n");
1905             queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
1906                 round_jiffies(LOW_BAT_CHECK_INTERVAL));
1907         }
1908     } else {
1909         di->flags.low_bat_delay = false;
1910         di->low_bat_cnt = 10;
1911         dev_warn(di->dev, "Battery voltage OK again\n");
1912     }
1913 
1914     /* This is needed to dispatch LOW_BAT */
1915     ab8500_fg_check_capacity_limits(di, false);
1916 }
1917 
1918 /**
1919  * ab8500_fg_battok_calc - calculate the bit pattern corresponding
1920  * to the target voltage.
1921  * @di:       pointer to the ab8500_fg structure
1922  * @target:   target voltage
1923  *
1924  * Returns bit pattern closest to the target voltage
1925  * valid return values are 0-14. (0-BATT_OK_MAX_NR_INCREMENTS)
1926  */
1927 
1928 static int ab8500_fg_battok_calc(struct ab8500_fg *di, int target)
1929 {
1930     if (target > BATT_OK_MIN +
1931         (BATT_OK_INCREMENT * BATT_OK_MAX_NR_INCREMENTS))
1932         return BATT_OK_MAX_NR_INCREMENTS;
1933     if (target < BATT_OK_MIN)
1934         return 0;
1935     return (target - BATT_OK_MIN) / BATT_OK_INCREMENT;
1936 }
1937 
1938 /**
1939  * ab8500_fg_battok_init_hw_register - init battok levels
1940  * @di:       pointer to the ab8500_fg structure
1941  *
1942  */
1943 
1944 static int ab8500_fg_battok_init_hw_register(struct ab8500_fg *di)
1945 {
1946     int selected;
1947     int sel0;
1948     int sel1;
1949     int cbp_sel0;
1950     int cbp_sel1;
1951     int ret;
1952     int new_val;
1953 
1954     sel0 = di->bm->fg_params->battok_falling_th_sel0;
1955     sel1 = di->bm->fg_params->battok_raising_th_sel1;
1956 
1957     cbp_sel0 = ab8500_fg_battok_calc(di, sel0);
1958     cbp_sel1 = ab8500_fg_battok_calc(di, sel1);
1959 
1960     selected = BATT_OK_MIN + cbp_sel0 * BATT_OK_INCREMENT;
1961 
1962     if (selected != sel0)
1963         dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1964             sel0, selected, cbp_sel0);
1965 
1966     selected = BATT_OK_MIN + cbp_sel1 * BATT_OK_INCREMENT;
1967 
1968     if (selected != sel1)
1969         dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1970             sel1, selected, cbp_sel1);
1971 
1972     new_val = cbp_sel0 | (cbp_sel1 << 4);
1973 
1974     dev_dbg(di->dev, "using: %x %d %d\n", new_val, cbp_sel0, cbp_sel1);
1975     ret = abx500_set_register_interruptible(di->dev, AB8500_SYS_CTRL2_BLOCK,
1976         AB8500_BATT_OK_REG, new_val);
1977     return ret;
1978 }
1979 
1980 /**
1981  * ab8500_fg_instant_work() - Run the FG state machine instantly
1982  * @work:   pointer to the work_struct structure
1983  *
1984  * Work queue function for instant work
1985  */
1986 static void ab8500_fg_instant_work(struct work_struct *work)
1987 {
1988     struct ab8500_fg *di = container_of(work, struct ab8500_fg, fg_work);
1989 
1990     ab8500_fg_algorithm(di);
1991 }
1992 
1993 /**
1994  * ab8500_fg_cc_data_end_handler() - end of data conversion isr.
1995  * @irq:       interrupt number
1996  * @_di:       pointer to the ab8500_fg structure
1997  *
1998  * Returns IRQ status(IRQ_HANDLED)
1999  */
2000 static irqreturn_t ab8500_fg_cc_data_end_handler(int irq, void *_di)
2001 {
2002     struct ab8500_fg *di = _di;
2003     if (!di->nbr_cceoc_irq_cnt) {
2004         di->nbr_cceoc_irq_cnt++;
2005         complete(&di->ab8500_fg_started);
2006     } else {
2007         di->nbr_cceoc_irq_cnt = 0;
2008         complete(&di->ab8500_fg_complete);
2009     }
2010     return IRQ_HANDLED;
2011 }
2012 
2013 /**
2014  * ab8500_fg_cc_int_calib_handler () - end of calibration isr.
2015  * @irq:       interrupt number
2016  * @_di:       pointer to the ab8500_fg structure
2017  *
2018  * Returns IRQ status(IRQ_HANDLED)
2019  */
2020 static irqreturn_t ab8500_fg_cc_int_calib_handler(int irq, void *_di)
2021 {
2022     struct ab8500_fg *di = _di;
2023     di->calib_state = AB8500_FG_CALIB_END;
2024     queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2025     return IRQ_HANDLED;
2026 }
2027 
2028 /**
2029  * ab8500_fg_cc_convend_handler() - isr to get battery avg current.
2030  * @irq:       interrupt number
2031  * @_di:       pointer to the ab8500_fg structure
2032  *
2033  * Returns IRQ status(IRQ_HANDLED)
2034  */
2035 static irqreturn_t ab8500_fg_cc_convend_handler(int irq, void *_di)
2036 {
2037     struct ab8500_fg *di = _di;
2038 
2039     queue_work(di->fg_wq, &di->fg_acc_cur_work);
2040 
2041     return IRQ_HANDLED;
2042 }
2043 
2044 /**
2045  * ab8500_fg_batt_ovv_handler() - Battery OVV occured
2046  * @irq:       interrupt number
2047  * @_di:       pointer to the ab8500_fg structure
2048  *
2049  * Returns IRQ status(IRQ_HANDLED)
2050  */
2051 static irqreturn_t ab8500_fg_batt_ovv_handler(int irq, void *_di)
2052 {
2053     struct ab8500_fg *di = _di;
2054 
2055     dev_dbg(di->dev, "Battery OVV\n");
2056 
2057     /* Schedule a new HW failure check */
2058     queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work, 0);
2059 
2060     return IRQ_HANDLED;
2061 }
2062 
2063 /**
2064  * ab8500_fg_lowbatf_handler() - Battery voltage is below LOW threshold
2065  * @irq:       interrupt number
2066  * @_di:       pointer to the ab8500_fg structure
2067  *
2068  * Returns IRQ status(IRQ_HANDLED)
2069  */
2070 static irqreturn_t ab8500_fg_lowbatf_handler(int irq, void *_di)
2071 {
2072     struct ab8500_fg *di = _di;
2073 
2074     /* Initiate handling in ab8500_fg_low_bat_work() if not already initiated. */
2075     if (!di->flags.low_bat_delay) {
2076         dev_warn(di->dev, "Battery voltage is below LOW threshold\n");
2077         di->flags.low_bat_delay = true;
2078         /*
2079          * Start a timer to check LOW_BAT again after some time
2080          * This is done to avoid shutdown on single voltage dips
2081          */
2082         queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
2083             round_jiffies(LOW_BAT_CHECK_INTERVAL));
2084     }
2085     return IRQ_HANDLED;
2086 }
2087 
2088 /**
2089  * ab8500_fg_get_property() - get the fg properties
2090  * @psy:    pointer to the power_supply structure
2091  * @psp:    pointer to the power_supply_property structure
2092  * @val:    pointer to the power_supply_propval union
2093  *
2094  * This function gets called when an application tries to get the
2095  * fg properties by reading the sysfs files.
2096  * voltage_now:     battery voltage
2097  * current_now:     battery instant current
2098  * current_avg:     battery average current
2099  * charge_full_design:  capacity where battery is considered full
2100  * charge_now:      battery capacity in nAh
2101  * capacity:        capacity in percent
2102  * capacity_level:  capacity level
2103  *
2104  * Returns error code in case of failure else 0 on success
2105  */
2106 static int ab8500_fg_get_property(struct power_supply *psy,
2107     enum power_supply_property psp,
2108     union power_supply_propval *val)
2109 {
2110     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2111 
2112     /*
2113      * If battery is identified as unknown and charging of unknown
2114      * batteries is disabled, we always report 100% capacity and
2115      * capacity level UNKNOWN, since we can't calculate
2116      * remaining capacity
2117      */
2118 
2119     switch (psp) {
2120     case POWER_SUPPLY_PROP_VOLTAGE_NOW:
2121         if (di->flags.bat_ovv)
2122             val->intval = BATT_OVV_VALUE;
2123         else
2124             val->intval = di->vbat_uv;
2125         break;
2126     case POWER_SUPPLY_PROP_CURRENT_NOW:
2127         val->intval = di->inst_curr_ua;
2128         break;
2129     case POWER_SUPPLY_PROP_CURRENT_AVG:
2130         val->intval = di->avg_curr_ua;
2131         break;
2132     case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
2133         val->intval = ab8500_fg_convert_mah_to_uwh(di,
2134                 di->bat_cap.max_mah_design);
2135         break;
2136     case POWER_SUPPLY_PROP_ENERGY_FULL:
2137         val->intval = ab8500_fg_convert_mah_to_uwh(di,
2138                 di->bat_cap.max_mah);
2139         break;
2140     case POWER_SUPPLY_PROP_ENERGY_NOW:
2141         if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2142                 di->flags.batt_id_received)
2143             val->intval = ab8500_fg_convert_mah_to_uwh(di,
2144                     di->bat_cap.max_mah);
2145         else
2146             val->intval = ab8500_fg_convert_mah_to_uwh(di,
2147                     di->bat_cap.prev_mah);
2148         break;
2149     case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
2150         val->intval = di->bat_cap.max_mah_design;
2151         break;
2152     case POWER_SUPPLY_PROP_CHARGE_FULL:
2153         val->intval = di->bat_cap.max_mah;
2154         break;
2155     case POWER_SUPPLY_PROP_CHARGE_NOW:
2156         if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2157                 di->flags.batt_id_received)
2158             val->intval = di->bat_cap.max_mah;
2159         else
2160             val->intval = di->bat_cap.prev_mah;
2161         break;
2162     case POWER_SUPPLY_PROP_CAPACITY:
2163         if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2164                 di->flags.batt_id_received)
2165             val->intval = 100;
2166         else
2167             val->intval = di->bat_cap.prev_percent;
2168         break;
2169     case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
2170         if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2171                 di->flags.batt_id_received)
2172             val->intval = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
2173         else
2174             val->intval = di->bat_cap.prev_level;
2175         break;
2176     default:
2177         return -EINVAL;
2178     }
2179     return 0;
2180 }
2181 
2182 static int ab8500_fg_get_ext_psy_data(struct device *dev, void *data)
2183 {
2184     struct power_supply *psy;
2185     struct power_supply *ext = dev_get_drvdata(dev);
2186     const char **supplicants = (const char **)ext->supplied_to;
2187     struct ab8500_fg *di;
2188     struct power_supply_battery_info *bi;
2189     union power_supply_propval ret;
2190     int j;
2191 
2192     psy = (struct power_supply *)data;
2193     di = power_supply_get_drvdata(psy);
2194     bi = di->bm->bi;
2195 
2196     /*
2197      * For all psy where the name of your driver
2198      * appears in any supplied_to
2199      */
2200     j = match_string(supplicants, ext->num_supplicants, psy->desc->name);
2201     if (j < 0)
2202         return 0;
2203 
2204     /* Go through all properties for the psy */
2205     for (j = 0; j < ext->desc->num_properties; j++) {
2206         enum power_supply_property prop;
2207         prop = ext->desc->properties[j];
2208 
2209         if (power_supply_get_property(ext, prop, &ret))
2210             continue;
2211 
2212         switch (prop) {
2213         case POWER_SUPPLY_PROP_STATUS:
2214             switch (ext->desc->type) {
2215             case POWER_SUPPLY_TYPE_BATTERY:
2216                 switch (ret.intval) {
2217                 case POWER_SUPPLY_STATUS_UNKNOWN:
2218                 case POWER_SUPPLY_STATUS_DISCHARGING:
2219                 case POWER_SUPPLY_STATUS_NOT_CHARGING:
2220                     if (!di->flags.charging)
2221                         break;
2222                     di->flags.charging = false;
2223                     di->flags.fully_charged = false;
2224                     if (di->bm->capacity_scaling)
2225                         ab8500_fg_update_cap_scalers(di);
2226                     queue_work(di->fg_wq, &di->fg_work);
2227                     break;
2228                 case POWER_SUPPLY_STATUS_FULL:
2229                     if (di->flags.fully_charged)
2230                         break;
2231                     di->flags.fully_charged = true;
2232                     di->flags.force_full = true;
2233                     /* Save current capacity as maximum */
2234                     di->bat_cap.max_mah = di->bat_cap.mah;
2235                     queue_work(di->fg_wq, &di->fg_work);
2236                     break;
2237                 case POWER_SUPPLY_STATUS_CHARGING:
2238                     if (di->flags.charging &&
2239                         !di->flags.fully_charged)
2240                         break;
2241                     di->flags.charging = true;
2242                     di->flags.fully_charged = false;
2243                     if (di->bm->capacity_scaling)
2244                         ab8500_fg_update_cap_scalers(di);
2245                     queue_work(di->fg_wq, &di->fg_work);
2246                     break;
2247                 }
2248                 break;
2249             default:
2250                 break;
2251             }
2252             break;
2253         case POWER_SUPPLY_PROP_TECHNOLOGY:
2254             switch (ext->desc->type) {
2255             case POWER_SUPPLY_TYPE_BATTERY:
2256                 if (!di->flags.batt_id_received &&
2257                     (bi && (bi->technology !=
2258                         POWER_SUPPLY_TECHNOLOGY_UNKNOWN))) {
2259                     di->flags.batt_id_received = true;
2260 
2261                     di->bat_cap.max_mah_design =
2262                         di->bm->bi->charge_full_design_uah;
2263 
2264                     di->bat_cap.max_mah =
2265                         di->bat_cap.max_mah_design;
2266 
2267                     di->vbat_nom_uv =
2268                         di->bm->bi->voltage_max_design_uv;
2269                 }
2270 
2271                 if (ret.intval)
2272                     di->flags.batt_unknown = false;
2273                 else
2274                     di->flags.batt_unknown = true;
2275                 break;
2276             default:
2277                 break;
2278             }
2279             break;
2280         case POWER_SUPPLY_PROP_TEMP:
2281             switch (ext->desc->type) {
2282             case POWER_SUPPLY_TYPE_BATTERY:
2283                 if (di->flags.batt_id_received)
2284                     di->bat_temp = ret.intval;
2285                 break;
2286             default:
2287                 break;
2288             }
2289             break;
2290         default:
2291             break;
2292         }
2293     }
2294     return 0;
2295 }
2296 
2297 /**
2298  * ab8500_fg_init_hw_registers() - Set up FG related registers
2299  * @di:     pointer to the ab8500_fg structure
2300  *
2301  * Set up battery OVV, low battery voltage registers
2302  */
2303 static int ab8500_fg_init_hw_registers(struct ab8500_fg *di)
2304 {
2305     int ret;
2306 
2307     /*
2308      * Set VBAT OVV (overvoltage) threshold to 4.75V (typ) this is what
2309      * the hardware supports, nothing else can be configured in hardware.
2310      * See this as an "outer limit" where the charger will certainly
2311      * shut down. Other (lower) overvoltage levels need to be implemented
2312      * in software.
2313      */
2314     ret = abx500_mask_and_set_register_interruptible(di->dev,
2315         AB8500_CHARGER,
2316         AB8500_BATT_OVV,
2317         BATT_OVV_TH_4P75,
2318         BATT_OVV_TH_4P75);
2319     if (ret) {
2320         dev_err(di->dev, "failed to set BATT_OVV\n");
2321         goto out;
2322     }
2323 
2324     /* Enable VBAT OVV detection */
2325     ret = abx500_mask_and_set_register_interruptible(di->dev,
2326         AB8500_CHARGER,
2327         AB8500_BATT_OVV,
2328         BATT_OVV_ENA,
2329         BATT_OVV_ENA);
2330     if (ret) {
2331         dev_err(di->dev, "failed to enable BATT_OVV\n");
2332         goto out;
2333     }
2334 
2335     /* Low Battery Voltage */
2336     ret = abx500_set_register_interruptible(di->dev,
2337         AB8500_SYS_CTRL2_BLOCK,
2338         AB8500_LOW_BAT_REG,
2339         ab8500_volt_to_regval(
2340             di->bm->fg_params->lowbat_threshold_uv) << 1 |
2341         LOW_BAT_ENABLE);
2342     if (ret) {
2343         dev_err(di->dev, "%s write failed\n", __func__);
2344         goto out;
2345     }
2346 
2347     /* Battery OK threshold */
2348     ret = ab8500_fg_battok_init_hw_register(di);
2349     if (ret) {
2350         dev_err(di->dev, "BattOk init write failed.\n");
2351         goto out;
2352     }
2353 
2354     if (is_ab8505(di->parent)) {
2355         ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2356             AB8505_RTC_PCUT_MAX_TIME_REG, di->bm->fg_params->pcut_max_time);
2357 
2358         if (ret) {
2359             dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_MAX_TIME_REG\n", __func__);
2360             goto out;
2361         }
2362 
2363         ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2364             AB8505_RTC_PCUT_FLAG_TIME_REG, di->bm->fg_params->pcut_flag_time);
2365 
2366         if (ret) {
2367             dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_FLAG_TIME_REG\n", __func__);
2368             goto out;
2369         }
2370 
2371         ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2372             AB8505_RTC_PCUT_RESTART_REG, di->bm->fg_params->pcut_max_restart);
2373 
2374         if (ret) {
2375             dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_RESTART_REG\n", __func__);
2376             goto out;
2377         }
2378 
2379         ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2380             AB8505_RTC_PCUT_DEBOUNCE_REG, di->bm->fg_params->pcut_debounce_time);
2381 
2382         if (ret) {
2383             dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_DEBOUNCE_REG\n", __func__);
2384             goto out;
2385         }
2386 
2387         ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2388             AB8505_RTC_PCUT_CTL_STATUS_REG, di->bm->fg_params->pcut_enable);
2389 
2390         if (ret) {
2391             dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_CTL_STATUS_REG\n", __func__);
2392             goto out;
2393         }
2394     }
2395 out:
2396     return ret;
2397 }
2398 
2399 /**
2400  * ab8500_fg_external_power_changed() - callback for power supply changes
2401  * @psy:       pointer to the structure power_supply
2402  *
2403  * This function is the entry point of the pointer external_power_changed
2404  * of the structure power_supply.
2405  * This function gets executed when there is a change in any external power
2406  * supply that this driver needs to be notified of.
2407  */
2408 static void ab8500_fg_external_power_changed(struct power_supply *psy)
2409 {
2410     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2411 
2412     class_for_each_device(power_supply_class, NULL,
2413         di->fg_psy, ab8500_fg_get_ext_psy_data);
2414 }
2415 
2416 /**
2417  * ab8500_fg_reinit_work() - work to reset the FG algorithm
2418  * @work:   pointer to the work_struct structure
2419  *
2420  * Used to reset the current battery capacity to be able to
2421  * retrigger a new voltage base capacity calculation. For
2422  * test and verification purpose.
2423  */
2424 static void ab8500_fg_reinit_work(struct work_struct *work)
2425 {
2426     struct ab8500_fg *di = container_of(work, struct ab8500_fg,
2427         fg_reinit_work.work);
2428 
2429     if (!di->flags.calibrate) {
2430         dev_dbg(di->dev, "Resetting FG state machine to init.\n");
2431         ab8500_fg_clear_cap_samples(di);
2432         ab8500_fg_calc_cap_discharge_voltage(di);
2433         ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
2434         ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
2435         queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2436 
2437     } else {
2438         dev_err(di->dev, "Residual offset calibration ongoing "
2439             "retrying..\n");
2440         /* Wait one second until next try*/
2441         queue_delayed_work(di->fg_wq, &di->fg_reinit_work,
2442             round_jiffies(1));
2443     }
2444 }
2445 
2446 /* Exposure to the sysfs interface */
2447 
2448 struct ab8500_fg_sysfs_entry {
2449     struct attribute attr;
2450     ssize_t (*show)(struct ab8500_fg *, char *);
2451     ssize_t (*store)(struct ab8500_fg *, const char *, size_t);
2452 };
2453 
2454 static ssize_t charge_full_show(struct ab8500_fg *di, char *buf)
2455 {
2456     return sprintf(buf, "%d\n", di->bat_cap.max_mah);
2457 }
2458 
2459 static ssize_t charge_full_store(struct ab8500_fg *di, const char *buf,
2460                  size_t count)
2461 {
2462     unsigned long charge_full;
2463     int ret;
2464 
2465     ret = kstrtoul(buf, 10, &charge_full);
2466     if (ret)
2467         return ret;
2468 
2469     di->bat_cap.max_mah = (int) charge_full;
2470     return count;
2471 }
2472 
2473 static ssize_t charge_now_show(struct ab8500_fg *di, char *buf)
2474 {
2475     return sprintf(buf, "%d\n", di->bat_cap.prev_mah);
2476 }
2477 
2478 static ssize_t charge_now_store(struct ab8500_fg *di, const char *buf,
2479                  size_t count)
2480 {
2481     unsigned long charge_now;
2482     int ret;
2483 
2484     ret = kstrtoul(buf, 10, &charge_now);
2485     if (ret)
2486         return ret;
2487 
2488     di->bat_cap.user_mah = (int) charge_now;
2489     di->flags.user_cap = true;
2490     queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2491     return count;
2492 }
2493 
2494 static struct ab8500_fg_sysfs_entry charge_full_attr =
2495     __ATTR(charge_full, 0644, charge_full_show, charge_full_store);
2496 
2497 static struct ab8500_fg_sysfs_entry charge_now_attr =
2498     __ATTR(charge_now, 0644, charge_now_show, charge_now_store);
2499 
2500 static ssize_t
2501 ab8500_fg_show(struct kobject *kobj, struct attribute *attr, char *buf)
2502 {
2503     struct ab8500_fg_sysfs_entry *entry;
2504     struct ab8500_fg *di;
2505 
2506     entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2507     di = container_of(kobj, struct ab8500_fg, fg_kobject);
2508 
2509     if (!entry->show)
2510         return -EIO;
2511 
2512     return entry->show(di, buf);
2513 }
2514 static ssize_t
2515 ab8500_fg_store(struct kobject *kobj, struct attribute *attr, const char *buf,
2516         size_t count)
2517 {
2518     struct ab8500_fg_sysfs_entry *entry;
2519     struct ab8500_fg *di;
2520 
2521     entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2522     di = container_of(kobj, struct ab8500_fg, fg_kobject);
2523 
2524     if (!entry->store)
2525         return -EIO;
2526 
2527     return entry->store(di, buf, count);
2528 }
2529 
2530 static const struct sysfs_ops ab8500_fg_sysfs_ops = {
2531     .show = ab8500_fg_show,
2532     .store = ab8500_fg_store,
2533 };
2534 
2535 static struct attribute *ab8500_fg_attrs[] = {
2536     &charge_full_attr.attr,
2537     &charge_now_attr.attr,
2538     NULL,
2539 };
2540 ATTRIBUTE_GROUPS(ab8500_fg);
2541 
2542 static struct kobj_type ab8500_fg_ktype = {
2543     .sysfs_ops = &ab8500_fg_sysfs_ops,
2544     .default_groups = ab8500_fg_groups,
2545 };
2546 
2547 /**
2548  * ab8500_fg_sysfs_exit() - de-init of sysfs entry
2549  * @di:                pointer to the struct ab8500_chargalg
2550  *
2551  * This function removes the entry in sysfs.
2552  */
2553 static void ab8500_fg_sysfs_exit(struct ab8500_fg *di)
2554 {
2555     kobject_del(&di->fg_kobject);
2556 }
2557 
2558 /**
2559  * ab8500_fg_sysfs_init() - init of sysfs entry
2560  * @di:                pointer to the struct ab8500_chargalg
2561  *
2562  * This function adds an entry in sysfs.
2563  * Returns error code in case of failure else 0(on success)
2564  */
2565 static int ab8500_fg_sysfs_init(struct ab8500_fg *di)
2566 {
2567     int ret = 0;
2568 
2569     ret = kobject_init_and_add(&di->fg_kobject,
2570         &ab8500_fg_ktype,
2571         NULL, "battery");
2572     if (ret < 0) {
2573         kobject_put(&di->fg_kobject);
2574         dev_err(di->dev, "failed to create sysfs entry\n");
2575     }
2576 
2577     return ret;
2578 }
2579 
2580 static ssize_t ab8505_powercut_flagtime_read(struct device *dev,
2581                  struct device_attribute *attr,
2582                  char *buf)
2583 {
2584     int ret;
2585     u8 reg_value;
2586     struct power_supply *psy = dev_get_drvdata(dev);
2587     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2588 
2589     ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2590         AB8505_RTC_PCUT_FLAG_TIME_REG, &reg_value);
2591 
2592     if (ret < 0) {
2593         dev_err(dev, "Failed to read AB8505_RTC_PCUT_FLAG_TIME_REG\n");
2594         goto fail;
2595     }
2596 
2597     return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7F));
2598 
2599 fail:
2600     return ret;
2601 }
2602 
2603 static ssize_t ab8505_powercut_flagtime_write(struct device *dev,
2604                   struct device_attribute *attr,
2605                   const char *buf, size_t count)
2606 {
2607     int ret;
2608     int reg_value;
2609     struct power_supply *psy = dev_get_drvdata(dev);
2610     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2611 
2612     if (kstrtoint(buf, 10, &reg_value))
2613         goto fail;
2614 
2615     if (reg_value > 0x7F) {
2616         dev_err(dev, "Incorrect parameter, echo 0 (1.98s) - 127 (15.625ms) for flagtime\n");
2617         goto fail;
2618     }
2619 
2620     ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2621         AB8505_RTC_PCUT_FLAG_TIME_REG, (u8)reg_value);
2622 
2623     if (ret < 0)
2624         dev_err(dev, "Failed to set AB8505_RTC_PCUT_FLAG_TIME_REG\n");
2625 
2626 fail:
2627     return count;
2628 }
2629 
2630 static ssize_t ab8505_powercut_maxtime_read(struct device *dev,
2631                  struct device_attribute *attr,
2632                  char *buf)
2633 {
2634     int ret;
2635     u8 reg_value;
2636     struct power_supply *psy = dev_get_drvdata(dev);
2637     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2638 
2639     ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2640         AB8505_RTC_PCUT_MAX_TIME_REG, &reg_value);
2641 
2642     if (ret < 0) {
2643         dev_err(dev, "Failed to read AB8505_RTC_PCUT_MAX_TIME_REG\n");
2644         goto fail;
2645     }
2646 
2647     return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7F));
2648 
2649 fail:
2650     return ret;
2651 
2652 }
2653 
2654 static ssize_t ab8505_powercut_maxtime_write(struct device *dev,
2655                   struct device_attribute *attr,
2656                   const char *buf, size_t count)
2657 {
2658     int ret;
2659     int reg_value;
2660     struct power_supply *psy = dev_get_drvdata(dev);
2661     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2662 
2663     if (kstrtoint(buf, 10, &reg_value))
2664         goto fail;
2665 
2666     if (reg_value > 0x7F) {
2667         dev_err(dev, "Incorrect parameter, echo 0 (0.0s) - 127 (1.98s) for maxtime\n");
2668         goto fail;
2669     }
2670 
2671     ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2672         AB8505_RTC_PCUT_MAX_TIME_REG, (u8)reg_value);
2673 
2674     if (ret < 0)
2675         dev_err(dev, "Failed to set AB8505_RTC_PCUT_MAX_TIME_REG\n");
2676 
2677 fail:
2678     return count;
2679 }
2680 
2681 static ssize_t ab8505_powercut_restart_read(struct device *dev,
2682                  struct device_attribute *attr,
2683                  char *buf)
2684 {
2685     int ret;
2686     u8 reg_value;
2687     struct power_supply *psy = dev_get_drvdata(dev);
2688     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2689 
2690     ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2691         AB8505_RTC_PCUT_RESTART_REG, &reg_value);
2692 
2693     if (ret < 0) {
2694         dev_err(dev, "Failed to read AB8505_RTC_PCUT_RESTART_REG\n");
2695         goto fail;
2696     }
2697 
2698     return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0xF));
2699 
2700 fail:
2701     return ret;
2702 }
2703 
2704 static ssize_t ab8505_powercut_restart_write(struct device *dev,
2705                          struct device_attribute *attr,
2706                          const char *buf, size_t count)
2707 {
2708     int ret;
2709     int reg_value;
2710     struct power_supply *psy = dev_get_drvdata(dev);
2711     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2712 
2713     if (kstrtoint(buf, 10, &reg_value))
2714         goto fail;
2715 
2716     if (reg_value > 0xF) {
2717         dev_err(dev, "Incorrect parameter, echo 0 - 15 for number of restart\n");
2718         goto fail;
2719     }
2720 
2721     ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2722                         AB8505_RTC_PCUT_RESTART_REG, (u8)reg_value);
2723 
2724     if (ret < 0)
2725         dev_err(dev, "Failed to set AB8505_RTC_PCUT_RESTART_REG\n");
2726 
2727 fail:
2728     return count;
2729 
2730 }
2731 
2732 static ssize_t ab8505_powercut_timer_read(struct device *dev,
2733                       struct device_attribute *attr,
2734                       char *buf)
2735 {
2736     int ret;
2737     u8 reg_value;
2738     struct power_supply *psy = dev_get_drvdata(dev);
2739     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2740 
2741     ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2742                         AB8505_RTC_PCUT_TIME_REG, &reg_value);
2743 
2744     if (ret < 0) {
2745         dev_err(dev, "Failed to read AB8505_RTC_PCUT_TIME_REG\n");
2746         goto fail;
2747     }
2748 
2749     return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7F));
2750 
2751 fail:
2752     return ret;
2753 }
2754 
2755 static ssize_t ab8505_powercut_restart_counter_read(struct device *dev,
2756                             struct device_attribute *attr,
2757                             char *buf)
2758 {
2759     int ret;
2760     u8 reg_value;
2761     struct power_supply *psy = dev_get_drvdata(dev);
2762     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2763 
2764     ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2765                         AB8505_RTC_PCUT_RESTART_REG, &reg_value);
2766 
2767     if (ret < 0) {
2768         dev_err(dev, "Failed to read AB8505_RTC_PCUT_RESTART_REG\n");
2769         goto fail;
2770     }
2771 
2772     return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0xF0) >> 4);
2773 
2774 fail:
2775     return ret;
2776 }
2777 
2778 static ssize_t ab8505_powercut_read(struct device *dev,
2779                     struct device_attribute *attr,
2780                     char *buf)
2781 {
2782     int ret;
2783     u8 reg_value;
2784     struct power_supply *psy = dev_get_drvdata(dev);
2785     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2786 
2787     ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2788                         AB8505_RTC_PCUT_CTL_STATUS_REG, &reg_value);
2789 
2790     if (ret < 0)
2791         goto fail;
2792 
2793     return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x1));
2794 
2795 fail:
2796     return ret;
2797 }
2798 
2799 static ssize_t ab8505_powercut_write(struct device *dev,
2800                      struct device_attribute *attr,
2801                      const char *buf, size_t count)
2802 {
2803     int ret;
2804     int reg_value;
2805     struct power_supply *psy = dev_get_drvdata(dev);
2806     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2807 
2808     if (kstrtoint(buf, 10, &reg_value))
2809         goto fail;
2810 
2811     if (reg_value > 0x1) {
2812         dev_err(dev, "Incorrect parameter, echo 0/1 to disable/enable Pcut feature\n");
2813         goto fail;
2814     }
2815 
2816     ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2817                         AB8505_RTC_PCUT_CTL_STATUS_REG, (u8)reg_value);
2818 
2819     if (ret < 0)
2820         dev_err(dev, "Failed to set AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2821 
2822 fail:
2823     return count;
2824 }
2825 
2826 static ssize_t ab8505_powercut_flag_read(struct device *dev,
2827                      struct device_attribute *attr,
2828                      char *buf)
2829 {
2830 
2831     int ret;
2832     u8 reg_value;
2833     struct power_supply *psy = dev_get_drvdata(dev);
2834     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2835 
2836     ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2837                         AB8505_RTC_PCUT_CTL_STATUS_REG,  &reg_value);
2838 
2839     if (ret < 0) {
2840         dev_err(dev, "Failed to read AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2841         goto fail;
2842     }
2843 
2844     return scnprintf(buf, PAGE_SIZE, "%d\n", ((reg_value & 0x10) >> 4));
2845 
2846 fail:
2847     return ret;
2848 }
2849 
2850 static ssize_t ab8505_powercut_debounce_read(struct device *dev,
2851                          struct device_attribute *attr,
2852                          char *buf)
2853 {
2854     int ret;
2855     u8 reg_value;
2856     struct power_supply *psy = dev_get_drvdata(dev);
2857     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2858 
2859     ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2860                         AB8505_RTC_PCUT_DEBOUNCE_REG,  &reg_value);
2861 
2862     if (ret < 0) {
2863         dev_err(dev, "Failed to read AB8505_RTC_PCUT_DEBOUNCE_REG\n");
2864         goto fail;
2865     }
2866 
2867     return scnprintf(buf, PAGE_SIZE, "%d\n", (reg_value & 0x7));
2868 
2869 fail:
2870     return ret;
2871 }
2872 
2873 static ssize_t ab8505_powercut_debounce_write(struct device *dev,
2874                           struct device_attribute *attr,
2875                           const char *buf, size_t count)
2876 {
2877     int ret;
2878     int reg_value;
2879     struct power_supply *psy = dev_get_drvdata(dev);
2880     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2881 
2882     if (kstrtoint(buf, 10, &reg_value))
2883         goto fail;
2884 
2885     if (reg_value > 0x7) {
2886         dev_err(dev, "Incorrect parameter, echo 0 to 7 for debounce setting\n");
2887         goto fail;
2888     }
2889 
2890     ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2891                         AB8505_RTC_PCUT_DEBOUNCE_REG, (u8)reg_value);
2892 
2893     if (ret < 0)
2894         dev_err(dev, "Failed to set AB8505_RTC_PCUT_DEBOUNCE_REG\n");
2895 
2896 fail:
2897     return count;
2898 }
2899 
2900 static ssize_t ab8505_powercut_enable_status_read(struct device *dev,
2901                           struct device_attribute *attr,
2902                           char *buf)
2903 {
2904     int ret;
2905     u8 reg_value;
2906     struct power_supply *psy = dev_get_drvdata(dev);
2907     struct ab8500_fg *di = power_supply_get_drvdata(psy);
2908 
2909     ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2910                         AB8505_RTC_PCUT_CTL_STATUS_REG, &reg_value);
2911 
2912     if (ret < 0) {
2913         dev_err(dev, "Failed to read AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2914         goto fail;
2915     }
2916 
2917     return scnprintf(buf, PAGE_SIZE, "%d\n", ((reg_value & 0x20) >> 5));
2918 
2919 fail:
2920     return ret;
2921 }
2922 
2923 static struct device_attribute ab8505_fg_sysfs_psy_attrs[] = {
2924     __ATTR(powercut_flagtime, (S_IRUGO | S_IWUSR | S_IWGRP),
2925         ab8505_powercut_flagtime_read, ab8505_powercut_flagtime_write),
2926     __ATTR(powercut_maxtime, (S_IRUGO | S_IWUSR | S_IWGRP),
2927         ab8505_powercut_maxtime_read, ab8505_powercut_maxtime_write),
2928     __ATTR(powercut_restart_max, (S_IRUGO | S_IWUSR | S_IWGRP),
2929         ab8505_powercut_restart_read, ab8505_powercut_restart_write),
2930     __ATTR(powercut_timer, S_IRUGO, ab8505_powercut_timer_read, NULL),
2931     __ATTR(powercut_restart_counter, S_IRUGO,
2932         ab8505_powercut_restart_counter_read, NULL),
2933     __ATTR(powercut_enable, (S_IRUGO | S_IWUSR | S_IWGRP),
2934         ab8505_powercut_read, ab8505_powercut_write),
2935     __ATTR(powercut_flag, S_IRUGO, ab8505_powercut_flag_read, NULL),
2936     __ATTR(powercut_debounce_time, (S_IRUGO | S_IWUSR | S_IWGRP),
2937         ab8505_powercut_debounce_read, ab8505_powercut_debounce_write),
2938     __ATTR(powercut_enable_status, S_IRUGO,
2939         ab8505_powercut_enable_status_read, NULL),
2940 };
2941 
2942 static int ab8500_fg_sysfs_psy_create_attrs(struct ab8500_fg *di)
2943 {
2944     unsigned int i;
2945 
2946     if (is_ab8505(di->parent)) {
2947         for (i = 0; i < ARRAY_SIZE(ab8505_fg_sysfs_psy_attrs); i++)
2948             if (device_create_file(&di->fg_psy->dev,
2949                            &ab8505_fg_sysfs_psy_attrs[i]))
2950                 goto sysfs_psy_create_attrs_failed_ab8505;
2951     }
2952     return 0;
2953 sysfs_psy_create_attrs_failed_ab8505:
2954     dev_err(&di->fg_psy->dev, "Failed creating sysfs psy attrs for ab8505.\n");
2955     while (i--)
2956         device_remove_file(&di->fg_psy->dev,
2957                    &ab8505_fg_sysfs_psy_attrs[i]);
2958 
2959     return -EIO;
2960 }
2961 
2962 static void ab8500_fg_sysfs_psy_remove_attrs(struct ab8500_fg *di)
2963 {
2964     unsigned int i;
2965 
2966     if (is_ab8505(di->parent)) {
2967         for (i = 0; i < ARRAY_SIZE(ab8505_fg_sysfs_psy_attrs); i++)
2968             (void)device_remove_file(&di->fg_psy->dev,
2969                          &ab8505_fg_sysfs_psy_attrs[i]);
2970     }
2971 }
2972 
2973 /* Exposure to the sysfs interface <<END>> */
2974 
2975 static int __maybe_unused ab8500_fg_resume(struct device *dev)
2976 {
2977     struct ab8500_fg *di = dev_get_drvdata(dev);
2978 
2979     /*
2980      * Change state if we're not charging. If we're charging we will wake
2981      * up on the FG IRQ
2982      */
2983     if (!di->flags.charging) {
2984         ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_WAKEUP);
2985         queue_work(di->fg_wq, &di->fg_work);
2986     }
2987 
2988     return 0;
2989 }
2990 
2991 static int __maybe_unused ab8500_fg_suspend(struct device *dev)
2992 {
2993     struct ab8500_fg *di = dev_get_drvdata(dev);
2994 
2995     flush_delayed_work(&di->fg_periodic_work);
2996     flush_work(&di->fg_work);
2997     flush_work(&di->fg_acc_cur_work);
2998     flush_delayed_work(&di->fg_reinit_work);
2999     flush_delayed_work(&di->fg_low_bat_work);
3000     flush_delayed_work(&di->fg_check_hw_failure_work);
3001 
3002     /*
3003      * If the FG is enabled we will disable it before going to suspend
3004      * only if we're not charging
3005      */
3006     if (di->flags.fg_enabled && !di->flags.charging)
3007         ab8500_fg_coulomb_counter(di, false);
3008 
3009     return 0;
3010 }
3011 
3012 /* ab8500 fg driver interrupts and their respective isr */
3013 static struct ab8500_fg_interrupts ab8500_fg_irq[] = {
3014     {"NCONV_ACCU", ab8500_fg_cc_convend_handler},
3015     {"BATT_OVV", ab8500_fg_batt_ovv_handler},
3016     {"LOW_BAT_F", ab8500_fg_lowbatf_handler},
3017     {"CC_INT_CALIB", ab8500_fg_cc_int_calib_handler},
3018     {"CCEOC", ab8500_fg_cc_data_end_handler},
3019 };
3020 
3021 static char *supply_interface[] = {
3022     "ab8500_chargalg",
3023     "ab8500_usb",
3024 };
3025 
3026 static const struct power_supply_desc ab8500_fg_desc = {
3027     .name           = "ab8500_fg",
3028     .type           = POWER_SUPPLY_TYPE_BATTERY,
3029     .properties     = ab8500_fg_props,
3030     .num_properties     = ARRAY_SIZE(ab8500_fg_props),
3031     .get_property       = ab8500_fg_get_property,
3032     .external_power_changed = ab8500_fg_external_power_changed,
3033 };
3034 
3035 static int ab8500_fg_bind(struct device *dev, struct device *master,
3036               void *data)
3037 {
3038     struct ab8500_fg *di = dev_get_drvdata(dev);
3039 
3040     di->bat_cap.max_mah_design = di->bm->bi->charge_full_design_uah;
3041     di->bat_cap.max_mah = di->bat_cap.max_mah_design;
3042     di->vbat_nom_uv = di->bm->bi->voltage_max_design_uv;
3043 
3044     /* Start the coulomb counter */
3045     ab8500_fg_coulomb_counter(di, true);
3046     /* Run the FG algorithm */
3047     queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
3048 
3049     return 0;
3050 }
3051 
3052 static void ab8500_fg_unbind(struct device *dev, struct device *master,
3053                  void *data)
3054 {
3055     struct ab8500_fg *di = dev_get_drvdata(dev);
3056     int ret;
3057 
3058     /* Disable coulomb counter */
3059     ret = ab8500_fg_coulomb_counter(di, false);
3060     if (ret)
3061         dev_err(dev, "failed to disable coulomb counter\n");
3062 
3063     flush_workqueue(di->fg_wq);
3064 }
3065 
3066 static const struct component_ops ab8500_fg_component_ops = {
3067     .bind = ab8500_fg_bind,
3068     .unbind = ab8500_fg_unbind,
3069 };
3070 
3071 static int ab8500_fg_probe(struct platform_device *pdev)
3072 {
3073     struct device *dev = &pdev->dev;
3074     struct power_supply_config psy_cfg = {};
3075     struct ab8500_fg *di;
3076     int i, irq;
3077     int ret = 0;
3078 
3079     di = devm_kzalloc(dev, sizeof(*di), GFP_KERNEL);
3080     if (!di)
3081         return -ENOMEM;
3082 
3083     di->bm = &ab8500_bm_data;
3084 
3085     mutex_init(&di->cc_lock);
3086 
3087     /* get parent data */
3088     di->dev = dev;
3089     di->parent = dev_get_drvdata(pdev->dev.parent);
3090 
3091     di->main_bat_v = devm_iio_channel_get(dev, "main_bat_v");
3092     if (IS_ERR(di->main_bat_v)) {
3093         ret = dev_err_probe(dev, PTR_ERR(di->main_bat_v),
3094                     "failed to get main battery ADC channel\n");
3095         return ret;
3096     }
3097 
3098     if (!of_property_read_u32(dev->of_node, "line-impedance-micro-ohms",
3099                   &di->line_impedance_uohm))
3100         dev_info(dev, "line impedance: %u uOhm\n",
3101              di->line_impedance_uohm);
3102 
3103     psy_cfg.supplied_to = supply_interface;
3104     psy_cfg.num_supplicants = ARRAY_SIZE(supply_interface);
3105     psy_cfg.drv_data = di;
3106 
3107     di->init_capacity = true;
3108 
3109     ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
3110     ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
3111 
3112     /* Create a work queue for running the FG algorithm */
3113     di->fg_wq = alloc_ordered_workqueue("ab8500_fg_wq", WQ_MEM_RECLAIM);
3114     if (di->fg_wq == NULL) {
3115         dev_err(dev, "failed to create work queue\n");
3116         return -ENOMEM;
3117     }
3118 
3119     /* Init work for running the fg algorithm instantly */
3120     INIT_WORK(&di->fg_work, ab8500_fg_instant_work);
3121 
3122     /* Init work for getting the battery accumulated current */
3123     INIT_WORK(&di->fg_acc_cur_work, ab8500_fg_acc_cur_work);
3124 
3125     /* Init work for reinitialising the fg algorithm */
3126     INIT_DEFERRABLE_WORK(&di->fg_reinit_work,
3127         ab8500_fg_reinit_work);
3128 
3129     /* Work delayed Queue to run the state machine */
3130     INIT_DEFERRABLE_WORK(&di->fg_periodic_work,
3131         ab8500_fg_periodic_work);
3132 
3133     /* Work to check low battery condition */
3134     INIT_DEFERRABLE_WORK(&di->fg_low_bat_work,
3135         ab8500_fg_low_bat_work);
3136 
3137     /* Init work for HW failure check */
3138     INIT_DEFERRABLE_WORK(&di->fg_check_hw_failure_work,
3139         ab8500_fg_check_hw_failure_work);
3140 
3141     /* Reset battery low voltage flag */
3142     di->flags.low_bat = false;
3143 
3144     /* Initialize low battery counter */
3145     di->low_bat_cnt = 10;
3146 
3147     /* Initialize OVV, and other registers */
3148     ret = ab8500_fg_init_hw_registers(di);
3149     if (ret) {
3150         dev_err(dev, "failed to initialize registers\n");
3151         destroy_workqueue(di->fg_wq);
3152         return ret;
3153     }
3154 
3155     /* Consider battery unknown until we're informed otherwise */
3156     di->flags.batt_unknown = true;
3157     di->flags.batt_id_received = false;
3158 
3159     /* Register FG power supply class */
3160     di->fg_psy = devm_power_supply_register(dev, &ab8500_fg_desc, &psy_cfg);
3161     if (IS_ERR(di->fg_psy)) {
3162         dev_err(dev, "failed to register FG psy\n");
3163         destroy_workqueue(di->fg_wq);
3164         return PTR_ERR(di->fg_psy);
3165     }
3166 
3167     di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
3168 
3169     /*
3170      * Initialize completion used to notify completion and start
3171      * of inst current
3172      */
3173     init_completion(&di->ab8500_fg_started);
3174     init_completion(&di->ab8500_fg_complete);
3175 
3176     /* Register primary interrupt handlers */
3177     for (i = 0; i < ARRAY_SIZE(ab8500_fg_irq); i++) {
3178         irq = platform_get_irq_byname(pdev, ab8500_fg_irq[i].name);
3179         if (irq < 0) {
3180             destroy_workqueue(di->fg_wq);
3181             return irq;
3182         }
3183 
3184         ret = devm_request_threaded_irq(dev, irq, NULL,
3185                   ab8500_fg_irq[i].isr,
3186                   IRQF_SHARED | IRQF_NO_SUSPEND | IRQF_ONESHOT,
3187                   ab8500_fg_irq[i].name, di);
3188 
3189         if (ret != 0) {
3190             dev_err(dev, "failed to request %s IRQ %d: %d\n",
3191                 ab8500_fg_irq[i].name, irq, ret);
3192             destroy_workqueue(di->fg_wq);
3193             return ret;
3194         }
3195         dev_dbg(dev, "Requested %s IRQ %d: %d\n",
3196             ab8500_fg_irq[i].name, irq, ret);
3197     }
3198 
3199     di->irq = platform_get_irq_byname(pdev, "CCEOC");
3200     disable_irq(di->irq);
3201     di->nbr_cceoc_irq_cnt = 0;
3202 
3203     platform_set_drvdata(pdev, di);
3204 
3205     ret = ab8500_fg_sysfs_init(di);
3206     if (ret) {
3207         dev_err(dev, "failed to create sysfs entry\n");
3208         destroy_workqueue(di->fg_wq);
3209         return ret;
3210     }
3211 
3212     ret = ab8500_fg_sysfs_psy_create_attrs(di);
3213     if (ret) {
3214         dev_err(dev, "failed to create FG psy\n");
3215         ab8500_fg_sysfs_exit(di);
3216         destroy_workqueue(di->fg_wq);
3217         return ret;
3218     }
3219 
3220     /* Calibrate the fg first time */
3221     di->flags.calibrate = true;
3222     di->calib_state = AB8500_FG_CALIB_INIT;
3223 
3224     /* Use room temp as default value until we get an update from driver. */
3225     di->bat_temp = 210;
3226 
3227     list_add_tail(&di->node, &ab8500_fg_list);
3228 
3229     return component_add(dev, &ab8500_fg_component_ops);
3230 }
3231 
3232 static int ab8500_fg_remove(struct platform_device *pdev)
3233 {
3234     struct ab8500_fg *di = platform_get_drvdata(pdev);
3235 
3236     destroy_workqueue(di->fg_wq);
3237     component_del(&pdev->dev, &ab8500_fg_component_ops);
3238     list_del(&di->node);
3239     ab8500_fg_sysfs_exit(di);
3240     ab8500_fg_sysfs_psy_remove_attrs(di);
3241 
3242     return 0;
3243 }
3244 
3245 static SIMPLE_DEV_PM_OPS(ab8500_fg_pm_ops, ab8500_fg_suspend, ab8500_fg_resume);
3246 
3247 static const struct of_device_id ab8500_fg_match[] = {
3248     { .compatible = "stericsson,ab8500-fg", },
3249     { },
3250 };
3251 MODULE_DEVICE_TABLE(of, ab8500_fg_match);
3252 
3253 struct platform_driver ab8500_fg_driver = {
3254     .probe = ab8500_fg_probe,
3255     .remove = ab8500_fg_remove,
3256     .driver = {
3257         .name = "ab8500-fg",
3258         .of_match_table = ab8500_fg_match,
3259         .pm = &ab8500_fg_pm_ops,
3260     },
3261 };
3262 MODULE_LICENSE("GPL v2");
3263 MODULE_AUTHOR("Johan Palsson, Karl Komierowski");
3264 MODULE_ALIAS("platform:ab8500-fg");
3265 MODULE_DESCRIPTION("AB8500 Fuel Gauge driver");