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