linux/drivers/power/ab8500_fg.c
<<
>>
Prefs
   1/*
   2 * Copyright (C) ST-Ericsson AB 2012
   3 *
   4 * Main and Back-up battery management driver.
   5 *
   6 * Note: Backup battery management is required in case of Li-Ion battery and not
   7 * for capacitive battery. HREF boards have capacitive battery and hence backup
   8 * battery management is not used and the supported code is available in this
   9 * driver.
  10 *
  11 * License Terms: GNU General Public License v2
  12 * Author:
  13 *      Johan Palsson <johan.palsson@stericsson.com>
  14 *      Karl Komierowski <karl.komierowski@stericsson.com>
  15 *      Arun R Murthy <arun.murthy@stericsson.com>
  16 */
  17
  18#include <linux/init.h>
  19#include <linux/module.h>
  20#include <linux/device.h>
  21#include <linux/interrupt.h>
  22#include <linux/platform_device.h>
  23#include <linux/power_supply.h>
  24#include <linux/kobject.h>
  25#include <linux/slab.h>
  26#include <linux/delay.h>
  27#include <linux/time.h>
  28#include <linux/of.h>
  29#include <linux/completion.h>
  30#include <linux/mfd/core.h>
  31#include <linux/mfd/abx500.h>
  32#include <linux/mfd/abx500/ab8500.h>
  33#include <linux/mfd/abx500/ab8500-bm.h>
  34#include <linux/mfd/abx500/ab8500-gpadc.h>
  35
  36#define MILLI_TO_MICRO                  1000
  37#define FG_LSB_IN_MA                    1627
  38#define QLSB_NANO_AMP_HOURS_X10         1129
  39#define INS_CURR_TIMEOUT                (3 * HZ)
  40
  41#define SEC_TO_SAMPLE(S)                (S * 4)
  42
  43#define NBR_AVG_SAMPLES                 20
  44
  45#define LOW_BAT_CHECK_INTERVAL          (2 * HZ)
  46
  47#define VALID_CAPACITY_SEC              (45 * 60) /* 45 minutes */
  48#define BATT_OK_MIN                     2360 /* mV */
  49#define BATT_OK_INCREMENT               50 /* mV */
  50#define BATT_OK_MAX_NR_INCREMENTS       0xE
  51
  52/* FG constants */
  53#define BATT_OVV                        0x01
  54
  55#define interpolate(x, x1, y1, x2, y2) \
  56        ((y1) + ((((y2) - (y1)) * ((x) - (x1))) / ((x2) - (x1))));
  57
  58#define to_ab8500_fg_device_info(x) container_of((x), \
  59        struct ab8500_fg, fg_psy);
  60
  61/**
  62 * struct ab8500_fg_interrupts - ab8500 fg interupts
  63 * @name:       name of the interrupt
  64 * @isr         function pointer to the isr
  65 */
  66struct ab8500_fg_interrupts {
  67        char *name;
  68        irqreturn_t (*isr)(int irq, void *data);
  69};
  70
  71enum ab8500_fg_discharge_state {
  72        AB8500_FG_DISCHARGE_INIT,
  73        AB8500_FG_DISCHARGE_INITMEASURING,
  74        AB8500_FG_DISCHARGE_INIT_RECOVERY,
  75        AB8500_FG_DISCHARGE_RECOVERY,
  76        AB8500_FG_DISCHARGE_READOUT_INIT,
  77        AB8500_FG_DISCHARGE_READOUT,
  78        AB8500_FG_DISCHARGE_WAKEUP,
  79};
  80
  81static char *discharge_state[] = {
  82        "DISCHARGE_INIT",
  83        "DISCHARGE_INITMEASURING",
  84        "DISCHARGE_INIT_RECOVERY",
  85        "DISCHARGE_RECOVERY",
  86        "DISCHARGE_READOUT_INIT",
  87        "DISCHARGE_READOUT",
  88        "DISCHARGE_WAKEUP",
  89};
  90
  91enum ab8500_fg_charge_state {
  92        AB8500_FG_CHARGE_INIT,
  93        AB8500_FG_CHARGE_READOUT,
  94};
  95
  96static char *charge_state[] = {
  97        "CHARGE_INIT",
  98        "CHARGE_READOUT",
  99};
 100
 101enum ab8500_fg_calibration_state {
 102        AB8500_FG_CALIB_INIT,
 103        AB8500_FG_CALIB_WAIT,
 104        AB8500_FG_CALIB_END,
 105};
 106
 107struct ab8500_fg_avg_cap {
 108        int avg;
 109        int samples[NBR_AVG_SAMPLES];
 110        __kernel_time_t time_stamps[NBR_AVG_SAMPLES];
 111        int pos;
 112        int nbr_samples;
 113        int sum;
 114};
 115
 116struct ab8500_fg_battery_capacity {
 117        int max_mah_design;
 118        int max_mah;
 119        int mah;
 120        int permille;
 121        int level;
 122        int prev_mah;
 123        int prev_percent;
 124        int prev_level;
 125        int user_mah;
 126};
 127
 128struct ab8500_fg_flags {
 129        bool fg_enabled;
 130        bool conv_done;
 131        bool charging;
 132        bool fully_charged;
 133        bool force_full;
 134        bool low_bat_delay;
 135        bool low_bat;
 136        bool bat_ovv;
 137        bool batt_unknown;
 138        bool calibrate;
 139        bool user_cap;
 140        bool batt_id_received;
 141};
 142
 143struct inst_curr_result_list {
 144        struct list_head list;
 145        int *result;
 146};
 147
 148/**
 149 * struct ab8500_fg - ab8500 FG device information
 150 * @dev:                Pointer to the structure device
 151 * @node:               a list of AB8500 FGs, hence prepared for reentrance
 152 * @irq                 holds the CCEOC interrupt number
 153 * @vbat:               Battery voltage in mV
 154 * @vbat_nom:           Nominal battery voltage in mV
 155 * @inst_curr:          Instantenous battery current in mA
 156 * @avg_curr:           Average battery current in mA
 157 * @bat_temp            battery temperature
 158 * @fg_samples:         Number of samples used in the FG accumulation
 159 * @accu_charge:        Accumulated charge from the last conversion
 160 * @recovery_cnt:       Counter for recovery mode
 161 * @high_curr_cnt:      Counter for high current mode
 162 * @init_cnt:           Counter for init mode
 163 * @recovery_needed:    Indicate if recovery is needed
 164 * @high_curr_mode:     Indicate if we're in high current mode
 165 * @init_capacity:      Indicate if initial capacity measuring should be done
 166 * @turn_off_fg:        True if fg was off before current measurement
 167 * @calib_state         State during offset calibration
 168 * @discharge_state:    Current discharge state
 169 * @charge_state:       Current charge state
 170 * @ab8500_fg_complete  Completion struct used for the instant current reading
 171 * @flags:              Structure for information about events triggered
 172 * @bat_cap:            Structure for battery capacity specific parameters
 173 * @avg_cap:            Average capacity filter
 174 * @parent:             Pointer to the struct ab8500
 175 * @gpadc:              Pointer to the struct gpadc
 176 * @bat:                Pointer to the abx500_bm platform data
 177 * @fg_psy:             Structure that holds the FG specific battery properties
 178 * @fg_wq:              Work queue for running the FG algorithm
 179 * @fg_periodic_work:   Work to run the FG algorithm periodically
 180 * @fg_low_bat_work:    Work to check low bat condition
 181 * @fg_reinit_work      Work used to reset and reinitialise the FG algorithm
 182 * @fg_work:            Work to run the FG algorithm instantly
 183 * @fg_acc_cur_work:    Work to read the FG accumulator
 184 * @fg_check_hw_failure_work:   Work for checking HW state
 185 * @cc_lock:            Mutex for locking the CC
 186 * @fg_kobject:         Structure of type kobject
 187 */
 188struct ab8500_fg {
 189        struct device *dev;
 190        struct list_head node;
 191        int irq;
 192        int vbat;
 193        int vbat_nom;
 194        int inst_curr;
 195        int avg_curr;
 196        int bat_temp;
 197        int fg_samples;
 198        int accu_charge;
 199        int recovery_cnt;
 200        int high_curr_cnt;
 201        int init_cnt;
 202        bool recovery_needed;
 203        bool high_curr_mode;
 204        bool init_capacity;
 205        bool turn_off_fg;
 206        enum ab8500_fg_calibration_state calib_state;
 207        enum ab8500_fg_discharge_state discharge_state;
 208        enum ab8500_fg_charge_state charge_state;
 209        struct completion ab8500_fg_complete;
 210        struct ab8500_fg_flags flags;
 211        struct ab8500_fg_battery_capacity bat_cap;
 212        struct ab8500_fg_avg_cap avg_cap;
 213        struct ab8500 *parent;
 214        struct ab8500_gpadc *gpadc;
 215        struct abx500_bm_data *bat;
 216        struct power_supply fg_psy;
 217        struct workqueue_struct *fg_wq;
 218        struct delayed_work fg_periodic_work;
 219        struct delayed_work fg_low_bat_work;
 220        struct delayed_work fg_reinit_work;
 221        struct work_struct fg_work;
 222        struct work_struct fg_acc_cur_work;
 223        struct delayed_work fg_check_hw_failure_work;
 224        struct mutex cc_lock;
 225        struct kobject fg_kobject;
 226};
 227static LIST_HEAD(ab8500_fg_list);
 228
 229/**
 230 * ab8500_fg_get() - returns a reference to the primary AB8500 fuel gauge
 231 * (i.e. the first fuel gauge in the instance list)
 232 */
 233struct ab8500_fg *ab8500_fg_get(void)
 234{
 235        struct ab8500_fg *fg;
 236
 237        if (list_empty(&ab8500_fg_list))
 238                return NULL;
 239
 240        fg = list_first_entry(&ab8500_fg_list, struct ab8500_fg, node);
 241        return fg;
 242}
 243
 244/* Main battery properties */
 245static enum power_supply_property ab8500_fg_props[] = {
 246        POWER_SUPPLY_PROP_VOLTAGE_NOW,
 247        POWER_SUPPLY_PROP_CURRENT_NOW,
 248        POWER_SUPPLY_PROP_CURRENT_AVG,
 249        POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
 250        POWER_SUPPLY_PROP_ENERGY_FULL,
 251        POWER_SUPPLY_PROP_ENERGY_NOW,
 252        POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
 253        POWER_SUPPLY_PROP_CHARGE_FULL,
 254        POWER_SUPPLY_PROP_CHARGE_NOW,
 255        POWER_SUPPLY_PROP_CAPACITY,
 256        POWER_SUPPLY_PROP_CAPACITY_LEVEL,
 257};
 258
 259/*
 260 * This array maps the raw hex value to lowbat voltage used by the AB8500
 261 * Values taken from the UM0836
 262 */
 263static int ab8500_fg_lowbat_voltage_map[] = {
 264        2300 ,
 265        2325 ,
 266        2350 ,
 267        2375 ,
 268        2400 ,
 269        2425 ,
 270        2450 ,
 271        2475 ,
 272        2500 ,
 273        2525 ,
 274        2550 ,
 275        2575 ,
 276        2600 ,
 277        2625 ,
 278        2650 ,
 279        2675 ,
 280        2700 ,
 281        2725 ,
 282        2750 ,
 283        2775 ,
 284        2800 ,
 285        2825 ,
 286        2850 ,
 287        2875 ,
 288        2900 ,
 289        2925 ,
 290        2950 ,
 291        2975 ,
 292        3000 ,
 293        3025 ,
 294        3050 ,
 295        3075 ,
 296        3100 ,
 297        3125 ,
 298        3150 ,
 299        3175 ,
 300        3200 ,
 301        3225 ,
 302        3250 ,
 303        3275 ,
 304        3300 ,
 305        3325 ,
 306        3350 ,
 307        3375 ,
 308        3400 ,
 309        3425 ,
 310        3450 ,
 311        3475 ,
 312        3500 ,
 313        3525 ,
 314        3550 ,
 315        3575 ,
 316        3600 ,
 317        3625 ,
 318        3650 ,
 319        3675 ,
 320        3700 ,
 321        3725 ,
 322        3750 ,
 323        3775 ,
 324        3800 ,
 325        3825 ,
 326        3850 ,
 327        3850 ,
 328};
 329
 330static u8 ab8500_volt_to_regval(int voltage)
 331{
 332        int i;
 333
 334        if (voltage < ab8500_fg_lowbat_voltage_map[0])
 335                return 0;
 336
 337        for (i = 0; i < ARRAY_SIZE(ab8500_fg_lowbat_voltage_map); i++) {
 338                if (voltage < ab8500_fg_lowbat_voltage_map[i])
 339                        return (u8) i - 1;
 340        }
 341
 342        /* If not captured above, return index of last element */
 343        return (u8) ARRAY_SIZE(ab8500_fg_lowbat_voltage_map) - 1;
 344}
 345
 346/**
 347 * ab8500_fg_is_low_curr() - Low or high current mode
 348 * @di:         pointer to the ab8500_fg structure
 349 * @curr:       the current to base or our decision on
 350 *
 351 * Low current mode if the current consumption is below a certain threshold
 352 */
 353static int ab8500_fg_is_low_curr(struct ab8500_fg *di, int curr)
 354{
 355        /*
 356         * We want to know if we're in low current mode
 357         */
 358        if (curr > -di->bat->fg_params->high_curr_threshold)
 359                return true;
 360        else
 361                return false;
 362}
 363
 364/**
 365 * ab8500_fg_add_cap_sample() - Add capacity to average filter
 366 * @di:         pointer to the ab8500_fg structure
 367 * @sample:     the capacity in mAh to add to the filter
 368 *
 369 * A capacity is added to the filter and a new mean capacity is calculated and
 370 * returned
 371 */
 372static int ab8500_fg_add_cap_sample(struct ab8500_fg *di, int sample)
 373{
 374        struct timespec ts;
 375        struct ab8500_fg_avg_cap *avg = &di->avg_cap;
 376
 377        getnstimeofday(&ts);
 378
 379        do {
 380                avg->sum += sample - avg->samples[avg->pos];
 381                avg->samples[avg->pos] = sample;
 382                avg->time_stamps[avg->pos] = ts.tv_sec;
 383                avg->pos++;
 384
 385                if (avg->pos == NBR_AVG_SAMPLES)
 386                        avg->pos = 0;
 387
 388                if (avg->nbr_samples < NBR_AVG_SAMPLES)
 389                        avg->nbr_samples++;
 390
 391                /*
 392                 * Check the time stamp for each sample. If too old,
 393                 * replace with latest sample
 394                 */
 395        } while (ts.tv_sec - VALID_CAPACITY_SEC > avg->time_stamps[avg->pos]);
 396
 397        avg->avg = avg->sum / avg->nbr_samples;
 398
 399        return avg->avg;
 400}
 401
 402/**
 403 * ab8500_fg_clear_cap_samples() - Clear average filter
 404 * @di:         pointer to the ab8500_fg structure
 405 *
 406 * The capacity filter is is reset to zero.
 407 */
 408static void ab8500_fg_clear_cap_samples(struct ab8500_fg *di)
 409{
 410        int i;
 411        struct ab8500_fg_avg_cap *avg = &di->avg_cap;
 412
 413        avg->pos = 0;
 414        avg->nbr_samples = 0;
 415        avg->sum = 0;
 416        avg->avg = 0;
 417
 418        for (i = 0; i < NBR_AVG_SAMPLES; i++) {
 419                avg->samples[i] = 0;
 420                avg->time_stamps[i] = 0;
 421        }
 422}
 423
 424/**
 425 * ab8500_fg_fill_cap_sample() - Fill average filter
 426 * @di:         pointer to the ab8500_fg structure
 427 * @sample:     the capacity in mAh to fill the filter with
 428 *
 429 * The capacity filter is filled with a capacity in mAh
 430 */
 431static void ab8500_fg_fill_cap_sample(struct ab8500_fg *di, int sample)
 432{
 433        int i;
 434        struct timespec ts;
 435        struct ab8500_fg_avg_cap *avg = &di->avg_cap;
 436
 437        getnstimeofday(&ts);
 438
 439        for (i = 0; i < NBR_AVG_SAMPLES; i++) {
 440                avg->samples[i] = sample;
 441                avg->time_stamps[i] = ts.tv_sec;
 442        }
 443
 444        avg->pos = 0;
 445        avg->nbr_samples = NBR_AVG_SAMPLES;
 446        avg->sum = sample * NBR_AVG_SAMPLES;
 447        avg->avg = sample;
 448}
 449
 450/**
 451 * ab8500_fg_coulomb_counter() - enable coulomb counter
 452 * @di:         pointer to the ab8500_fg structure
 453 * @enable:     enable/disable
 454 *
 455 * Enable/Disable coulomb counter.
 456 * On failure returns negative value.
 457 */
 458static int ab8500_fg_coulomb_counter(struct ab8500_fg *di, bool enable)
 459{
 460        int ret = 0;
 461        mutex_lock(&di->cc_lock);
 462        if (enable) {
 463                /* To be able to reprogram the number of samples, we have to
 464                 * first stop the CC and then enable it again */
 465                ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
 466                        AB8500_RTC_CC_CONF_REG, 0x00);
 467                if (ret)
 468                        goto cc_err;
 469
 470                /* Program the samples */
 471                ret = abx500_set_register_interruptible(di->dev,
 472                        AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
 473                        di->fg_samples);
 474                if (ret)
 475                        goto cc_err;
 476
 477                /* Start the CC */
 478                ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
 479                        AB8500_RTC_CC_CONF_REG,
 480                        (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
 481                if (ret)
 482                        goto cc_err;
 483
 484                di->flags.fg_enabled = true;
 485        } else {
 486                /* Clear any pending read requests */
 487                ret = abx500_set_register_interruptible(di->dev,
 488                        AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG, 0);
 489                if (ret)
 490                        goto cc_err;
 491
 492                ret = abx500_set_register_interruptible(di->dev,
 493                        AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU_CTRL, 0);
 494                if (ret)
 495                        goto cc_err;
 496
 497                /* Stop the CC */
 498                ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
 499                        AB8500_RTC_CC_CONF_REG, 0);
 500                if (ret)
 501                        goto cc_err;
 502
 503                di->flags.fg_enabled = false;
 504
 505        }
 506        dev_dbg(di->dev, " CC enabled: %d Samples: %d\n",
 507                enable, di->fg_samples);
 508
 509        mutex_unlock(&di->cc_lock);
 510
 511        return ret;
 512cc_err:
 513        dev_err(di->dev, "%s Enabling coulomb counter failed\n", __func__);
 514        mutex_unlock(&di->cc_lock);
 515        return ret;
 516}
 517
 518/**
 519 * ab8500_fg_inst_curr_start() - start battery instantaneous current
 520 * @di:         pointer to the ab8500_fg structure
 521 *
 522 * Returns 0 or error code
 523 * Note: This is part "one" and has to be called before
 524 * ab8500_fg_inst_curr_finalize()
 525 */
 526 int ab8500_fg_inst_curr_start(struct ab8500_fg *di)
 527{
 528        u8 reg_val;
 529        int ret;
 530
 531        mutex_lock(&di->cc_lock);
 532
 533        ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
 534                AB8500_RTC_CC_CONF_REG, &reg_val);
 535        if (ret < 0)
 536                goto fail;
 537
 538        if (!(reg_val & CC_PWR_UP_ENA)) {
 539                dev_dbg(di->dev, "%s Enable FG\n", __func__);
 540                di->turn_off_fg = true;
 541
 542                /* Program the samples */
 543                ret = abx500_set_register_interruptible(di->dev,
 544                        AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
 545                        SEC_TO_SAMPLE(10));
 546                if (ret)
 547                        goto fail;
 548
 549                /* Start the CC */
 550                ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
 551                        AB8500_RTC_CC_CONF_REG,
 552                        (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
 553                if (ret)
 554                        goto fail;
 555        } else {
 556                di->turn_off_fg = false;
 557        }
 558
 559        /* Return and WFI */
 560        INIT_COMPLETION(di->ab8500_fg_complete);
 561        enable_irq(di->irq);
 562
 563        /* Note: cc_lock is still locked */
 564        return 0;
 565fail:
 566        mutex_unlock(&di->cc_lock);
 567        return ret;
 568}
 569
 570/**
 571 * ab8500_fg_inst_curr_done() - check if fg conversion is done
 572 * @di:         pointer to the ab8500_fg structure
 573 *
 574 * Returns 1 if conversion done, 0 if still waiting
 575 */
 576int ab8500_fg_inst_curr_done(struct ab8500_fg *di)
 577{
 578        return completion_done(&di->ab8500_fg_complete);
 579}
 580
 581/**
 582 * ab8500_fg_inst_curr_finalize() - battery instantaneous current
 583 * @di:         pointer to the ab8500_fg structure
 584 * @res:        battery instantenous current(on success)
 585 *
 586 * Returns 0 or an error code
 587 * Note: This is part "two" and has to be called at earliest 250 ms
 588 * after ab8500_fg_inst_curr_start()
 589 */
 590int ab8500_fg_inst_curr_finalize(struct ab8500_fg *di, int *res)
 591{
 592        u8 low, high;
 593        int val;
 594        int ret;
 595        int timeout;
 596
 597        if (!completion_done(&di->ab8500_fg_complete)) {
 598                timeout = wait_for_completion_timeout(&di->ab8500_fg_complete,
 599                        INS_CURR_TIMEOUT);
 600                dev_dbg(di->dev, "Finalize time: %d ms\n",
 601                        ((INS_CURR_TIMEOUT - timeout) * 1000) / HZ);
 602                if (!timeout) {
 603                        ret = -ETIME;
 604                        disable_irq(di->irq);
 605                        dev_err(di->dev, "completion timed out [%d]\n",
 606                                __LINE__);
 607                        goto fail;
 608                }
 609        }
 610
 611        disable_irq(di->irq);
 612
 613        ret = abx500_mask_and_set_register_interruptible(di->dev,
 614                        AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
 615                        READ_REQ, READ_REQ);
 616
 617        /* 100uS between read request and read is needed */
 618        usleep_range(100, 100);
 619
 620        /* Read CC Sample conversion value Low and high */
 621        ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 622                AB8500_GASG_CC_SMPL_CNVL_REG,  &low);
 623        if (ret < 0)
 624                goto fail;
 625
 626        ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 627                AB8500_GASG_CC_SMPL_CNVH_REG,  &high);
 628        if (ret < 0)
 629                goto fail;
 630
 631        /*
 632         * negative value for Discharging
 633         * convert 2's compliment into decimal
 634         */
 635        if (high & 0x10)
 636                val = (low | (high << 8) | 0xFFFFE000);
 637        else
 638                val = (low | (high << 8));
 639
 640        /*
 641         * Convert to unit value in mA
 642         * Full scale input voltage is
 643         * 66.660mV => LSB = 66.660mV/(4096*res) = 1.627mA
 644         * Given a 250ms conversion cycle time the LSB corresponds
 645         * to 112.9 nAh. Convert to current by dividing by the conversion
 646         * time in hours (250ms = 1 / (3600 * 4)h)
 647         * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
 648         */
 649        val = (val * QLSB_NANO_AMP_HOURS_X10 * 36 * 4) /
 650                (1000 * di->bat->fg_res);
 651
 652        if (di->turn_off_fg) {
 653                dev_dbg(di->dev, "%s Disable FG\n", __func__);
 654
 655                /* Clear any pending read requests */
 656                ret = abx500_set_register_interruptible(di->dev,
 657                        AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG, 0);
 658                if (ret)
 659                        goto fail;
 660
 661                /* Stop the CC */
 662                ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
 663                        AB8500_RTC_CC_CONF_REG, 0);
 664                if (ret)
 665                        goto fail;
 666        }
 667        mutex_unlock(&di->cc_lock);
 668        (*res) = val;
 669
 670        return 0;
 671fail:
 672        mutex_unlock(&di->cc_lock);
 673        return ret;
 674}
 675
 676/**
 677 * ab8500_fg_inst_curr_blocking() - battery instantaneous current
 678 * @di:         pointer to the ab8500_fg structure
 679 * @res:        battery instantenous current(on success)
 680 *
 681 * Returns 0 else error code
 682 */
 683int ab8500_fg_inst_curr_blocking(struct ab8500_fg *di)
 684{
 685        int ret;
 686        int res = 0;
 687
 688        ret = ab8500_fg_inst_curr_start(di);
 689        if (ret) {
 690                dev_err(di->dev, "Failed to initialize fg_inst\n");
 691                return 0;
 692        }
 693
 694        ret = ab8500_fg_inst_curr_finalize(di, &res);
 695        if (ret) {
 696                dev_err(di->dev, "Failed to finalize fg_inst\n");
 697                return 0;
 698        }
 699
 700        return res;
 701}
 702
 703/**
 704 * ab8500_fg_acc_cur_work() - average battery current
 705 * @work:       pointer to the work_struct structure
 706 *
 707 * Updated the average battery current obtained from the
 708 * coulomb counter.
 709 */
 710static void ab8500_fg_acc_cur_work(struct work_struct *work)
 711{
 712        int val;
 713        int ret;
 714        u8 low, med, high;
 715
 716        struct ab8500_fg *di = container_of(work,
 717                struct ab8500_fg, fg_acc_cur_work);
 718
 719        mutex_lock(&di->cc_lock);
 720        ret = abx500_set_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 721                AB8500_GASG_CC_NCOV_ACCU_CTRL, RD_NCONV_ACCU_REQ);
 722        if (ret)
 723                goto exit;
 724
 725        ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 726                AB8500_GASG_CC_NCOV_ACCU_LOW,  &low);
 727        if (ret < 0)
 728                goto exit;
 729
 730        ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 731                AB8500_GASG_CC_NCOV_ACCU_MED,  &med);
 732        if (ret < 0)
 733                goto exit;
 734
 735        ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 736                AB8500_GASG_CC_NCOV_ACCU_HIGH, &high);
 737        if (ret < 0)
 738                goto exit;
 739
 740        /* Check for sign bit in case of negative value, 2's compliment */
 741        if (high & 0x10)
 742                val = (low | (med << 8) | (high << 16) | 0xFFE00000);
 743        else
 744                val = (low | (med << 8) | (high << 16));
 745
 746        /*
 747         * Convert to uAh
 748         * Given a 250ms conversion cycle time the LSB corresponds
 749         * to 112.9 nAh.
 750         * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
 751         */
 752        di->accu_charge = (val * QLSB_NANO_AMP_HOURS_X10) /
 753                (100 * di->bat->fg_res);
 754
 755        /*
 756         * Convert to unit value in mA
 757         * Full scale input voltage is
 758         * 66.660mV => LSB = 66.660mV/(4096*res) = 1.627mA
 759         * Given a 250ms conversion cycle time the LSB corresponds
 760         * to 112.9 nAh. Convert to current by dividing by the conversion
 761         * time in hours (= samples / (3600 * 4)h)
 762         * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
 763         */
 764        di->avg_curr = (val * QLSB_NANO_AMP_HOURS_X10 * 36) /
 765                (1000 * di->bat->fg_res * (di->fg_samples / 4));
 766
 767        di->flags.conv_done = true;
 768
 769        mutex_unlock(&di->cc_lock);
 770
 771        queue_work(di->fg_wq, &di->fg_work);
 772
 773        return;
 774exit:
 775        dev_err(di->dev,
 776                "Failed to read or write gas gauge registers\n");
 777        mutex_unlock(&di->cc_lock);
 778        queue_work(di->fg_wq, &di->fg_work);
 779}
 780
 781/**
 782 * ab8500_fg_bat_voltage() - get battery voltage
 783 * @di:         pointer to the ab8500_fg structure
 784 *
 785 * Returns battery voltage(on success) else error code
 786 */
 787static int ab8500_fg_bat_voltage(struct ab8500_fg *di)
 788{
 789        int vbat;
 790        static int prev;
 791
 792        vbat = ab8500_gpadc_convert(di->gpadc, MAIN_BAT_V);
 793        if (vbat < 0) {
 794                dev_err(di->dev,
 795                        "%s gpadc conversion failed, using previous value\n",
 796                        __func__);
 797                return prev;
 798        }
 799
 800        prev = vbat;
 801        return vbat;
 802}
 803
 804/**
 805 * ab8500_fg_volt_to_capacity() - Voltage based capacity
 806 * @di:         pointer to the ab8500_fg structure
 807 * @voltage:    The voltage to convert to a capacity
 808 *
 809 * Returns battery capacity in per mille based on voltage
 810 */
 811static int ab8500_fg_volt_to_capacity(struct ab8500_fg *di, int voltage)
 812{
 813        int i, tbl_size;
 814        struct abx500_v_to_cap *tbl;
 815        int cap = 0;
 816
 817        tbl = di->bat->bat_type[di->bat->batt_id].v_to_cap_tbl,
 818        tbl_size = di->bat->bat_type[di->bat->batt_id].n_v_cap_tbl_elements;
 819
 820        for (i = 0; i < tbl_size; ++i) {
 821                if (voltage > tbl[i].voltage)
 822                        break;
 823        }
 824
 825        if ((i > 0) && (i < tbl_size)) {
 826                cap = interpolate(voltage,
 827                        tbl[i].voltage,
 828                        tbl[i].capacity * 10,
 829                        tbl[i-1].voltage,
 830                        tbl[i-1].capacity * 10);
 831        } else if (i == 0) {
 832                cap = 1000;
 833        } else {
 834                cap = 0;
 835        }
 836
 837        dev_dbg(di->dev, "%s Vbat: %d, Cap: %d per mille",
 838                __func__, voltage, cap);
 839
 840        return cap;
 841}
 842
 843/**
 844 * ab8500_fg_uncomp_volt_to_capacity() - Uncompensated voltage based capacity
 845 * @di:         pointer to the ab8500_fg structure
 846 *
 847 * Returns battery capacity based on battery voltage that is not compensated
 848 * for the voltage drop due to the load
 849 */
 850static int ab8500_fg_uncomp_volt_to_capacity(struct ab8500_fg *di)
 851{
 852        di->vbat = ab8500_fg_bat_voltage(di);
 853        return ab8500_fg_volt_to_capacity(di, di->vbat);
 854}
 855
 856/**
 857 * ab8500_fg_battery_resistance() - Returns the battery inner resistance
 858 * @di:         pointer to the ab8500_fg structure
 859 *
 860 * Returns battery inner resistance added with the fuel gauge resistor value
 861 * to get the total resistance in the whole link from gnd to bat+ node.
 862 */
 863static int ab8500_fg_battery_resistance(struct ab8500_fg *di)
 864{
 865        int i, tbl_size;
 866        struct batres_vs_temp *tbl;
 867        int resist = 0;
 868
 869        tbl = di->bat->bat_type[di->bat->batt_id].batres_tbl;
 870        tbl_size = di->bat->bat_type[di->bat->batt_id].n_batres_tbl_elements;
 871
 872        for (i = 0; i < tbl_size; ++i) {
 873                if (di->bat_temp / 10 > tbl[i].temp)
 874                        break;
 875        }
 876
 877        if ((i > 0) && (i < tbl_size)) {
 878                resist = interpolate(di->bat_temp / 10,
 879                        tbl[i].temp,
 880                        tbl[i].resist,
 881                        tbl[i-1].temp,
 882                        tbl[i-1].resist);
 883        } else if (i == 0) {
 884                resist = tbl[0].resist;
 885        } else {
 886                resist = tbl[tbl_size - 1].resist;
 887        }
 888
 889        dev_dbg(di->dev, "%s Temp: %d battery internal resistance: %d"
 890            " fg resistance %d, total: %d (mOhm)\n",
 891                __func__, di->bat_temp, resist, di->bat->fg_res / 10,
 892                (di->bat->fg_res / 10) + resist);
 893
 894        /* fg_res variable is in 0.1mOhm */
 895        resist += di->bat->fg_res / 10;
 896
 897        return resist;
 898}
 899
 900/**
 901 * ab8500_fg_load_comp_volt_to_capacity() - Load compensated voltage based capacity
 902 * @di:         pointer to the ab8500_fg structure
 903 *
 904 * Returns battery capacity based on battery voltage that is load compensated
 905 * for the voltage drop
 906 */
 907static int ab8500_fg_load_comp_volt_to_capacity(struct ab8500_fg *di)
 908{
 909        int vbat_comp, res;
 910        int i = 0;
 911        int vbat = 0;
 912
 913        ab8500_fg_inst_curr_start(di);
 914
 915        do {
 916                vbat += ab8500_fg_bat_voltage(di);
 917                i++;
 918                msleep(5);
 919        } while (!ab8500_fg_inst_curr_done(di));
 920
 921        ab8500_fg_inst_curr_finalize(di, &di->inst_curr);
 922
 923        di->vbat = vbat / i;
 924        res = ab8500_fg_battery_resistance(di);
 925
 926        /* Use Ohms law to get the load compensated voltage */
 927        vbat_comp = di->vbat - (di->inst_curr * res) / 1000;
 928
 929        dev_dbg(di->dev, "%s Measured Vbat: %dmV,Compensated Vbat %dmV, "
 930                "R: %dmOhm, Current: %dmA Vbat Samples: %d\n",
 931                __func__, di->vbat, vbat_comp, res, di->inst_curr, i);
 932
 933        return ab8500_fg_volt_to_capacity(di, vbat_comp);
 934}
 935
 936/**
 937 * ab8500_fg_convert_mah_to_permille() - Capacity in mAh to permille
 938 * @di:         pointer to the ab8500_fg structure
 939 * @cap_mah:    capacity in mAh
 940 *
 941 * Converts capacity in mAh to capacity in permille
 942 */
 943static int ab8500_fg_convert_mah_to_permille(struct ab8500_fg *di, int cap_mah)
 944{
 945        return (cap_mah * 1000) / di->bat_cap.max_mah_design;
 946}
 947
 948/**
 949 * ab8500_fg_convert_permille_to_mah() - Capacity in permille to mAh
 950 * @di:         pointer to the ab8500_fg structure
 951 * @cap_pm:     capacity in permille
 952 *
 953 * Converts capacity in permille to capacity in mAh
 954 */
 955static int ab8500_fg_convert_permille_to_mah(struct ab8500_fg *di, int cap_pm)
 956{
 957        return cap_pm * di->bat_cap.max_mah_design / 1000;
 958}
 959
 960/**
 961 * ab8500_fg_convert_mah_to_uwh() - Capacity in mAh to uWh
 962 * @di:         pointer to the ab8500_fg structure
 963 * @cap_mah:    capacity in mAh
 964 *
 965 * Converts capacity in mAh to capacity in uWh
 966 */
 967static int ab8500_fg_convert_mah_to_uwh(struct ab8500_fg *di, int cap_mah)
 968{
 969        u64 div_res;
 970        u32 div_rem;
 971
 972        div_res = ((u64) cap_mah) * ((u64) di->vbat_nom);
 973        div_rem = do_div(div_res, 1000);
 974
 975        /* Make sure to round upwards if necessary */
 976        if (div_rem >= 1000 / 2)
 977                div_res++;
 978
 979        return (int) div_res;
 980}
 981
 982/**
 983 * ab8500_fg_calc_cap_charging() - Calculate remaining capacity while charging
 984 * @di:         pointer to the ab8500_fg structure
 985 *
 986 * Return the capacity in mAh based on previous calculated capcity and the FG
 987 * accumulator register value. The filter is filled with this capacity
 988 */
 989static int ab8500_fg_calc_cap_charging(struct ab8500_fg *di)
 990{
 991        dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
 992                __func__,
 993                di->bat_cap.mah,
 994                di->accu_charge);
 995
 996        /* Capacity should not be less than 0 */
 997        if (di->bat_cap.mah + di->accu_charge > 0)
 998                di->bat_cap.mah += di->accu_charge;
 999        else
