Merge tag 'powerpc-5.3-2' of git://git.kernel.org/pub/scm/linux/kernel/git/powerpc...
[linux-2.6-microblaze.git] / drivers / power / supply / ab8500_btemp.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) ST-Ericsson SA 2012
4  *
5  * Battery temperature driver for AB8500
6  *
7  * Author:
8  *      Johan Palsson <johan.palsson@stericsson.com>
9  *      Karl Komierowski <karl.komierowski@stericsson.com>
10  *      Arun R Murthy <arun.murthy@stericsson.com>
11  */
12
13 #include <linux/init.h>
14 #include <linux/module.h>
15 #include <linux/device.h>
16 #include <linux/interrupt.h>
17 #include <linux/delay.h>
18 #include <linux/slab.h>
19 #include <linux/platform_device.h>
20 #include <linux/power_supply.h>
21 #include <linux/completion.h>
22 #include <linux/workqueue.h>
23 #include <linux/jiffies.h>
24 #include <linux/of.h>
25 #include <linux/mfd/core.h>
26 #include <linux/mfd/abx500.h>
27 #include <linux/mfd/abx500/ab8500.h>
28 #include <linux/mfd/abx500/ab8500-bm.h>
29 #include <linux/mfd/abx500/ab8500-gpadc.h>
30
31 #define VTVOUT_V                        1800
32
33 #define BTEMP_THERMAL_LOW_LIMIT         -10
34 #define BTEMP_THERMAL_MED_LIMIT         0
35 #define BTEMP_THERMAL_HIGH_LIMIT_52     52
36 #define BTEMP_THERMAL_HIGH_LIMIT_57     57
37 #define BTEMP_THERMAL_HIGH_LIMIT_62     62
38
39 #define BTEMP_BATCTRL_CURR_SRC_7UA      7
40 #define BTEMP_BATCTRL_CURR_SRC_20UA     20
41
42 #define BTEMP_BATCTRL_CURR_SRC_16UA     16
43 #define BTEMP_BATCTRL_CURR_SRC_18UA     18
44
45 #define BTEMP_BATCTRL_CURR_SRC_60UA     60
46 #define BTEMP_BATCTRL_CURR_SRC_120UA    120
47
48 /**
49  * struct ab8500_btemp_interrupts - ab8500 interrupts
50  * @name:       name of the interrupt
51  * @isr         function pointer to the isr
52  */
53 struct ab8500_btemp_interrupts {
54         char *name;
55         irqreturn_t (*isr)(int irq, void *data);
56 };
57
58 struct ab8500_btemp_events {
59         bool batt_rem;
60         bool btemp_high;
61         bool btemp_medhigh;
62         bool btemp_lowmed;
63         bool btemp_low;
64         bool ac_conn;
65         bool usb_conn;
66 };
67
68 struct ab8500_btemp_ranges {
69         int btemp_high_limit;
70         int btemp_med_limit;
71         int btemp_low_limit;
72 };
73
74 /**
75  * struct ab8500_btemp - ab8500 BTEMP device information
76  * @dev:                Pointer to the structure device
77  * @node:               List of AB8500 BTEMPs, hence prepared for reentrance
78  * @curr_source:        What current source we use, in uA
79  * @bat_temp:           Dispatched battery temperature in degree Celsius
80  * @prev_bat_temp       Last measured battery temperature in degree Celsius
81  * @parent:             Pointer to the struct ab8500
82  * @gpadc:              Pointer to the struct gpadc
83  * @fg:                 Pointer to the struct fg
84  * @bm:                 Platform specific battery management information
85  * @btemp_psy:          Structure for BTEMP specific battery properties
86  * @events:             Structure for information about events triggered
87  * @btemp_ranges:       Battery temperature range structure
88  * @btemp_wq:           Work queue for measuring the temperature periodically
89  * @btemp_periodic_work:        Work for measuring the temperature periodically
90  * @initialized:        True if battery id read.
91  */
92 struct ab8500_btemp {
93         struct device *dev;
94         struct list_head node;
95         int curr_source;
96         int bat_temp;
97         int prev_bat_temp;
98         struct ab8500 *parent;
99         struct ab8500_gpadc *gpadc;
100         struct ab8500_fg *fg;
101         struct abx500_bm_data *bm;
102         struct power_supply *btemp_psy;
103         struct ab8500_btemp_events events;
104         struct ab8500_btemp_ranges btemp_ranges;
105         struct workqueue_struct *btemp_wq;
106         struct delayed_work btemp_periodic_work;
107         bool initialized;
108 };
109
110 /* BTEMP power supply properties */
111 static enum power_supply_property ab8500_btemp_props[] = {
112         POWER_SUPPLY_PROP_PRESENT,
113         POWER_SUPPLY_PROP_ONLINE,
114         POWER_SUPPLY_PROP_TECHNOLOGY,
115         POWER_SUPPLY_PROP_TEMP,
116 };
117
118 static LIST_HEAD(ab8500_btemp_list);
119
120 /**
121  * ab8500_btemp_get() - returns a reference to the primary AB8500 BTEMP
122  * (i.e. the first BTEMP in the instance list)
123  */
124 struct ab8500_btemp *ab8500_btemp_get(void)
125 {
126         return list_first_entry(&ab8500_btemp_list, struct ab8500_btemp, node);
127 }
128 EXPORT_SYMBOL(ab8500_btemp_get);
129
130 /**
131  * ab8500_btemp_batctrl_volt_to_res() - convert batctrl voltage to resistance
132  * @di:         pointer to the ab8500_btemp structure
133  * @v_batctrl:  measured batctrl voltage
134  * @inst_curr:  measured instant current
135  *
136  * This function returns the battery resistance that is
137  * derived from the BATCTRL voltage.
138  * Returns value in Ohms.
139  */
140 static int ab8500_btemp_batctrl_volt_to_res(struct ab8500_btemp *di,
141         int v_batctrl, int inst_curr)
142 {
143         int rbs;
144
145         if (is_ab8500_1p1_or_earlier(di->parent)) {
146                 /*
147                  * For ABB cut1.0 and 1.1 BAT_CTRL is internally
148                  * connected to 1.8V through a 450k resistor
149                  */
150                 return (450000 * (v_batctrl)) / (1800 - v_batctrl);
151         }
152
153         if (di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL) {
154                 /*
155                  * If the battery has internal NTC, we use the current
156                  * source to calculate the resistance.
157                  */
158                 rbs = (v_batctrl * 1000
159                        - di->bm->gnd_lift_resistance * inst_curr)
160                       / di->curr_source;
161         } else {
162                 /*
163                  * BAT_CTRL is internally
164                  * connected to 1.8V through a 80k resistor
165                  */
166                 rbs = (80000 * (v_batctrl)) / (1800 - v_batctrl);
167         }
168
169         return rbs;
170 }
171
172 /**
173  * ab8500_btemp_read_batctrl_voltage() - measure batctrl voltage
174  * @di:         pointer to the ab8500_btemp structure
175  *
176  * This function returns the voltage on BATCTRL. Returns value in mV.
177  */
178 static int ab8500_btemp_read_batctrl_voltage(struct ab8500_btemp *di)
179 {
180         int vbtemp;
181         static int prev;
182
183         vbtemp = ab8500_gpadc_convert(di->gpadc, BAT_CTRL);
184         if (vbtemp < 0) {
185                 dev_err(di->dev,
186                         "%s gpadc conversion failed, using previous value",
187                         __func__);
188                 return prev;
189         }
190         prev = vbtemp;
191         return vbtemp;
192 }
193
194 /**
195  * ab8500_btemp_curr_source_enable() - enable/disable batctrl current source
196  * @di:         pointer to the ab8500_btemp structure
197  * @enable:     enable or disable the current source
198  *
199  * Enable or disable the current sources for the BatCtrl AD channel
200  */
201 static int ab8500_btemp_curr_source_enable(struct ab8500_btemp *di,
202         bool enable)
203 {
204         int curr;
205         int ret = 0;
206
207         /*
208          * BATCTRL current sources are included on AB8500 cut2.0
209          * and future versions
210          */
211         if (is_ab8500_1p1_or_earlier(di->parent))
212                 return 0;
213
214         /* Only do this for batteries with internal NTC */
215         if (di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL && enable) {
216
217                 if (di->curr_source == BTEMP_BATCTRL_CURR_SRC_7UA)
218                         curr = BAT_CTRL_7U_ENA;
219                 else
220                         curr = BAT_CTRL_20U_ENA;
221
222                 dev_dbg(di->dev, "Set BATCTRL %duA\n", di->curr_source);
223
224                 ret = abx500_mask_and_set_register_interruptible(di->dev,
225                         AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
226                         FORCE_BAT_CTRL_CMP_HIGH, FORCE_BAT_CTRL_CMP_HIGH);
227                 if (ret) {
228                         dev_err(di->dev, "%s failed setting cmp_force\n",
229                                 __func__);
230                         return ret;
231                 }
232
233                 /*
234                  * We have to wait one 32kHz cycle before enabling
235                  * the current source, since ForceBatCtrlCmpHigh needs
236                  * to be written in a separate cycle
237                  */
238                 udelay(32);
239
240                 ret = abx500_set_register_interruptible(di->dev,
241                         AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
242                         FORCE_BAT_CTRL_CMP_HIGH | curr);
243                 if (ret) {
244                         dev_err(di->dev, "%s failed enabling current source\n",
245                                 __func__);
246                         goto disable_curr_source;
247                 }
248         } else if (di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL && !enable) {
249                 dev_dbg(di->dev, "Disable BATCTRL curr source\n");
250
251                 /* Write 0 to the curr bits */
252                 ret = abx500_mask_and_set_register_interruptible(
253                         di->dev,
254                         AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
255                         BAT_CTRL_7U_ENA | BAT_CTRL_20U_ENA,
256                         ~(BAT_CTRL_7U_ENA | BAT_CTRL_20U_ENA));
257
258                 if (ret) {
259                         dev_err(di->dev, "%s failed disabling current source\n",
260                                 __func__);
261                         goto disable_curr_source;
262                 }
263
264                 /* Enable Pull-Up and comparator */
265                 ret = abx500_mask_and_set_register_interruptible(di->dev,
266                         AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
267                         BAT_CTRL_PULL_UP_ENA | BAT_CTRL_CMP_ENA,
268                         BAT_CTRL_PULL_UP_ENA | BAT_CTRL_CMP_ENA);
269                 if (ret) {
270                         dev_err(di->dev, "%s failed enabling PU and comp\n",
271                                 __func__);
272                         goto enable_pu_comp;
273                 }
274
275                 /*
276                  * We have to wait one 32kHz cycle before disabling
277                  * ForceBatCtrlCmpHigh since this needs to be written
278                  * in a separate cycle
279                  */
280                 udelay(32);
281
282                 /* Disable 'force comparator' */
283                 ret = abx500_mask_and_set_register_interruptible(di->dev,
284                         AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
285                         FORCE_BAT_CTRL_CMP_HIGH, ~FORCE_BAT_CTRL_CMP_HIGH);
286                 if (ret) {
287                         dev_err(di->dev, "%s failed disabling force comp\n",
288                                 __func__);
289                         goto disable_force_comp;
290                 }
291         }
292         return ret;
293
294         /*
295          * We have to try unsetting FORCE_BAT_CTRL_CMP_HIGH one more time
296          * if we got an error above
297          */
298 disable_curr_source:
299         /* Write 0 to the curr bits */
300         ret = abx500_mask_and_set_register_interruptible(di->dev,
301                 AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
302                 BAT_CTRL_7U_ENA | BAT_CTRL_20U_ENA,
303                 ~(BAT_CTRL_7U_ENA | BAT_CTRL_20U_ENA));
304
305         if (ret) {
306                 dev_err(di->dev, "%s failed disabling current source\n",
307                         __func__);
308                 return ret;
309         }
310 enable_pu_comp:
311         /* Enable Pull-Up and comparator */
312         ret = abx500_mask_and_set_register_interruptible(di->dev,
313                 AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
314                 BAT_CTRL_PULL_UP_ENA | BAT_CTRL_CMP_ENA,
315                 BAT_CTRL_PULL_UP_ENA | BAT_CTRL_CMP_ENA);
316         if (ret) {
317                 dev_err(di->dev, "%s failed enabling PU and comp\n",
318                         __func__);
319                 return ret;
320         }
321
322 disable_force_comp:
323         /*
324          * We have to wait one 32kHz cycle before disabling
325          * ForceBatCtrlCmpHigh since this needs to be written
326          * in a separate cycle
327          */
328         udelay(32);
329
330         /* Disable 'force comparator' */
331         ret = abx500_mask_and_set_register_interruptible(di->dev,
332                 AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
333                 FORCE_BAT_CTRL_CMP_HIGH, ~FORCE_BAT_CTRL_CMP_HIGH);
334         if (ret) {
335                 dev_err(di->dev, "%s failed disabling force comp\n",
336                         __func__);
337                 return ret;
338         }
339
340         return ret;
341 }
342
343 /**
344  * ab8500_btemp_get_batctrl_res() - get battery resistance
345  * @di:         pointer to the ab8500_btemp structure
346  *
347  * This function returns the battery pack identification resistance.
348  * Returns value in Ohms.
349  */
350 static int ab8500_btemp_get_batctrl_res(struct ab8500_btemp *di)
351 {
352         int ret;
353         int batctrl = 0;
354         int res;
355         int inst_curr;
356         int i;
357
358         /*
359          * BATCTRL current sources are included on AB8500 cut2.0
360          * and future versions
361          */
362         ret = ab8500_btemp_curr_source_enable(di, true);
363         if (ret) {
364                 dev_err(di->dev, "%s curr source enabled failed\n", __func__);
365                 return ret;
366         }
367
368         if (!di->fg)
369                 di->fg = ab8500_fg_get();
370         if (!di->fg) {
371                 dev_err(di->dev, "No fg found\n");
372                 return -EINVAL;
373         }
374
375         ret = ab8500_fg_inst_curr_start(di->fg);
376
377         if (ret) {
378                 dev_err(di->dev, "Failed to start current measurement\n");
379                 return ret;
380         }
381
382         do {
383                 msleep(20);
384         } while (!ab8500_fg_inst_curr_started(di->fg));
385
386         i = 0;
387
388         do {
389                 batctrl += ab8500_btemp_read_batctrl_voltage(di);
390                 i++;
391                 msleep(20);
392         } while (!ab8500_fg_inst_curr_done(di->fg));
393         batctrl /= i;
394
395         ret = ab8500_fg_inst_curr_finalize(di->fg, &inst_curr);
396         if (ret) {
397                 dev_err(di->dev, "Failed to finalize current measurement\n");
398                 return ret;
399         }
400
401         res = ab8500_btemp_batctrl_volt_to_res(di, batctrl, inst_curr);
402
403         ret = ab8500_btemp_curr_source_enable(di, false);
404         if (ret) {
405                 dev_err(di->dev, "%s curr source disable failed\n", __func__);
406                 return ret;
407         }
408
409         dev_dbg(di->dev, "%s batctrl: %d res: %d inst_curr: %d samples: %d\n",
410                 __func__, batctrl, res, inst_curr, i);
411
412         return res;
413 }
414
415 /**
416  * ab8500_btemp_res_to_temp() - resistance to temperature
417  * @di:         pointer to the ab8500_btemp structure
418  * @tbl:        pointer to the resiatance to temperature table
419  * @tbl_size:   size of the resistance to temperature table
420  * @res:        resistance to calculate the temperature from
421  *
422  * This function returns the battery temperature in degrees Celsius
423  * based on the NTC resistance.
424  */
425 static int ab8500_btemp_res_to_temp(struct ab8500_btemp *di,
426         const struct abx500_res_to_temp *tbl, int tbl_size, int res)
427 {
428         int i;
429         /*
430          * Calculate the formula for the straight line
431          * Simple interpolation if we are within
432          * the resistance table limits, extrapolate
433          * if resistance is outside the limits.
434          */
435         if (res > tbl[0].resist)
436                 i = 0;
437         else if (res <= tbl[tbl_size - 1].resist)
438                 i = tbl_size - 2;
439         else {
440                 i = 0;
441                 while (!(res <= tbl[i].resist &&
442                         res > tbl[i + 1].resist))
443                         i++;
444         }
445
446         return tbl[i].temp + ((tbl[i + 1].temp - tbl[i].temp) *
447                 (res - tbl[i].resist)) / (tbl[i + 1].resist - tbl[i].resist);
448 }
449
450 /**
451  * ab8500_btemp_measure_temp() - measure battery temperature
452  * @di:         pointer to the ab8500_btemp structure
453  *
454  * Returns battery temperature (on success) else the previous temperature
455  */
456 static int ab8500_btemp_measure_temp(struct ab8500_btemp *di)
457 {
458         int temp;
459         static int prev;
460         int rbat, rntc, vntc;
461         u8 id;
462
463         id = di->bm->batt_id;
464
465         if (di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL &&
466                         id != BATTERY_UNKNOWN) {
467
468                 rbat = ab8500_btemp_get_batctrl_res(di);
469                 if (rbat < 0) {
470                         dev_err(di->dev, "%s get batctrl res failed\n",
471                                 __func__);
472                         /*
473                          * Return out-of-range temperature so that
474                          * charging is stopped
475                          */
476                         return BTEMP_THERMAL_LOW_LIMIT;
477                 }
478
479                 temp = ab8500_btemp_res_to_temp(di,
480                         di->bm->bat_type[id].r_to_t_tbl,
481                         di->bm->bat_type[id].n_temp_tbl_elements, rbat);
482         } else {
483                 vntc = ab8500_gpadc_convert(di->gpadc, BTEMP_BALL);
484                 if (vntc < 0) {
485                         dev_err(di->dev,
486                                 "%s gpadc conversion failed,"
487                                 " using previous value\n", __func__);
488                         return prev;
489                 }
490                 /*
491                  * The PCB NTC is sourced from VTVOUT via a 230kOhm
492                  * resistor.
493                  */
494                 rntc = 230000 * vntc / (VTVOUT_V - vntc);
495
496                 temp = ab8500_btemp_res_to_temp(di,
497                         di->bm->bat_type[id].r_to_t_tbl,
498                         di->bm->bat_type[id].n_temp_tbl_elements, rntc);
499                 prev = temp;
500         }
501         dev_dbg(di->dev, "Battery temperature is %d\n", temp);
502         return temp;
503 }
504
505 /**
506  * ab8500_btemp_id() - Identify the connected battery
507  * @di:         pointer to the ab8500_btemp structure
508  *
509  * This function will try to identify the battery by reading the ID
510  * resistor. Some brands use a combined ID resistor with a NTC resistor to
511  * both be able to identify and to read the temperature of it.
512  */
513 static int ab8500_btemp_id(struct ab8500_btemp *di)
514 {
515         int res;
516         u8 i;
517
518         di->curr_source = BTEMP_BATCTRL_CURR_SRC_7UA;
519         di->bm->batt_id = BATTERY_UNKNOWN;
520
521         res =  ab8500_btemp_get_batctrl_res(di);
522         if (res < 0) {
523                 dev_err(di->dev, "%s get batctrl res failed\n", __func__);
524                 return -ENXIO;
525         }
526
527         /* BATTERY_UNKNOWN is defined on position 0, skip it! */
528         for (i = BATTERY_UNKNOWN + 1; i < di->bm->n_btypes; i++) {
529                 if ((res <= di->bm->bat_type[i].resis_high) &&
530                         (res >= di->bm->bat_type[i].resis_low)) {
531                         dev_dbg(di->dev, "Battery detected on %s"
532                                 " low %d < res %d < high: %d"
533                                 " index: %d\n",
534                                 di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL ?
535                                 "BATCTRL" : "BATTEMP",
536                                 di->bm->bat_type[i].resis_low, res,
537                                 di->bm->bat_type[i].resis_high, i);
538
539                         di->bm->batt_id = i;
540                         break;
541                 }
542         }
543
544         if (di->bm->batt_id == BATTERY_UNKNOWN) {
545                 dev_warn(di->dev, "Battery identified as unknown"
546                         ", resistance %d Ohm\n", res);
547                 return -ENXIO;
548         }
549
550         /*
551          * We only have to change current source if the
552          * detected type is Type 1.
553          */
554         if (di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL &&
555             di->bm->batt_id == 1) {
556                 dev_dbg(di->dev, "Set BATCTRL current source to 20uA\n");
557                 di->curr_source = BTEMP_BATCTRL_CURR_SRC_20UA;
558         }
559
560         return di->bm->batt_id;
561 }
562
563 /**
564  * ab8500_btemp_periodic_work() - Measuring the temperature periodically
565  * @work:       pointer to the work_struct structure
566  *
567  * Work function for measuring the temperature periodically
568  */
569 static void ab8500_btemp_periodic_work(struct work_struct *work)
570 {
571         int interval;
572         int bat_temp;
573         struct ab8500_btemp *di = container_of(work,
574                 struct ab8500_btemp, btemp_periodic_work.work);
575
576         if (!di->initialized) {
577                 /* Identify the battery */
578                 if (ab8500_btemp_id(di) < 0)
579                         dev_warn(di->dev, "failed to identify the battery\n");
580         }
581
582         bat_temp = ab8500_btemp_measure_temp(di);
583         /*
584          * Filter battery temperature.
585          * Allow direct updates on temperature only if two samples result in
586          * same temperature. Else only allow 1 degree change from previous
587          * reported value in the direction of the new measurement.
588          */
589         if ((bat_temp == di->prev_bat_temp) || !di->initialized) {
590                 if ((di->bat_temp != di->prev_bat_temp) || !di->initialized) {
591                         di->initialized = true;
592                         di->bat_temp = bat_temp;
593                         power_supply_changed(di->btemp_psy);
594                 }
595         } else if (bat_temp < di->prev_bat_temp) {
596                 di->bat_temp--;
597                 power_supply_changed(di->btemp_psy);
598         } else if (bat_temp > di->prev_bat_temp) {
599                 di->bat_temp++;
600                 power_supply_changed(di->btemp_psy);
601         }
602         di->prev_bat_temp = bat_temp;
603
604         if (di->events.ac_conn || di->events.usb_conn)
605                 interval = di->bm->temp_interval_chg;
606         else
607                 interval = di->bm->temp_interval_nochg;
608
609         /* Schedule a new measurement */
610         queue_delayed_work(di->btemp_wq,
611                 &di->btemp_periodic_work,
612                 round_jiffies(interval * HZ));
613 }
614
615 /**
616  * ab8500_btemp_batctrlindb_handler() - battery removal detected
617  * @irq:       interrupt number
618  * @_di:       void pointer that has to address of ab8500_btemp
619  *
620  * Returns IRQ status(IRQ_HANDLED)
621  */
622 static irqreturn_t ab8500_btemp_batctrlindb_handler(int irq, void *_di)
623 {
624         struct ab8500_btemp *di = _di;
625         dev_err(di->dev, "Battery removal detected!\n");
626
627         di->events.batt_rem = true;
628         power_supply_changed(di->btemp_psy);
629
630         return IRQ_HANDLED;
631 }
632
633 /**
634  * ab8500_btemp_templow_handler() - battery temp lower than 10 degrees
635  * @irq:       interrupt number
636  * @_di:       void pointer that has to address of ab8500_btemp
637  *
638  * Returns IRQ status(IRQ_HANDLED)
639  */
640 static irqreturn_t ab8500_btemp_templow_handler(int irq, void *_di)
641 {
642         struct ab8500_btemp *di = _di;
643
644         if (is_ab8500_3p3_or_earlier(di->parent)) {
645                 dev_dbg(di->dev, "Ignore false btemp low irq"
646                         " for ABB cut 1.0, 1.1, 2.0 and 3.3\n");
647         } else {
648                 dev_crit(di->dev, "Battery temperature lower than -10deg c\n");
649
650                 di->events.btemp_low = true;
651                 di->events.btemp_high = false;
652                 di->events.btemp_medhigh = false;
653                 di->events.btemp_lowmed = false;
654                 power_supply_changed(di->btemp_psy);
655         }
656
657         return IRQ_HANDLED;
658 }
659
660 /**
661  * ab8500_btemp_temphigh_handler() - battery temp higher than max temp
662  * @irq:       interrupt number
663  * @_di:       void pointer that has to address of ab8500_btemp
664  *
665  * Returns IRQ status(IRQ_HANDLED)
666  */
667 static irqreturn_t ab8500_btemp_temphigh_handler(int irq, void *_di)
668 {
669         struct ab8500_btemp *di = _di;
670
671         dev_crit(di->dev, "Battery temperature is higher than MAX temp\n");
672
673         di->events.btemp_high = true;
674         di->events.btemp_medhigh = false;
675         di->events.btemp_lowmed = false;
676         di->events.btemp_low = false;
677         power_supply_changed(di->btemp_psy);
678
679         return IRQ_HANDLED;
680 }
681
682 /**
683  * ab8500_btemp_lowmed_handler() - battery temp between low and medium
684  * @irq:       interrupt number
685  * @_di:       void pointer that has to address of ab8500_btemp
686  *
687  * Returns IRQ status(IRQ_HANDLED)
688  */
689 static irqreturn_t ab8500_btemp_lowmed_handler(int irq, void *_di)
690 {
691         struct ab8500_btemp *di = _di;
692
693         dev_dbg(di->dev, "Battery temperature is between low and medium\n");
694
695         di->events.btemp_lowmed = true;
696         di->events.btemp_medhigh = false;
697         di->events.btemp_high = false;
698         di->events.btemp_low = false;
699         power_supply_changed(di->btemp_psy);
700
701         return IRQ_HANDLED;
702 }
703
704 /**
705  * ab8500_btemp_medhigh_handler() - battery temp between medium and high
706  * @irq:       interrupt number
707  * @_di:       void pointer that has to address of ab8500_btemp
708  *
709  * Returns IRQ status(IRQ_HANDLED)
710  */
711 static irqreturn_t ab8500_btemp_medhigh_handler(int irq, void *_di)
712 {
713         struct ab8500_btemp *di = _di;
714
715         dev_dbg(di->dev, "Battery temperature is between medium and high\n");
716
717         di->events.btemp_medhigh = true;
718         di->events.btemp_lowmed = false;
719         di->events.btemp_high = false;
720         di->events.btemp_low = false;
721         power_supply_changed(di->btemp_psy);
722
723         return IRQ_HANDLED;
724 }
725
726 /**
727  * ab8500_btemp_periodic() - Periodic temperature measurements
728  * @di:         pointer to the ab8500_btemp structure
729  * @enable:     enable or disable periodic temperature measurements
730  *
731  * Starts of stops periodic temperature measurements. Periodic measurements
732  * should only be done when a charger is connected.
733  */
734 static void ab8500_btemp_periodic(struct ab8500_btemp *di,
735         bool enable)
736 {
737         dev_dbg(di->dev, "Enable periodic temperature measurements: %d\n",
738                 enable);
739         /*
740          * Make sure a new measurement is done directly by cancelling
741          * any pending work
742          */
743         cancel_delayed_work_sync(&di->btemp_periodic_work);
744
745         if (enable)
746                 queue_delayed_work(di->btemp_wq, &di->btemp_periodic_work, 0);
747 }
748
749 /**
750  * ab8500_btemp_get_temp() - get battery temperature
751  * @di:         pointer to the ab8500_btemp structure
752  *
753  * Returns battery temperature
754  */
755 int ab8500_btemp_get_temp(struct ab8500_btemp *di)
756 {
757         int temp = 0;
758
759         /*
760          * The BTEMP events are not reliabe on AB8500 cut3.3
761          * and prior versions
762          */
763         if (is_ab8500_3p3_or_earlier(di->parent)) {
764                 temp = di->bat_temp * 10;
765         } else {
766                 if (di->events.btemp_low) {
767                         if (temp > di->btemp_ranges.btemp_low_limit)
768                                 temp = di->btemp_ranges.btemp_low_limit * 10;
769                         else
770                                 temp = di->bat_temp * 10;
771                 } else if (di->events.btemp_high) {
772                         if (temp < di->btemp_ranges.btemp_high_limit)
773                                 temp = di->btemp_ranges.btemp_high_limit * 10;
774                         else
775                                 temp = di->bat_temp * 10;
776                 } else if (di->events.btemp_lowmed) {
777                         if (temp > di->btemp_ranges.btemp_med_limit)
778                                 temp = di->btemp_ranges.btemp_med_limit * 10;
779                         else
780                                 temp = di->bat_temp * 10;
781                 } else if (di->events.btemp_medhigh) {
782                         if (temp < di->btemp_ranges.btemp_med_limit)
783                                 temp = di->btemp_ranges.btemp_med_limit * 10;
784                         else
785                                 temp = di->bat_temp * 10;
786                 } else
787                         temp = di->bat_temp * 10;
788         }
789         return temp;
790 }
791 EXPORT_SYMBOL(ab8500_btemp_get_temp);
792
793 /**
794  * ab8500_btemp_get_batctrl_temp() - get the temperature
795  * @btemp:      pointer to the btemp structure
796  *
797  * Returns the batctrl temperature in millidegrees
798  */
799 int ab8500_btemp_get_batctrl_temp(struct ab8500_btemp *btemp)
800 {
801         return btemp->bat_temp * 1000;
802 }
803 EXPORT_SYMBOL(ab8500_btemp_get_batctrl_temp);
804
805 /**
806  * ab8500_btemp_get_property() - get the btemp properties
807  * @psy:        pointer to the power_supply structure
808  * @psp:        pointer to the power_supply_property structure
809  * @val:        pointer to the power_supply_propval union
810  *
811  * This function gets called when an application tries to get the btemp
812  * properties by reading the sysfs files.
813  * online:      presence of the battery
814  * present:     presence of the battery
815  * technology:  battery technology
816  * temp:        battery temperature
817  * Returns error code in case of failure else 0(on success)
818  */
819 static int ab8500_btemp_get_property(struct power_supply *psy,
820         enum power_supply_property psp,
821         union power_supply_propval *val)
822 {
823         struct ab8500_btemp *di = power_supply_get_drvdata(psy);
824
825         switch (psp) {
826         case POWER_SUPPLY_PROP_PRESENT:
827         case POWER_SUPPLY_PROP_ONLINE:
828                 if (di->events.batt_rem)
829                         val->intval = 0;
830                 else
831                         val->intval = 1;
832                 break;
833         case POWER_SUPPLY_PROP_TECHNOLOGY:
834                 val->intval = di->bm->bat_type[di->bm->batt_id].name;
835                 break;
836         case POWER_SUPPLY_PROP_TEMP:
837                 val->intval = ab8500_btemp_get_temp(di);
838                 break;
839         default:
840                 return -EINVAL;
841         }
842         return 0;
843 }
844
845 static int ab8500_btemp_get_ext_psy_data(struct device *dev, void *data)
846 {
847         struct power_supply *psy;
848         struct power_supply *ext = dev_get_drvdata(dev);
849         const char **supplicants = (const char **)ext->supplied_to;
850         struct ab8500_btemp *di;
851         union power_supply_propval ret;
852         int j;
853
854         psy = (struct power_supply *)data;
855         di = power_supply_get_drvdata(psy);
856
857         /*
858          * For all psy where the name of your driver
859          * appears in any supplied_to
860          */
861         j = match_string(supplicants, ext->num_supplicants, psy->desc->name);
862         if (j < 0)
863                 return 0;
864
865         /* Go through all properties for the psy */
866         for (j = 0; j < ext->desc->num_properties; j++) {
867                 enum power_supply_property prop;
868                 prop = ext->desc->properties[j];
869
870                 if (power_supply_get_property(ext, prop, &ret))
871                         continue;
872
873                 switch (prop) {
874                 case POWER_SUPPLY_PROP_PRESENT:
875                         switch (ext->desc->type) {
876                         case POWER_SUPPLY_TYPE_MAINS:
877                                 /* AC disconnected */
878                                 if (!ret.intval && di->events.ac_conn) {
879                                         di->events.ac_conn = false;
880                                 }
881                                 /* AC connected */
882                                 else if (ret.intval && !di->events.ac_conn) {
883                                         di->events.ac_conn = true;
884                                         if (!di->events.usb_conn)
885                                                 ab8500_btemp_periodic(di, true);
886                                 }
887                                 break;
888                         case POWER_SUPPLY_TYPE_USB:
889                                 /* USB disconnected */
890                                 if (!ret.intval && di->events.usb_conn) {
891                                         di->events.usb_conn = false;
892                                 }
893                                 /* USB connected */
894                                 else if (ret.intval && !di->events.usb_conn) {
895                                         di->events.usb_conn = true;
896                                         if (!di->events.ac_conn)
897                                                 ab8500_btemp_periodic(di, true);
898                                 }
899                                 break;
900                         default:
901                                 break;
902                         }
903                         break;
904                 default:
905                         break;
906                 }
907         }
908         return 0;
909 }
910
911 /**
912  * ab8500_btemp_external_power_changed() - callback for power supply changes
913  * @psy:       pointer to the structure power_supply
914  *
915  * This function is pointing to the function pointer external_power_changed
916  * of the structure power_supply.
917  * This function gets executed when there is a change in the external power
918  * supply to the btemp.
919  */
920 static void ab8500_btemp_external_power_changed(struct power_supply *psy)
921 {
922         struct ab8500_btemp *di = power_supply_get_drvdata(psy);
923
924         class_for_each_device(power_supply_class, NULL,
925                 di->btemp_psy, ab8500_btemp_get_ext_psy_data);
926 }
927
928 /* ab8500 btemp driver interrupts and their respective isr */
929 static struct ab8500_btemp_interrupts ab8500_btemp_irq[] = {
930         {"BAT_CTRL_INDB", ab8500_btemp_batctrlindb_handler},
931         {"BTEMP_LOW", ab8500_btemp_templow_handler},
932         {"BTEMP_HIGH", ab8500_btemp_temphigh_handler},
933         {"BTEMP_LOW_MEDIUM", ab8500_btemp_lowmed_handler},
934         {"BTEMP_MEDIUM_HIGH", ab8500_btemp_medhigh_handler},
935 };
936
937 #if defined(CONFIG_PM)
938 static int ab8500_btemp_resume(struct platform_device *pdev)
939 {
940         struct ab8500_btemp *di = platform_get_drvdata(pdev);
941
942         ab8500_btemp_periodic(di, true);
943
944         return 0;
945 }
946
947 static int ab8500_btemp_suspend(struct platform_device *pdev,
948         pm_message_t state)
949 {
950         struct ab8500_btemp *di = platform_get_drvdata(pdev);
951
952         ab8500_btemp_periodic(di, false);
953
954         return 0;
955 }
956 #else
957 #define ab8500_btemp_suspend      NULL
958 #define ab8500_btemp_resume       NULL
959 #endif
960
961 static int ab8500_btemp_remove(struct platform_device *pdev)
962 {
963         struct ab8500_btemp *di = platform_get_drvdata(pdev);
964         int i, irq;
965
966         /* Disable interrupts */
967         for (i = 0; i < ARRAY_SIZE(ab8500_btemp_irq); i++) {
968                 irq = platform_get_irq_byname(pdev, ab8500_btemp_irq[i].name);
969                 free_irq(irq, di);
970         }
971
972         /* Delete the work queue */
973         destroy_workqueue(di->btemp_wq);
974
975         flush_scheduled_work();
976         power_supply_unregister(di->btemp_psy);
977
978         return 0;
979 }
980
981 static char *supply_interface[] = {
982         "ab8500_chargalg",
983         "ab8500_fg",
984 };
985
986 static const struct power_supply_desc ab8500_btemp_desc = {
987         .name                   = "ab8500_btemp",
988         .type                   = POWER_SUPPLY_TYPE_BATTERY,
989         .properties             = ab8500_btemp_props,
990         .num_properties         = ARRAY_SIZE(ab8500_btemp_props),
991         .get_property           = ab8500_btemp_get_property,
992         .external_power_changed = ab8500_btemp_external_power_changed,
993 };
994
995 static int ab8500_btemp_probe(struct platform_device *pdev)
996 {
997         struct device_node *np = pdev->dev.of_node;
998         struct abx500_bm_data *plat = pdev->dev.platform_data;
999         struct power_supply_config psy_cfg = {};
1000         struct ab8500_btemp *di;
1001         int irq, i, ret = 0;
1002         u8 val;
1003
1004         di = devm_kzalloc(&pdev->dev, sizeof(*di), GFP_KERNEL);
1005         if (!di) {
1006                 dev_err(&pdev->dev, "%s no mem for ab8500_btemp\n", __func__);
1007                 return -ENOMEM;
1008         }
1009
1010         if (!plat) {
1011                 dev_err(&pdev->dev, "no battery management data supplied\n");
1012                 return -EINVAL;
1013         }
1014         di->bm = plat;
1015
1016         if (np) {
1017                 ret = ab8500_bm_of_probe(&pdev->dev, np, di->bm);
1018                 if (ret) {
1019                         dev_err(&pdev->dev, "failed to get battery information\n");
1020                         return ret;
1021                 }
1022         }
1023
1024         /* get parent data */
1025         di->dev = &pdev->dev;
1026         di->parent = dev_get_drvdata(pdev->dev.parent);
1027         di->gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
1028
1029         di->initialized = false;
1030
1031         psy_cfg.supplied_to = supply_interface;
1032         psy_cfg.num_supplicants = ARRAY_SIZE(supply_interface);
1033         psy_cfg.drv_data = di;
1034
1035         /* Create a work queue for the btemp */
1036         di->btemp_wq =
1037                 alloc_workqueue("ab8500_btemp_wq", WQ_MEM_RECLAIM, 0);
1038         if (di->btemp_wq == NULL) {
1039                 dev_err(di->dev, "failed to create work queue\n");
1040                 return -ENOMEM;
1041         }
1042
1043         /* Init work for measuring temperature periodically */
1044         INIT_DEFERRABLE_WORK(&di->btemp_periodic_work,
1045                 ab8500_btemp_periodic_work);
1046
1047         /* Set BTEMP thermal limits. Low and Med are fixed */
1048         di->btemp_ranges.btemp_low_limit = BTEMP_THERMAL_LOW_LIMIT;
1049         di->btemp_ranges.btemp_med_limit = BTEMP_THERMAL_MED_LIMIT;
1050
1051         ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER,
1052                 AB8500_BTEMP_HIGH_TH, &val);
1053         if (ret < 0) {
1054                 dev_err(di->dev, "%s ab8500 read failed\n", __func__);
1055                 goto free_btemp_wq;
1056         }
1057         switch (val) {
1058         case BTEMP_HIGH_TH_57_0:
1059         case BTEMP_HIGH_TH_57_1:
1060                 di->btemp_ranges.btemp_high_limit =
1061                         BTEMP_THERMAL_HIGH_LIMIT_57;
1062                 break;
1063         case BTEMP_HIGH_TH_52:
1064                 di->btemp_ranges.btemp_high_limit =
1065                         BTEMP_THERMAL_HIGH_LIMIT_52;
1066                 break;
1067         case BTEMP_HIGH_TH_62:
1068                 di->btemp_ranges.btemp_high_limit =
1069                         BTEMP_THERMAL_HIGH_LIMIT_62;
1070                 break;
1071         }
1072
1073         /* Register BTEMP power supply class */
1074         di->btemp_psy = power_supply_register(di->dev, &ab8500_btemp_desc,
1075                                               &psy_cfg);
1076         if (IS_ERR(di->btemp_psy)) {
1077                 dev_err(di->dev, "failed to register BTEMP psy\n");
1078                 ret = PTR_ERR(di->btemp_psy);
1079                 goto free_btemp_wq;
1080         }
1081
1082         /* Register interrupts */
1083         for (i = 0; i < ARRAY_SIZE(ab8500_btemp_irq); i++) {
1084                 irq = platform_get_irq_byname(pdev, ab8500_btemp_irq[i].name);
1085                 ret = request_threaded_irq(irq, NULL, ab8500_btemp_irq[i].isr,
1086                         IRQF_SHARED | IRQF_NO_SUSPEND,
1087                         ab8500_btemp_irq[i].name, di);
1088
1089                 if (ret) {
1090                         dev_err(di->dev, "failed to request %s IRQ %d: %d\n"
1091                                 , ab8500_btemp_irq[i].name, irq, ret);
1092                         goto free_irq;
1093                 }
1094                 dev_dbg(di->dev, "Requested %s IRQ %d: %d\n",
1095                         ab8500_btemp_irq[i].name, irq, ret);
1096         }
1097
1098         platform_set_drvdata(pdev, di);
1099
1100         /* Kick off periodic temperature measurements */
1101         ab8500_btemp_periodic(di, true);
1102         list_add_tail(&di->node, &ab8500_btemp_list);
1103
1104         return ret;
1105
1106 free_irq:
1107         power_supply_unregister(di->btemp_psy);
1108
1109         /* We also have to free all successfully registered irqs */
1110         for (i = i - 1; i >= 0; i--) {
1111                 irq = platform_get_irq_byname(pdev, ab8500_btemp_irq[i].name);
1112                 free_irq(irq, di);
1113         }
1114 free_btemp_wq:
1115         destroy_workqueue(di->btemp_wq);
1116         return ret;
1117 }
1118
1119 static const struct of_device_id ab8500_btemp_match[] = {
1120         { .compatible = "stericsson,ab8500-btemp", },
1121         { },
1122 };
1123
1124 static struct platform_driver ab8500_btemp_driver = {
1125         .probe = ab8500_btemp_probe,
1126         .remove = ab8500_btemp_remove,
1127         .suspend = ab8500_btemp_suspend,
1128         .resume = ab8500_btemp_resume,
1129         .driver = {
1130                 .name = "ab8500-btemp",
1131                 .of_match_table = ab8500_btemp_match,
1132         },
1133 };
1134
1135 static int __init ab8500_btemp_init(void)
1136 {
1137         return platform_driver_register(&ab8500_btemp_driver);
1138 }
1139
1140 static void __exit ab8500_btemp_exit(void)
1141 {
1142         platform_driver_unregister(&ab8500_btemp_driver);
1143 }
1144
1145 device_initcall(ab8500_btemp_init);
1146 module_exit(ab8500_btemp_exit);
1147
1148 MODULE_LICENSE("GPL v2");
1149 MODULE_AUTHOR("Johan Palsson, Karl Komierowski, Arun R Murthy");
1150 MODULE_ALIAS("platform:ab8500-btemp");
1151 MODULE_DESCRIPTION("AB8500 battery temperature driver");