xref: /openbmc/linux/drivers/thermal/qcom/tsens.c (revision ee7da21a)
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 (IS_ERR(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 (IS_ERR(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_1) {
607 		ret = regmap_field_read(priv->rf[valid_idx], &valid);
608 		if (ret)
609 			return ret;
610 		while (!valid) {
611 			/* Valid bit is 0 for 6 AHB clock cycles.
612 			 * At 19.2MHz, 1 AHB clock is ~60ns.
613 			 * We should enter this loop very, very rarely.
614 			 */
615 			ndelay(400);
616 			ret = regmap_field_read(priv->rf[valid_idx], &valid);
617 			if (ret)
618 				return ret;
619 		}
620 	}
621 
622 	/* Valid bit is set, OK to read the temperature */
623 	*temp = tsens_hw_to_mC(s, temp_idx);
624 
625 	return 0;
626 }
627 
628 int get_temp_common(const struct tsens_sensor *s, int *temp)
629 {
630 	struct tsens_priv *priv = s->priv;
631 	int hw_id = s->hw_id;
632 	int last_temp = 0, ret, trdy;
633 	unsigned long timeout;
634 
635 	timeout = jiffies + usecs_to_jiffies(TIMEOUT_US);
636 	do {
637 		if (tsens_version(priv) == VER_0) {
638 			ret = regmap_field_read(priv->rf[TRDY], &trdy);
639 			if (ret)
640 				return ret;
641 			if (!trdy)
642 				continue;
643 		}
644 
645 		ret = regmap_field_read(priv->rf[LAST_TEMP_0 + hw_id], &last_temp);
646 		if (ret)
647 			return ret;
648 
649 		*temp = code_to_degc(last_temp, s) * 1000;
650 
651 		return 0;
652 	} while (time_before(jiffies, timeout));
653 
654 	return -ETIMEDOUT;
655 }
656 
657 #ifdef CONFIG_DEBUG_FS
658 static int dbg_sensors_show(struct seq_file *s, void *data)
659 {
660 	struct platform_device *pdev = s->private;
661 	struct tsens_priv *priv = platform_get_drvdata(pdev);
662 	int i;
663 
664 	seq_printf(s, "max: %2d\nnum: %2d\n\n",
665 		   priv->feat->max_sensors, priv->num_sensors);
666 
667 	seq_puts(s, "      id    slope   offset\n--------------------------\n");
668 	for (i = 0;  i < priv->num_sensors; i++) {
669 		seq_printf(s, "%8d %8d %8d\n", priv->sensor[i].hw_id,
670 			   priv->sensor[i].slope, priv->sensor[i].offset);
671 	}
672 
673 	return 0;
674 }
675 
676 static int dbg_version_show(struct seq_file *s, void *data)
677 {
678 	struct platform_device *pdev = s->private;
679 	struct tsens_priv *priv = platform_get_drvdata(pdev);
680 	u32 maj_ver, min_ver, step_ver;
681 	int ret;
682 
683 	if (tsens_version(priv) > VER_0_1) {
684 		ret = regmap_field_read(priv->rf[VER_MAJOR], &maj_ver);
685 		if (ret)
686 			return ret;
687 		ret = regmap_field_read(priv->rf[VER_MINOR], &min_ver);
688 		if (ret)
689 			return ret;
690 		ret = regmap_field_read(priv->rf[VER_STEP], &step_ver);
691 		if (ret)
692 			return ret;
693 		seq_printf(s, "%d.%d.%d\n", maj_ver, min_ver, step_ver);
694 	} else {
695 		seq_puts(s, "0.1.0\n");
696 	}
697 
698 	return 0;
699 }
700 
701 DEFINE_SHOW_ATTRIBUTE(dbg_version);
702 DEFINE_SHOW_ATTRIBUTE(dbg_sensors);
703 
704 static void tsens_debug_init(struct platform_device *pdev)
705 {
706 	struct tsens_priv *priv = platform_get_drvdata(pdev);
707 	struct dentry *root, *file;
708 
709 	root = debugfs_lookup("tsens", NULL);
710 	if (!root)
711 		priv->debug_root = debugfs_create_dir("tsens", NULL);
712 	else
713 		priv->debug_root = root;
714 
715 	file = debugfs_lookup("version", priv->debug_root);
716 	if (!file)
717 		debugfs_create_file("version", 0444, priv->debug_root,
718 				    pdev, &dbg_version_fops);
719 
720 	/* A directory for each instance of the TSENS IP */
721 	priv->debug = debugfs_create_dir(dev_name(&pdev->dev), priv->debug_root);
722 	debugfs_create_file("sensors", 0444, priv->debug, pdev, &dbg_sensors_fops);
723 }
724 #else
725 static inline void tsens_debug_init(struct platform_device *pdev) {}
726 #endif
727 
728 static const struct regmap_config tsens_config = {
729 	.name		= "tm",
730 	.reg_bits	= 32,
731 	.val_bits	= 32,
732 	.reg_stride	= 4,
733 };
734 
735 static const struct regmap_config tsens_srot_config = {
736 	.name		= "srot",
737 	.reg_bits	= 32,
738 	.val_bits	= 32,
739 	.reg_stride	= 4,
740 };
741 
742 int __init init_common(struct tsens_priv *priv)
743 {
744 	void __iomem *tm_base, *srot_base;
745 	struct device *dev = priv->dev;
746 	u32 ver_minor;
747 	struct resource *res;
748 	u32 enabled;
749 	int ret, i, j;
750 	struct platform_device *op = of_find_device_by_node(priv->dev->of_node);
751 
752 	if (!op)
753 		return -EINVAL;
754 
755 	if (op->num_resources > 1) {
756 		/* DT with separate SROT and TM address space */
757 		priv->tm_offset = 0;
758 		res = platform_get_resource(op, IORESOURCE_MEM, 1);
759 		srot_base = devm_ioremap_resource(dev, res);
760 		if (IS_ERR(srot_base)) {
761 			ret = PTR_ERR(srot_base);
762 			goto err_put_device;
763 		}
764 
765 		priv->srot_map = devm_regmap_init_mmio(dev, srot_base,
766 						       &tsens_srot_config);
767 		if (IS_ERR(priv->srot_map)) {
768 			ret = PTR_ERR(priv->srot_map);
769 			goto err_put_device;
770 		}
771 	} else {
772 		/* old DTs where SROT and TM were in a contiguous 2K block */
773 		priv->tm_offset = 0x1000;
774 	}
775 
776 	if (tsens_version(priv) >= VER_0_1) {
777 		res = platform_get_resource(op, IORESOURCE_MEM, 0);
778 		tm_base = devm_ioremap_resource(dev, res);
779 		if (IS_ERR(tm_base)) {
780 			ret = PTR_ERR(tm_base);
781 			goto err_put_device;
782 		}
783 
784 		priv->tm_map = devm_regmap_init_mmio(dev, tm_base, &tsens_config);
785 	} else { /* VER_0 share the same gcc regs using a syscon */
786 		struct device *parent = priv->dev->parent;
787 
788 		if (parent)
789 			priv->tm_map = syscon_node_to_regmap(parent->of_node);
790 	}
791 
792 	if (IS_ERR_OR_NULL(priv->tm_map)) {
793 		if (!priv->tm_map)
794 			ret = -ENODEV;
795 		else
796 			ret = PTR_ERR(priv->tm_map);
797 		goto err_put_device;
798 	}
799 
800 	/* VER_0 have only tm_map */
801 	if (!priv->srot_map)
802 		priv->srot_map = priv->tm_map;
803 
804 	if (tsens_version(priv) > VER_0_1) {
805 		for (i = VER_MAJOR; i <= VER_STEP; i++) {
806 			priv->rf[i] = devm_regmap_field_alloc(dev, priv->srot_map,
807 							      priv->fields[i]);
808 			if (IS_ERR(priv->rf[i])) {
809 				ret = PTR_ERR(priv->rf[i]);
810 				goto err_put_device;
811 			}
812 		}
813 		ret = regmap_field_read(priv->rf[VER_MINOR], &ver_minor);
814 		if (ret)
815 			goto err_put_device;
816 	}
817 
818 	priv->rf[TSENS_EN] = devm_regmap_field_alloc(dev, priv->srot_map,
819 						     priv->fields[TSENS_EN]);
820 	if (IS_ERR(priv->rf[TSENS_EN])) {
821 		ret = PTR_ERR(priv->rf[TSENS_EN]);
822 		goto err_put_device;
823 	}
824 	/* in VER_0 TSENS need to be explicitly enabled */
825 	if (tsens_version(priv) == VER_0)
826 		regmap_field_write(priv->rf[TSENS_EN], 1);
827 
828 	ret = regmap_field_read(priv->rf[TSENS_EN], &enabled);
829 	if (ret)
830 		goto err_put_device;
831 	if (!enabled) {
832 		dev_err(dev, "%s: device not enabled\n", __func__);
833 		ret = -ENODEV;
834 		goto err_put_device;
835 	}
836 
837 	priv->rf[SENSOR_EN] = devm_regmap_field_alloc(dev, priv->srot_map,
838 						      priv->fields[SENSOR_EN]);
839 	if (IS_ERR(priv->rf[SENSOR_EN])) {
840 		ret = PTR_ERR(priv->rf[SENSOR_EN]);
841 		goto err_put_device;
842 	}
843 	priv->rf[INT_EN] = devm_regmap_field_alloc(dev, priv->tm_map,
844 						   priv->fields[INT_EN]);
845 	if (IS_ERR(priv->rf[INT_EN])) {
846 		ret = PTR_ERR(priv->rf[INT_EN]);
847 		goto err_put_device;
848 	}
849 
850 	priv->rf[TSENS_SW_RST] =
851 		devm_regmap_field_alloc(dev, priv->srot_map, priv->fields[TSENS_SW_RST]);
852 	if (IS_ERR(priv->rf[TSENS_SW_RST])) {
853 		ret = PTR_ERR(priv->rf[TSENS_SW_RST]);
854 		goto err_put_device;
855 	}
856 
857 	priv->rf[TRDY] = devm_regmap_field_alloc(dev, priv->tm_map, priv->fields[TRDY]);
858 	if (IS_ERR(priv->rf[TRDY])) {
859 		ret = PTR_ERR(priv->rf[TRDY]);
860 		goto err_put_device;
861 	}
862 
863 	/* This loop might need changes if enum regfield_ids is reordered */
864 	for (j = LAST_TEMP_0; j <= UP_THRESH_15; j += 16) {
865 		for (i = 0; i < priv->feat->max_sensors; i++) {
866 			int idx = j + i;
867 
868 			priv->rf[idx] = devm_regmap_field_alloc(dev,
869 								priv->tm_map,
870 								priv->fields[idx]);
871 			if (IS_ERR(priv->rf[idx])) {
872 				ret = PTR_ERR(priv->rf[idx]);
873 				goto err_put_device;
874 			}
875 		}
876 	}
877 
878 	if (priv->feat->crit_int || tsens_version(priv) < VER_0_1) {
879 		/* Loop might need changes if enum regfield_ids is reordered */
880 		for (j = CRITICAL_STATUS_0; j <= CRIT_THRESH_15; j += 16) {
881 			for (i = 0; i < priv->feat->max_sensors; i++) {
882 				int idx = j + i;
883 
884 				priv->rf[idx] =
885 					devm_regmap_field_alloc(dev,
886 								priv->tm_map,
887 								priv->fields[idx]);
888 				if (IS_ERR(priv->rf[idx])) {
889 					ret = PTR_ERR(priv->rf[idx]);
890 					goto err_put_device;
891 				}
892 			}
893 		}
894 	}
895 
896 	if (tsens_version(priv) > VER_1_X &&  ver_minor > 2) {
897 		/* Watchdog is present only on v2.3+ */
898 		priv->feat->has_watchdog = 1;
899 		for (i = WDOG_BARK_STATUS; i <= CC_MON_MASK; i++) {
900 			priv->rf[i] = devm_regmap_field_alloc(dev, priv->tm_map,
901 							      priv->fields[i]);
902 			if (IS_ERR(priv->rf[i])) {
903 				ret = PTR_ERR(priv->rf[i]);
904 				goto err_put_device;
905 			}
906 		}
907 		/*
908 		 * Watchdog is already enabled, unmask the bark.
909 		 * Disable cycle completion monitoring
910 		 */
911 		regmap_field_write(priv->rf[WDOG_BARK_MASK], 0);
912 		regmap_field_write(priv->rf[CC_MON_MASK], 1);
913 	}
914 
915 	spin_lock_init(&priv->ul_lock);
916 
917 	/* VER_0 interrupt doesn't need to be enabled */
918 	if (tsens_version(priv) >= VER_0_1)
919 		tsens_enable_irq(priv);
920 
921 	tsens_debug_init(op);
922 
923 err_put_device:
924 	put_device(&op->dev);
925 	return ret;
926 }
927 
928 static int tsens_get_temp(void *data, int *temp)
929 {
930 	struct tsens_sensor *s = data;
931 	struct tsens_priv *priv = s->priv;
932 
933 	return priv->ops->get_temp(s, temp);
934 }
935 
936 static int tsens_get_trend(void *data, int trip, enum thermal_trend *trend)
937 {
938 	struct tsens_sensor *s = data;
939 	struct tsens_priv *priv = s->priv;
940 
941 	if (priv->ops->get_trend)
942 		return priv->ops->get_trend(s, trend);
943 
944 	return -ENOTSUPP;
945 }
946 
947 static int  __maybe_unused tsens_suspend(struct device *dev)
948 {
949 	struct tsens_priv *priv = dev_get_drvdata(dev);
950 
951 	if (priv->ops && priv->ops->suspend)
952 		return priv->ops->suspend(priv);
953 
954 	return 0;
955 }
956 
957 static int __maybe_unused tsens_resume(struct device *dev)
958 {
959 	struct tsens_priv *priv = dev_get_drvdata(dev);
960 
961 	if (priv->ops && priv->ops->resume)
962 		return priv->ops->resume(priv);
963 
964 	return 0;
965 }
966 
967 static SIMPLE_DEV_PM_OPS(tsens_pm_ops, tsens_suspend, tsens_resume);
968 
969 static const struct of_device_id tsens_table[] = {
970 	{
971 		.compatible = "qcom,ipq8064-tsens",
972 		.data = &data_8960,
973 	}, {
974 		.compatible = "qcom,mdm9607-tsens",
975 		.data = &data_9607,
976 	}, {
977 		.compatible = "qcom,msm8916-tsens",
978 		.data = &data_8916,
979 	}, {
980 		.compatible = "qcom,msm8939-tsens",
981 		.data = &data_8939,
982 	}, {
983 		.compatible = "qcom,msm8974-tsens",
984 		.data = &data_8974,
985 	}, {
986 		.compatible = "qcom,msm8976-tsens",
987 		.data = &data_8976,
988 	}, {
989 		.compatible = "qcom,msm8996-tsens",
990 		.data = &data_8996,
991 	}, {
992 		.compatible = "qcom,tsens-v1",
993 		.data = &data_tsens_v1,
994 	}, {
995 		.compatible = "qcom,tsens-v2",
996 		.data = &data_tsens_v2,
997 	},
998 	{}
999 };
1000 MODULE_DEVICE_TABLE(of, tsens_table);
1001 
1002 static const struct thermal_zone_of_device_ops tsens_of_ops = {
1003 	.get_temp = tsens_get_temp,
1004 	.get_trend = tsens_get_trend,
1005 	.set_trips = tsens_set_trips,
1006 };
1007 
1008 static int tsens_register_irq(struct tsens_priv *priv, char *irqname,
1009 			      irq_handler_t thread_fn)
1010 {
1011 	struct platform_device *pdev;
1012 	int ret, irq;
1013 
1014 	pdev = of_find_device_by_node(priv->dev->of_node);
1015 	if (!pdev)
1016 		return -ENODEV;
1017 
1018 	irq = platform_get_irq_byname(pdev, irqname);
1019 	if (irq < 0) {
1020 		ret = irq;
1021 		/* For old DTs with no IRQ defined */
1022 		if (irq == -ENXIO)
1023 			ret = 0;
1024 	} else {
1025 		/* VER_0 interrupt is TRIGGER_RISING, VER_0_1 and up is ONESHOT */
1026 		if (tsens_version(priv) == VER_0)
1027 			ret = devm_request_threaded_irq(&pdev->dev, irq,
1028 							thread_fn, NULL,
1029 							IRQF_TRIGGER_RISING,
1030 							dev_name(&pdev->dev),
1031 							priv);
1032 		else
1033 			ret = devm_request_threaded_irq(&pdev->dev, irq, NULL,
1034 							thread_fn, IRQF_ONESHOT,
1035 							dev_name(&pdev->dev),
1036 							priv);
1037 
1038 		if (ret)
1039 			dev_err(&pdev->dev, "%s: failed to get irq\n",
1040 				__func__);
1041 		else
1042 			enable_irq_wake(irq);
1043 	}
1044 
1045 	put_device(&pdev->dev);
1046 	return ret;
1047 }
1048 
1049 static int tsens_register(struct tsens_priv *priv)
1050 {
1051 	int i, ret;
1052 	struct thermal_zone_device *tzd;
1053 
1054 	for (i = 0;  i < priv->num_sensors; i++) {
1055 		priv->sensor[i].priv = priv;
1056 		tzd = devm_thermal_zone_of_sensor_register(priv->dev, priv->sensor[i].hw_id,
1057 							   &priv->sensor[i],
1058 							   &tsens_of_ops);
1059 		if (IS_ERR(tzd))
1060 			continue;
1061 		priv->sensor[i].tzd = tzd;
1062 		if (priv->ops->enable)
1063 			priv->ops->enable(priv, i);
1064 	}
1065 
1066 	/* VER_0 require to set MIN and MAX THRESH
1067 	 * These 2 regs are set using the:
1068 	 * - CRIT_THRESH_0 for MAX THRESH hardcoded to 120°C
1069 	 * - CRIT_THRESH_1 for MIN THRESH hardcoded to   0°C
1070 	 */
1071 	if (tsens_version(priv) < VER_0_1) {
1072 		regmap_field_write(priv->rf[CRIT_THRESH_0],
1073 				   tsens_mC_to_hw(priv->sensor, 120000));
1074 
1075 		regmap_field_write(priv->rf[CRIT_THRESH_1],
1076 				   tsens_mC_to_hw(priv->sensor, 0));
1077 	}
1078 
1079 	ret = tsens_register_irq(priv, "uplow", tsens_irq_thread);
1080 	if (ret < 0)
1081 		return ret;
1082 
1083 	if (priv->feat->crit_int)
1084 		ret = tsens_register_irq(priv, "critical",
1085 					 tsens_critical_irq_thread);
1086 
1087 	return ret;
1088 }
1089 
1090 static int tsens_probe(struct platform_device *pdev)
1091 {
1092 	int ret, i;
1093 	struct device *dev;
1094 	struct device_node *np;
1095 	struct tsens_priv *priv;
1096 	const struct tsens_plat_data *data;
1097 	const struct of_device_id *id;
1098 	u32 num_sensors;
1099 
1100 	if (pdev->dev.of_node)
1101 		dev = &pdev->dev;
1102 	else
1103 		dev = pdev->dev.parent;
1104 
1105 	np = dev->of_node;
1106 
1107 	id = of_match_node(tsens_table, np);
1108 	if (id)
1109 		data = id->data;
1110 	else
1111 		data = &data_8960;
1112 
1113 	num_sensors = data->num_sensors;
1114 
1115 	if (np)
1116 		of_property_read_u32(np, "#qcom,sensors", &num_sensors);
1117 
1118 	if (num_sensors <= 0) {
1119 		dev_err(dev, "%s: invalid number of sensors\n", __func__);
1120 		return -EINVAL;
1121 	}
1122 
1123 	priv = devm_kzalloc(dev,
1124 			     struct_size(priv, sensor, num_sensors),
1125 			     GFP_KERNEL);
1126 	if (!priv)
1127 		return -ENOMEM;
1128 
1129 	priv->dev = dev;
1130 	priv->num_sensors = num_sensors;
1131 	priv->ops = data->ops;
1132 	for (i = 0;  i < priv->num_sensors; i++) {
1133 		if (data->hw_ids)
1134 			priv->sensor[i].hw_id = data->hw_ids[i];
1135 		else
1136 			priv->sensor[i].hw_id = i;
1137 	}
1138 	priv->feat = data->feat;
1139 	priv->fields = data->fields;
1140 
1141 	platform_set_drvdata(pdev, priv);
1142 
1143 	if (!priv->ops || !priv->ops->init || !priv->ops->get_temp)
1144 		return -EINVAL;
1145 
1146 	ret = priv->ops->init(priv);
1147 	if (ret < 0) {
1148 		dev_err(dev, "%s: init failed\n", __func__);
1149 		return ret;
1150 	}
1151 
1152 	if (priv->ops->calibrate) {
1153 		ret = priv->ops->calibrate(priv);
1154 		if (ret < 0) {
1155 			if (ret != -EPROBE_DEFER)
1156 				dev_err(dev, "%s: calibration failed\n", __func__);
1157 			return ret;
1158 		}
1159 	}
1160 
1161 	return tsens_register(priv);
1162 }
1163 
1164 static int tsens_remove(struct platform_device *pdev)
1165 {
1166 	struct tsens_priv *priv = platform_get_drvdata(pdev);
1167 
1168 	debugfs_remove_recursive(priv->debug_root);
1169 	tsens_disable_irq(priv);
1170 	if (priv->ops->disable)
1171 		priv->ops->disable(priv);
1172 
1173 	return 0;
1174 }
1175 
1176 static struct platform_driver tsens_driver = {
1177 	.probe = tsens_probe,
1178 	.remove = tsens_remove,
1179 	.driver = {
1180 		.name = "qcom-tsens",
1181 		.pm	= &tsens_pm_ops,
1182 		.of_match_table = tsens_table,
1183 	},
1184 };
1185 module_platform_driver(tsens_driver);
1186 
1187 MODULE_LICENSE("GPL v2");
1188 MODULE_DESCRIPTION("QCOM Temperature Sensor driver");
1189 MODULE_ALIAS("platform:qcom-tsens");
1190