1// SPDX-License-Identifier: GPL-2.0
2/*
3 *  of-thermal.c - Generic Thermal Management device tree support.
4 *
5 *  Copyright (C) 2013 Texas Instruments
6 *  Copyright (C) 2013 Eduardo Valentin <eduardo.valentin@ti.com>
7 */
8
9#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10
11#include <linux/err.h>
12#include <linux/export.h>
13#include <linux/of.h>
14#include <linux/slab.h>
15#include <linux/thermal.h>
16#include <linux/types.h>
17#include <linux/string.h>
18
19#include "thermal_core.h"
20
21/***   functions parsing device tree nodes   ***/
22
23static int of_find_trip_id(struct device_node *np, struct device_node *trip)
24{
25	struct device_node *trips;
26	struct device_node *t;
27	int i = 0;
28
29	trips = of_get_child_by_name(np, "trips");
30	if (!trips) {
31		pr_err("Failed to find 'trips' node\n");
32		return -EINVAL;
33	}
34
35	/*
36	 * Find the trip id point associated with the cooling device map
37	 */
38	for_each_child_of_node(trips, t) {
39
40		if (t == trip) {
41			of_node_put(t);
42			goto out;
43		}
44		i++;
45	}
46
47	i = -ENXIO;
48out:
49	of_node_put(trips);
50
51	return i;
52}
53
54/*
55 * It maps 'enum thermal_trip_type' found in include/linux/thermal.h
56 * into the device tree binding of 'trip', property type.
57 */
58static const char * const trip_types[] = {
59	[THERMAL_TRIP_ACTIVE]	= "active",
60	[THERMAL_TRIP_PASSIVE]	= "passive",
61	[THERMAL_TRIP_HOT]	= "hot",
62	[THERMAL_TRIP_CRITICAL]	= "critical",
63};
64
65/**
66 * thermal_of_get_trip_type - Get phy mode for given device_node
67 * @np:	Pointer to the given device_node
68 * @type: Pointer to resulting trip type
69 *
70 * The function gets trip type string from property 'type',
71 * and store its index in trip_types table in @type,
72 *
73 * Return: 0 on success, or errno in error case.
74 */
75static int thermal_of_get_trip_type(struct device_node *np,
76				    enum thermal_trip_type *type)
77{
78	const char *t;
79	int err, i;
80
81	err = of_property_read_string(np, "type", &t);
82	if (err < 0)
83		return err;
84
85	for (i = 0; i < ARRAY_SIZE(trip_types); i++)
86		if (!strcasecmp(t, trip_types[i])) {
87			*type = i;
88			return 0;
89		}
90
91	return -ENODEV;
92}
93
94static int thermal_of_populate_trip(struct device_node *np,
95				    struct thermal_trip *trip)
96{
97	int prop;
98	int ret;
99
100	ret = of_property_read_u32(np, "temperature", &prop);
101	if (ret < 0) {
102		pr_err("missing temperature property\n");
103		return ret;
104	}
105	trip->temperature = prop;
106
107	ret = of_property_read_u32(np, "hysteresis", &prop);
108	if (ret < 0) {
109		pr_err("missing hysteresis property\n");
110		return ret;
111	}
112	trip->hysteresis = prop;
113
114	ret = thermal_of_get_trip_type(np, &trip->type);
115	if (ret < 0) {
116		pr_err("wrong trip type property\n");
117		return ret;
118	}
119
120	trip->flags = THERMAL_TRIP_FLAG_RW_TEMP;
121
122	return 0;
123}
124
125static struct thermal_trip *thermal_of_trips_init(struct device_node *np, int *ntrips)
126{
127	struct thermal_trip *tt;
128	struct device_node *trips, *trip;
129	int ret, count;
130
131	trips = of_get_child_by_name(np, "trips");
132	if (!trips) {
133		pr_err("Failed to find 'trips' node\n");
134		return ERR_PTR(-EINVAL);
135	}
136
137	count = of_get_child_count(trips);
138	if (!count) {
139		pr_err("No trip point defined\n");
140		ret = -EINVAL;
141		goto out_of_node_put;
142	}
143
144	tt = kzalloc(sizeof(*tt) * count, GFP_KERNEL);
145	if (!tt) {
146		ret = -ENOMEM;
147		goto out_of_node_put;
148	}
149
150	*ntrips = count;
151
152	count = 0;
153	for_each_child_of_node(trips, trip) {
154		ret = thermal_of_populate_trip(trip, &tt[count++]);
155		if (ret)
156			goto out_kfree;
157	}
158
159	of_node_put(trips);
160
161	return tt;
162
163out_kfree:
164	kfree(tt);
165	*ntrips = 0;
166out_of_node_put:
167	of_node_put(trips);
168
169	return ERR_PTR(ret);
170}
171
172static struct device_node *of_thermal_zone_find(struct device_node *sensor, int id)
173{
174	struct device_node *np, *tz;
175	struct of_phandle_args sensor_specs;
176
177	np = of_find_node_by_name(NULL, "thermal-zones");
178	if (!np) {
179		pr_debug("No thermal zones description\n");
180		return ERR_PTR(-ENODEV);
181	}
182
183	/*
184	 * Search for each thermal zone, a defined sensor
185	 * corresponding to the one passed as parameter
186	 */
187	for_each_available_child_of_node(np, tz) {
188
189		int count, i;
190
191		count = of_count_phandle_with_args(tz, "thermal-sensors",
192						   "#thermal-sensor-cells");
193		if (count <= 0) {
194			pr_err("%pOFn: missing thermal sensor\n", tz);
195			tz = ERR_PTR(-EINVAL);
196			goto out;
197		}
198
199		for (i = 0; i < count; i++) {
200
201			int ret;
202
203			ret = of_parse_phandle_with_args(tz, "thermal-sensors",
204							 "#thermal-sensor-cells",
205							 i, &sensor_specs);
206			if (ret < 0) {
207				pr_err("%pOFn: Failed to read thermal-sensors cells: %d\n", tz, ret);
208				tz = ERR_PTR(ret);
209				goto out;
210			}
211
212			if ((sensor == sensor_specs.np) && id == (sensor_specs.args_count ?
213								  sensor_specs.args[0] : 0)) {
214				pr_debug("sensor %pOFn id=%d belongs to %pOFn\n", sensor, id, tz);
215				goto out;
216			}
217		}
218	}
219	tz = ERR_PTR(-ENODEV);
220out:
221	of_node_put(np);
222	return tz;
223}
224
225static int thermal_of_monitor_init(struct device_node *np, int *delay, int *pdelay)
226{
227	int ret;
228
229	ret = of_property_read_u32(np, "polling-delay-passive", pdelay);
230	if (ret == -EINVAL) {
231		*pdelay = 0;
232	} else if (ret < 0) {
233		pr_err("%pOFn: Couldn't get polling-delay-passive: %d\n", np, ret);
234		return ret;
235	}
236
237	ret = of_property_read_u32(np, "polling-delay", delay);
238	if (ret == -EINVAL) {
239		*delay = 0;
240	} else if (ret < 0) {
241		pr_err("%pOFn: Couldn't get polling-delay: %d\n", np, ret);
242		return ret;
243	}
244
245	return 0;
246}
247
248static void thermal_of_parameters_init(struct device_node *np,
249				       struct thermal_zone_params *tzp)
250{
251	int coef[2];
252	int ncoef = ARRAY_SIZE(coef);
253	int prop, ret;
254
255	tzp->no_hwmon = true;
256
257	if (!of_property_read_u32(np, "sustainable-power", &prop))
258		tzp->sustainable_power = prop;
259
260	/*
261	 * For now, the thermal framework supports only one sensor per
262	 * thermal zone. Thus, we are considering only the first two
263	 * values as slope and offset.
264	 */
265	ret = of_property_read_u32_array(np, "coefficients", coef, ncoef);
266	if (ret) {
267		coef[0] = 1;
268		coef[1] = 0;
269	}
270
271	tzp->slope = coef[0];
272	tzp->offset = coef[1];
273}
274
275static struct device_node *thermal_of_zone_get_by_name(struct thermal_zone_device *tz)
276{
277	struct device_node *np, *tz_np;
278
279	np = of_find_node_by_name(NULL, "thermal-zones");
280	if (!np)
281		return ERR_PTR(-ENODEV);
282
283	tz_np = of_get_child_by_name(np, tz->type);
284
285	of_node_put(np);
286
287	if (!tz_np)
288		return ERR_PTR(-ENODEV);
289
290	return tz_np;
291}
292
293static int __thermal_of_unbind(struct device_node *map_np, int index, int trip_id,
294			       struct thermal_zone_device *tz, struct thermal_cooling_device *cdev)
295{
296	struct of_phandle_args cooling_spec;
297	int ret;
298
299	ret = of_parse_phandle_with_args(map_np, "cooling-device", "#cooling-cells",
300					 index, &cooling_spec);
301
302	if (ret < 0) {
303		pr_err("Invalid cooling-device entry\n");
304		return ret;
305	}
306
307	of_node_put(cooling_spec.np);
308
309	if (cooling_spec.args_count < 2) {
310		pr_err("wrong reference to cooling device, missing limits\n");
311		return -EINVAL;
312	}
313
314	if (cooling_spec.np != cdev->np)
315		return 0;
316
317	ret = thermal_zone_unbind_cooling_device(tz, trip_id, cdev);
318	if (ret)
319		pr_err("Failed to unbind '%s' with '%s': %d\n", tz->type, cdev->type, ret);
320
321	return ret;
322}
323
324static int __thermal_of_bind(struct device_node *map_np, int index, int trip_id,
325			     struct thermal_zone_device *tz, struct thermal_cooling_device *cdev)
326{
327	struct of_phandle_args cooling_spec;
328	int ret, weight = THERMAL_WEIGHT_DEFAULT;
329
330	of_property_read_u32(map_np, "contribution", &weight);
331
332	ret = of_parse_phandle_with_args(map_np, "cooling-device", "#cooling-cells",
333					 index, &cooling_spec);
334
335	if (ret < 0) {
336		pr_err("Invalid cooling-device entry\n");
337		return ret;
338	}
339
340	of_node_put(cooling_spec.np);
341
342	if (cooling_spec.args_count < 2) {
343		pr_err("wrong reference to cooling device, missing limits\n");
344		return -EINVAL;
345	}
346
347	if (cooling_spec.np != cdev->np)
348		return 0;
349
350	ret = thermal_zone_bind_cooling_device(tz, trip_id, cdev, cooling_spec.args[1],
351					       cooling_spec.args[0],
352					       weight);
353	if (ret)
354		pr_err("Failed to bind '%s' with '%s': %d\n", tz->type, cdev->type, ret);
355
356	return ret;
357}
358
359static int thermal_of_for_each_cooling_device(struct device_node *tz_np, struct device_node *map_np,
360					      struct thermal_zone_device *tz, struct thermal_cooling_device *cdev,
361					      int (*action)(struct device_node *, int, int,
362							    struct thermal_zone_device *, struct thermal_cooling_device *))
363{
364	struct device_node *tr_np;
365	int count, i, trip_id;
366
367	tr_np = of_parse_phandle(map_np, "trip", 0);
368	if (!tr_np)
369		return -ENODEV;
370
371	trip_id = of_find_trip_id(tz_np, tr_np);
372	if (trip_id < 0)
373		return trip_id;
374
375	count = of_count_phandle_with_args(map_np, "cooling-device", "#cooling-cells");
376	if (count <= 0) {
377		pr_err("Add a cooling_device property with at least one device\n");
378		return -ENOENT;
379	}
380
381	/*
382	 * At this point, we don't want to bail out when there is an
383	 * error, we will try to bind/unbind as many as possible
384	 * cooling devices
385	 */
386	for (i = 0; i < count; i++)
387		action(map_np, i, trip_id, tz, cdev);
388
389	return 0;
390}
391
392static int thermal_of_for_each_cooling_maps(struct thermal_zone_device *tz,
393					    struct thermal_cooling_device *cdev,
394					    int (*action)(struct device_node *, int, int,
395							  struct thermal_zone_device *, struct thermal_cooling_device *))
396{
397	struct device_node *tz_np, *cm_np, *child;
398	int ret = 0;
399
400	tz_np = thermal_of_zone_get_by_name(tz);
401	if (IS_ERR(tz_np)) {
402		pr_err("Failed to get node tz by name\n");
403		return PTR_ERR(tz_np);
404	}
405
406	cm_np = of_get_child_by_name(tz_np, "cooling-maps");
407	if (!cm_np)
408		goto out;
409
410	for_each_child_of_node(cm_np, child) {
411		ret = thermal_of_for_each_cooling_device(tz_np, child, tz, cdev, action);
412		if (ret) {
413			of_node_put(child);
414			break;
415		}
416	}
417
418	of_node_put(cm_np);
419out:
420	of_node_put(tz_np);
421
422	return ret;
423}
424
425static int thermal_of_bind(struct thermal_zone_device *tz,
426			   struct thermal_cooling_device *cdev)
427{
428	return thermal_of_for_each_cooling_maps(tz, cdev, __thermal_of_bind);
429}
430
431static int thermal_of_unbind(struct thermal_zone_device *tz,
432			     struct thermal_cooling_device *cdev)
433{
434	return thermal_of_for_each_cooling_maps(tz, cdev, __thermal_of_unbind);
435}
436
437/**
438 * thermal_of_zone_unregister - Cleanup the specific allocated ressources
439 *
440 * This function disables the thermal zone and frees the different
441 * ressources allocated specific to the thermal OF.
442 *
443 * @tz: a pointer to the thermal zone structure
444 */
445static void thermal_of_zone_unregister(struct thermal_zone_device *tz)
446{
447	thermal_zone_device_disable(tz);
448	thermal_zone_device_unregister(tz);
449}
450
451/**
452 * thermal_of_zone_register - Register a thermal zone with device node
453 * sensor
454 *
455 * The thermal_of_zone_register() parses a device tree given a device
456 * node sensor and identifier. It searches for the thermal zone
457 * associated to the couple sensor/id and retrieves all the thermal
458 * zone properties and registers new thermal zone with those
459 * properties.
460 *
461 * @sensor: A device node pointer corresponding to the sensor in the device tree
462 * @id: An integer as sensor identifier
463 * @data: A private data to be stored in the thermal zone dedicated private area
464 * @ops: A set of thermal sensor ops
465 *
466 * Return: a valid thermal zone structure pointer on success.
467 *	- EINVAL: if the device tree thermal description is malformed
468 *	- ENOMEM: if one structure can not be allocated
469 *	- Other negative errors are returned by the underlying called functions
470 */
471static struct thermal_zone_device *thermal_of_zone_register(struct device_node *sensor, int id, void *data,
472							    const struct thermal_zone_device_ops *ops)
473{
474	struct thermal_zone_device_ops of_ops = *ops;
475	struct thermal_zone_device *tz;
476	struct thermal_trip *trips;
477	struct thermal_zone_params tzp = {};
478	struct device_node *np;
479	const char *action;
480	int delay, pdelay;
481	int ntrips;
482	int ret;
483
484	np = of_thermal_zone_find(sensor, id);
485	if (IS_ERR(np)) {
486		if (PTR_ERR(np) != -ENODEV)
487			pr_err("Failed to find thermal zone for %pOFn id=%d\n", sensor, id);
488		return ERR_CAST(np);
489	}
490
491	trips = thermal_of_trips_init(np, &ntrips);
492	if (IS_ERR(trips)) {
493		pr_err("Failed to find trip points for %pOFn id=%d\n", sensor, id);
494		return ERR_CAST(trips);
495	}
496
497	ret = thermal_of_monitor_init(np, &delay, &pdelay);
498	if (ret) {
499		pr_err("Failed to initialize monitoring delays from %pOFn\n", np);
500		goto out_kfree_trips;
501	}
502
503	thermal_of_parameters_init(np, &tzp);
504
505	of_ops.bind = thermal_of_bind;
506	of_ops.unbind = thermal_of_unbind;
507
508	ret = of_property_read_string(np, "critical-action", &action);
509	if (!ret)
510		if (!of_ops.critical && !strcasecmp(action, "reboot"))
511			of_ops.critical = thermal_zone_device_critical_reboot;
512
513	tz = thermal_zone_device_register_with_trips(np->name, trips, ntrips,
514						     data, &of_ops, &tzp,
515						     pdelay, delay);
516	if (IS_ERR(tz)) {
517		ret = PTR_ERR(tz);
518		pr_err("Failed to register thermal zone %pOFn: %d\n", np, ret);
519		goto out_kfree_trips;
520	}
521
522	kfree(trips);
523
524	ret = thermal_zone_device_enable(tz);
525	if (ret) {
526		pr_err("Failed to enabled thermal zone '%s', id=%d: %d\n",
527		       tz->type, tz->id, ret);
528		thermal_of_zone_unregister(tz);
529		return ERR_PTR(ret);
530	}
531
532	return tz;
533
534out_kfree_trips:
535	kfree(trips);
536
537	return ERR_PTR(ret);
538}
539
540static void devm_thermal_of_zone_release(struct device *dev, void *res)
541{
542	thermal_of_zone_unregister(*(struct thermal_zone_device **)res);
543}
544
545static int devm_thermal_of_zone_match(struct device *dev, void *res,
546				      void *data)
547{
548	struct thermal_zone_device **r = res;
549
550	if (WARN_ON(!r || !*r))
551		return 0;
552
553	return *r == data;
554}
555
556/**
557 * devm_thermal_of_zone_register - register a thermal tied with the sensor life cycle
558 *
559 * This function is the device version of the thermal_of_zone_register() function.
560 *
561 * @dev: a device structure pointer to sensor to be tied with the thermal zone OF life cycle
562 * @sensor_id: the sensor identifier
563 * @data: a pointer to a private data to be stored in the thermal zone 'devdata' field
564 * @ops: a pointer to the ops structure associated with the sensor
565 */
566struct thermal_zone_device *devm_thermal_of_zone_register(struct device *dev, int sensor_id, void *data,
567							  const struct thermal_zone_device_ops *ops)
568{
569	struct thermal_zone_device **ptr, *tzd;
570
571	ptr = devres_alloc(devm_thermal_of_zone_release, sizeof(*ptr),
572			   GFP_KERNEL);
573	if (!ptr)
574		return ERR_PTR(-ENOMEM);
575
576	tzd = thermal_of_zone_register(dev->of_node, sensor_id, data, ops);
577	if (IS_ERR(tzd)) {
578		devres_free(ptr);
579		return tzd;
580	}
581
582	*ptr = tzd;
583	devres_add(dev, ptr);
584
585	return tzd;
586}
587EXPORT_SYMBOL_GPL(devm_thermal_of_zone_register);
588
589/**
590 * devm_thermal_of_zone_unregister - Resource managed version of
591 *				thermal_of_zone_unregister().
592 * @dev: Device for which which resource was allocated.
593 * @tz: a pointer to struct thermal_zone where the sensor is registered.
594 *
595 * This function removes the sensor callbacks and private data from the
596 * thermal zone device registered with devm_thermal_zone_of_sensor_register()
597 * API. It will also silent the zone by remove the .get_temp() and .get_trend()
598 * thermal zone device callbacks.
599 * Normally this function will not need to be called and the resource
600 * management code will ensure that the resource is freed.
601 */
602void devm_thermal_of_zone_unregister(struct device *dev, struct thermal_zone_device *tz)
603{
604	WARN_ON(devres_release(dev, devm_thermal_of_zone_release,
605			       devm_thermal_of_zone_match, tz));
606}
607EXPORT_SYMBOL_GPL(devm_thermal_of_zone_unregister);
608