xref: /openbmc/linux/drivers/thermal/qcom/tsens.c (revision 6523d3b2)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2015, The Linux Foundation. All rights reserved.
4  * Copyright (c) 2019, 2020, Linaro Ltd.
5  */
6 
7 #include <linux/debugfs.h>
8 #include <linux/err.h>
9 #include <linux/io.h>
10 #include <linux/module.h>
11 #include <linux/nvmem-consumer.h>
12 #include <linux/of.h>
13 #include <linux/of_address.h>
14 #include <linux/of_platform.h>
15 #include <linux/mfd/syscon.h>
16 #include <linux/platform_device.h>
17 #include <linux/pm.h>
18 #include <linux/regmap.h>
19 #include <linux/slab.h>
20 #include <linux/thermal.h>
21 #include "tsens.h"
22 
23 /**
24  * struct tsens_irq_data - IRQ status and temperature violations
25  * @up_viol:        upper threshold violated
26  * @up_thresh:      upper threshold temperature value
27  * @up_irq_mask:    mask register for upper threshold irqs
28  * @up_irq_clear:   clear register for uppper threshold irqs
29  * @low_viol:       lower threshold violated
30  * @low_thresh:     lower threshold temperature value
31  * @low_irq_mask:   mask register for lower threshold irqs
32  * @low_irq_clear:  clear register for lower threshold irqs
33  * @crit_viol:      critical threshold violated
34  * @crit_thresh:    critical threshold temperature value
35  * @crit_irq_mask:  mask register for critical threshold irqs
36  * @crit_irq_clear: clear register for critical threshold irqs
37  *
38  * Structure containing data about temperature threshold settings and
39  * irq status if they were violated.
40  */
41 struct tsens_irq_data {
42 	u32 up_viol;
43 	int up_thresh;
44 	u32 up_irq_mask;
45 	u32 up_irq_clear;
46 	u32 low_viol;
47 	int low_thresh;
48 	u32 low_irq_mask;
49 	u32 low_irq_clear;
50 	u32 crit_viol;
51 	u32 crit_thresh;
52 	u32 crit_irq_mask;
53 	u32 crit_irq_clear;
54 };
55 
56 char *qfprom_read(struct device *dev, const char *cname)
57 {
58 	struct nvmem_cell *cell;
59 	ssize_t data;
60 	char *ret;
61 
62 	cell = nvmem_cell_get(dev, cname);
63 	if (IS_ERR(cell))
64 		return ERR_CAST(cell);
65 
66 	ret = nvmem_cell_read(cell, &data);
67 	nvmem_cell_put(cell);
68 
69 	return ret;
70 }
71 
72 /*
73  * Use this function on devices where slope and offset calculations
74  * depend on calibration data read from qfprom. On others the slope
75  * and offset values are derived from tz->tzp->slope and tz->tzp->offset
76  * resp.
77  */
78 void compute_intercept_slope(struct tsens_priv *priv, u32 *p1,
79 			     u32 *p2, u32 mode)
80 {
81 	int i;
82 	int num, den;
83 
84 	for (i = 0; i < priv->num_sensors; i++) {
85 		dev_dbg(priv->dev,
86 			"%s: sensor%d - data_point1:%#x data_point2:%#x\n",
87 			__func__, i, p1[i], p2[i]);
88 
89 		if (!priv->sensor[i].slope)
90 			priv->sensor[i].slope = SLOPE_DEFAULT;
91 		if (mode == TWO_PT_CALIB) {
92 			/*
93 			 * slope (m) = adc_code2 - adc_code1 (y2 - y1)/
94 			 *	temp_120_degc - temp_30_degc (x2 - x1)
95 			 */
96 			num = p2[i] - p1[i];
97 			num *= SLOPE_FACTOR;
98 			den = CAL_DEGC_PT2 - CAL_DEGC_PT1;
99 			priv->sensor[i].slope = num / den;
100 		}
101 
102 		priv->sensor[i].offset = (p1[i] * SLOPE_FACTOR) -
103 				(CAL_DEGC_PT1 *
104 				priv->sensor[i].slope);
105 		dev_dbg(priv->dev, "%s: offset:%d\n", __func__,
106 			priv->sensor[i].offset);
107 	}
108 }
109 
110 static inline u32 degc_to_code(int degc, const struct tsens_sensor *s)
111 {
112 	u64 code = div_u64(((u64)degc * s->slope + s->offset), SLOPE_FACTOR);
113 
114 	pr_debug("%s: raw_code: 0x%llx, degc:%d\n", __func__, code, degc);
115 	return clamp_val(code, THRESHOLD_MIN_ADC_CODE, THRESHOLD_MAX_ADC_CODE);
116 }
117 
118 static inline int code_to_degc(u32 adc_code, const struct tsens_sensor *s)
119 {
120 	int degc, num, den;
121 
122 	num = (adc_code * SLOPE_FACTOR) - s->offset;
123 	den = s->slope;
124 
125 	if (num > 0)
126 		degc = num + (den / 2);
127 	else if (num < 0)
128 		degc = num - (den / 2);
129 	else
130 		degc = num;
131 
132 	degc /= den;
133 
134 	return degc;
135 }
136 
137 /**
138  * tsens_hw_to_mC - Return sign-extended temperature in mCelsius.
139  * @s:     Pointer to sensor struct
140  * @field: Index into regmap_field array pointing to temperature data
141  *
142  * This function handles temperature returned in ADC code or deciCelsius
143  * depending on IP version.
144  *
145  * Return: Temperature in milliCelsius on success, a negative errno will
146  * be returned in error cases
147  */
148 static int tsens_hw_to_mC(const struct tsens_sensor *s, int field)
149 {
150 	struct tsens_priv *priv = s->priv;
151 	u32 resolution;
152 	u32 temp = 0;
153 	int ret;
154 
155 	resolution = priv->fields[LAST_TEMP_0].msb -
156 		priv->fields[LAST_TEMP_0].lsb;
157 
158 	ret = regmap_field_read(priv->rf[field], &temp);
159 	if (ret)
160 		return ret;
161 
162 	/* Convert temperature from ADC code to milliCelsius */
163 	if (priv->feat->adc)
164 		return code_to_degc(temp, s) * 1000;
165 
166 	/* deciCelsius -> milliCelsius along with sign extension */
167 	return sign_extend32(temp, resolution) * 100;
168 }
169 
170 /**
171  * tsens_mC_to_hw - Convert temperature to hardware register value
172  * @s: Pointer to sensor struct
173  * @temp: temperature in milliCelsius to be programmed to hardware
174  *
175  * This function outputs the value to be written to hardware in ADC code
176  * or deciCelsius depending on IP version.
177  *
178  * Return: ADC code or temperature in deciCelsius.
179  */
180 static int tsens_mC_to_hw(const struct tsens_sensor *s, int temp)
181 {
182 	struct tsens_priv *priv = s->priv;
183 
184 	/* milliC to adc code */
185 	if (priv->feat->adc)
186 		return degc_to_code(temp / 1000, s);
187 
188 	/* milliC to deciC */
189 	return temp / 100;
190 }
191 
192 static inline enum tsens_ver tsens_version(struct tsens_priv *priv)
193 {
194 	return priv->feat->ver_major;
195 }
196 
197 static void tsens_set_interrupt_v1(struct tsens_priv *priv, u32 hw_id,
198 				   enum tsens_irq_type irq_type, bool enable)
199 {
200 	u32 index = 0;
201 
202 	switch (irq_type) {
203 	case UPPER:
204 		index = UP_INT_CLEAR_0 + hw_id;
205 		break;
206 	case LOWER:
207 		index = LOW_INT_CLEAR_0 + hw_id;
208 		break;
209 	case CRITICAL:
210 		/* No critical interrupts before v2 */
211 		return;
212 	}
213 	regmap_field_write(priv->rf[index], enable ? 0 : 1);
214 }
215 
216 static void tsens_set_interrupt_v2(struct tsens_priv *priv, u32 hw_id,
217 				   enum tsens_irq_type irq_type, bool enable)
218 {
219 	u32 index_mask = 0, index_clear = 0;
220 
221 	/*
222 	 * To enable the interrupt flag for a sensor:
223 	 *    - clear the mask bit
224 	 * To disable the interrupt flag for a sensor:
225 	 *    - Mask further interrupts for this sensor
226 	 *    - Write 1 followed by 0 to clear the interrupt
227 	 */
228 	switch (irq_type) {
229 	case UPPER:
230 		index_mask  = UP_INT_MASK_0 + hw_id;
231 		index_clear = UP_INT_CLEAR_0 + hw_id;
232 		break;
233 	case LOWER:
234 		index_mask  = LOW_INT_MASK_0 + hw_id;
235 		index_clear = LOW_INT_CLEAR_0 + hw_id;
236 		break;
237 	case CRITICAL:
238 		index_mask  = CRIT_INT_MASK_0 + hw_id;
239 		index_clear = CRIT_INT_CLEAR_0 + hw_id;
240 		break;
241 	}
242 
243 	if (enable) {
244 		regmap_field_write(priv->rf[index_mask], 0);
245 	} else {
246 		regmap_field_write(priv->rf[index_mask],  1);
247 		regmap_field_write(priv->rf[index_clear], 1);
248 		regmap_field_write(priv->rf[index_clear], 0);
249 	}
250 }
251 
252 /**
253  * tsens_set_interrupt - Set state of an interrupt
254  * @priv: Pointer to tsens controller private data
255  * @hw_id: Hardware ID aka. sensor number
256  * @irq_type: irq_type from enum tsens_irq_type
257  * @enable: false = disable, true = enable
258  *
259  * Call IP-specific function to set state of an interrupt
260  *
261  * Return: void
262  */
263 static void tsens_set_interrupt(struct tsens_priv *priv, u32 hw_id,
264 				enum tsens_irq_type irq_type, bool enable)
265 {
266 	dev_dbg(priv->dev, "[%u] %s: %s -> %s\n", hw_id, __func__,
267 		irq_type ? ((irq_type == 1) ? "UP" : "CRITICAL") : "LOW",
268 		enable ? "en" : "dis");
269 	if (tsens_version(priv) > VER_1_X)
270 		tsens_set_interrupt_v2(priv, hw_id, irq_type, enable);
271 	else
272 		tsens_set_interrupt_v1(priv, hw_id, irq_type, enable);
273 }
274 
275 /**
276  * tsens_threshold_violated - Check if a sensor temperature violated a preset threshold
277  * @priv: Pointer to tsens controller private data
278  * @hw_id: Hardware ID aka. sensor number
279  * @d: Pointer to irq state data
280  *
281  * Return: 0 if threshold was not violated, 1 if it was violated and negative
282  * errno in case of errors
283  */
284 static int tsens_threshold_violated(struct tsens_priv *priv, u32 hw_id,
285 				    struct tsens_irq_data *d)
286 {
287 	int ret;
288 
289 	ret = regmap_field_read(priv->rf[UPPER_STATUS_0 + hw_id], &d->up_viol);
290 	if (ret)
291 		return ret;
292 	ret = regmap_field_read(priv->rf[LOWER_STATUS_0 + hw_id], &d->low_viol);
293 	if (ret)
294 		return ret;
295 
296 	if (priv->feat->crit_int) {
297 		ret = regmap_field_read(priv->rf[CRITICAL_STATUS_0 + hw_id],
298 					&d->crit_viol);
299 		if (ret)
300 			return ret;
301 	}
302 
303 	if (d->up_viol || d->low_viol || d->crit_viol)
304 		return 1;
305 
306 	return 0;
307 }
308 
309 static int tsens_read_irq_state(struct tsens_priv *priv, u32 hw_id,
310 				const struct tsens_sensor *s,
311 				struct tsens_irq_data *d)
312 {
313 	int ret;
314 
315 	ret = regmap_field_read(priv->rf[UP_INT_CLEAR_0 + hw_id], &d->up_irq_clear);
316 	if (ret)
317 		return ret;
318 	ret = regmap_field_read(priv->rf[LOW_INT_CLEAR_0 + hw_id], &d->low_irq_clear);
319 	if (ret)
320 		return ret;
321 	if (tsens_version(priv) > VER_1_X) {
322 		ret = regmap_field_read(priv->rf[UP_INT_MASK_0 + hw_id], &d->up_irq_mask);
323 		if (ret)
324 			return ret;
325 		ret = regmap_field_read(priv->rf[LOW_INT_MASK_0 + hw_id], &d->low_irq_mask);
326 		if (ret)
327 			return ret;
328 		ret = regmap_field_read(priv->rf[CRIT_INT_CLEAR_0 + hw_id],
329 					&d->crit_irq_clear);
330 		if (ret)
331 			return ret;
332 		ret = regmap_field_read(priv->rf[CRIT_INT_MASK_0 + hw_id],
333 					&d->crit_irq_mask);
334 		if (ret)
335 			return ret;
336 
337 		d->crit_thresh = tsens_hw_to_mC(s, CRIT_THRESH_0 + hw_id);
338 	} else {
339 		/* No mask register on older TSENS */
340 		d->up_irq_mask = 0;
341 		d->low_irq_mask = 0;
342 		d->crit_irq_clear = 0;
343 		d->crit_irq_mask = 0;
344 		d->crit_thresh = 0;
345 	}
346 
347 	d->up_thresh  = tsens_hw_to_mC(s, UP_THRESH_0 + hw_id);
348 	d->low_thresh = tsens_hw_to_mC(s, LOW_THRESH_0 + hw_id);
349 
350 	dev_dbg(priv->dev, "[%u] %s%s: status(%u|%u|%u) | clr(%u|%u|%u) | mask(%u|%u|%u)\n",
351 		hw_id, __func__,
352 		(d->up_viol || d->low_viol || d->crit_viol) ? "(V)" : "",
353 		d->low_viol, d->up_viol, d->crit_viol,
354 		d->low_irq_clear, d->up_irq_clear, d->crit_irq_clear,
355 		d->low_irq_mask, d->up_irq_mask, d->crit_irq_mask);
356 	dev_dbg(priv->dev, "[%u] %s%s: thresh: (%d:%d:%d)\n", hw_id, __func__,
357 		(d->up_viol || d->low_viol || d->crit_viol) ? "(V)" : "",
358 		d->low_thresh, d->up_thresh, d->crit_thresh);
359 
360 	return 0;
361 }
362 
363 static inline u32 masked_irq(u32 hw_id, u32 mask, enum tsens_ver ver)
364 {
365 	if (ver > VER_1_X)
366 		return mask & (1 << hw_id);
367 
368 	/* v1, v0.1 don't have a irq mask register */
369 	return 0;
370 }
371 
372 /**
373  * tsens_critical_irq_thread() - Threaded handler for critical interrupts
374  * @irq: irq number
375  * @data: tsens controller private data
376  *
377  * Check FSM watchdog bark status and clear if needed.
378  * Check all sensors to find ones that violated their critical threshold limits.
379  * Clear and then re-enable the interrupt.
380  *
381  * The level-triggered interrupt might deassert if the temperature returned to
382  * within the threshold limits by the time the handler got scheduled. We
383  * consider the irq to have been handled in that case.
384  *
385  * Return: IRQ_HANDLED
386  */
387 static irqreturn_t tsens_critical_irq_thread(int irq, void *data)
388 {
389 	struct tsens_priv *priv = data;
390 	struct tsens_irq_data d;
391 	int temp, ret, i;
392 	u32 wdog_status, wdog_count;
393 
394 	if (priv->feat->has_watchdog) {
395 		ret = regmap_field_read(priv->rf[WDOG_BARK_STATUS],
396 					&wdog_status);
397 		if (ret)
398 			return ret;
399 
400 		if (wdog_status) {
401 			/* Clear WDOG interrupt */
402 			regmap_field_write(priv->rf[WDOG_BARK_CLEAR], 1);
403 			regmap_field_write(priv->rf[WDOG_BARK_CLEAR], 0);
404 			ret = regmap_field_read(priv->rf[WDOG_BARK_COUNT],
405 						&wdog_count);
406 			if (ret)
407 				return ret;
408 			if (wdog_count)
409 				dev_dbg(priv->dev, "%s: watchdog count: %d\n",
410 					__func__, wdog_count);
411 
412 			/* Fall through to handle critical interrupts if any */
413 		}
414 	}
415 
416 	for (i = 0; i < priv->num_sensors; i++) {
417 		const struct tsens_sensor *s = &priv->sensor[i];
418 		u32 hw_id = s->hw_id;
419 
420 		if (!s->tzd)
421 			continue;
422 		if (!tsens_threshold_violated(priv, hw_id, &d))
423 			continue;
424 		ret = get_temp_tsens_valid(s, &temp);
425 		if (ret) {
426 			dev_err(priv->dev, "[%u] %s: error reading sensor\n",
427 				hw_id, __func__);
428 			continue;
429 		}
430 
431 		tsens_read_irq_state(priv, hw_id, s, &d);
432 		if (d.crit_viol &&
433 		    !masked_irq(hw_id, d.crit_irq_mask, tsens_version(priv))) {
434 			/* Mask critical interrupts, unused on Linux */
435 			tsens_set_interrupt(priv, hw_id, CRITICAL, false);
436 		}
437 	}
438 
439 	return IRQ_HANDLED;
440 }
441 
442 /**
443  * tsens_irq_thread - Threaded interrupt handler for uplow interrupts
444  * @irq: irq number
445  * @data: tsens controller private data
446  *
447  * Check all sensors to find ones that violated their threshold limits. If the
448  * temperature is still outside the limits, call thermal_zone_device_update() to
449  * update the thresholds, else re-enable the interrupts.
450  *
451  * The level-triggered interrupt might deassert if the temperature returned to
452  * within the threshold limits by the time the handler got scheduled. We
453  * consider the irq to have been handled in that case.
454  *
455  * Return: IRQ_HANDLED
456  */
457 static irqreturn_t tsens_irq_thread(int irq, void *data)
458 {
459 	struct tsens_priv *priv = data;
460 	struct tsens_irq_data d;
461 	bool enable = true, disable = false;
462 	unsigned long flags;
463 	int temp, ret, i;
464 
465 	for (i = 0; i < priv->num_sensors; i++) {
466 		bool trigger = false;
467 		const struct tsens_sensor *s = &priv->sensor[i];
468 		u32 hw_id = s->hw_id;
469 
470 		if (!s->tzd)
471 			continue;
472 		if (!tsens_threshold_violated(priv, hw_id, &d))
473 			continue;
474 		ret = get_temp_tsens_valid(s, &temp);
475 		if (ret) {
476 			dev_err(priv->dev, "[%u] %s: error reading sensor\n",
477 				hw_id, __func__);
478 			continue;
479 		}
480 
481 		spin_lock_irqsave(&priv->ul_lock, flags);
482 
483 		tsens_read_irq_state(priv, hw_id, s, &d);
484 
485 		if (d.up_viol &&
486 		    !masked_irq(hw_id, d.up_irq_mask, tsens_version(priv))) {
487 			tsens_set_interrupt(priv, hw_id, UPPER, disable);
488 			if (d.up_thresh > temp) {
489 				dev_dbg(priv->dev, "[%u] %s: re-arm upper\n",
490 					hw_id, __func__);
491 				tsens_set_interrupt(priv, hw_id, UPPER, enable);
492 			} else {
493 				trigger = true;
494 				/* Keep irq masked */
495 			}
496 		} else if (d.low_viol &&
497 			   !masked_irq(hw_id, d.low_irq_mask, tsens_version(priv))) {
498 			tsens_set_interrupt(priv, hw_id, LOWER, disable);
499 			if (d.low_thresh < temp) {
500 				dev_dbg(priv->dev, "[%u] %s: re-arm low\n",
501 					hw_id, __func__);
502 				tsens_set_interrupt(priv, hw_id, LOWER, enable);
503 			} else {
504 				trigger = true;
505 				/* Keep irq masked */
506 			}
507 		}
508 
509 		spin_unlock_irqrestore(&priv->ul_lock, flags);
510 
511 		if (trigger) {
512 			dev_dbg(priv->dev, "[%u] %s: TZ update trigger (%d mC)\n",
513 				hw_id, __func__, temp);
514 			thermal_zone_device_update(s->tzd,
515 						   THERMAL_EVENT_UNSPECIFIED);
516 		} else {
517 			dev_dbg(priv->dev, "[%u] %s: no violation:  %d\n",
518 				hw_id, __func__, temp);
519 		}
520 
521 		if (tsens_version(priv) < VER_0_1) {
522 			/* Constraint: There is only 1 interrupt control register for all
523 			 * 11 temperature sensor. So monitoring more than 1 sensor based
524 			 * on interrupts will yield inconsistent result. To overcome this
525 			 * issue we will monitor only sensor 0 which is the master sensor.
526 			 */
527 			break;
528 		}
529 	}
530 
531 	return IRQ_HANDLED;
532 }
533 
534 static int tsens_set_trips(void *_sensor, int low, int high)
535 {
536 	struct tsens_sensor *s = _sensor;
537 	struct tsens_priv *priv = s->priv;
538 	struct device *dev = priv->dev;
539 	struct tsens_irq_data d;
540 	unsigned long flags;
541 	int high_val, low_val, cl_high, cl_low;
542 	u32 hw_id = s->hw_id;
543 
544 	if (tsens_version(priv) < VER_0_1) {
545 		/* Pre v0.1 IP had a single register for each type of interrupt
546 		 * and thresholds
547 		 */
548 		hw_id = 0;
549 	}
550 
551 	dev_dbg(dev, "[%u] %s: proposed thresholds: (%d:%d)\n",
552 		hw_id, __func__, low, high);
553 
554 	cl_high = clamp_val(high, -40000, 120000);
555 	cl_low  = clamp_val(low, -40000, 120000);
556 
557 	high_val = tsens_mC_to_hw(s, cl_high);
558 	low_val  = tsens_mC_to_hw(s, cl_low);
559 
560 	spin_lock_irqsave(&priv->ul_lock, flags);
561 
562 	tsens_read_irq_state(priv, hw_id, s, &d);
563 
564 	/* Write the new thresholds and clear the status */
565 	regmap_field_write(priv->rf[LOW_THRESH_0 + hw_id], low_val);
566 	regmap_field_write(priv->rf[UP_THRESH_0 + hw_id], high_val);
567 	tsens_set_interrupt(priv, hw_id, LOWER, true);
568 	tsens_set_interrupt(priv, hw_id, UPPER, true);
569 
570 	spin_unlock_irqrestore(&priv->ul_lock, flags);
571 
572 	dev_dbg(dev, "[%u] %s: (%d:%d)->(%d:%d)\n",
573 		hw_id, __func__, d.low_thresh, d.up_thresh, cl_low, cl_high);
574 
575 	return 0;
576 }
577 
578 static int tsens_enable_irq(struct tsens_priv *priv)
579 {
580 	int ret;
581 	int val = tsens_version(priv) > VER_1_X ? 7 : 1;
582 
583 	ret = regmap_field_write(priv->rf[INT_EN], val);
584 	if (ret < 0)
585 		dev_err(priv->dev, "%s: failed to enable interrupts\n",
586 			__func__);
587 
588 	return ret;
589 }
590 
591 static void tsens_disable_irq(struct tsens_priv *priv)
592 {
593 	regmap_field_write(priv->rf[INT_EN], 0);
594 }
595 
596 int get_temp_tsens_valid(const struct tsens_sensor *s, int *temp)
597 {
598 	struct tsens_priv *priv = s->priv;
599 	int hw_id = s->hw_id;
600 	u32 temp_idx = LAST_TEMP_0 + hw_id;
601 	u32 valid_idx = VALID_0 + hw_id;
602 	u32 valid;
603 	int ret;
604 
605 	/* VER_0 doesn't have VALID bit */
606 	if (tsens_version(priv) == VER_0)
607 		goto get_temp;
608 
609 	/* Valid bit is 0 for 6 AHB clock cycles.
610 	 * At 19.2MHz, 1 AHB clock is ~60ns.
611 	 * We should enter this loop very, very rarely.
612 	 * Wait 1 us since it's the min of poll_timeout macro.
613 	 * Old value was 400 ns.
614 	 */
615 	ret = regmap_field_read_poll_timeout(priv->rf[valid_idx], valid,
616 					     valid, 1, 20 * USEC_PER_MSEC);
617 	if (ret)
618 		return ret;
619 
620 get_temp:
621 	/* Valid bit is set, OK to read the temperature */
622 	*temp = tsens_hw_to_mC(s, temp_idx);
623 
624 	return 0;
625 }
626 
627 int get_temp_common(const struct tsens_sensor *s, int *temp)
628 {
629 	struct tsens_priv *priv = s->priv;
630 	int hw_id = s->hw_id;
631 	int last_temp = 0, ret, trdy;
632 	unsigned long timeout;
633 
634 	timeout = jiffies + usecs_to_jiffies(TIMEOUT_US);
635 	do {
636 		if (tsens_version(priv) == VER_0) {
637 			ret = regmap_field_read(priv->rf[TRDY], &trdy);
638 			if (ret)
639 				return ret;
640 			if (!trdy)
641 				continue;
642 		}
643 
644 		ret = regmap_field_read(priv->rf[LAST_TEMP_0 + hw_id], &last_temp);
645 		if (ret)
646 			return ret;
647 
648 		*temp = code_to_degc(last_temp, s) * 1000;
649 
650 		return 0;
651 	} while (time_before(jiffies, timeout));
652 
653 	return -ETIMEDOUT;
654 }
655 
656 #ifdef CONFIG_DEBUG_FS
657 static int dbg_sensors_show(struct seq_file *s, void *data)
658 {
659 	struct platform_device *pdev = s->private;
660 	struct tsens_priv *priv = platform_get_drvdata(pdev);
661 	int i;
662 
663 	seq_printf(s, "max: %2d\nnum: %2d\n\n",
664 		   priv->feat->max_sensors, priv->num_sensors);
665 
666 	seq_puts(s, "      id    slope   offset\n--------------------------\n");
667 	for (i = 0;  i < priv->num_sensors; i++) {
668 		seq_printf(s, "%8d %8d %8d\n", priv->sensor[i].hw_id,
669 			   priv->sensor[i].slope, priv->sensor[i].offset);
670 	}
671 
672 	return 0;
673 }
674 
675 static int dbg_version_show(struct seq_file *s, void *data)
676 {
677 	struct platform_device *pdev = s->private;
678 	struct tsens_priv *priv = platform_get_drvdata(pdev);
679 	u32 maj_ver, min_ver, step_ver;
680 	int ret;
681 
682 	if (tsens_version(priv) > VER_0_1) {
683 		ret = regmap_field_read(priv->rf[VER_MAJOR], &maj_ver);
684 		if (ret)
685 			return ret;
686 		ret = regmap_field_read(priv->rf[VER_MINOR], &min_ver);
687 		if (ret)
688 			return ret;
689 		ret = regmap_field_read(priv->rf[VER_STEP], &step_ver);
690 		if (ret)
691 			return ret;
692 		seq_printf(s, "%d.%d.%d\n", maj_ver, min_ver, step_ver);
693 	} else {
694 		seq_puts(s, "0.1.0\n");
695 	}
696 
697 	return 0;
698 }
699 
700 DEFINE_SHOW_ATTRIBUTE(dbg_version);
701 DEFINE_SHOW_ATTRIBUTE(dbg_sensors);
702 
703 static void tsens_debug_init(struct platform_device *pdev)
704 {
705 	struct tsens_priv *priv = platform_get_drvdata(pdev);
706 	struct dentry *root, *file;
707 
708 	root = debugfs_lookup("tsens", NULL);
709 	if (!root)
710 		priv->debug_root = debugfs_create_dir("tsens", NULL);
711 	else
712 		priv->debug_root = root;
713 
714 	file = debugfs_lookup("version", priv->debug_root);
715 	if (!file)
716 		debugfs_create_file("version", 0444, priv->debug_root,
717 				    pdev, &dbg_version_fops);
718 
719 	/* A directory for each instance of the TSENS IP */
720 	priv->debug = debugfs_create_dir(dev_name(&pdev->dev), priv->debug_root);
721 	debugfs_create_file("sensors", 0444, priv->debug, pdev, &dbg_sensors_fops);
722 }
723 #else
724 static inline void tsens_debug_init(struct platform_device *pdev) {}
725 #endif
726 
727 static const struct regmap_config tsens_config = {
728 	.name		= "tm",
729 	.reg_bits	= 32,
730 	.val_bits	= 32,
731 	.reg_stride	= 4,
732 };
733 
734 static const struct regmap_config tsens_srot_config = {
735 	.name		= "srot",
736 	.reg_bits	= 32,
737 	.val_bits	= 32,
738 	.reg_stride	= 4,
739 };
740 
741 int __init init_common(struct tsens_priv *priv)
742 {
743 	void __iomem *tm_base, *srot_base;
744 	struct device *dev = priv->dev;
745 	u32 ver_minor;
746 	struct resource *res;
747 	u32 enabled;
748 	int ret, i, j;
749 	struct platform_device *op = of_find_device_by_node(priv->dev->of_node);
750 
751 	if (!op)
752 		return -EINVAL;
753 
754 	if (op->num_resources > 1) {
755 		/* DT with separate SROT and TM address space */
756 		priv->tm_offset = 0;
757 		res = platform_get_resource(op, IORESOURCE_MEM, 1);
758 		srot_base = devm_ioremap_resource(dev, res);
759 		if (IS_ERR(srot_base)) {
760 			ret = PTR_ERR(srot_base);
761 			goto err_put_device;
762 		}
763 
764 		priv->srot_map = devm_regmap_init_mmio(dev, srot_base,
765 						       &tsens_srot_config);
766 		if (IS_ERR(priv->srot_map)) {
767 			ret = PTR_ERR(priv->srot_map);
768 			goto err_put_device;
769 		}
770 	} else {
771 		/* old DTs where SROT and TM were in a contiguous 2K block */
772 		priv->tm_offset = 0x1000;
773 	}
774 
775 	if (tsens_version(priv) >= VER_0_1) {
776 		res = platform_get_resource(op, IORESOURCE_MEM, 0);
777 		tm_base = devm_ioremap_resource(dev, res);
778 		if (IS_ERR(tm_base)) {
779 			ret = PTR_ERR(tm_base);
780 			goto err_put_device;
781 		}
782 
783 		priv->tm_map = devm_regmap_init_mmio(dev, tm_base, &tsens_config);
784 	} else { /* VER_0 share the same gcc regs using a syscon */
785 		struct device *parent = priv->dev->parent;
786 
787 		if (parent)
788 			priv->tm_map = syscon_node_to_regmap(parent->of_node);
789 	}
790 
791 	if (IS_ERR_OR_NULL(priv->tm_map)) {
792 		if (!priv->tm_map)
793 			ret = -ENODEV;
794 		else
795 			ret = PTR_ERR(priv->tm_map);
796 		goto err_put_device;
797 	}
798 
799 	/* VER_0 have only tm_map */
800 	if (!priv->srot_map)
801 		priv->srot_map = priv->tm_map;
802 
803 	if (tsens_version(priv) > VER_0_1) {
804 		for (i = VER_MAJOR; i <= VER_STEP; i++) {
805 			priv->rf[i] = devm_regmap_field_alloc(dev, priv->srot_map,
806 							      priv->fields[i]);
807 			if (IS_ERR(priv->rf[i])) {
808 				ret = PTR_ERR(priv->rf[i]);
809 				goto err_put_device;
810 			}
811 		}
812 		ret = regmap_field_read(priv->rf[VER_MINOR], &ver_minor);
813 		if (ret)
814 			goto err_put_device;
815 	}
816 
817 	priv->rf[TSENS_EN] = devm_regmap_field_alloc(dev, priv->srot_map,
818 						     priv->fields[TSENS_EN]);
819 	if (IS_ERR(priv->rf[TSENS_EN])) {
820 		ret = PTR_ERR(priv->rf[TSENS_EN]);
821 		goto err_put_device;
822 	}
823 	/* in VER_0 TSENS need to be explicitly enabled */
824 	if (tsens_version(priv) == VER_0)
825 		regmap_field_write(priv->rf[TSENS_EN], 1);
826 
827 	ret = regmap_field_read(priv->rf[TSENS_EN], &enabled);
828 	if (ret)
829 		goto err_put_device;
830 	if (!enabled) {
831 		dev_err(dev, "%s: device not enabled\n", __func__);
832 		ret = -ENODEV;
833 		goto err_put_device;
834 	}
835 
836 	priv->rf[SENSOR_EN] = devm_regmap_field_alloc(dev, priv->srot_map,
837 						      priv->fields[SENSOR_EN]);
838 	if (IS_ERR(priv->rf[SENSOR_EN])) {
839 		ret = PTR_ERR(priv->rf[SENSOR_EN]);
840 		goto err_put_device;
841 	}
842 	priv->rf[INT_EN] = devm_regmap_field_alloc(dev, priv->tm_map,
843 						   priv->fields[INT_EN]);
844 	if (IS_ERR(priv->rf[INT_EN])) {
845 		ret = PTR_ERR(priv->rf[INT_EN]);
846 		goto err_put_device;
847 	}
848 
849 	priv->rf[TSENS_SW_RST] =
850 		devm_regmap_field_alloc(dev, priv->srot_map, priv->fields[TSENS_SW_RST]);
851 	if (IS_ERR(priv->rf[TSENS_SW_RST])) {
852 		ret = PTR_ERR(priv->rf[TSENS_SW_RST]);
853 		goto err_put_device;
854 	}
855 
856 	priv->rf[TRDY] = devm_regmap_field_alloc(dev, priv->tm_map, priv->fields[TRDY]);
857 	if (IS_ERR(priv->rf[TRDY])) {
858 		ret = PTR_ERR(priv->rf[TRDY]);
859 		goto err_put_device;
860 	}
861 
862 	/* This loop might need changes if enum regfield_ids is reordered */
863 	for (j = LAST_TEMP_0; j <= UP_THRESH_15; j += 16) {
864 		for (i = 0; i < priv->feat->max_sensors; i++) {
865 			int idx = j + i;
866 
867 			priv->rf[idx] = devm_regmap_field_alloc(dev,
868 								priv->tm_map,
869 								priv->fields[idx]);
870 			if (IS_ERR(priv->rf[idx])) {
871 				ret = PTR_ERR(priv->rf[idx]);
872 				goto err_put_device;
873 			}
874 		}
875 	}
876 
877 	if (priv->feat->crit_int || tsens_version(priv) < VER_0_1) {
878 		/* Loop might need changes if enum regfield_ids is reordered */
879 		for (j = CRITICAL_STATUS_0; j <= CRIT_THRESH_15; j += 16) {
880 			for (i = 0; i < priv->feat->max_sensors; i++) {
881 				int idx = j + i;
882 
883 				priv->rf[idx] =
884 					devm_regmap_field_alloc(dev,
885 								priv->tm_map,
886 								priv->fields[idx]);
887 				if (IS_ERR(priv->rf[idx])) {
888 					ret = PTR_ERR(priv->rf[idx]);
889 					goto err_put_device;
890 				}
891 			}
892 		}
893 	}
894 
895 	if (tsens_version(priv) > VER_1_X &&  ver_minor > 2) {
896 		/* Watchdog is present only on v2.3+ */
897 		priv->feat->has_watchdog = 1;
898 		for (i = WDOG_BARK_STATUS; i <= CC_MON_MASK; i++) {
899 			priv->rf[i] = devm_regmap_field_alloc(dev, priv->tm_map,
900 							      priv->fields[i]);
901 			if (IS_ERR(priv->rf[i])) {
902 				ret = PTR_ERR(priv->rf[i]);
903 				goto err_put_device;
904 			}
905 		}
906 		/*
907 		 * Watchdog is already enabled, unmask the bark.
908 		 * Disable cycle completion monitoring
909 		 */
910 		regmap_field_write(priv->rf[WDOG_BARK_MASK], 0);
911 		regmap_field_write(priv->rf[CC_MON_MASK], 1);
912 	}
913 
914 	spin_lock_init(&priv->ul_lock);
915 
916 	/* VER_0 interrupt doesn't need to be enabled */
917 	if (tsens_version(priv) >= VER_0_1)
918 		tsens_enable_irq(priv);
919 
920 	tsens_debug_init(op);
921 
922 err_put_device:
923 	put_device(&op->dev);
924 	return ret;
925 }
926 
927 static int tsens_get_temp(void *data, int *temp)
928 {
929 	struct tsens_sensor *s = data;
930 	struct tsens_priv *priv = s->priv;
931 
932 	return priv->ops->get_temp(s, temp);
933 }
934 
935 static int tsens_get_trend(void *data, int trip, enum thermal_trend *trend)
936 {
937 	struct tsens_sensor *s = data;
938 	struct tsens_priv *priv = s->priv;
939 
940 	if (priv->ops->get_trend)
941 		return priv->ops->get_trend(s, trend);
942 
943 	return -ENOTSUPP;
944 }
945 
946 static int  __maybe_unused tsens_suspend(struct device *dev)
947 {
948 	struct tsens_priv *priv = dev_get_drvdata(dev);
949 
950 	if (priv->ops && priv->ops->suspend)
951 		return priv->ops->suspend(priv);
952 
953 	return 0;
954 }
955 
956 static int __maybe_unused tsens_resume(struct device *dev)
957 {
958 	struct tsens_priv *priv = dev_get_drvdata(dev);
959 
960 	if (priv->ops && priv->ops->resume)
961 		return priv->ops->resume(priv);
962 
963 	return 0;
964 }
965 
966 static SIMPLE_DEV_PM_OPS(tsens_pm_ops, tsens_suspend, tsens_resume);
967 
968 static const struct of_device_id tsens_table[] = {
969 	{
970 		.compatible = "qcom,ipq8064-tsens",
971 		.data = &data_8960,
972 	}, {
973 		.compatible = "qcom,mdm9607-tsens",
974 		.data = &data_9607,
975 	}, {
976 		.compatible = "qcom,msm8916-tsens",
977 		.data = &data_8916,
978 	}, {
979 		.compatible = "qcom,msm8939-tsens",
980 		.data = &data_8939,
981 	}, {
982 		.compatible = "qcom,msm8974-tsens",
983 		.data = &data_8974,
984 	}, {
985 		.compatible = "qcom,msm8976-tsens",
986 		.data = &data_8976,
987 	}, {
988 		.compatible = "qcom,msm8996-tsens",
989 		.data = &data_8996,
990 	}, {
991 		.compatible = "qcom,tsens-v1",
992 		.data = &data_tsens_v1,
993 	}, {
994 		.compatible = "qcom,tsens-v2",
995 		.data = &data_tsens_v2,
996 	},
997 	{}
998 };
999 MODULE_DEVICE_TABLE(of, tsens_table);
1000 
1001 static const struct thermal_zone_of_device_ops tsens_of_ops = {
1002 	.get_temp = tsens_get_temp,
1003 	.get_trend = tsens_get_trend,
1004 	.set_trips = tsens_set_trips,
1005 };
1006 
1007 static int tsens_register_irq(struct tsens_priv *priv, char *irqname,
1008 			      irq_handler_t thread_fn)
1009 {
1010 	struct platform_device *pdev;
1011 	int ret, irq;
1012 
1013 	pdev = of_find_device_by_node(priv->dev->of_node);
1014 	if (!pdev)
1015 		return -ENODEV;
1016 
1017 	irq = platform_get_irq_byname(pdev, irqname);
1018 	if (irq < 0) {
1019 		ret = irq;
1020 		/* For old DTs with no IRQ defined */
1021 		if (irq == -ENXIO)
1022 			ret = 0;
1023 	} else {
1024 		/* VER_0 interrupt is TRIGGER_RISING, VER_0_1 and up is ONESHOT */
1025 		if (tsens_version(priv) == VER_0)
1026 			ret = devm_request_threaded_irq(&pdev->dev, irq,
1027 							thread_fn, NULL,
1028 							IRQF_TRIGGER_RISING,
1029 							dev_name(&pdev->dev),
1030 							priv);
1031 		else
1032 			ret = devm_request_threaded_irq(&pdev->dev, irq, NULL,
1033 							thread_fn, IRQF_ONESHOT,
1034 							dev_name(&pdev->dev),
1035 							priv);
1036 
1037 		if (ret)
1038 			dev_err(&pdev->dev, "%s: failed to get irq\n",
1039 				__func__);
1040 		else
1041 			enable_irq_wake(irq);
1042 	}
1043 
1044 	put_device(&pdev->dev);
1045 	return ret;
1046 }
1047 
1048 static int tsens_register(struct tsens_priv *priv)
1049 {
1050 	int i, ret;
1051 	struct thermal_zone_device *tzd;
1052 
1053 	for (i = 0;  i < priv->num_sensors; i++) {
1054 		priv->sensor[i].priv = priv;
1055 		tzd = devm_thermal_zone_of_sensor_register(priv->dev, priv->sensor[i].hw_id,
1056 							   &priv->sensor[i],
1057 							   &tsens_of_ops);
1058 		if (IS_ERR(tzd))
1059 			continue;
1060 		priv->sensor[i].tzd = tzd;
1061 		if (priv->ops->enable)
1062 			priv->ops->enable(priv, i);
1063 	}
1064 
1065 	/* VER_0 require to set MIN and MAX THRESH
1066 	 * These 2 regs are set using the:
1067 	 * - CRIT_THRESH_0 for MAX THRESH hardcoded to 120°C
1068 	 * - CRIT_THRESH_1 for MIN THRESH hardcoded to   0°C
1069 	 */
1070 	if (tsens_version(priv) < VER_0_1) {
1071 		regmap_field_write(priv->rf[CRIT_THRESH_0],
1072 				   tsens_mC_to_hw(priv->sensor, 120000));
1073 
1074 		regmap_field_write(priv->rf[CRIT_THRESH_1],
1075 				   tsens_mC_to_hw(priv->sensor, 0));
1076 	}
1077 
1078 	ret = tsens_register_irq(priv, "uplow", tsens_irq_thread);
1079 	if (ret < 0)
1080 		return ret;
1081 
1082 	if (priv->feat->crit_int)
1083 		ret = tsens_register_irq(priv, "critical",
1084 					 tsens_critical_irq_thread);
1085 
1086 	return ret;
1087 }
1088 
1089 static int tsens_probe(struct platform_device *pdev)
1090 {
1091 	int ret, i;
1092 	struct device *dev;
1093 	struct device_node *np;
1094 	struct tsens_priv *priv;
1095 	const struct tsens_plat_data *data;
1096 	const struct of_device_id *id;
1097 	u32 num_sensors;
1098 
1099 	if (pdev->dev.of_node)
1100 		dev = &pdev->dev;
1101 	else
1102 		dev = pdev->dev.parent;
1103 
1104 	np = dev->of_node;
1105 
1106 	id = of_match_node(tsens_table, np);
1107 	if (id)
1108 		data = id->data;
1109 	else
1110 		data = &data_8960;
1111 
1112 	num_sensors = data->num_sensors;
1113 
1114 	if (np)
1115 		of_property_read_u32(np, "#qcom,sensors", &num_sensors);
1116 
1117 	if (num_sensors <= 0) {
1118 		dev_err(dev, "%s: invalid number of sensors\n", __func__);
1119 		return -EINVAL;
1120 	}
1121 
1122 	priv = devm_kzalloc(dev,
1123 			     struct_size(priv, sensor, num_sensors),
1124 			     GFP_KERNEL);
1125 	if (!priv)
1126 		return -ENOMEM;
1127 
1128 	priv->dev = dev;
1129 	priv->num_sensors = num_sensors;
1130 	priv->ops = data->ops;
1131 	for (i = 0;  i < priv->num_sensors; i++) {
1132 		if (data->hw_ids)
1133 			priv->sensor[i].hw_id = data->hw_ids[i];
1134 		else
1135 			priv->sensor[i].hw_id = i;
1136 	}
1137 	priv->feat = data->feat;
1138 	priv->fields = data->fields;
1139 
1140 	platform_set_drvdata(pdev, priv);
1141 
1142 	if (!priv->ops || !priv->ops->init || !priv->ops->get_temp)
1143 		return -EINVAL;
1144 
1145 	ret = priv->ops->init(priv);
1146 	if (ret < 0) {
1147 		dev_err(dev, "%s: init failed\n", __func__);
1148 		return ret;
1149 	}
1150 
1151 	if (priv->ops->calibrate) {
1152 		ret = priv->ops->calibrate(priv);
1153 		if (ret < 0) {
1154 			if (ret != -EPROBE_DEFER)
1155 				dev_err(dev, "%s: calibration failed\n", __func__);
1156 			return ret;
1157 		}
1158 	}
1159 
1160 	return tsens_register(priv);
1161 }
1162 
1163 static int tsens_remove(struct platform_device *pdev)
1164 {
1165 	struct tsens_priv *priv = platform_get_drvdata(pdev);
1166 
1167 	debugfs_remove_recursive(priv->debug_root);
1168 	tsens_disable_irq(priv);
1169 	if (priv->ops->disable)
1170 		priv->ops->disable(priv);
1171 
1172 	return 0;
1173 }
1174 
1175 static struct platform_driver tsens_driver = {
1176 	.probe = tsens_probe,
1177 	.remove = tsens_remove,
1178 	.driver = {
1179 		.name = "qcom-tsens",
1180 		.pm	= &tsens_pm_ops,
1181 		.of_match_table = tsens_table,
1182 	},
1183 };
1184 module_platform_driver(tsens_driver);
1185 
1186 MODULE_LICENSE("GPL v2");
1187 MODULE_DESCRIPTION("QCOM Temperature Sensor driver");
1188 MODULE_ALIAS("platform:qcom-tsens");
1189