xref: /openbmc/linux/drivers/hwmon/bt1-pvt.c (revision 349f631d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2020 BAIKAL ELECTRONICS, JSC
4  *
5  * Authors:
6  *   Maxim Kaurkin <maxim.kaurkin@baikalelectronics.ru>
7  *   Serge Semin <Sergey.Semin@baikalelectronics.ru>
8  *
9  * Baikal-T1 Process, Voltage, Temperature sensor driver
10  */
11 
12 #include <linux/bitfield.h>
13 #include <linux/bitops.h>
14 #include <linux/clk.h>
15 #include <linux/completion.h>
16 #include <linux/delay.h>
17 #include <linux/device.h>
18 #include <linux/hwmon-sysfs.h>
19 #include <linux/hwmon.h>
20 #include <linux/interrupt.h>
21 #include <linux/io.h>
22 #include <linux/kernel.h>
23 #include <linux/ktime.h>
24 #include <linux/limits.h>
25 #include <linux/module.h>
26 #include <linux/mutex.h>
27 #include <linux/of.h>
28 #include <linux/platform_device.h>
29 #include <linux/seqlock.h>
30 #include <linux/sysfs.h>
31 #include <linux/types.h>
32 
33 #include "bt1-pvt.h"
34 
35 /*
36  * For the sake of the code simplification we created the sensors info table
37  * with the sensor names, activation modes, threshold registers base address
38  * and the thresholds bit fields.
39  */
40 static const struct pvt_sensor_info pvt_info[] = {
41 	PVT_SENSOR_INFO(0, "CPU Core Temperature", hwmon_temp, TEMP, TTHRES),
42 	PVT_SENSOR_INFO(0, "CPU Core Voltage", hwmon_in, VOLT, VTHRES),
43 	PVT_SENSOR_INFO(1, "CPU Core Low-Vt", hwmon_in, LVT, LTHRES),
44 	PVT_SENSOR_INFO(2, "CPU Core High-Vt", hwmon_in, HVT, HTHRES),
45 	PVT_SENSOR_INFO(3, "CPU Core Standard-Vt", hwmon_in, SVT, STHRES),
46 };
47 
48 /*
49  * The original translation formulae of the temperature (in degrees of Celsius)
50  * to PVT data and vice-versa are following:
51  * N = 1.8322e-8*(T^4) + 2.343e-5*(T^3) + 8.7018e-3*(T^2) + 3.9269*(T^1) +
52  *     1.7204e2,
53  * T = -1.6743e-11*(N^4) + 8.1542e-8*(N^3) + -1.8201e-4*(N^2) +
54  *     3.1020e-1*(N^1) - 4.838e1,
55  * where T = [-48.380, 147.438]C and N = [0, 1023].
56  * They must be accordingly altered to be suitable for the integer arithmetics.
57  * The technique is called 'factor redistribution', which just makes sure the
58  * multiplications and divisions are made so to have a result of the operations
59  * within the integer numbers limit. In addition we need to translate the
60  * formulae to accept millidegrees of Celsius. Here what they look like after
61  * the alterations:
62  * N = (18322e-20*(T^4) + 2343e-13*(T^3) + 87018e-9*(T^2) + 39269e-3*T +
63  *     17204e2) / 1e4,
64  * T = -16743e-12*(D^4) + 81542e-9*(D^3) - 182010e-6*(D^2) + 310200e-3*D -
65  *     48380,
66  * where T = [-48380, 147438] mC and N = [0, 1023].
67  */
68 static const struct pvt_poly __maybe_unused poly_temp_to_N = {
69 	.total_divider = 10000,
70 	.terms = {
71 		{4, 18322, 10000, 10000},
72 		{3, 2343, 10000, 10},
73 		{2, 87018, 10000, 10},
74 		{1, 39269, 1000, 1},
75 		{0, 1720400, 1, 1}
76 	}
77 };
78 
79 static const struct pvt_poly poly_N_to_temp = {
80 	.total_divider = 1,
81 	.terms = {
82 		{4, -16743, 1000, 1},
83 		{3, 81542, 1000, 1},
84 		{2, -182010, 1000, 1},
85 		{1, 310200, 1000, 1},
86 		{0, -48380, 1, 1}
87 	}
88 };
89 
90 /*
91  * Similar alterations are performed for the voltage conversion equations.
92  * The original formulae are:
93  * N = 1.8658e3*V - 1.1572e3,
94  * V = (N + 1.1572e3) / 1.8658e3,
95  * where V = [0.620, 1.168] V and N = [0, 1023].
96  * After the optimization they looks as follows:
97  * N = (18658e-3*V - 11572) / 10,
98  * V = N * 10^5 / 18658 + 11572 * 10^4 / 18658.
99  */
100 static const struct pvt_poly __maybe_unused poly_volt_to_N = {
101 	.total_divider = 10,
102 	.terms = {
103 		{1, 18658, 1000, 1},
104 		{0, -11572, 1, 1}
105 	}
106 };
107 
108 static const struct pvt_poly poly_N_to_volt = {
109 	.total_divider = 10,
110 	.terms = {
111 		{1, 100000, 18658, 1},
112 		{0, 115720000, 1, 18658}
113 	}
114 };
115 
116 /*
117  * Here is the polynomial calculation function, which performs the
118  * redistributed terms calculations. It's pretty straightforward. We walk
119  * over each degree term up to the free one, and perform the redistributed
120  * multiplication of the term coefficient, its divider (as for the rationale
121  * fraction representation), data power and the rational fraction divider
122  * leftover. Then all of this is collected in a total sum variable, which
123  * value is normalized by the total divider before being returned.
124  */
125 static long pvt_calc_poly(const struct pvt_poly *poly, long data)
126 {
127 	const struct pvt_poly_term *term = poly->terms;
128 	long tmp, ret = 0;
129 	int deg;
130 
131 	do {
132 		tmp = term->coef;
133 		for (deg = 0; deg < term->deg; ++deg)
134 			tmp = mult_frac(tmp, data, term->divider);
135 		ret += tmp / term->divider_leftover;
136 	} while ((term++)->deg);
137 
138 	return ret / poly->total_divider;
139 }
140 
141 static inline u32 pvt_update(void __iomem *reg, u32 mask, u32 data)
142 {
143 	u32 old;
144 
145 	old = readl_relaxed(reg);
146 	writel((old & ~mask) | (data & mask), reg);
147 
148 	return old & mask;
149 }
150 
151 /*
152  * Baikal-T1 PVT mode can be updated only when the controller is disabled.
153  * So first we disable it, then set the new mode together with the controller
154  * getting back enabled. The same concerns the temperature trim and
155  * measurements timeout. If it is necessary the interface mutex is supposed
156  * to be locked at the time the operations are performed.
157  */
158 static inline void pvt_set_mode(struct pvt_hwmon *pvt, u32 mode)
159 {
160 	u32 old;
161 
162 	mode = FIELD_PREP(PVT_CTRL_MODE_MASK, mode);
163 
164 	old = pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, 0);
165 	pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_MODE_MASK | PVT_CTRL_EN,
166 		   mode | old);
167 }
168 
169 static inline u32 pvt_calc_trim(long temp)
170 {
171 	temp = clamp_val(temp, 0, PVT_TRIM_TEMP);
172 
173 	return DIV_ROUND_UP(temp, PVT_TRIM_STEP);
174 }
175 
176 static inline void pvt_set_trim(struct pvt_hwmon *pvt, u32 trim)
177 {
178 	u32 old;
179 
180 	trim = FIELD_PREP(PVT_CTRL_TRIM_MASK, trim);
181 
182 	old = pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, 0);
183 	pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_TRIM_MASK | PVT_CTRL_EN,
184 		   trim | old);
185 }
186 
187 static inline void pvt_set_tout(struct pvt_hwmon *pvt, u32 tout)
188 {
189 	u32 old;
190 
191 	old = pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, 0);
192 	writel(tout, pvt->regs + PVT_TTIMEOUT);
193 	pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, old);
194 }
195 
196 /*
197  * This driver can optionally provide the hwmon alarms for each sensor the PVT
198  * controller supports. The alarms functionality is made compile-time
199  * configurable due to the hardware interface implementation peculiarity
200  * described further in this comment. So in case if alarms are unnecessary in
201  * your system design it's recommended to have them disabled to prevent the PVT
202  * IRQs being periodically raised to get the data cache/alarms status up to
203  * date.
204  *
205  * Baikal-T1 PVT embedded controller is based on the Analog Bits PVT sensor,
206  * but is equipped with a dedicated control wrapper. It exposes the PVT
207  * sub-block registers space via the APB3 bus. In addition the wrapper provides
208  * a common interrupt vector of the sensors conversion completion events and
209  * threshold value alarms. Alas the wrapper interface hasn't been fully thought
210  * through. There is only one sensor can be activated at a time, for which the
211  * thresholds comparator is enabled right after the data conversion is
212  * completed. Due to this if alarms need to be implemented for all available
213  * sensors we can't just set the thresholds and enable the interrupts. We need
214  * to enable the sensors one after another and let the controller to detect
215  * the alarms by itself at each conversion. This also makes pointless to handle
216  * the alarms interrupts, since in occasion they happen synchronously with
217  * data conversion completion. The best driver design would be to have the
218  * completion interrupts enabled only and keep the converted value in the
219  * driver data cache. This solution is implemented if hwmon alarms are enabled
220  * in this driver. In case if the alarms are disabled, the conversion is
221  * performed on demand at the time a sensors input file is read.
222  */
223 
224 #if defined(CONFIG_SENSORS_BT1_PVT_ALARMS)
225 
226 #define pvt_hard_isr NULL
227 
228 static irqreturn_t pvt_soft_isr(int irq, void *data)
229 {
230 	const struct pvt_sensor_info *info;
231 	struct pvt_hwmon *pvt = data;
232 	struct pvt_cache *cache;
233 	u32 val, thres_sts, old;
234 
235 	/*
236 	 * DVALID bit will be cleared by reading the data. We need to save the
237 	 * status before the next conversion happens. Threshold events will be
238 	 * handled a bit later.
239 	 */
240 	thres_sts = readl(pvt->regs + PVT_RAW_INTR_STAT);
241 
242 	/*
243 	 * Then lets recharge the PVT interface with the next sampling mode.
244 	 * Lock the interface mutex to serialize trim, timeouts and alarm
245 	 * thresholds settings.
246 	 */
247 	cache = &pvt->cache[pvt->sensor];
248 	info = &pvt_info[pvt->sensor];
249 	pvt->sensor = (pvt->sensor == PVT_SENSOR_LAST) ?
250 		      PVT_SENSOR_FIRST : (pvt->sensor + 1);
251 
252 	/*
253 	 * For some reason we have to mask the interrupt before changing the
254 	 * mode, otherwise sometimes the temperature mode doesn't get
255 	 * activated even though the actual mode in the ctrl register
256 	 * corresponds to one. Then we read the data. By doing so we also
257 	 * recharge the data conversion. After this the mode corresponding
258 	 * to the next sensor in the row is set. Finally we enable the
259 	 * interrupts back.
260 	 */
261 	mutex_lock(&pvt->iface_mtx);
262 
263 	old = pvt_update(pvt->regs + PVT_INTR_MASK, PVT_INTR_DVALID,
264 			 PVT_INTR_DVALID);
265 
266 	val = readl(pvt->regs + PVT_DATA);
267 
268 	pvt_set_mode(pvt, pvt_info[pvt->sensor].mode);
269 
270 	pvt_update(pvt->regs + PVT_INTR_MASK, PVT_INTR_DVALID, old);
271 
272 	mutex_unlock(&pvt->iface_mtx);
273 
274 	/*
275 	 * We can now update the data cache with data just retrieved from the
276 	 * sensor. Lock write-seqlock to make sure the reader has a coherent
277 	 * data.
278 	 */
279 	write_seqlock(&cache->data_seqlock);
280 
281 	cache->data = FIELD_GET(PVT_DATA_DATA_MASK, val);
282 
283 	write_sequnlock(&cache->data_seqlock);
284 
285 	/*
286 	 * While PVT core is doing the next mode data conversion, we'll check
287 	 * whether the alarms were triggered for the current sensor. Note that
288 	 * according to the documentation only one threshold IRQ status can be
289 	 * set at a time, that's why if-else statement is utilized.
290 	 */
291 	if ((thres_sts & info->thres_sts_lo) ^ cache->thres_sts_lo) {
292 		WRITE_ONCE(cache->thres_sts_lo, thres_sts & info->thres_sts_lo);
293 		hwmon_notify_event(pvt->hwmon, info->type, info->attr_min_alarm,
294 				   info->channel);
295 	} else if ((thres_sts & info->thres_sts_hi) ^ cache->thres_sts_hi) {
296 		WRITE_ONCE(cache->thres_sts_hi, thres_sts & info->thres_sts_hi);
297 		hwmon_notify_event(pvt->hwmon, info->type, info->attr_max_alarm,
298 				   info->channel);
299 	}
300 
301 	return IRQ_HANDLED;
302 }
303 
304 static inline umode_t pvt_limit_is_visible(enum pvt_sensor_type type)
305 {
306 	return 0644;
307 }
308 
309 static inline umode_t pvt_alarm_is_visible(enum pvt_sensor_type type)
310 {
311 	return 0444;
312 }
313 
314 static int pvt_read_data(struct pvt_hwmon *pvt, enum pvt_sensor_type type,
315 			 long *val)
316 {
317 	struct pvt_cache *cache = &pvt->cache[type];
318 	unsigned int seq;
319 	u32 data;
320 
321 	do {
322 		seq = read_seqbegin(&cache->data_seqlock);
323 		data = cache->data;
324 	} while (read_seqretry(&cache->data_seqlock, seq));
325 
326 	if (type == PVT_TEMP)
327 		*val = pvt_calc_poly(&poly_N_to_temp, data);
328 	else
329 		*val = pvt_calc_poly(&poly_N_to_volt, data);
330 
331 	return 0;
332 }
333 
334 static int pvt_read_limit(struct pvt_hwmon *pvt, enum pvt_sensor_type type,
335 			  bool is_low, long *val)
336 {
337 	u32 data;
338 
339 	/* No need in serialization, since it is just read from MMIO. */
340 	data = readl(pvt->regs + pvt_info[type].thres_base);
341 
342 	if (is_low)
343 		data = FIELD_GET(PVT_THRES_LO_MASK, data);
344 	else
345 		data = FIELD_GET(PVT_THRES_HI_MASK, data);
346 
347 	if (type == PVT_TEMP)
348 		*val = pvt_calc_poly(&poly_N_to_temp, data);
349 	else
350 		*val = pvt_calc_poly(&poly_N_to_volt, data);
351 
352 	return 0;
353 }
354 
355 static int pvt_write_limit(struct pvt_hwmon *pvt, enum pvt_sensor_type type,
356 			   bool is_low, long val)
357 {
358 	u32 data, limit, mask;
359 	int ret;
360 
361 	if (type == PVT_TEMP) {
362 		val = clamp(val, PVT_TEMP_MIN, PVT_TEMP_MAX);
363 		data = pvt_calc_poly(&poly_temp_to_N, val);
364 	} else {
365 		val = clamp(val, PVT_VOLT_MIN, PVT_VOLT_MAX);
366 		data = pvt_calc_poly(&poly_volt_to_N, val);
367 	}
368 
369 	/* Serialize limit update, since a part of the register is changed. */
370 	ret = mutex_lock_interruptible(&pvt->iface_mtx);
371 	if (ret)
372 		return ret;
373 
374 	/* Make sure the upper and lower ranges don't intersect. */
375 	limit = readl(pvt->regs + pvt_info[type].thres_base);
376 	if (is_low) {
377 		limit = FIELD_GET(PVT_THRES_HI_MASK, limit);
378 		data = clamp_val(data, PVT_DATA_MIN, limit);
379 		data = FIELD_PREP(PVT_THRES_LO_MASK, data);
380 		mask = PVT_THRES_LO_MASK;
381 	} else {
382 		limit = FIELD_GET(PVT_THRES_LO_MASK, limit);
383 		data = clamp_val(data, limit, PVT_DATA_MAX);
384 		data = FIELD_PREP(PVT_THRES_HI_MASK, data);
385 		mask = PVT_THRES_HI_MASK;
386 	}
387 
388 	pvt_update(pvt->regs + pvt_info[type].thres_base, mask, data);
389 
390 	mutex_unlock(&pvt->iface_mtx);
391 
392 	return 0;
393 }
394 
395 static int pvt_read_alarm(struct pvt_hwmon *pvt, enum pvt_sensor_type type,
396 			  bool is_low, long *val)
397 {
398 	if (is_low)
399 		*val = !!READ_ONCE(pvt->cache[type].thres_sts_lo);
400 	else
401 		*val = !!READ_ONCE(pvt->cache[type].thres_sts_hi);
402 
403 	return 0;
404 }
405 
406 static const struct hwmon_channel_info *pvt_channel_info[] = {
407 	HWMON_CHANNEL_INFO(chip,
408 			   HWMON_C_REGISTER_TZ | HWMON_C_UPDATE_INTERVAL),
409 	HWMON_CHANNEL_INFO(temp,
410 			   HWMON_T_INPUT | HWMON_T_TYPE | HWMON_T_LABEL |
411 			   HWMON_T_MIN | HWMON_T_MIN_ALARM |
412 			   HWMON_T_MAX | HWMON_T_MAX_ALARM |
413 			   HWMON_T_OFFSET),
414 	HWMON_CHANNEL_INFO(in,
415 			   HWMON_I_INPUT | HWMON_I_LABEL |
416 			   HWMON_I_MIN | HWMON_I_MIN_ALARM |
417 			   HWMON_I_MAX | HWMON_I_MAX_ALARM,
418 			   HWMON_I_INPUT | HWMON_I_LABEL |
419 			   HWMON_I_MIN | HWMON_I_MIN_ALARM |
420 			   HWMON_I_MAX | HWMON_I_MAX_ALARM,
421 			   HWMON_I_INPUT | HWMON_I_LABEL |
422 			   HWMON_I_MIN | HWMON_I_MIN_ALARM |
423 			   HWMON_I_MAX | HWMON_I_MAX_ALARM,
424 			   HWMON_I_INPUT | HWMON_I_LABEL |
425 			   HWMON_I_MIN | HWMON_I_MIN_ALARM |
426 			   HWMON_I_MAX | HWMON_I_MAX_ALARM),
427 	NULL
428 };
429 
430 #else /* !CONFIG_SENSORS_BT1_PVT_ALARMS */
431 
432 static irqreturn_t pvt_hard_isr(int irq, void *data)
433 {
434 	struct pvt_hwmon *pvt = data;
435 	struct pvt_cache *cache;
436 	u32 val;
437 
438 	/*
439 	 * Mask the DVALID interrupt so after exiting from the handler a
440 	 * repeated conversion wouldn't happen.
441 	 */
442 	pvt_update(pvt->regs + PVT_INTR_MASK, PVT_INTR_DVALID,
443 		   PVT_INTR_DVALID);
444 
445 	/*
446 	 * Nothing special for alarm-less driver. Just read the data, update
447 	 * the cache and notify a waiter of this event.
448 	 */
449 	val = readl(pvt->regs + PVT_DATA);
450 	if (!(val & PVT_DATA_VALID)) {
451 		dev_err(pvt->dev, "Got IRQ when data isn't valid\n");
452 		return IRQ_HANDLED;
453 	}
454 
455 	cache = &pvt->cache[pvt->sensor];
456 
457 	WRITE_ONCE(cache->data, FIELD_GET(PVT_DATA_DATA_MASK, val));
458 
459 	complete(&cache->conversion);
460 
461 	return IRQ_HANDLED;
462 }
463 
464 #define pvt_soft_isr NULL
465 
466 static inline umode_t pvt_limit_is_visible(enum pvt_sensor_type type)
467 {
468 	return 0;
469 }
470 
471 static inline umode_t pvt_alarm_is_visible(enum pvt_sensor_type type)
472 {
473 	return 0;
474 }
475 
476 static int pvt_read_data(struct pvt_hwmon *pvt, enum pvt_sensor_type type,
477 			 long *val)
478 {
479 	struct pvt_cache *cache = &pvt->cache[type];
480 	unsigned long timeout;
481 	u32 data;
482 	int ret;
483 
484 	/*
485 	 * Lock PVT conversion interface until data cache is updated. The
486 	 * data read procedure is following: set the requested PVT sensor
487 	 * mode, enable IRQ and conversion, wait until conversion is finished,
488 	 * then disable conversion and IRQ, and read the cached data.
489 	 */
490 	ret = mutex_lock_interruptible(&pvt->iface_mtx);
491 	if (ret)
492 		return ret;
493 
494 	pvt->sensor = type;
495 	pvt_set_mode(pvt, pvt_info[type].mode);
496 
497 	/*
498 	 * Unmask the DVALID interrupt and enable the sensors conversions.
499 	 * Do the reverse procedure when conversion is done.
500 	 */
501 	pvt_update(pvt->regs + PVT_INTR_MASK, PVT_INTR_DVALID, 0);
502 	pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, PVT_CTRL_EN);
503 
504 	/*
505 	 * Wait with timeout since in case if the sensor is suddenly powered
506 	 * down the request won't be completed and the caller will hang up on
507 	 * this procedure until the power is back up again. Multiply the
508 	 * timeout by the factor of two to prevent a false timeout.
509 	 */
510 	timeout = 2 * usecs_to_jiffies(ktime_to_us(pvt->timeout));
511 	ret = wait_for_completion_timeout(&cache->conversion, timeout);
512 
513 	pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, 0);
514 	pvt_update(pvt->regs + PVT_INTR_MASK, PVT_INTR_DVALID,
515 		   PVT_INTR_DVALID);
516 
517 	data = READ_ONCE(cache->data);
518 
519 	mutex_unlock(&pvt->iface_mtx);
520 
521 	if (!ret)
522 		return -ETIMEDOUT;
523 
524 	if (type == PVT_TEMP)
525 		*val = pvt_calc_poly(&poly_N_to_temp, data);
526 	else
527 		*val = pvt_calc_poly(&poly_N_to_volt, data);
528 
529 	return 0;
530 }
531 
532 static int pvt_read_limit(struct pvt_hwmon *pvt, enum pvt_sensor_type type,
533 			  bool is_low, long *val)
534 {
535 	return -EOPNOTSUPP;
536 }
537 
538 static int pvt_write_limit(struct pvt_hwmon *pvt, enum pvt_sensor_type type,
539 			   bool is_low, long val)
540 {
541 	return -EOPNOTSUPP;
542 }
543 
544 static int pvt_read_alarm(struct pvt_hwmon *pvt, enum pvt_sensor_type type,
545 			  bool is_low, long *val)
546 {
547 	return -EOPNOTSUPP;
548 }
549 
550 static const struct hwmon_channel_info *pvt_channel_info[] = {
551 	HWMON_CHANNEL_INFO(chip,
552 			   HWMON_C_REGISTER_TZ | HWMON_C_UPDATE_INTERVAL),
553 	HWMON_CHANNEL_INFO(temp,
554 			   HWMON_T_INPUT | HWMON_T_TYPE | HWMON_T_LABEL |
555 			   HWMON_T_OFFSET),
556 	HWMON_CHANNEL_INFO(in,
557 			   HWMON_I_INPUT | HWMON_I_LABEL,
558 			   HWMON_I_INPUT | HWMON_I_LABEL,
559 			   HWMON_I_INPUT | HWMON_I_LABEL,
560 			   HWMON_I_INPUT | HWMON_I_LABEL),
561 	NULL
562 };
563 
564 #endif /* !CONFIG_SENSORS_BT1_PVT_ALARMS */
565 
566 static inline bool pvt_hwmon_channel_is_valid(enum hwmon_sensor_types type,
567 					      int ch)
568 {
569 	switch (type) {
570 	case hwmon_temp:
571 		if (ch < 0 || ch >= PVT_TEMP_CHS)
572 			return false;
573 		break;
574 	case hwmon_in:
575 		if (ch < 0 || ch >= PVT_VOLT_CHS)
576 			return false;
577 		break;
578 	default:
579 		break;
580 	}
581 
582 	/* The rest of the types are independent from the channel number. */
583 	return true;
584 }
585 
586 static umode_t pvt_hwmon_is_visible(const void *data,
587 				    enum hwmon_sensor_types type,
588 				    u32 attr, int ch)
589 {
590 	if (!pvt_hwmon_channel_is_valid(type, ch))
591 		return 0;
592 
593 	switch (type) {
594 	case hwmon_chip:
595 		switch (attr) {
596 		case hwmon_chip_update_interval:
597 			return 0644;
598 		}
599 		break;
600 	case hwmon_temp:
601 		switch (attr) {
602 		case hwmon_temp_input:
603 		case hwmon_temp_type:
604 		case hwmon_temp_label:
605 			return 0444;
606 		case hwmon_temp_min:
607 		case hwmon_temp_max:
608 			return pvt_limit_is_visible(ch);
609 		case hwmon_temp_min_alarm:
610 		case hwmon_temp_max_alarm:
611 			return pvt_alarm_is_visible(ch);
612 		case hwmon_temp_offset:
613 			return 0644;
614 		}
615 		break;
616 	case hwmon_in:
617 		switch (attr) {
618 		case hwmon_in_input:
619 		case hwmon_in_label:
620 			return 0444;
621 		case hwmon_in_min:
622 		case hwmon_in_max:
623 			return pvt_limit_is_visible(PVT_VOLT + ch);
624 		case hwmon_in_min_alarm:
625 		case hwmon_in_max_alarm:
626 			return pvt_alarm_is_visible(PVT_VOLT + ch);
627 		}
628 		break;
629 	default:
630 		break;
631 	}
632 
633 	return 0;
634 }
635 
636 static int pvt_read_trim(struct pvt_hwmon *pvt, long *val)
637 {
638 	u32 data;
639 
640 	data = readl(pvt->regs + PVT_CTRL);
641 	*val = FIELD_GET(PVT_CTRL_TRIM_MASK, data) * PVT_TRIM_STEP;
642 
643 	return 0;
644 }
645 
646 static int pvt_write_trim(struct pvt_hwmon *pvt, long val)
647 {
648 	u32 trim;
649 	int ret;
650 
651 	/*
652 	 * Serialize trim update, since a part of the register is changed and
653 	 * the controller is supposed to be disabled during this operation.
654 	 */
655 	ret = mutex_lock_interruptible(&pvt->iface_mtx);
656 	if (ret)
657 		return ret;
658 
659 	trim = pvt_calc_trim(val);
660 	pvt_set_trim(pvt, trim);
661 
662 	mutex_unlock(&pvt->iface_mtx);
663 
664 	return 0;
665 }
666 
667 static int pvt_read_timeout(struct pvt_hwmon *pvt, long *val)
668 {
669 	int ret;
670 
671 	ret = mutex_lock_interruptible(&pvt->iface_mtx);
672 	if (ret)
673 		return ret;
674 
675 	/* Return the result in msec as hwmon sysfs interface requires. */
676 	*val = ktime_to_ms(pvt->timeout);
677 
678 	mutex_unlock(&pvt->iface_mtx);
679 
680 	return 0;
681 }
682 
683 static int pvt_write_timeout(struct pvt_hwmon *pvt, long val)
684 {
685 	unsigned long rate;
686 	ktime_t kt, cache;
687 	u32 data;
688 	int ret;
689 
690 	rate = clk_get_rate(pvt->clks[PVT_CLOCK_REF].clk);
691 	if (!rate)
692 		return -ENODEV;
693 
694 	/*
695 	 * If alarms are enabled, the requested timeout must be divided
696 	 * between all available sensors to have the requested delay
697 	 * applicable to each individual sensor.
698 	 */
699 	cache = kt = ms_to_ktime(val);
700 #if defined(CONFIG_SENSORS_BT1_PVT_ALARMS)
701 	kt = ktime_divns(kt, PVT_SENSORS_NUM);
702 #endif
703 
704 	/*
705 	 * Subtract a constant lag, which always persists due to the limited
706 	 * PVT sampling rate. Make sure the timeout is not negative.
707 	 */
708 	kt = ktime_sub_ns(kt, PVT_TOUT_MIN);
709 	if (ktime_to_ns(kt) < 0)
710 		kt = ktime_set(0, 0);
711 
712 	/*
713 	 * Finally recalculate the timeout in terms of the reference clock
714 	 * period.
715 	 */
716 	data = ktime_divns(kt * rate, NSEC_PER_SEC);
717 
718 	/*
719 	 * Update the measurements delay, but lock the interface first, since
720 	 * we have to disable PVT in order to have the new delay actually
721 	 * updated.
722 	 */
723 	ret = mutex_lock_interruptible(&pvt->iface_mtx);
724 	if (ret)
725 		return ret;
726 
727 	pvt_set_tout(pvt, data);
728 	pvt->timeout = cache;
729 
730 	mutex_unlock(&pvt->iface_mtx);
731 
732 	return 0;
733 }
734 
735 static int pvt_hwmon_read(struct device *dev, enum hwmon_sensor_types type,
736 			  u32 attr, int ch, long *val)
737 {
738 	struct pvt_hwmon *pvt = dev_get_drvdata(dev);
739 
740 	if (!pvt_hwmon_channel_is_valid(type, ch))
741 		return -EINVAL;
742 
743 	switch (type) {
744 	case hwmon_chip:
745 		switch (attr) {
746 		case hwmon_chip_update_interval:
747 			return pvt_read_timeout(pvt, val);
748 		}
749 		break;
750 	case hwmon_temp:
751 		switch (attr) {
752 		case hwmon_temp_input:
753 			return pvt_read_data(pvt, ch, val);
754 		case hwmon_temp_type:
755 			*val = 1;
756 			return 0;
757 		case hwmon_temp_min:
758 			return pvt_read_limit(pvt, ch, true, val);
759 		case hwmon_temp_max:
760 			return pvt_read_limit(pvt, ch, false, val);
761 		case hwmon_temp_min_alarm:
762 			return pvt_read_alarm(pvt, ch, true, val);
763 		case hwmon_temp_max_alarm:
764 			return pvt_read_alarm(pvt, ch, false, val);
765 		case hwmon_temp_offset:
766 			return pvt_read_trim(pvt, val);
767 		}
768 		break;
769 	case hwmon_in:
770 		switch (attr) {
771 		case hwmon_in_input:
772 			return pvt_read_data(pvt, PVT_VOLT + ch, val);
773 		case hwmon_in_min:
774 			return pvt_read_limit(pvt, PVT_VOLT + ch, true, val);
775 		case hwmon_in_max:
776 			return pvt_read_limit(pvt, PVT_VOLT + ch, false, val);
777 		case hwmon_in_min_alarm:
778 			return pvt_read_alarm(pvt, PVT_VOLT + ch, true, val);
779 		case hwmon_in_max_alarm:
780 			return pvt_read_alarm(pvt, PVT_VOLT + ch, false, val);
781 		}
782 		break;
783 	default:
784 		break;
785 	}
786 
787 	return -EOPNOTSUPP;
788 }
789 
790 static int pvt_hwmon_read_string(struct device *dev,
791 				 enum hwmon_sensor_types type,
792 				 u32 attr, int ch, const char **str)
793 {
794 	if (!pvt_hwmon_channel_is_valid(type, ch))
795 		return -EINVAL;
796 
797 	switch (type) {
798 	case hwmon_temp:
799 		switch (attr) {
800 		case hwmon_temp_label:
801 			*str = pvt_info[ch].label;
802 			return 0;
803 		}
804 		break;
805 	case hwmon_in:
806 		switch (attr) {
807 		case hwmon_in_label:
808 			*str = pvt_info[PVT_VOLT + ch].label;
809 			return 0;
810 		}
811 		break;
812 	default:
813 		break;
814 	}
815 
816 	return -EOPNOTSUPP;
817 }
818 
819 static int pvt_hwmon_write(struct device *dev, enum hwmon_sensor_types type,
820 			   u32 attr, int ch, long val)
821 {
822 	struct pvt_hwmon *pvt = dev_get_drvdata(dev);
823 
824 	if (!pvt_hwmon_channel_is_valid(type, ch))
825 		return -EINVAL;
826 
827 	switch (type) {
828 	case hwmon_chip:
829 		switch (attr) {
830 		case hwmon_chip_update_interval:
831 			return pvt_write_timeout(pvt, val);
832 		}
833 		break;
834 	case hwmon_temp:
835 		switch (attr) {
836 		case hwmon_temp_min:
837 			return pvt_write_limit(pvt, ch, true, val);
838 		case hwmon_temp_max:
839 			return pvt_write_limit(pvt, ch, false, val);
840 		case hwmon_temp_offset:
841 			return pvt_write_trim(pvt, val);
842 		}
843 		break;
844 	case hwmon_in:
845 		switch (attr) {
846 		case hwmon_in_min:
847 			return pvt_write_limit(pvt, PVT_VOLT + ch, true, val);
848 		case hwmon_in_max:
849 			return pvt_write_limit(pvt, PVT_VOLT + ch, false, val);
850 		}
851 		break;
852 	default:
853 		break;
854 	}
855 
856 	return -EOPNOTSUPP;
857 }
858 
859 static const struct hwmon_ops pvt_hwmon_ops = {
860 	.is_visible = pvt_hwmon_is_visible,
861 	.read = pvt_hwmon_read,
862 	.read_string = pvt_hwmon_read_string,
863 	.write = pvt_hwmon_write
864 };
865 
866 static const struct hwmon_chip_info pvt_hwmon_info = {
867 	.ops = &pvt_hwmon_ops,
868 	.info = pvt_channel_info
869 };
870 
871 static void pvt_clear_data(void *data)
872 {
873 	struct pvt_hwmon *pvt = data;
874 #if !defined(CONFIG_SENSORS_BT1_PVT_ALARMS)
875 	int idx;
876 
877 	for (idx = 0; idx < PVT_SENSORS_NUM; ++idx)
878 		complete_all(&pvt->cache[idx].conversion);
879 #endif
880 
881 	mutex_destroy(&pvt->iface_mtx);
882 }
883 
884 static struct pvt_hwmon *pvt_create_data(struct platform_device *pdev)
885 {
886 	struct device *dev = &pdev->dev;
887 	struct pvt_hwmon *pvt;
888 	int ret, idx;
889 
890 	pvt = devm_kzalloc(dev, sizeof(*pvt), GFP_KERNEL);
891 	if (!pvt)
892 		return ERR_PTR(-ENOMEM);
893 
894 	ret = devm_add_action(dev, pvt_clear_data, pvt);
895 	if (ret) {
896 		dev_err(dev, "Can't add PVT data clear action\n");
897 		return ERR_PTR(ret);
898 	}
899 
900 	pvt->dev = dev;
901 	pvt->sensor = PVT_SENSOR_FIRST;
902 	mutex_init(&pvt->iface_mtx);
903 
904 #if defined(CONFIG_SENSORS_BT1_PVT_ALARMS)
905 	for (idx = 0; idx < PVT_SENSORS_NUM; ++idx)
906 		seqlock_init(&pvt->cache[idx].data_seqlock);
907 #else
908 	for (idx = 0; idx < PVT_SENSORS_NUM; ++idx)
909 		init_completion(&pvt->cache[idx].conversion);
910 #endif
911 
912 	return pvt;
913 }
914 
915 static int pvt_request_regs(struct pvt_hwmon *pvt)
916 {
917 	struct platform_device *pdev = to_platform_device(pvt->dev);
918 	struct resource *res;
919 
920 	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
921 	if (!res) {
922 		dev_err(pvt->dev, "Couldn't find PVT memresource\n");
923 		return -EINVAL;
924 	}
925 
926 	pvt->regs = devm_ioremap_resource(pvt->dev, res);
927 	if (IS_ERR(pvt->regs))
928 		return PTR_ERR(pvt->regs);
929 
930 	return 0;
931 }
932 
933 static void pvt_disable_clks(void *data)
934 {
935 	struct pvt_hwmon *pvt = data;
936 
937 	clk_bulk_disable_unprepare(PVT_CLOCK_NUM, pvt->clks);
938 }
939 
940 static int pvt_request_clks(struct pvt_hwmon *pvt)
941 {
942 	int ret;
943 
944 	pvt->clks[PVT_CLOCK_APB].id = "pclk";
945 	pvt->clks[PVT_CLOCK_REF].id = "ref";
946 
947 	ret = devm_clk_bulk_get(pvt->dev, PVT_CLOCK_NUM, pvt->clks);
948 	if (ret) {
949 		dev_err(pvt->dev, "Couldn't get PVT clocks descriptors\n");
950 		return ret;
951 	}
952 
953 	ret = clk_bulk_prepare_enable(PVT_CLOCK_NUM, pvt->clks);
954 	if (ret) {
955 		dev_err(pvt->dev, "Couldn't enable the PVT clocks\n");
956 		return ret;
957 	}
958 
959 	ret = devm_add_action_or_reset(pvt->dev, pvt_disable_clks, pvt);
960 	if (ret) {
961 		dev_err(pvt->dev, "Can't add PVT clocks disable action\n");
962 		return ret;
963 	}
964 
965 	return 0;
966 }
967 
968 static int pvt_check_pwr(struct pvt_hwmon *pvt)
969 {
970 	unsigned long tout;
971 	int ret = 0;
972 	u32 data;
973 
974 	/*
975 	 * Test out the sensor conversion functionality. If it is not done on
976 	 * time then the domain must have been unpowered and we won't be able
977 	 * to use the device later in this driver.
978 	 * Note If the power source is lost during the normal driver work the
979 	 * data read procedure will either return -ETIMEDOUT (for the
980 	 * alarm-less driver configuration) or just stop the repeated
981 	 * conversion. In the later case alas we won't be able to detect the
982 	 * problem.
983 	 */
984 	pvt_update(pvt->regs + PVT_INTR_MASK, PVT_INTR_ALL, PVT_INTR_ALL);
985 	pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, PVT_CTRL_EN);
986 	pvt_set_tout(pvt, 0);
987 	readl(pvt->regs + PVT_DATA);
988 
989 	tout = PVT_TOUT_MIN / NSEC_PER_USEC;
990 	usleep_range(tout, 2 * tout);
991 
992 	data = readl(pvt->regs + PVT_DATA);
993 	if (!(data & PVT_DATA_VALID)) {
994 		ret = -ENODEV;
995 		dev_err(pvt->dev, "Sensor is powered down\n");
996 	}
997 
998 	pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, 0);
999 
1000 	return ret;
1001 }
1002 
1003 static int pvt_init_iface(struct pvt_hwmon *pvt)
1004 {
1005 	unsigned long rate;
1006 	u32 trim, temp;
1007 
1008 	rate = clk_get_rate(pvt->clks[PVT_CLOCK_REF].clk);
1009 	if (!rate) {
1010 		dev_err(pvt->dev, "Invalid reference clock rate\n");
1011 		return -ENODEV;
1012 	}
1013 
1014 	/*
1015 	 * Make sure all interrupts and controller are disabled so not to
1016 	 * accidentally have ISR executed before the driver data is fully
1017 	 * initialized. Clear the IRQ status as well.
1018 	 */
1019 	pvt_update(pvt->regs + PVT_INTR_MASK, PVT_INTR_ALL, PVT_INTR_ALL);
1020 	pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, 0);
1021 	readl(pvt->regs + PVT_CLR_INTR);
1022 	readl(pvt->regs + PVT_DATA);
1023 
1024 	/* Setup default sensor mode, timeout and temperature trim. */
1025 	pvt_set_mode(pvt, pvt_info[pvt->sensor].mode);
1026 	pvt_set_tout(pvt, PVT_TOUT_DEF);
1027 
1028 	/*
1029 	 * Preserve the current ref-clock based delay (Ttotal) between the
1030 	 * sensors data samples in the driver data so not to recalculate it
1031 	 * each time on the data requests and timeout reads. It consists of the
1032 	 * delay introduced by the internal ref-clock timer (N / Fclk) and the
1033 	 * constant timeout caused by each conversion latency (Tmin):
1034 	 *   Ttotal = N / Fclk + Tmin
1035 	 * If alarms are enabled the sensors are polled one after another and
1036 	 * in order to get the next measurement of a particular sensor the
1037 	 * caller will have to wait for at most until all the others are
1038 	 * polled. In that case the formulae will look a bit different:
1039 	 *   Ttotal = 5 * (N / Fclk + Tmin)
1040 	 */
1041 #if defined(CONFIG_SENSORS_BT1_PVT_ALARMS)
1042 	pvt->timeout = ktime_set(PVT_SENSORS_NUM * PVT_TOUT_DEF, 0);
1043 	pvt->timeout = ktime_divns(pvt->timeout, rate);
1044 	pvt->timeout = ktime_add_ns(pvt->timeout, PVT_SENSORS_NUM * PVT_TOUT_MIN);
1045 #else
1046 	pvt->timeout = ktime_set(PVT_TOUT_DEF, 0);
1047 	pvt->timeout = ktime_divns(pvt->timeout, rate);
1048 	pvt->timeout = ktime_add_ns(pvt->timeout, PVT_TOUT_MIN);
1049 #endif
1050 
1051 	trim = PVT_TRIM_DEF;
1052 	if (!of_property_read_u32(pvt->dev->of_node,
1053 	     "baikal,pvt-temp-offset-millicelsius", &temp))
1054 		trim = pvt_calc_trim(temp);
1055 
1056 	pvt_set_trim(pvt, trim);
1057 
1058 	return 0;
1059 }
1060 
1061 static int pvt_request_irq(struct pvt_hwmon *pvt)
1062 {
1063 	struct platform_device *pdev = to_platform_device(pvt->dev);
1064 	int ret;
1065 
1066 	pvt->irq = platform_get_irq(pdev, 0);
1067 	if (pvt->irq < 0)
1068 		return pvt->irq;
1069 
1070 	ret = devm_request_threaded_irq(pvt->dev, pvt->irq,
1071 					pvt_hard_isr, pvt_soft_isr,
1072 #if defined(CONFIG_SENSORS_BT1_PVT_ALARMS)
1073 					IRQF_SHARED | IRQF_TRIGGER_HIGH |
1074 					IRQF_ONESHOT,
1075 #else
1076 					IRQF_SHARED | IRQF_TRIGGER_HIGH,
1077 #endif
1078 					"pvt", pvt);
1079 	if (ret) {
1080 		dev_err(pvt->dev, "Couldn't request PVT IRQ\n");
1081 		return ret;
1082 	}
1083 
1084 	return 0;
1085 }
1086 
1087 static int pvt_create_hwmon(struct pvt_hwmon *pvt)
1088 {
1089 	pvt->hwmon = devm_hwmon_device_register_with_info(pvt->dev, "pvt", pvt,
1090 		&pvt_hwmon_info, NULL);
1091 	if (IS_ERR(pvt->hwmon)) {
1092 		dev_err(pvt->dev, "Couldn't create hwmon device\n");
1093 		return PTR_ERR(pvt->hwmon);
1094 	}
1095 
1096 	return 0;
1097 }
1098 
1099 #if defined(CONFIG_SENSORS_BT1_PVT_ALARMS)
1100 
1101 static void pvt_disable_iface(void *data)
1102 {
1103 	struct pvt_hwmon *pvt = data;
1104 
1105 	mutex_lock(&pvt->iface_mtx);
1106 	pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, 0);
1107 	pvt_update(pvt->regs + PVT_INTR_MASK, PVT_INTR_DVALID,
1108 		   PVT_INTR_DVALID);
1109 	mutex_unlock(&pvt->iface_mtx);
1110 }
1111 
1112 static int pvt_enable_iface(struct pvt_hwmon *pvt)
1113 {
1114 	int ret;
1115 
1116 	ret = devm_add_action(pvt->dev, pvt_disable_iface, pvt);
1117 	if (ret) {
1118 		dev_err(pvt->dev, "Can't add PVT disable interface action\n");
1119 		return ret;
1120 	}
1121 
1122 	/*
1123 	 * Enable sensors data conversion and IRQ. We need to lock the
1124 	 * interface mutex since hwmon has just been created and the
1125 	 * corresponding sysfs files are accessible from user-space,
1126 	 * which theoretically may cause races.
1127 	 */
1128 	mutex_lock(&pvt->iface_mtx);
1129 	pvt_update(pvt->regs + PVT_INTR_MASK, PVT_INTR_DVALID, 0);
1130 	pvt_update(pvt->regs + PVT_CTRL, PVT_CTRL_EN, PVT_CTRL_EN);
1131 	mutex_unlock(&pvt->iface_mtx);
1132 
1133 	return 0;
1134 }
1135 
1136 #else /* !CONFIG_SENSORS_BT1_PVT_ALARMS */
1137 
1138 static int pvt_enable_iface(struct pvt_hwmon *pvt)
1139 {
1140 	return 0;
1141 }
1142 
1143 #endif /* !CONFIG_SENSORS_BT1_PVT_ALARMS */
1144 
1145 static int pvt_probe(struct platform_device *pdev)
1146 {
1147 	struct pvt_hwmon *pvt;
1148 	int ret;
1149 
1150 	pvt = pvt_create_data(pdev);
1151 	if (IS_ERR(pvt))
1152 		return PTR_ERR(pvt);
1153 
1154 	ret = pvt_request_regs(pvt);
1155 	if (ret)
1156 		return ret;
1157 
1158 	ret = pvt_request_clks(pvt);
1159 	if (ret)
1160 		return ret;
1161 
1162 	ret = pvt_check_pwr(pvt);
1163 	if (ret)
1164 		return ret;
1165 
1166 	ret = pvt_init_iface(pvt);
1167 	if (ret)
1168 		return ret;
1169 
1170 	ret = pvt_request_irq(pvt);
1171 	if (ret)
1172 		return ret;
1173 
1174 	ret = pvt_create_hwmon(pvt);
1175 	if (ret)
1176 		return ret;
1177 
1178 	ret = pvt_enable_iface(pvt);
1179 	if (ret)
1180 		return ret;
1181 
1182 	return 0;
1183 }
1184 
1185 static const struct of_device_id pvt_of_match[] = {
1186 	{ .compatible = "baikal,bt1-pvt" },
1187 	{ }
1188 };
1189 MODULE_DEVICE_TABLE(of, pvt_of_match);
1190 
1191 static struct platform_driver pvt_driver = {
1192 	.probe = pvt_probe,
1193 	.driver = {
1194 		.name = "bt1-pvt",
1195 		.of_match_table = pvt_of_match
1196 	}
1197 };
1198 module_platform_driver(pvt_driver);
1199 
1200 MODULE_AUTHOR("Maxim Kaurkin <maxim.kaurkin@baikalelectronics.ru>");
1201 MODULE_DESCRIPTION("Baikal-T1 PVT driver");
1202 MODULE_LICENSE("GPL v2");
1203