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