1000                di->bat_cap.mah = 0;
1001        /*
1002         * We force capacity to 100% once when the algorithm
1003         * reports that it's full.
1004         */
1005        if (di->bat_cap.mah >= di->bat_cap.max_mah_design ||
1006                di->flags.force_full) {
1007                di->bat_cap.mah = di->bat_cap.max_mah_design;
1008        }
1009
1010        ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1011        di->bat_cap.permille =
1012                ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1013
1014        /* We need to update battery voltage and inst current when charging */
1015        di->vbat = ab8500_fg_bat_voltage(di);
1016        di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1017
1018        return di->bat_cap.mah;
1019}
1020
1021/**
1022 * ab8500_fg_calc_cap_discharge_voltage() - Capacity in discharge with voltage
1023 * @di:         pointer to the ab8500_fg structure
1024 * @comp:       if voltage should be load compensated before capacity calc
1025 *
1026 * Return the capacity in mAh based on the battery voltage. The voltage can
1027 * either be load compensated or not. This value is added to the filter and a
1028 * new mean value is calculated and returned.
1029 */
1030static int ab8500_fg_calc_cap_discharge_voltage(struct ab8500_fg *di, bool comp)
1031{
1032        int permille, mah;
1033
1034        if (comp)
1035                permille = ab8500_fg_load_comp_volt_to_capacity(di);
1036        else
1037                permille = ab8500_fg_uncomp_volt_to_capacity(di);
1038
1039        mah = ab8500_fg_convert_permille_to_mah(di, permille);
1040
1041        di->bat_cap.mah = ab8500_fg_add_cap_sample(di, mah);
1042        di->bat_cap.permille =
1043                ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1044
1045        return di->bat_cap.mah;
1046}
1047
1048/**
1049 * ab8500_fg_calc_cap_discharge_fg() - Capacity in discharge with FG
1050 * @di:         pointer to the ab8500_fg structure
1051 *
1052 * Return the capacity in mAh based on previous calculated capcity and the FG
1053 * accumulator register value. This value is added to the filter and a
1054 * new mean value is calculated and returned.
1055 */
1056static int ab8500_fg_calc_cap_discharge_fg(struct ab8500_fg *di)
1057{
1058        int permille_volt, permille;
1059
1060        dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1061                __func__,
1062                di->bat_cap.mah,
1063                di->accu_charge);
1064
1065        /* Capacity should not be less than 0 */
1066        if (di->bat_cap.mah + di->accu_charge > 0)
1067                di->bat_cap.mah += di->accu_charge;
1068        else
1069                di->bat_cap.mah = 0;
1070
1071        if (di->bat_cap.mah >= di->bat_cap.max_mah_design)
1072                di->bat_cap.mah = di->bat_cap.max_mah_design;
1073
1074        /*
1075         * Check against voltage based capacity. It can not be lower
1076         * than what the uncompensated voltage says
1077         */
1078        permille = ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1079        permille_volt = ab8500_fg_uncomp_volt_to_capacity(di);
1080
1081        if (permille < permille_volt) {
1082                di->bat_cap.permille = permille_volt;
1083                di->bat_cap.mah = ab8500_fg_convert_permille_to_mah(di,
1084                        di->bat_cap.permille);
1085
1086                dev_dbg(di->dev, "%s voltage based: perm %d perm_volt %d\n",
1087                        __func__,
1088                        permille,
1089                        permille_volt);
1090
1091                ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1092        } else {
1093                ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1094                di->bat_cap.permille =
1095                        ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1096        }
1097
1098        return di->bat_cap.mah;
1099}
1100
1101/**
1102 * ab8500_fg_capacity_level() - Get the battery capacity level
1103 * @di:         pointer to the ab8500_fg structure
1104 *
1105 * Get the battery capacity level based on the capacity in percent
1106 */
1107static int ab8500_fg_capacity_level(struct ab8500_fg *di)
1108{
1109        int ret, percent;
1110
1111        percent = di->bat_cap.permille / 10;
1112
1113        if (percent <= di->bat->cap_levels->critical ||
1114                di->flags.low_bat)
1115                ret = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1116        else if (percent <= di->bat->cap_levels->low)
1117                ret = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1118        else if (percent <= di->bat->cap_levels->normal)
1119                ret = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1120        else if (percent <= di->bat->cap_levels->high)
1121                ret = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
1122        else
1123                ret = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1124
1125        return ret;
1126}
1127
1128/**
1129 * ab8500_fg_check_capacity_limits() - Check if capacity has changed
1130 * @di:         pointer to the ab8500_fg structure
1131 * @init:       capacity is allowed to go up in init mode
1132 *
1133 * Check if capacity or capacity limit has changed and notify the system
1134 * about it using the power_supply framework
1135 */
1136static void ab8500_fg_check_capacity_limits(struct ab8500_fg *di, bool init)
1137{
1138        bool changed = false;
1139
1140        di->bat_cap.level = ab8500_fg_capacity_level(di);
1141
1142        if (di->bat_cap.level != di->bat_cap.prev_level) {
1143                /*
1144                 * We do not allow reported capacity level to go up
1145                 * unless we're charging or if we're in init
1146                 */
1147                if (!(!di->flags.charging && di->bat_cap.level >
1148                        di->bat_cap.prev_level) || init) {
1149                        dev_dbg(di->dev, "level changed from %d to %d\n",
1150                                di->bat_cap.prev_level,
1151                                di->bat_cap.level);
1152                        di->bat_cap.prev_level = di->bat_cap.level;
1153                        changed = true;
1154                } else {
1155                        dev_dbg(di->dev, "level not allowed to go up "
1156                                "since no charger is connected: %d to %d\n",
1157                                di->bat_cap.prev_level,
1158                                di->bat_cap.level);
1159                }
1160        }
1161
1162        /*
1163         * If we have received the LOW_BAT IRQ, set capacity to 0 to initiate
1164         * shutdown
1165         */
1166        if (di->flags.low_bat) {
1167                dev_dbg(di->dev, "Battery low, set capacity to 0\n");
1168                di->bat_cap.prev_percent = 0;
1169                di->bat_cap.permille = 0;
1170                di->bat_cap.prev_mah = 0;
1171                di->bat_cap.mah = 0;
1172                changed = true;
1173        } else if (di->flags.fully_charged) {
1174                /*
1175                 * We report 100% if algorithm reported fully charged
1176                 * unless capacity drops too much
1177                 */
1178                if (di->flags.force_full) {
1179                        di->bat_cap.prev_percent = di->bat_cap.permille / 10;
1180                        di->bat_cap.prev_mah = di->bat_cap.mah;
1181                } else if (!di->flags.force_full &&
1182                        di->bat_cap.prev_percent !=
1183                        (di->bat_cap.permille) / 10 &&
1184                        (di->bat_cap.permille / 10) <
1185                        di->bat->fg_params->maint_thres) {
1186                        dev_dbg(di->dev,
1187                                "battery reported full "
1188                                "but capacity dropping: %d\n",
1189                                di->bat_cap.permille / 10);
1190                        di->bat_cap.prev_percent = di->bat_cap.permille / 10;
1191                        di->bat_cap.prev_mah = di->bat_cap.mah;
1192
1193                        changed = true;
1194                }
1195        } else if (di->bat_cap.prev_percent != di->bat_cap.permille / 10) {
1196                if (di->bat_cap.permille / 10 == 0) {
1197                        /*
1198                         * We will not report 0% unless we've got
1199                         * the LOW_BAT IRQ, no matter what the FG
1200                         * algorithm says.
1201                         */
1202                        di->bat_cap.prev_percent = 1;
1203                        di->bat_cap.permille = 1;
1204                        di->bat_cap.prev_mah = 1;
1205                        di->bat_cap.mah = 1;
1206
1207                        changed = true;
1208                } else if (!(!di->flags.charging &&
1209                        (di->bat_cap.permille / 10) >
1210                        di->bat_cap.prev_percent) || init) {
1211                        /*
1212                         * We do not allow reported capacity to go up
1213                         * unless we're charging or if we're in init
1214                         */
1215                        dev_dbg(di->dev,
1216                                "capacity changed from %d to %d (%d)\n",
1217                                di->bat_cap.prev_percent,
1218                                di->bat_cap.permille / 10,
1219                                di->bat_cap.permille);
1220                        di->bat_cap.prev_percent = di->bat_cap.permille / 10;
1221                        di->bat_cap.prev_mah = di->bat_cap.mah;
1222
1223                        changed = true;
1224                } else {
1225                        dev_dbg(di->dev, "capacity not allowed to go up since "
1226                                "no charger is connected: %d to %d (%d)\n",
1227                                di->bat_cap.prev_percent,
1228                                di->bat_cap.permille / 10,
1229                                di->bat_cap.permille);
1230                }
1231        }
1232
1233        if (changed) {
1234                power_supply_changed(&di->fg_psy);
1235                if (di->flags.fully_charged && di->flags.force_full) {
1236                        dev_dbg(di->dev, "Battery full, notifying.\n");
1237                        di->flags.force_full = false;
1238                        sysfs_notify(&di->fg_kobject, NULL, "charge_full");
1239                }
1240                sysfs_notify(&di->fg_kobject, NULL, "charge_now");
1241        }
1242}
1243
1244static void ab8500_fg_charge_state_to(struct ab8500_fg *di,
1245        enum ab8500_fg_charge_state new_state)
1246{
1247        dev_dbg(di->dev, "Charge state from %d [%s] to %d [%s]\n",
1248                di->charge_state,
1249                charge_state[di->charge_state],
1250                new_state,
1251                charge_state[new_state]);
1252
1253        di->charge_state = new_state;
1254}
1255
1256static void ab8500_fg_discharge_state_to(struct ab8500_fg *di,
1257        enum ab8500_fg_discharge_state new_state)
1258{
1259        dev_dbg(di->dev, "Disharge state from %d [%s] to %d [%s]\n",
1260                di->discharge_state,
1261                discharge_state[di->discharge_state],
1262                new_state,
1263                discharge_state[new_state]);
1264
1265        di->discharge_state = new_state;
1266}
1267
1268/**
1269 * ab8500_fg_algorithm_charging() - FG algorithm for when charging
1270 * @di:         pointer to the ab8500_fg structure
1271 *
1272 * Battery capacity calculation state machine for when we're charging
1273 */
1274static void ab8500_fg_algorithm_charging(struct ab8500_fg *di)
1275{
1276        /*
1277         * If we change to discharge mode
1278         * we should start with recovery
1279         */
1280        if (di->discharge_state != AB8500_FG_DISCHARGE_INIT_RECOVERY)
1281                ab8500_fg_discharge_state_to(di,
1282                        AB8500_FG_DISCHARGE_INIT_RECOVERY);
1283
1284        switch (di->charge_state) {
1285        case AB8500_FG_CHARGE_INIT:
1286                di->fg_samples = SEC_TO_SAMPLE(
1287                        di->bat->fg_params->accu_charging);
1288
1289                ab8500_fg_coulomb_counter(di, true);
1290                ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_READOUT);
1291
1292                break;
1293
1294        case AB8500_FG_CHARGE_READOUT:
1295                /*
1296                 * Read the FG and calculate the new capacity
1297                 */
1298                mutex_lock(&di->cc_lock);
1299                if (!di->flags.conv_done) {
1300                        /* Wasn't the CC IRQ that got us here */
1301                        mutex_unlock(&di->cc_lock);
1302                        dev_dbg(di->dev, "%s CC conv not done\n",
1303                                __func__);
1304
1305                        break;
1306                }
1307                di->flags.conv_done = false;
1308                mutex_unlock(&di->cc_lock);
1309
1310                ab8500_fg_calc_cap_charging(di);
1311
1312                break;
1313
1314        default:
1315                break;
1316        }
1317
1318        /* Check capacity limits */
1319        ab8500_fg_check_capacity_limits(di, false);
1320}
1321
1322static void force_capacity(struct ab8500_fg *di)
1323{
1324        int cap;
1325
1326        ab8500_fg_clear_cap_samples(di);
1327        cap = di->bat_cap.user_mah;
1328        if (cap > di->bat_cap.max_mah_design) {
1329                dev_dbg(di->dev, "Remaining cap %d can't be bigger than total"
1330                        " %d\n", cap, di->bat_cap.max_mah_design);
1331                cap = di->bat_cap.max_mah_design;
1332        }
1333        ab8500_fg_fill_cap_sample(di, di->bat_cap.user_mah);
1334        di->bat_cap.permille = ab8500_fg_convert_mah_to_permille(di, cap);
1335        di->bat_cap.mah = cap;
1336        ab8500_fg_check_capacity_limits(di, true);
1337}
1338
1339static bool check_sysfs_capacity(struct ab8500_fg *di)
1340{
1341        int cap, lower, upper;
1342        int cap_permille;
1343
1344        cap = di->bat_cap.user_mah;
1345
1346        cap_permille = ab8500_fg_convert_mah_to_permille(di,
1347                di->bat_cap.user_mah);
1348
1349        lower = di->bat_cap.permille - di->bat->fg_params->user_cap_limit * 10;
1350        upper = di->bat_cap.permille + di->bat->fg_params->user_cap_limit * 10;
1351
1352        if (lower < 0)
1353                lower = 0;
1354        /* 1000 is permille, -> 100 percent */
1355        if (upper > 1000)
1356                upper = 1000;
1357
1358        dev_dbg(di->dev, "Capacity limits:"
1359                " (Lower: %d User: %d Upper: %d) [user: %d, was: %d]\n",
1360                lower, cap_permille, upper, cap, di->bat_cap.mah);
1361
1362        /* If within limits, use the saved capacity and exit estimation...*/
1363        if (cap_permille > lower && cap_permille < upper) {
1364                dev_dbg(di->dev, "OK! Using users cap %d uAh now\n", cap);
1365                force_capacity(di);
1366                return true;
1367        }
1368        dev_dbg(di->dev, "Capacity from user out of limits, ignoring");
1369        return false;
1370}
1371
1372/**
1373 * ab8500_fg_algorithm_discharging() - FG algorithm for when discharging
1374 * @di:         pointer to the ab8500_fg structure
1375 *
1376 * Battery capacity calculation state machine for when we're discharging
1377 */
1378static void ab8500_fg_algorithm_discharging(struct ab8500_fg *di)
1379{
1380        int sleep_time;
1381
1382        /* If we change to charge mode we should start with init */
1383        if (di->charge_state != AB8500_FG_CHARGE_INIT)
1384                ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
1385
1386        switch (di->discharge_state) {
1387        case AB8500_FG_DISCHARGE_INIT:
1388                /* We use the FG IRQ to work on */
1389                di->init_cnt = 0;
1390                di->fg_samples = SEC_TO_SAMPLE(di->bat->fg_params->init_timer);
1391                ab8500_fg_coulomb_counter(di, true);
1392                ab8500_fg_discharge_state_to(di,
1393                        AB8500_FG_DISCHARGE_INITMEASURING);
1394
1395                /* Intentional fallthrough */
1396        case AB8500_FG_DISCHARGE_INITMEASURING:
1397                /*
1398                 * Discard a number of samples during startup.
1399                 * After that, use compensated voltage for a few
1400                 * samples to get an initial capacity.
1401                 * Then go to READOUT
1402                 */
1403                sleep_time = di->bat->fg_params->init_timer;
1404
1405                /* Discard the first [x] seconds */
1406                if (di->init_cnt >
1407                        di->bat->fg_params->init_discard_time) {
1408                        ab8500_fg_calc_cap_discharge_voltage(di, true);
1409
1410                        ab8500_fg_check_capacity_limits(di, true);
1411                }
1412
1413                di->init_cnt += sleep_time;
1414                if (di->init_cnt > di->bat->fg_params->init_total_time)
1415                        ab8500_fg_discharge_state_to(di,
1416                                AB8500_FG_DISCHARGE_READOUT_INIT);
1417
1418                break;
1419
1420        case AB8500_FG_DISCHARGE_INIT_RECOVERY:
1421                di->recovery_cnt = 0;
1422                di->recovery_needed = true;
1423                ab8500_fg_discharge_state_to(di,
1424                        AB8500_FG_DISCHARGE_RECOVERY);
1425
1426                /* Intentional fallthrough */
1427
1428        case AB8500_FG_DISCHARGE_RECOVERY:
1429                sleep_time = di->bat->fg_params->recovery_sleep_timer;
1430
1431                /*
1432                 * We should check the power consumption
1433                 * If low, go to READOUT (after x min) or
1434                 * RECOVERY_SLEEP if time left.
1435                 * If high, go to READOUT
1436                 */
1437                di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1438
1439                if (ab8500_fg_is_low_curr(di, di->inst_curr)) {
1440                        if (di->recovery_cnt >
1441                                di->bat->fg_params->recovery_total_time) {
1442                                di->fg_samples = SEC_TO_SAMPLE(
1443                                        di->bat->fg_params->accu_high_curr);
1444                                ab8500_fg_coulomb_counter(di, true);
1445                                ab8500_fg_discharge_state_to(di,
1446                                        AB8500_FG_DISCHARGE_READOUT);
1447                                di->recovery_needed = false;
1448                        } else {
1449                                queue_delayed_work(di->fg_wq,
1450                                        &di->fg_periodic_work,
1451                                        sleep_time * HZ);
1452                        }
1453                        di->recovery_cnt += sleep_time;
1454                } else {
1455                        di->fg_samples = SEC_TO_SAMPLE(
1456                                di->bat->fg_params->accu_high_curr);
1457                        ab8500_fg_coulomb_counter(di, true);
1458                        ab8500_fg_discharge_state_to(di,
1459                                AB8500_FG_DISCHARGE_READOUT);
1460                }
1461                break;
1462
1463        case AB8500_FG_DISCHARGE_READOUT_INIT:
1464                di->fg_samples = SEC_TO_SAMPLE(
1465                        di->bat->fg_params->accu_high_curr);
1466                ab8500_fg_coulomb_counter(di, true);
1467                ab8500_fg_discharge_state_to(di,
1468                                AB8500_FG_DISCHARGE_READOUT);
1469                break;
1470
1471        case AB8500_FG_DISCHARGE_READOUT:
1472                di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1473
1474                if (ab8500_fg_is_low_curr(di, di->inst_curr)) {
1475                        /* Detect mode change */
1476                        if (di->high_curr_mode) {
1477                                di->high_curr_mode = false;
1478                                di->high_curr_cnt = 0;
1479                        }
1480
1481                        if (di->recovery_needed) {
1482                                ab8500_fg_discharge_state_to(di,
1483                                        AB8500_FG_DISCHARGE_RECOVERY);
1484
1485                                queue_delayed_work(di->fg_wq,
1486                                        &di->fg_periodic_work, 0);
1487
1488                                break;
1489                        }
1490
1491                        ab8500_fg_calc_cap_discharge_voltage(di, true);
1492                } else {
1493                        mutex_lock(&di->cc_lock);
1494                        if (!di->flags.conv_done) {
1495                                /* Wasn't the CC IRQ that got us here */
1496                                mutex_unlock(&di->cc_lock);
1497                                dev_dbg(di->dev, "%s CC conv not done\n",
1498                                        __func__);
1499
1500                                break;
1501                        }
1502                        di->flags.conv_done = false;
1503                        mutex_unlock(&di->cc_lock);
1504
1505                        /* Detect mode change */
1506                        if (!di->high_curr_mode) {
1507                                di->high_curr_mode = true;
1508                                di->high_curr_cnt = 0;
1509                        }
1510
1511                        di->high_curr_cnt +=
1512                                di->bat->fg_params->accu_high_curr;
1513                        if (di->high_curr_cnt >
1514                                di->bat->fg_params->high_curr_time)
1515                                di->recovery_needed = true;
1516
1517                        ab8500_fg_calc_cap_discharge_fg(di);
1518                }
1519
1520                ab8500_fg_check_capacity_limits(di, false);
1521
1522                break;
1523
1524        case AB8500_FG_DISCHARGE_WAKEUP:
1525                ab8500_fg_coulomb_counter(di, true);
1526                di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1527
1528                ab8500_fg_calc_cap_discharge_voltage(di, true);
1529
1530                di->fg_samples = SEC_TO_SAMPLE(
1531                        di->bat->fg_params->accu_high_curr);
1532                ab8500_fg_coulomb_counter(di, true);
1533                ab8500_fg_discharge_state_to(di,
1534                                AB8500_FG_DISCHARGE_READOUT);
1535
1536                ab8500_fg_check_capacity_limits(di, false);
1537
1538                break;
1539
1540        default:
1541                break;
1542        }
1543}
1544
1545/**
1546 * ab8500_fg_algorithm_calibrate() - Internal columb counter offset calibration
1547 * @di:         pointer to the ab8500_fg structure
1548 *
1549 */
1550static void ab8500_fg_algorithm_calibrate(struct ab8500_fg *di)
1551{
1552        int ret;
1553
1554        switch (di->calib_state) {
1555        case AB8500_FG_CALIB_INIT:
1556                dev_dbg(di->dev, "Calibration ongoing...\n");
1557
1558                ret = abx500_mask_and_set_register_interruptible(di->dev,
1559                        AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1560                        CC_INT_CAL_N_AVG_MASK, CC_INT_CAL_SAMPLES_8);
1561                if (ret < 0)
1562                        goto err;
1563
1564                ret = abx500_mask_and_set_register_interruptible(di->dev,
1565                        AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1566                        CC_INTAVGOFFSET_ENA, CC_INTAVGOFFSET_ENA);
1567                if (ret < 0)
1568                        goto err;
1569                di->calib_state = AB8500_FG_CALIB_WAIT;
1570                break;
1571        case AB8500_FG_CALIB_END:
1572                ret = abx500_mask_and_set_register_interruptible(di->dev,
1573                        AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1574                        CC_MUXOFFSET, CC_MUXOFFSET);
1575                if (ret < 0)
1576                        goto err;
1577                di->flags.calibrate = false;
1578                dev_dbg(di->dev, "Calibration done...\n");
1579                queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1580                break;
1581        case AB8500_FG_CALIB_WAIT:
1582                dev_dbg(di->dev, "Calibration WFI\n");
1583        default:
1584                break;
1585        }
1586        return;
1587err:
1588        /* Something went wrong, don't calibrate then */
1589        dev_err(di->dev, "failed to calibrate the CC\n");
1590        di->flags.calibrate = false;
1591        di->calib_state = AB8500_FG_CALIB_INIT;
1592        queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1593}
1594
1595/**
1596 * ab8500_fg_algorithm() - Entry point for the FG algorithm
1597 * @di:         pointer to the ab8500_fg structure
1598 *
1599 * Entry point for the battery capacity calculation state machine
1600 */
1601static void ab8500_fg_algorithm(struct ab8500_fg *di)
1602{
1603        if (di->flags.calibrate)
1604                ab8500_fg_algorithm_calibrate(di);
1605        else {
1606                if (di->flags.charging)
1607                        ab8500_fg_algorithm_charging(di);
1608                else
1609                        ab8500_fg_algorithm_discharging(di);
1610        }
1611
1612        dev_dbg(di->dev, "[FG_DATA] %d %d %d %d %d %d %d %d %d "
1613                "%d %d %d %d %d %d %d\n",
1614                di->bat_cap.max_mah_design,
1615                di->bat_cap.mah,
1616                di->bat_cap.permille,
1617                di->bat_cap.level,
1618                di->bat_cap.prev_mah,
1619                di->bat_cap.prev_percent,
1620                di->bat_cap.prev_level,
1621                di->vbat,
1622                di->inst_curr,
1623                di->avg_curr,
1624                di->accu_charge,
1625                di->flags.charging,
1626                di->charge_state,
1627                di->discharge_state,
1628                di->high_curr_mode,
1629                di->recovery_needed);
1630}
1631
1632/**
1633 * ab8500_fg_periodic_work() - Run the FG state machine periodically
1634 * @work:       pointer to the work_struct structure
1635 *
1636 * Work queue function for periodic work
1637 */
1638static void ab8500_fg_periodic_work(struct work_struct *work)
1639{
1640        struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1641                fg_periodic_work.work);
1642
1643        if (di->init_capacity) {
1644                /* A dummy read that will return 0 */
1645                di->inst_curr = ab8500_fg_inst_curr_blocking(di);
1646                /* Get an initial capacity calculation */
1647                ab8500_fg_calc_cap_discharge_voltage(di, true);
1648                ab8500_fg_check_capacity_limits(di, true);
1649                di->init_capacity = false;
1650
1651                queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1652        } else if (di->flags.user_cap) {
1653                if (check_sysfs_capacity(di)) {
1654                        ab8500_fg_check_capacity_limits(di, true);
1655                        if (di->flags.charging)
1656                                ab8500_fg_charge_state_to(di,
1657                                        AB8500_FG_CHARGE_INIT);
1658                        else
1659                                ab8500_fg_discharge_state_to(di,
1660                                        AB8500_FG_DISCHARGE_READOUT_INIT);
1661                }
1662                di->flags.user_cap = false;
1663                queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1664        } else
1665                ab8500_fg_algorithm(di);
1666
1667}
1668
1669/**
1670 * ab8500_fg_check_hw_failure_work() - Check OVV_BAT condition
1671 * @work:       pointer to the work_struct structure
1672 *
1673 * Work queue function for checking the OVV_BAT condition
1674 */
1675static void ab8500_fg_check_hw_failure_work(struct work_struct *work)
1676{
1677        int ret;
1678        u8 reg_value;
1679
1680        struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1681                fg_check_hw_failure_work.work);
1682
1683        /*
1684         * If we have had a battery over-voltage situation,
1685         * check ovv-bit to see if it should be reset.
1686         */
1687        if (di->flags.bat_ovv) {
1688                ret = abx500_get_register_interruptible(di->dev,
1689                        AB8500_CHARGER, AB8500_CH_STAT_REG,
1690                        &reg_value);
1691                if (ret < 0) {
1692                        dev_err(di->dev, "%s ab8500 read failed\n", __func__);
1693                        return;
1694                }
1695                if ((reg_value & BATT_OVV) != BATT_OVV) {
1696                        dev_dbg(di->dev, "Battery recovered from OVV\n");
1697                        di->flags.bat_ovv = false;
1698                        power_supply_changed(&di->fg_psy);
1699                        return;
1700                }
1701
1702                /* Not yet recovered from ovv, reschedule this test */
1703                queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work,
1704                                   round_jiffies(HZ));
1705        }
1706}
1707
1708/**
1709 * ab8500_fg_low_bat_work() - Check LOW_BAT condition
1710 * @work:       pointer to the work_struct structure
1711 *
1712 * Work queue function for checking the LOW_BAT condition
1713 */
1714static void ab8500_fg_low_bat_work(struct work_struct *work)
1715{
1716        int vbat;
1717
1718        struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1719                fg_low_bat_work.work);
1720
1721        vbat = ab8500_fg_bat_voltage(di);
1722
1723        /* Check if LOW_BAT still fulfilled */
1724        if (vbat < di->bat->fg_params->lowbat_threshold) {
1725                di->flags.low_bat = true;
1726                dev_warn(di->dev, "Battery voltage still LOW\n");
1727
1728                /*
1729                 * We need to re-schedule this check to be able to detect
1730                 * if the voltage increases again during charging
1731                 */
1732                queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
1733                        round_jiffies(LOW_BAT_CHECK_INTERVAL));
1734        } else {
1735                di->flags.low_bat = false;
1736                dev_warn(di->dev, "Battery voltage OK again\n");
1737        }
1738
1739        /* This is needed to dispatch LOW_BAT */
1740        ab8500_fg_check_capacity_limits(di, false);
1741
1742        /* Set this flag to check if LOW_BAT IRQ still occurs */
1743        di->flags.low_bat_delay = false;
1744}
1745
1746/**
1747 * ab8500_fg_battok_calc - calculate the bit pattern corresponding
1748 * to the target voltage.
1749 * @di:       pointer to the ab8500_fg structure
1750 * @target    target voltage
1751 *
1752 * Returns bit pattern closest to the target voltage
1753 * valid return values are 0-14. (0-BATT_OK_MAX_NR_INCREMENTS)
1754 */
1755
1756static int ab8500_fg_battok_calc(struct ab8500_fg *di, int target)
1757{
1758        if (target > BATT_OK_MIN +
1759                (BATT_OK_INCREMENT * BATT_OK_MAX_NR_INCREMENTS))
1760                return BATT_OK_MAX_NR_INCREMENTS;
1761        if (target < BATT_OK_MIN)
1762                return 0;
1763        return (target - BATT_OK_MIN) / BATT_OK_INCREMENT;
1764}
1765
1766/**
1767 * ab8500_fg_battok_init_hw_register - init battok levels
1768 * @di:       pointer to the ab8500_fg structure
1769 *
1770 */
1771
1772static int ab8500_fg_battok_init_hw_register(struct ab8500_fg *di)
1773{
1774        int selected;
1775        int sel0;
1776        int sel1;
1777        int cbp_sel0;
1778        int cbp_sel1;
1779        int ret;
1780        int new_val;
1781
1782        sel0 = di->bat->fg_params->battok_falling_th_sel0;
1783        sel1 = di->bat->fg_params->battok_raising_th_sel1;
1784
1785        cbp_sel0 = ab8500_fg_battok_calc(di, sel0);
1786        cbp_sel1 = ab8500_fg_battok_calc(di, sel1);
1787
1788        selected = BATT_OK_MIN + cbp_sel0 * BATT_OK_INCREMENT;
1789
1790        if (selected != sel0)
1791                dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1792                        sel0, selected, cbp_sel0);
1793
1794        selected = BATT_OK_MIN + cbp_sel1 * BATT_OK_INCREMENT;
1795
1796        if (selected != sel1)
1797                dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1798                        sel1, selected, cbp_sel1);
1799
1800        new_val = cbp_sel0 | (cbp_sel1 << 4);
1801
1802        dev_dbg(di->dev, "using: %x %d %d\n", new_val, cbp_sel0, cbp_sel1);
1803        ret = abx500_set_register_interruptible(di->dev, AB8500_SYS_CTRL2_BLOCK,
1804                AB8500_BATT_OK_REG, new_val);
1805        return ret;
1806}
1807
1808/**
1809 * ab8500_fg_instant_work() - Run the FG state machine instantly
1810 * @work:       pointer to the work_struct structure
1811 *
1812 * Work queue function for instant work
1813 */
1814static void ab8500_fg_instant_work(struct work_struct *work)
1815{
1816        struct ab8500_fg *di = container_of(work, struct ab8500_fg, fg_work);
1817
1818        ab8500_fg_algorithm(di);
1819}
1820
1821/**
1822 * ab8500_fg_cc_data_end_handler() - isr to get battery avg current.
1823 * @irq:       interrupt number
1824 * @_di:       pointer to the ab8500_fg structure
1825 *
1826 * Returns IRQ status(IRQ_HANDLED)
1827 */
1828static irqreturn_t ab8500_fg_cc_data_end_handler(int irq, void *_di)
1829{
1830        struct ab8500_fg *di = _di;
1831        complete(&di->ab8500_fg_complete);
1832        return IRQ_HANDLED;
1833}
1834
1835/**
1836 * ab8500_fg_cc_convend_handler() - isr to get battery avg current.
1837 * @irq:       interrupt number
1838 * @_di:       pointer to the ab8500_fg structure
1839 *
1840 * Returns IRQ status(IRQ_HANDLED)
1841 */
1842static irqreturn_t ab8500_fg_cc_int_calib_handler(int irq, void *_di)
1843{
1844        struct ab8500_fg *di = _di;
1845        di->calib_state = AB8500_FG_CALIB_END;
1846        queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1847        return IRQ_HANDLED;
1848}
1849
1850/**
1851 * ab8500_fg_cc_convend_handler() - isr to get battery avg current.
1852 * @irq:       interrupt number
1853 * @_di:       pointer to the ab8500_fg structure
1854 *
1855 * Returns IRQ status(IRQ_HANDLED)
1856 */
1857static irqreturn_t ab8500_fg_cc_convend_handler(int irq, void *_di)
1858{
1859        struct ab8500_fg *di = _di;
1860
1861        queue_work(di->fg_wq, &di->fg_acc_cur_work);
1862
1863        return IRQ_HANDLED;
1864}
1865
1866/**
1867 * ab8500_fg_batt_ovv_handler() - Battery OVV occured
1868 * @irq:       interrupt number
1869 * @_di:       pointer to the ab8500_fg structure
1870 *
1871 * Returns IRQ status(IRQ_HANDLED)
1872 */
1873static irqreturn_t ab8500_fg_batt_ovv_handler(int irq, void *_di)
1874{
1875        struct ab8500_fg *di = _di;
1876
1877        dev_dbg(di->dev, "Battery OVV\n");
1878        di->flags.bat_ovv = true;
1879        power_supply_changed(&di->fg_psy);
1880
1881        /* Schedule a new HW failure check */
1882        queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work, 0);
1883
1884        return IRQ_HANDLED;
1885}
1886
1887/**
1888 * ab8500_fg_lowbatf_handler() - Battery voltage is below LOW threshold
1889 * @irq:       interrupt number
1890 * @_di:       pointer to the ab8500_fg structure
1891 *
1892 * Returns IRQ status(IRQ_HANDLED)
1893 */
1894static irqreturn_t ab8500_fg_lowbatf_handler(int irq, void *_di)
1895{
1896        struct ab8500_fg *di = _di;
1897
1898        if (!di->flags.low_bat_delay) {
1899                dev_warn(di->dev, "Battery voltage is below LOW threshold\n");
1900                di->flags.low_bat_delay = true;
1901                /*
1902                 * Start a timer to check LOW_BAT again after some time
1903                 * This is done to avoid shutdown on single voltage dips
1904                 */
1905                queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
1906                        round_jiffies(LOW_BAT_CHECK_INTERVAL));
1907        }
1908        return IRQ_HANDLED;
1909}
1910
1911/**
1912 * ab8500_fg_get_property() - get the fg properties
1913 * @psy:        pointer to the power_supply structure
1914 * @psp:        pointer to the power_supply_property structure
1915 * @val:        pointer to the power_supply_propval union
1916 *
1917 * This function gets called when an application tries to get the
1918 * fg properties by reading the sysfs files.
1919 * voltage_now:         battery voltage
1920 * current_now:         battery instant current
1921 * current_avg:         battery average current
1922 * charge_full_design:  capacity where battery is considered full
1923 * charge_now:          battery capacity in nAh
1924 * capacity:            capacity in percent
1925 * capacity_level:      capacity level
1926 *
1927 * Returns error code in case of failure else 0 on success
1928 */
1929static int ab8500_fg_get_property(struct power_supply *psy,
1930        enum power_supply_property psp,
1931        union power_supply_propval *val)
1932{
1933        struct ab8500_fg *di;
1934
1935        di = to_ab8500_fg_device_info(psy);
1936
1937        /*
1938         * If battery is identified as unknown and charging of unknown
1939         * batteries is disabled, we always report 100% capacity and
1940         * capacity level UNKNOWN, since we can't calculate
1941         * remaining capacity
1942         */
1943
1944        switch (psp) {
1945        case POWER_SUPPLY_PROP_VOLTAGE_NOW:
1946                if (di->flags.bat_ovv)
1947                        val->intval = BATT_OVV_VALUE * 1000;
1948                else
1949                        val->intval = di->vbat * 1000;
1950                break;
1951        case POWER_SUPPLY_PROP_CURRENT_NOW:
1952                val->intval = di->inst_curr * 1000;
1953                break;
1954        case POWER_SUPPLY_PROP_CURRENT_AVG:
1955                val->intval = di->avg_curr * 1000;
1956                break;
1957        case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
1958                val->intval = ab8500_fg_convert_mah_to_uwh(di,
1959                                di->bat_cap.max_mah_design);
1960                break;
1961        case POWER_SUPPLY_PROP_ENERGY_FULL:
1962                val->intval = ab8500_fg_convert_mah_to_uwh(di,
1963                                di->bat_cap.max_mah);
1964                break;
1965        case POWER_SUPPLY_PROP_ENERGY_NOW:
1966                if (di->flags.batt_unknown && !di->bat->chg_unknown_bat &&
1967                                di->flags.batt_id_received)
1968                        val->intval = ab8500_fg_convert_mah_to_uwh(di,
1969                                        di->bat_cap.max_mah);
1970                else
1971                        val->intval = ab8500_fg_convert_mah_to_uwh(di,
1972                                        di->bat_cap.prev_mah);
1973                break;
1974        case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
1975                val->intval = di->bat_cap.max_mah_design;
1976                break;
1977        case POWER_SUPPLY_PROP_CHARGE_FULL:
1978                val->intval = di->bat_cap.max_mah;
1979                break;
1980        case POWER_SUPPLY_PROP_CHARGE_NOW:
1981                if (di->flags.batt_unknown && !di->bat->chg_unknown_bat &&
1982                                di->flags.batt_id_received)
1983                        val->intval = di->bat_cap.max_mah;
1984                else
1985                        val->intval = di->bat_cap.prev_mah;
1986                break;
1987        case POWER_SUPPLY_PROP_CAPACITY:
1988                if (di->flags.batt_unknown && !di->bat->chg_unknown_bat &&
1989                                di->flags.batt_id_received)
1990                        val->intval = 100;
1991                else
1992                        val->intval = di->bat_cap.prev_percent;
1993                break;
1994        case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
1995                if (di->flags.batt_unknown && !di->bat->chg_unknown_bat &&
1996                                di->flags.batt_id_received)
1997                        val->intval = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
1998                else
1999                        val->intval = di->bat_cap.prev_level;
2000                break;
2001        default:
2002                return -EINVAL;
2003        }
2004        return 0;
2005}
2006
2007static int ab8500_fg_get_ext_psy_data(struct device *dev, void *data)
2008{
2009        struct power_supply *psy;
2010        struct power_supply *ext;
2011        struct ab8500_fg *di;
2012        union power_supply_propval ret;
2013        int i, j;
2014        bool psy_found = false;
2015
2016        psy = (struct power_supply *)data;
2017        ext = dev_get_drvdata(dev);
2018        di = to_ab8500_fg_device_info(psy);
2019
2020        /*
2021         * For all psy where the name of your driver
2022         * appears in any supplied_to
2023         */
2024        for (i = 0; i < ext->num_supplicants; i++) {
2025                if (!strcmp(ext->supplied_to[i], psy->name))
2026                        psy_found = true;
2027        }
2028
2029        if (!psy_found)
2030                return 0;
2031
2032        /* Go through all properties for the psy */
2033        for (j = 0; j < ext->num_properties; j++) {
2034                enum power_supply_property prop;
2035                prop = ext->properties[j];
2036
2037                if (ext->get_property(ext, prop, &ret))
2038                        continue;
2039
2040                switch (prop) {
2041                case POWER_SUPPLY_PROP_STATUS:
2042                        switch (ext->type) {
2043                        case POWER_SUPPLY_TYPE_BATTERY:
2044                                switch (ret.intval) {
2045                                case POWER_SUPPLY_STATUS_UNKNOWN:
2046                                case POWER_SUPPLY_STATUS_DISCHARGING:
2047                                case POWER_SUPPLY_STATUS_NOT_CHARGING:
2048                                        if (!di->flags.charging)
2049                                                break;
2050                                        di->flags.charging = false;
2051                                        di->flags.fully_charged = false;
2052                                        queue_work(di->fg_wq, &di->fg_work);
2053                                        break;
2054                                case POWER_SUPPLY_STATUS_FULL:
2055                                        if (di->flags.fully_charged)
2056                                                break;
2057                                        di->flags.fully_charged = true;
2058                                        di->flags.force_full = true;
2059                                        /* Save current capacity as maximum */
2060                                        di->bat_cap.max_mah = di->bat_cap.mah;
2061                                        queue_work(di->fg_wq, &di->fg_work);
2062                                        break;
2063                                case POWER_SUPPLY_STATUS_CHARGING:
2064                                        if (di->flags.charging)
2065                                                break;
2066                                        di->flags.charging = true;
2067                                        di->flags.fully_charged = false;
2068                                        queue_work(di->fg_wq, &di->fg_work);
2069                                        break;
2070                                };
2071                        default:
2072                                break;
2073                        };
2074                        break;
2075                case POWER_SUPPLY_PROP_TECHNOLOGY:
2076                        switch (ext->type) {
2077                        case POWER_SUPPLY_TYPE_BATTERY:
2078                                if (!di->flags.batt_id_received) {
2079                                        const struct abx500_battery_type *b;
2080
2081                                        b = &(di->bat->bat_type[di->bat->batt_id]);
2082
2083                                        di->flags.batt_id_received = true;
2084
2085                                        di->bat_cap.max_mah_design =
2086                                                MILLI_TO_MICRO *
2087                                                b->charge_full_design;
2088
2089                                        di->bat_cap.max_mah =
2090                                                di->bat_cap.max_mah_design;
2091
2092                                        di->vbat_nom = b->nominal_voltage;
2093                                }
2094
2095                                if (ret.intval)
2096                                        di->flags.batt_unknown = false;
2097                                else
2098                                        di->flags.batt_unknown = true;
2099                                break;
2100                        default:
2101                                break;
2102                        }
2103                        break;
2104                case POWER_SUPPLY_PROP_TEMP:
2105                        switch (ext->type) {
2106                        case POWER_SUPPLY_TYPE_BATTERY:
2107                            if (di->flags.batt_id_received)
2108                                di->bat_temp = ret.intval;
2109                                break;
2110                        default:
2111                                break;
2112                        }
2113                        break;
2114                default:
2115                        break;
2116                }
2117        }
2118        return 0;
2119}
2120
2121/**
2122 * ab8500_fg_init_hw_registers() - Set up FG related registers
2123 * @di:         pointer to the ab8500_fg structure
2124 *
2125 * Set up battery OVV, low battery voltage registers
2126 */
2127static int ab8500_fg_init_hw_registers(struct ab8500_fg *di)
2128{
2129        int ret;
2130
2131        /* Set VBAT OVV threshold */
2132        ret = abx500_mask_and_set_register_interruptible(di->dev,
2133                AB8500_CHARGER,
2134                AB8500_BATT_OVV,
2135                BATT_OVV_TH_4P75,
2136                BATT_OVV_TH_4P75);
2137        if (ret) {
2138                dev_err(di->dev, "failed to set BATT_OVV\n");
2139                goto out;
2140        }
2141
2142        /* Enable VBAT OVV detection */
2143        ret = abx500_mask_and_set_register_interruptible(di->dev,
2144                AB8500_CHARGER,
2145                AB8500_BATT_OVV,
2146                BATT_OVV_ENA,
2147                BATT_OVV_ENA);
2148        if (ret) {
2149                dev_err(di->dev, "failed to enable BATT_OVV\n");
2150                goto out;
2151        }
2152
2153        /* Low Battery Voltage */
2154        ret = abx500_set_register_interruptible(di->dev,
2155                AB8500_SYS_CTRL2_BLOCK,
2156                AB8500_LOW_BAT_REG,
2157                ab8500_volt_to_regval(
2158                        di->bat->fg_params->lowbat_threshold) << 1 |
2159                LOW_BAT_ENABLE);
2160        if (ret) {
2161                dev_err(di->dev, "%s write failed\n", __func__);
2162                goto out;
2163        }
2164
2165        /* Battery OK threshold */
2166        ret = ab8500_fg_battok_init_hw_register(di);
2167        if (ret) {
2168                dev_err(di->dev, "BattOk init write failed.\n");
2169                goto out;
2170        }
2171out:
2172        return ret;
2173}
2174
2175/**
2176 * ab8500_fg_external_power_changed() - callback for power supply changes
2177 * @psy:       pointer to the structure power_supply
2178 *
2179 * This function is the entry point of the pointer external_power_changed
2180 * of the structure power_supply.
2181 * This function gets executed when there is a change in any external power
2182 * supply that this driver needs to be notified of.
2183 */
2184static void ab8500_fg_external_power_changed(struct power_supply *psy)
2185{
2186        struct ab8500_fg *di = to_ab8500_fg_device_info(psy);
2187
2188        class_for_each_device(power_supply_class, NULL,
2189                &di->fg_psy, ab8500_fg_get_ext_psy_data);
2190}
2191
2192/**
2193 * abab8500_fg_reinit_work() - work to reset the FG algorithm
2194 * @work:       pointer to the work_struct structure
2195 *
2196 * Used to reset the current battery capacity to be able to
2197 * retrigger a new voltage base capacity calculation. For
2198 * test and verification purpose.
2199 */
2200static void ab8500_fg_reinit_work(struct work_struct *work)
2201{
2202        struct ab8500_fg *di = container_of(work, struct ab8500_fg,
2203                fg_reinit_work.work);
2204
2205        if (di->flags.calibrate == false) {
2206                dev_dbg(di->dev, "Resetting FG state machine to init.\n");
2207                ab8500_fg_clear_cap_samples(di);
2208                ab8500_fg_calc_cap_discharge_voltage(di, true);
2209                ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
2210                ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
2211                queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2212
2213        } else {
2214                dev_err(di->dev, "Residual offset calibration ongoing "
2215                        "retrying..\n");
2216                /* Wait one second until next try*/
2217                queue_delayed_work(di->fg_wq, &di->fg_reinit_work,
2218                        round_jiffies(1));
2219        }
2220}
2221
2222/**
2223 * ab8500_fg_reinit() - forces FG algorithm to reinitialize with current values
2224 *
2225 * This function can be used to force the FG algorithm to recalculate a new
2226 * voltage based battery capacity.
2227 */
2228void ab8500_fg_reinit(void)
2229{
2230        struct ab8500_fg *di = ab8500_fg_get();
2231        /* User won't be notified if a null pointer returned. */
2232        if (di != NULL)
2233                queue_delayed_work(di->fg_wq, &di->fg_reinit_work, 0);
2234}
2235
2236/* Exposure to the sysfs interface */
2237
2238struct ab8500_fg_sysfs_entry {
2239        struct attribute attr;
2240        ssize_t (*show)(struct ab8500_fg *, char *);
2241        ssize_t (*store)(struct ab8500_fg *, const char *, size_t);
2242};
2243
2244static ssize_t charge_full_show(struct ab8500_fg *di, char *buf)
2245{
2246        return sprintf(buf, "%d\n", di->bat_cap.max_mah);
2247}
2248
2249static ssize_t charge_full_store(struct ab8500_fg *di, const char *buf,
2250                                 size_t count)
2251{
2252        unsigned long charge_full;
2253        ssize_t ret = -EINVAL;
2254
2255        ret = strict_strtoul(buf, 10, &charge_full);
2256
2257        dev_dbg(di->dev, "Ret %zd charge_full %lu", ret, charge_full);
2258
2259        if (!ret) {
2260                di->bat_cap.max_mah = (int) charge_full;
2261                ret = count;
2262        }
2263        return ret;
2264}
2265
2266static ssize_t charge_now_show(struct ab8500_fg *di, char *buf)
2267{
2268        return sprintf(buf, "%d\n", di->bat_cap.prev_mah);
2269}
2270
2271static ssize_t charge_now_store(struct ab8500_fg *di, const char *buf,
2272                                 size_t count)
2273{
2274        unsigned long charge_now;
2275        ssize_t ret;
2276
2277        ret = strict_strtoul(buf, 10, &charge_now);
2278
2279        dev_dbg(di->dev, "Ret %zd charge_now %lu was %d",
2280                ret, charge_now, di->bat_cap.prev_mah);
2281
2282        if (!ret) {
2283                di->bat_cap.user_mah = (int) charge_now;
2284                di->flags.user_cap = true;
2285                ret = count;
2286                queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2287        }
2288        return ret;
2289}
2290
2291static struct ab8500_fg_sysfs_entry charge_full_attr =
2292        __ATTR(charge_full, 0644, charge_full_show, charge_full_store);
2293
2294static struct ab8500_fg_sysfs_entry charge_now_attr =
2295        __ATTR(charge_now, 0644, charge_now_show, charge_now_store);
2296
2297static ssize_t
2298ab8500_fg_show(struct kobject *kobj, struct attribute *attr, char *buf)
2299{
2300        struct ab8500_fg_sysfs_entry *entry;
2301        struct ab8500_fg *di;
2302
2303        entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2304        di = container_of(kobj, struct ab8500_fg, fg_kobject);
2305
2306        if (!entry->show)
2307                return -EIO;
2308
2309        return entry->show(di, buf);
2310}
2311static ssize_t
2312ab8500_fg_store(struct kobject *kobj, struct attribute *attr, const char *buf,
2313                size_t count)
2314{
2315        struct ab8500_fg_sysfs_entry *entry;
2316        struct ab8500_fg *di;
2317
2318        entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2319        di = container_of(kobj, struct ab8500_fg, fg_kobject);
2320
2321        if (!entry->store)
2322                return -EIO;
2323
2324        return entry->store(di, buf, count);
2325}
2326
2327static const struct sysfs_ops ab8500_fg_sysfs_ops = {
2328        .show = ab8500_fg_show,
2329        .store = ab8500_fg_store,
2330};
2331
2332static struct attribute *ab8500_fg_attrs[] = {
2333        &charge_full_attr.attr,
2334        &charge_now_attr.attr,
2335        NULL,
2336};
2337
2338static struct kobj_type ab8500_fg_ktype = {
2339        .sysfs_ops = &ab8500_fg_sysfs_ops,
2340        .default_attrs = ab8500_fg_attrs,
2341};
2342
2343/**
2344 * ab8500_chargalg_sysfs_exit() - de-init of sysfs entry
2345 * @di:                pointer to the struct ab8500_chargalg
2346 *
2347 * This function removes the entry in sysfs.
2348 */
2349static void ab8500_fg_sysfs_exit(struct ab8500_fg *di)
2350{
2351        kobject_del(&di->fg_kobject);
2352}
2353
2354/**
2355 * ab8500_chargalg_sysfs_init() - init of sysfs entry
2356 * @di:                pointer to the struct ab8500_chargalg
2357 *
2358 * This function adds an entry in sysfs.
2359 * Returns error code in case of failure else 0(on success)
2360 */
2361static int ab8500_fg_sysfs_init(struct ab8500_fg *di)
2362{
2363        int ret = 0;
2364
2365        ret = kobject_init_and_add(&di->fg_kobject,
2366                &ab8500_fg_ktype,
2367                NULL, "battery");
2368        if (ret < 0)
2369                dev_err(di->dev, "failed to create sysfs entry\n");
2370
2371        return ret;
2372}
2373/* Exposure to the sysfs interface <<END>> */
2374
2375#if defined(CONFIG_PM)
2376static int ab8500_fg_resume(struct platform_device *pdev)
2377{
2378        struct ab8500_fg *di = platform_get_drvdata(pdev);
2379
2380        /*
2381         * Change state if we're not charging. If we're charging we will wake
2382         * up on the FG IRQ
2383         */
2384        if (!di->flags.charging) {
2385                ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_WAKEUP);
2386                queue_work(di->fg_wq, &di->fg_work);
2387        }
2388
2389        return 0;
2390}
2391
2392static int ab8500_fg_suspend(struct platform_device *pdev,
2393        pm_message_t state)
2394{
2395        struct ab8500_fg *di = platform_get_drvdata(pdev);
2396
2397        flush_delayed_work(&di->fg_periodic_work);
2398
2399        /*
2400         * If the FG is enabled we will disable it before going to suspend
2401         * only if we're not charging
2402         */
2403        if (di->flags.fg_enabled && !di->flags.charging)
2404                ab8500_fg_coulomb_counter(di, false);
2405
2406        return 0;
2407}
2408#else
2409#define ab8500_fg_suspend      NULL
2410#define ab8500_fg_resume       NULL
2411#endif
2412
2413static int ab8500_fg_remove(struct platform_device *pdev)
2414{
2415        int ret = 0;
2416        struct ab8500_fg *di = platform_get_drvdata(pdev);
2417
2418        list_del(&di->node);
2419
2420        /* Disable coulomb counter */
2421        ret = ab8500_fg_coulomb_counter(di, false);
2422        if (ret)
2423                dev_err(di->dev, "failed to disable coulomb counter\n");
2424
2425        destroy_workqueue(di->fg_wq);
2426        ab8500_fg_sysfs_exit(di);
2427
2428        flush_scheduled_work();
2429        power_supply_unregister(&di->fg_psy);
2430        platform_set_drvdata(pdev, NULL);
2431        return ret;
2432}
2433
2434/* ab8500 fg driver interrupts and their respective isr */
2435static struct ab8500_fg_interrupts ab8500_fg_irq[] = {
2436        {"NCONV_ACCU", ab8500_fg_cc_convend_handler},
2437        {"BATT_OVV", ab8500_fg_batt_ovv_handler},
2438        {"LOW_BAT_F", ab8500_fg_lowbatf_handler},
2439        {"CC_INT_CALIB", ab8500_fg_cc_int_calib_handler},
2440        {"CCEOC", ab8500_fg_cc_data_end_handler},
2441};
2442
2443static char *supply_interface[] = {
2444        "ab8500_chargalg",
2445        "ab8500_usb",
2446};
2447
2448static int ab8500_fg_probe(struct platform_device *pdev)
2449{
2450        struct device_node *np = pdev->dev.of_node;
2451        struct ab8500_fg *di;
2452        int i, irq;
2453        int ret = 0;
2454
2455        di = devm_kzalloc(&pdev->dev, sizeof(*di), GFP_KERNEL);
2456        if (!di) {
2457                dev_err(&pdev->dev, "%s no mem for ab8500_fg\n", __func__);
2458                return -ENOMEM;
2459        }
2460        di->bat = pdev->mfd_cell->platform_data;
2461        if (!di->bat) {
2462                if (np) {
2463                        ret = bmdevs_of_probe(&pdev->dev, np, &di->bat);
2464                        if (ret) {
2465                                dev_err(&pdev->dev,
2466                                        "failed to get battery information\n");
2467                                return ret;
2468                        }
2469                } else {
2470                        dev_err(&pdev->dev, "missing dt node for ab8500_fg\n");
2471                        return -EINVAL;
2472                }
2473        } else {
2474                dev_info(&pdev->dev, "falling back to legacy platform data\n");
2475        }
2476
2477        mutex_init(&di->cc_lock);
2478
2479        /* get parent data */
2480        di->dev = &pdev->dev;
2481        di->parent = dev_get_drvdata(pdev->dev.parent);
2482        di->gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
2483
2484        di->fg_psy.name = "ab8500_fg";
2485        di->fg_psy.type = POWER_SUPPLY_TYPE_BATTERY;
2486        di->fg_psy.properties = ab8500_fg_props;
2487        di->fg_psy.num_properties = ARRAY_SIZE(ab8500_fg_props);
2488        di->fg_psy.get_property = ab8500_fg_get_property;
2489        di->fg_psy.supplied_to = supply_interface;
2490        di->fg_psy.num_supplicants = ARRAY_SIZE(supply_interface),
2491        di->fg_psy.external_power_changed = ab8500_fg_external_power_changed;
2492
2493        di->bat_cap.max_mah_design = MILLI_TO_MICRO *
2494                di->bat->bat_type[di->bat->batt_id].charge_full_design;
2495
2496        di->bat_cap.max_mah = di->bat_cap.max_mah_design;
2497
2498        di->vbat_nom = di->bat->bat_type[di->bat->batt_id].nominal_voltage;
2499
2500        di->init_capacity = true;
2501
2502        ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
2503        ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
2504
2505        /* Create a work queue for running the FG algorithm */
2506        di->fg_wq = create_singlethread_workqueue("ab8500_fg_wq");
2507        if (di->fg_wq == NULL) {
2508                dev_err(di->dev, "failed to create work queue\n");
2509                return -ENOMEM;
2510        }
2511
2512        /* Init work for running the fg algorithm instantly */
2513        INIT_WORK(&di->fg_work, ab8500_fg_instant_work);
2514
2515        /* Init work for getting the battery accumulated current */
2516        INIT_WORK(&di->fg_acc_cur_work, ab8500_fg_acc_cur_work);
2517
2518        /* Init work for reinitialising the fg algorithm */
2519        INIT_DEFERRABLE_WORK(&di->fg_reinit_work,
2520                ab8500_fg_reinit_work);
2521
2522        /* Work delayed Queue to run the state machine */
2523        INIT_DEFERRABLE_WORK(&di->fg_periodic_work,
2524                ab8500_fg_periodic_work);
2525
2526        /* Work to check low battery condition */
2527        INIT_DEFERRABLE_WORK(&di->fg_low_bat_work,
2528                ab8500_fg_low_bat_work);
2529
2530        /* Init work for HW failure check */
2531        INIT_DEFERRABLE_WORK(&di->fg_check_hw_failure_work,
2532                ab8500_fg_check_hw_failure_work);
2533
2534        /* Initialize OVV, and other registers */
2535        ret = ab8500_fg_init_hw_registers(di);
2536        if (ret) {
2537                dev_err(di->dev, "failed to initialize registers\n");
2538                goto free_inst_curr_wq;
2539        }
2540
2541        /* Consider battery unknown until we're informed otherwise */
2542        di->flags.batt_unknown = true;
2543        di->flags.batt_id_received = false;
2544
2545        /* Register FG power supply class */
2546        ret = power_supply_register(di->dev, &di->fg_psy);
2547        if (ret) {
2548                dev_err(di->dev, "failed to register FG psy\n");
2549                goto free_inst_curr_wq;
2550        }
2551
2552        di->fg_samples = SEC_TO_SAMPLE(di->bat->fg_params->init_timer);
2553        ab8500_fg_coulomb_counter(di, true);
2554
2555        /* Initialize completion used to notify completion of inst current */
2556        init_completion(&di->ab8500_fg_complete);
2557
2558        /* Register interrupts */
2559        for (i = 0; i < ARRAY_SIZE(ab8500_fg_irq); i++) {
2560                irq = platform_get_irq_byname(pdev, ab8500_fg_irq[i].name);
2561                ret = request_threaded_irq(irq, NULL, ab8500_fg_irq[i].isr,
2562                        IRQF_SHARED | IRQF_NO_SUSPEND,
2563                        ab8500_fg_irq[i].name, di);
2564
2565                if (ret != 0) {
2566                        dev_err(di->dev, "failed to request %s IRQ %d: %d\n"
2567                                , ab8500_fg_irq[i].name, irq, ret);
2568                        goto free_irq;
2569                }
2570                dev_dbg(di->dev, "Requested %s IRQ %d: %d\n",
2571                        ab8500_fg_irq[i].name, irq, ret);
2572        }
2573        di->irq = platform_get_irq_byname(pdev, "CCEOC");
2574        disable_irq(di->irq);
2575
2576        platform_set_drvdata(pdev, di);
2577
2578        ret = ab8500_fg_sysfs_init(di);
2579        if (ret) {
2580                dev_err(di->dev, "failed to create sysfs entry\n");
2581                goto free_irq;
2582        }
2583
2584        /* Calibrate the fg first time */
2585        di->flags.calibrate = true;
2586        di->calib_state = AB8500_FG_CALIB_INIT;
2587
2588        /* Use room temp as default value until we get an update from driver. */
2589        di->bat_temp = 210;
2590
2591        /* Run the FG algorithm */
2592        queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2593
2594        list_add_tail(&di->node, &ab8500_fg_list);
2595
2596        return ret;
2597
2598free_irq:
2599        power_supply_unregister(&di->fg_psy);
2600
2601        /* We also have to free all successfully registered irqs */
2602        for (i = i - 1; i >= 0; i--) {
2603                irq = platform_get_irq_byname(pdev, ab8500_fg_irq[i].name);
2604                free_irq(irq, di);
2605        }
2606free_inst_curr_wq:
2607        destroy_workqueue(di->fg_wq);
2608        return ret;
2609}
2610
2611static const struct of_device_id ab8500_fg_match[] = {
2612        { .compatible = "stericsson,ab8500-fg", },
2613        { },
2614};
2615
2616static struct platform_driver ab8500_fg_driver = {
2617        .probe = ab8500_fg_probe,
2618        .remove = ab8500_fg_remove,
2619        .suspend = ab8500_fg_suspend,
2620        .resume = ab8500_fg_resume,
2621        .driver = {
2622                .name = "ab8500-fg",
2623                .owner = THIS_MODULE,
2624                .of_match_table = ab8500_fg_match,
2625        },
2626};
2627
2628static int __init ab8500_fg_init(void)
2629{
2630        return platform_driver_register(&ab8500_fg_driver);
2631}
2632
2633static void __exit ab8500_fg_exit(void)
2634{
2635        platform_driver_unregister(&ab8500_fg_driver);
2636}
2637
2638subsys_initcall_sync(ab8500_fg_init);
2639module_exit(ab8500_fg_exit);
2640
2641MODULE_LICENSE("GPL v2");
2642MODULE_AUTHOR("Johan Palsson, Karl Komierowski");
2643MODULE_ALIAS("platform:ab8500-fg");
2644MODULE_DESCRIPTION("AB8500 Fuel Gauge driver");
2645
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.