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