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