xref: /linux/drivers/thermal/thermal_core.c (revision 4403278e4ea2f654f8130a5c03eb8b4516a0f201)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  thermal.c - Generic Thermal Management Sysfs support.
4  *
5  *  Copyright (C) 2008 Intel Corp
6  *  Copyright (C) 2008 Zhang Rui <rui.zhang@intel.com>
7  *  Copyright (C) 2008 Sujith Thomas <sujith.thomas@intel.com>
8  */
9 
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11 
12 #include <linux/device.h>
13 #include <linux/err.h>
14 #include <linux/export.h>
15 #include <linux/slab.h>
16 #include <linux/kdev_t.h>
17 #include <linux/idr.h>
18 #include <linux/thermal.h>
19 #include <linux/reboot.h>
20 #include <linux/string.h>
21 #include <linux/of.h>
22 #include <linux/suspend.h>
23 
24 #define CREATE_TRACE_POINTS
25 #include "thermal_trace.h"
26 
27 #include "thermal_core.h"
28 #include "thermal_hwmon.h"
29 
30 static DEFINE_IDA(thermal_tz_ida);
31 static DEFINE_IDA(thermal_cdev_ida);
32 
33 static LIST_HEAD(thermal_tz_list);
34 static LIST_HEAD(thermal_cdev_list);
35 static LIST_HEAD(thermal_governor_list);
36 
37 static DEFINE_MUTEX(thermal_list_lock);
38 static DEFINE_MUTEX(thermal_governor_lock);
39 
40 static struct thermal_governor *def_governor;
41 
42 static bool thermal_pm_suspended;
43 
44 static struct workqueue_struct *thermal_wq __ro_after_init;
45 
46 /*
47  * Governor section: set of functions to handle thermal governors
48  *
49  * Functions to help in the life cycle of thermal governors within
50  * the thermal core and by the thermal governor code.
51  */
52 
53 static struct thermal_governor *__find_governor(const char *name)
54 {
55 	struct thermal_governor *pos;
56 
57 	if (!name || !name[0])
58 		return def_governor;
59 
60 	list_for_each_entry(pos, &thermal_governor_list, governor_list)
61 		if (!strncasecmp(name, pos->name, THERMAL_NAME_LENGTH))
62 			return pos;
63 
64 	return NULL;
65 }
66 
67 /**
68  * bind_previous_governor() - bind the previous governor of the thermal zone
69  * @tz:		a valid pointer to a struct thermal_zone_device
70  * @failed_gov_name:	the name of the governor that failed to register
71  *
72  * Register the previous governor of the thermal zone after a new
73  * governor has failed to be bound.
74  */
75 static void bind_previous_governor(struct thermal_zone_device *tz,
76 				   const char *failed_gov_name)
77 {
78 	if (tz->governor && tz->governor->bind_to_tz) {
79 		if (tz->governor->bind_to_tz(tz)) {
80 			dev_err(&tz->device,
81 				"governor %s failed to bind and the previous one (%s) failed to bind again, thermal zone %s has no governor\n",
82 				failed_gov_name, tz->governor->name, tz->type);
83 			tz->governor = NULL;
84 		}
85 	}
86 }
87 
88 /**
89  * thermal_set_governor() - Switch to another governor
90  * @tz:		a valid pointer to a struct thermal_zone_device
91  * @new_gov:	pointer to the new governor
92  *
93  * Change the governor of thermal zone @tz.
94  *
95  * Return: 0 on success, an error if the new governor's bind_to_tz() failed.
96  */
97 static int thermal_set_governor(struct thermal_zone_device *tz,
98 				struct thermal_governor *new_gov)
99 {
100 	int ret = 0;
101 
102 	if (tz->governor && tz->governor->unbind_from_tz)
103 		tz->governor->unbind_from_tz(tz);
104 
105 	if (new_gov && new_gov->bind_to_tz) {
106 		ret = new_gov->bind_to_tz(tz);
107 		if (ret) {
108 			bind_previous_governor(tz, new_gov->name);
109 
110 			return ret;
111 		}
112 	}
113 
114 	tz->governor = new_gov;
115 
116 	return ret;
117 }
118 
119 static int __init thermal_register_governor(struct thermal_governor *governor)
120 {
121 
122 	if (!governor)
123 		return -EINVAL;
124 
125 	if (__find_governor(governor->name))
126 		return -EBUSY;
127 
128 	list_add(&governor->governor_list, &thermal_governor_list);
129 
130 	if (strncmp(governor->name, DEFAULT_THERMAL_GOVERNOR, THERMAL_NAME_LENGTH))
131 		return 0;
132 
133 	if (!def_governor)
134 		def_governor = governor;
135 
136 	return 0;
137 }
138 
139 int thermal_zone_device_set_policy(struct thermal_zone_device *tz,
140 				   char *policy)
141 {
142 	struct thermal_governor *gov;
143 	int ret = -EINVAL;
144 
145 	guard(mutex)(&thermal_governor_lock);
146 	guard(thermal_zone)(tz);
147 
148 	gov = __find_governor(strim(policy));
149 	if (gov)
150 		ret = thermal_set_governor(tz, gov);
151 
152 	thermal_notify_tz_gov_change(tz, policy);
153 
154 	return ret;
155 }
156 
157 int thermal_build_list_of_policies(char *buf)
158 {
159 	struct thermal_governor *pos;
160 	ssize_t count = 0;
161 
162 	guard(mutex)(&thermal_governor_lock);
163 
164 	list_for_each_entry(pos, &thermal_governor_list, governor_list) {
165 		count += sysfs_emit_at(buf, count, "%s ", pos->name);
166 	}
167 	count += sysfs_emit_at(buf, count, "\n");
168 
169 	return count;
170 }
171 
172 static void __init thermal_unregister_governors(void)
173 {
174 	struct thermal_governor *gov, *pos;
175 
176 	guard(mutex)(&thermal_governor_lock);
177 
178 	list_for_each_entry_safe(gov, pos, &thermal_governor_list, governor_list)
179 		list_del(&gov->governor_list);
180 }
181 
182 static int __init thermal_register_governors(void)
183 {
184 	struct thermal_governor **governor;
185 
186 	guard(mutex)(&thermal_governor_lock);
187 
188 	for_each_governor_table(governor) {
189 		int ret;
190 
191 		ret = thermal_register_governor(*governor);
192 		if (ret) {
193 			pr_err("Failed to register governor: '%s'",
194 			       (*governor)->name);
195 			return ret;
196 		}
197 
198 		pr_info("Registered thermal governor '%s'", (*governor)->name);
199 	}
200 
201 	return 0;
202 }
203 
204 static int __thermal_zone_device_set_mode(struct thermal_zone_device *tz,
205 					  enum thermal_device_mode mode)
206 {
207 	if (tz->ops.change_mode) {
208 		int ret;
209 
210 		ret = tz->ops.change_mode(tz, mode);
211 		if (ret)
212 			return ret;
213 	}
214 
215 	tz->mode = mode;
216 
217 	return 0;
218 }
219 
220 static void thermal_zone_broken_disable(struct thermal_zone_device *tz)
221 {
222 	struct thermal_trip_desc *td;
223 
224 	dev_err(&tz->device, "Unable to get temperature, disabling!\n");
225 	/*
226 	 * This function only runs for enabled thermal zones, so no need to
227 	 * check for the current mode.
228 	 */
229 	__thermal_zone_device_set_mode(tz, THERMAL_DEVICE_DISABLED);
230 	thermal_notify_tz_disable(tz);
231 
232 	for_each_trip_desc(tz, td) {
233 		if (td->trip.type == THERMAL_TRIP_CRITICAL &&
234 		    td->trip.temperature > THERMAL_TEMP_INVALID) {
235 			dev_crit(&tz->device,
236 				 "Disabled thermal zone with critical trip point\n");
237 			return;
238 		}
239 	}
240 }
241 
242 /*
243  * Zone update section: main control loop applied to each zone while monitoring
244  * in polling mode. The monitoring is done using a workqueue.
245  * Same update may be done on a zone by calling thermal_zone_device_update().
246  *
247  * An update means:
248  * - Non-critical trips will invoke the governor responsible for that zone;
249  * - Hot trips will produce a notification to userspace;
250  * - Critical trip point will cause a system shutdown.
251  */
252 static void thermal_zone_device_set_polling(struct thermal_zone_device *tz,
253 					    unsigned long delay)
254 {
255 	if (delay > HZ)
256 		delay = round_jiffies_relative(delay);
257 
258 	mod_delayed_work(thermal_wq, &tz->poll_queue, delay);
259 }
260 
261 static void thermal_zone_recheck(struct thermal_zone_device *tz, int error)
262 {
263 	if (error == -EAGAIN) {
264 		thermal_zone_device_set_polling(tz, THERMAL_RECHECK_DELAY);
265 		return;
266 	}
267 
268 	/*
269 	 * Print the message once to reduce log noise.  It will be followed by
270 	 * another one if the temperature cannot be determined after multiple
271 	 * attempts.
272 	 */
273 	if (tz->recheck_delay_jiffies == THERMAL_RECHECK_DELAY)
274 		dev_info(&tz->device, "Temperature check failed (%d)\n", error);
275 
276 	thermal_zone_device_set_polling(tz, tz->recheck_delay_jiffies);
277 
278 	tz->recheck_delay_jiffies += max(tz->recheck_delay_jiffies >> 1, 1ULL);
279 	if (tz->recheck_delay_jiffies > THERMAL_MAX_RECHECK_DELAY) {
280 		thermal_zone_broken_disable(tz);
281 		/*
282 		 * Restore the original recheck delay value to allow the thermal
283 		 * zone to try to recover when it is reenabled by user space.
284 		 */
285 		tz->recheck_delay_jiffies = THERMAL_RECHECK_DELAY;
286 	}
287 }
288 
289 static void monitor_thermal_zone(struct thermal_zone_device *tz)
290 {
291 	if (tz->passive > 0 && tz->passive_delay_jiffies)
292 		thermal_zone_device_set_polling(tz, tz->passive_delay_jiffies);
293 	else if (tz->polling_delay_jiffies)
294 		thermal_zone_device_set_polling(tz, tz->polling_delay_jiffies);
295 }
296 
297 static struct thermal_governor *thermal_get_tz_governor(struct thermal_zone_device *tz)
298 {
299 	if (tz->governor)
300 		return tz->governor;
301 
302 	return def_governor;
303 }
304 
305 void thermal_governor_update_tz(struct thermal_zone_device *tz,
306 				enum thermal_notify_event reason)
307 {
308 	if (!tz->governor || !tz->governor->update_tz)
309 		return;
310 
311 	tz->governor->update_tz(tz, reason);
312 }
313 
314 static void thermal_zone_device_halt(struct thermal_zone_device *tz,
315 				     enum hw_protection_action action)
316 {
317 	/*
318 	 * poweroff_delay_ms must be a carefully profiled positive value.
319 	 * Its a must for forced_emergency_poweroff_work to be scheduled.
320 	 */
321 	int poweroff_delay_ms = CONFIG_THERMAL_EMERGENCY_POWEROFF_DELAY_MS;
322 	const char *msg = "Temperature too high";
323 
324 	dev_emerg(&tz->device, "%s: critical temperature reached\n", tz->type);
325 
326 	__hw_protection_trigger(msg, poweroff_delay_ms, action);
327 }
328 
329 void thermal_zone_device_critical(struct thermal_zone_device *tz)
330 {
331 	thermal_zone_device_halt(tz, HWPROT_ACT_DEFAULT);
332 }
333 EXPORT_SYMBOL(thermal_zone_device_critical);
334 
335 void thermal_zone_device_critical_shutdown(struct thermal_zone_device *tz)
336 {
337 	thermal_zone_device_halt(tz, HWPROT_ACT_SHUTDOWN);
338 }
339 
340 void thermal_zone_device_critical_reboot(struct thermal_zone_device *tz)
341 {
342 	thermal_zone_device_halt(tz, HWPROT_ACT_REBOOT);
343 }
344 
345 static void handle_critical_trips(struct thermal_zone_device *tz,
346 				  const struct thermal_trip *trip)
347 {
348 	trace_thermal_zone_trip(tz, thermal_zone_trip_id(tz, trip), trip->type);
349 
350 	if (trip->type == THERMAL_TRIP_CRITICAL)
351 		tz->ops.critical(tz);
352 	else if (tz->ops.hot)
353 		tz->ops.hot(tz);
354 }
355 
356 static void move_trip_to_sorted_list(struct thermal_trip_desc *td,
357 				     struct list_head *list)
358 {
359 	struct thermal_trip_desc *entry;
360 
361 	/*
362 	 * Delete upfront and then add to make relocation within the same list
363 	 * work.
364 	 */
365 	list_del(&td->list_node);
366 
367 	/* Assume that the new entry is likely to be the last one. */
368 	list_for_each_entry_reverse(entry, list, list_node) {
369 		if (entry->threshold <= td->threshold) {
370 			list_add(&td->list_node, &entry->list_node);
371 			return;
372 		}
373 	}
374 	list_add(&td->list_node, list);
375 }
376 
377 static void move_to_trips_high(struct thermal_zone_device *tz,
378 			       struct thermal_trip_desc *td)
379 {
380 	td->threshold = td->trip.temperature;
381 	move_trip_to_sorted_list(td, &tz->trips_high);
382 }
383 
384 static void move_to_trips_reached(struct thermal_zone_device *tz,
385 				  struct thermal_trip_desc *td)
386 {
387 	td->threshold = td->trip.temperature - td->trip.hysteresis;
388 	move_trip_to_sorted_list(td, &tz->trips_reached);
389 }
390 
391 static void move_to_trips_invalid(struct thermal_zone_device *tz,
392 				  struct thermal_trip_desc *td)
393 {
394 	td->threshold = INT_MAX;
395 	list_move(&td->list_node, &tz->trips_invalid);
396 }
397 
398 static void thermal_governor_trip_crossed(struct thermal_governor *governor,
399 					  struct thermal_zone_device *tz,
400 					  const struct thermal_trip *trip,
401 					  bool upward)
402 {
403 	if (trip->type == THERMAL_TRIP_HOT || trip->type == THERMAL_TRIP_CRITICAL)
404 		return;
405 
406 	if (governor->trip_crossed)
407 		governor->trip_crossed(tz, trip, upward);
408 }
409 
410 static void thermal_trip_crossed(struct thermal_zone_device *tz,
411 				 struct thermal_trip_desc *td,
412 				 struct thermal_governor *governor,
413 				 bool upward)
414 {
415 	const struct thermal_trip *trip = &td->trip;
416 
417 	if (upward) {
418 		if (trip->type == THERMAL_TRIP_PASSIVE)
419 			tz->passive++;
420 		else if (trip->type == THERMAL_TRIP_CRITICAL ||
421 			 trip->type == THERMAL_TRIP_HOT)
422 			handle_critical_trips(tz, trip);
423 
424 		thermal_notify_tz_trip_up(tz, trip);
425 		thermal_debug_tz_trip_up(tz, trip);
426 	} else {
427 		if (trip->type == THERMAL_TRIP_PASSIVE) {
428 			tz->passive--;
429 			WARN_ON(tz->passive < 0);
430 		}
431 		thermal_notify_tz_trip_down(tz, trip);
432 		thermal_debug_tz_trip_down(tz, trip);
433 	}
434 	thermal_governor_trip_crossed(governor, tz, trip, upward);
435 }
436 
437 void thermal_zone_set_trip_hyst(struct thermal_zone_device *tz,
438 				struct thermal_trip *trip, int hyst)
439 {
440 	struct thermal_trip_desc *td = trip_to_trip_desc(trip);
441 
442 	WRITE_ONCE(trip->hysteresis, hyst);
443 	thermal_notify_tz_trip_change(tz, trip);
444 	/*
445 	 * If the zone temperature is above or at the trip temperature, the trip
446 	 * is in the trips_reached list and its threshold is equal to its low
447 	 * temperature.  It needs to stay in that list, but its threshold needs
448 	 * to be updated and the list ordering may need to be restored.
449 	 */
450 	if (tz->temperature >= td->threshold)
451 		move_to_trips_reached(tz, td);
452 }
453 
454 void thermal_zone_set_trip_temp(struct thermal_zone_device *tz,
455 				struct thermal_trip *trip, int temp)
456 {
457 	struct thermal_trip_desc *td = trip_to_trip_desc(trip);
458 	int old_temp = trip->temperature;
459 
460 	if (old_temp == temp)
461 		return;
462 
463 	WRITE_ONCE(trip->temperature, temp);
464 	thermal_notify_tz_trip_change(tz, trip);
465 
466 	if (old_temp == THERMAL_TEMP_INVALID) {
467 		/*
468 		 * The trip was invalid before the change, so move it to the
469 		 * trips_high list regardless of the new temperature value
470 		 * because there is no mitigation under way for it.  If a
471 		 * mitigation needs to be started, the trip will be moved to the
472 		 * trips_reached list later.
473 		 */
474 		move_to_trips_high(tz, td);
475 		return;
476 	}
477 
478 	if (temp == THERMAL_TEMP_INVALID) {
479 		/*
480 		 * If the trip is in the trips_reached list, mitigation is under
481 		 * way for it and it needs to be stopped because the trip is
482 		 * effectively going away.
483 		 */
484 		if (tz->temperature >= td->threshold)
485 			thermal_trip_crossed(tz, td, thermal_get_tz_governor(tz), false);
486 
487 		move_to_trips_invalid(tz, td);
488 		return;
489 	}
490 
491 	/*
492 	 * The trip stays on its current list, but its threshold needs to be
493 	 * updated due to the temperature change and the list ordering may need
494 	 * to be restored.
495 	 */
496 	if (tz->temperature >= td->threshold)
497 		move_to_trips_reached(tz, td);
498 	else
499 		move_to_trips_high(tz, td);
500 }
501 EXPORT_SYMBOL_GPL(thermal_zone_set_trip_temp);
502 
503 static void thermal_zone_handle_trips(struct thermal_zone_device *tz,
504 				      struct thermal_governor *governor,
505 				      int *low, int *high)
506 {
507 	struct thermal_trip_desc *td, *next;
508 	LIST_HEAD(way_down_list);
509 
510 	/* Check the trips that were below or at the zone temperature. */
511 	list_for_each_entry_safe_reverse(td, next, &tz->trips_reached, list_node) {
512 		if (td->threshold <= tz->temperature)
513 			break;
514 
515 		thermal_trip_crossed(tz, td, governor, false);
516 		/*
517 		 * The current trips_high list needs to be processed before
518 		 * adding new entries to it, so put them on a temporary list.
519 		 */
520 		list_move(&td->list_node, &way_down_list);
521 	}
522 	/* Check the trips that were previously above the zone temperature. */
523 	list_for_each_entry_safe(td, next, &tz->trips_high, list_node) {
524 		if (td->threshold > tz->temperature)
525 			break;
526 
527 		thermal_trip_crossed(tz, td, governor, true);
528 		move_to_trips_reached(tz, td);
529 	}
530 	/* Move all of the trips from the temporary list to trips_high. */
531 	list_for_each_entry_safe(td, next, &way_down_list, list_node)
532 		move_to_trips_high(tz, td);
533 
534 	if (!list_empty(&tz->trips_reached)) {
535 		td = list_last_entry(&tz->trips_reached,
536 				     struct thermal_trip_desc, list_node);
537 		/*
538 		 * Set the "low" value below the current trip threshold in case
539 		 * the zone temperature is at that threshold and stays there,
540 		 * which would trigger a new interrupt immediately in vain.
541 		 */
542 		*low = td->threshold - 1;
543 	}
544 	if (!list_empty(&tz->trips_high)) {
545 		td = list_first_entry(&tz->trips_high,
546 				      struct thermal_trip_desc, list_node);
547 		*high = td->threshold;
548 	}
549 }
550 
551 void __thermal_zone_device_update(struct thermal_zone_device *tz,
552 				  enum thermal_notify_event event)
553 {
554 	struct thermal_governor *governor = thermal_get_tz_governor(tz);
555 	int low = -INT_MAX, high = INT_MAX;
556 	int temp, ret;
557 
558 	if (tz->state != TZ_STATE_READY || tz->mode != THERMAL_DEVICE_ENABLED)
559 		return;
560 
561 	ret = __thermal_zone_get_temp(tz, &temp);
562 	if (ret) {
563 		thermal_zone_recheck(tz, ret);
564 		return;
565 	} else if (temp <= THERMAL_TEMP_INVALID) {
566 		/*
567 		 * Special case: No valid temperature value is available, but
568 		 * the zone owner does not want the core to do anything about
569 		 * it.  Continue regular zone polling if needed, so that this
570 		 * function can be called again, but skip everything else.
571 		 */
572 		goto monitor;
573 	}
574 
575 	tz->recheck_delay_jiffies = THERMAL_RECHECK_DELAY;
576 
577 	tz->last_temperature = tz->temperature;
578 	tz->temperature = temp;
579 
580 	trace_thermal_temperature(tz);
581 
582 	thermal_genl_sampling_temp(tz->id, temp);
583 
584 	tz->notify_event = event;
585 
586 	thermal_zone_handle_trips(tz, governor, &low, &high);
587 
588 	thermal_thresholds_handle(tz, &low, &high);
589 
590 	thermal_zone_set_trips(tz, low, high);
591 
592 	if (governor->manage)
593 		governor->manage(tz);
594 
595 	thermal_debug_update_trip_stats(tz);
596 
597 monitor:
598 	monitor_thermal_zone(tz);
599 }
600 
601 static int thermal_zone_device_set_mode(struct thermal_zone_device *tz,
602 					enum thermal_device_mode mode)
603 {
604 	int ret;
605 
606 	guard(thermal_zone)(tz);
607 
608 	/* do nothing if mode isn't changing */
609 	if (mode == tz->mode)
610 		return 0;
611 
612 	ret = __thermal_zone_device_set_mode(tz, mode);
613 	if (ret)
614 		return ret;
615 
616 	__thermal_zone_device_update(tz, THERMAL_EVENT_UNSPECIFIED);
617 
618 	if (mode == THERMAL_DEVICE_ENABLED)
619 		thermal_notify_tz_enable(tz);
620 	else
621 		thermal_notify_tz_disable(tz);
622 
623 	return 0;
624 }
625 
626 int thermal_zone_device_enable(struct thermal_zone_device *tz)
627 {
628 	return thermal_zone_device_set_mode(tz, THERMAL_DEVICE_ENABLED);
629 }
630 EXPORT_SYMBOL_GPL(thermal_zone_device_enable);
631 
632 int thermal_zone_device_disable(struct thermal_zone_device *tz)
633 {
634 	return thermal_zone_device_set_mode(tz, THERMAL_DEVICE_DISABLED);
635 }
636 EXPORT_SYMBOL_GPL(thermal_zone_device_disable);
637 
638 void thermal_zone_device_update(struct thermal_zone_device *tz,
639 				enum thermal_notify_event event)
640 {
641 	guard(thermal_zone)(tz);
642 
643 	__thermal_zone_device_update(tz, event);
644 }
645 EXPORT_SYMBOL_GPL(thermal_zone_device_update);
646 
647 int for_each_thermal_governor(int (*cb)(struct thermal_governor *, void *),
648 			      void *data)
649 {
650 	struct thermal_governor *gov;
651 
652 	guard(mutex)(&thermal_governor_lock);
653 
654 	list_for_each_entry(gov, &thermal_governor_list, governor_list) {
655 		int ret;
656 
657 		ret = cb(gov, data);
658 		if (ret)
659 			return ret;
660 	}
661 
662 	return 0;
663 }
664 
665 int for_each_thermal_cooling_device(int (*cb)(struct thermal_cooling_device *,
666 					      void *), void *data)
667 {
668 	struct thermal_cooling_device *cdev;
669 
670 	guard(mutex)(&thermal_list_lock);
671 
672 	list_for_each_entry(cdev, &thermal_cdev_list, node) {
673 		int ret;
674 
675 		ret = cb(cdev, data);
676 		if (ret)
677 			return ret;
678 	}
679 
680 	return 0;
681 }
682 
683 int for_each_thermal_zone(int (*cb)(struct thermal_zone_device *, void *),
684 			  void *data)
685 {
686 	struct thermal_zone_device *tz;
687 
688 	guard(mutex)(&thermal_list_lock);
689 
690 	list_for_each_entry(tz, &thermal_tz_list, node) {
691 		int ret;
692 
693 		ret = cb(tz, data);
694 		if (ret)
695 			return ret;
696 	}
697 
698 	return 0;
699 }
700 
701 struct thermal_zone_device *thermal_zone_get_by_id(int id)
702 {
703 	struct thermal_zone_device *tz;
704 
705 	guard(mutex)(&thermal_list_lock);
706 
707 	list_for_each_entry(tz, &thermal_tz_list, node) {
708 		if (tz->id == id) {
709 			get_device(&tz->device);
710 			return tz;
711 		}
712 	}
713 
714 	return NULL;
715 }
716 
717 /*
718  * Device management section: cooling devices, zones devices, and binding
719  *
720  * Set of functions provided by the thermal core for:
721  * - cooling devices lifecycle: registration, unregistration,
722  *				binding, and unbinding.
723  * - thermal zone devices lifecycle: registration, unregistration,
724  *				     binding, and unbinding.
725  */
726 
727 static int thermal_instance_add(struct thermal_instance *new_instance,
728 				struct thermal_cooling_device *cdev,
729 				struct thermal_trip_desc *td)
730 {
731 	struct thermal_instance *instance;
732 
733 	list_for_each_entry(instance, &td->thermal_instances, trip_node) {
734 		if (instance->cdev == cdev)
735 			return -EEXIST;
736 	}
737 
738 	list_add_tail(&new_instance->trip_node, &td->thermal_instances);
739 
740 	guard(cooling_dev)(cdev);
741 
742 	list_add_tail(&new_instance->cdev_node, &cdev->thermal_instances);
743 
744 	return 0;
745 }
746 
747 /**
748  * thermal_bind_cdev_to_trip - bind a cooling device to a thermal zone
749  * @tz:		pointer to struct thermal_zone_device
750  * @td:		descriptor of the trip point to bind @cdev to
751  * @cdev:	pointer to struct thermal_cooling_device
752  * @cool_spec:	cooling specification for the trip point and @cdev
753  *
754  * This interface function bind a thermal cooling device to the certain trip
755  * point of a thermal zone device.
756  * This function is usually called in the thermal zone device .bind callback.
757  *
758  * Return: 0 on success, the proper error value otherwise.
759  */
760 static int thermal_bind_cdev_to_trip(struct thermal_zone_device *tz,
761 				     struct thermal_trip_desc *td,
762 				     struct thermal_cooling_device *cdev,
763 				     struct cooling_spec *cool_spec)
764 {
765 	struct thermal_instance *dev;
766 	bool upper_no_limit;
767 	int result;
768 
769 	/* lower default 0, upper default max_state */
770 	if (cool_spec->lower == THERMAL_NO_LIMIT)
771 		cool_spec->lower = 0;
772 
773 	if (cool_spec->upper == THERMAL_NO_LIMIT) {
774 		cool_spec->upper = cdev->max_state;
775 		upper_no_limit = true;
776 	} else {
777 		upper_no_limit = false;
778 	}
779 
780 	if (cool_spec->lower > cool_spec->upper || cool_spec->upper > cdev->max_state)
781 		return -EINVAL;
782 
783 	dev = kzalloc_obj(*dev);
784 	if (!dev)
785 		return -ENOMEM;
786 
787 	dev->cdev = cdev;
788 	dev->trip = &td->trip;
789 	dev->upper = cool_spec->upper;
790 	dev->upper_no_limit = upper_no_limit;
791 	dev->lower = cool_spec->lower;
792 	dev->target = THERMAL_NO_TARGET;
793 	dev->weight = cool_spec->weight;
794 
795 	result = ida_alloc(&tz->ida, GFP_KERNEL);
796 	if (result < 0)
797 		goto free_mem;
798 
799 	dev->id = result;
800 	snprintf(dev->name, sizeof(dev->name), "cdev%d", dev->id);
801 	result =
802 	    sysfs_create_link(&tz->device.kobj, &cdev->device.kobj, dev->name);
803 	if (result)
804 		goto release_ida;
805 
806 	snprintf(dev->attr_name, sizeof(dev->attr_name), "cdev%d_trip_point",
807 		 dev->id);
808 	sysfs_attr_init(&dev->attr.attr);
809 	dev->attr.attr.name = dev->attr_name;
810 	dev->attr.attr.mode = 0444;
811 	dev->attr.show = trip_point_show;
812 	result = device_create_file(&tz->device, &dev->attr);
813 	if (result)
814 		goto remove_symbol_link;
815 
816 	snprintf(dev->weight_attr_name, sizeof(dev->weight_attr_name),
817 		 "cdev%d_weight", dev->id);
818 	sysfs_attr_init(&dev->weight_attr.attr);
819 	dev->weight_attr.attr.name = dev->weight_attr_name;
820 	dev->weight_attr.attr.mode = S_IWUSR | S_IRUGO;
821 	dev->weight_attr.show = weight_show;
822 	dev->weight_attr.store = weight_store;
823 	result = device_create_file(&tz->device, &dev->weight_attr);
824 	if (result)
825 		goto remove_trip_file;
826 
827 	result = thermal_instance_add(dev, cdev, td);
828 	if (result)
829 		goto remove_weight_file;
830 
831 	thermal_governor_update_tz(tz, THERMAL_TZ_BIND_CDEV);
832 
833 	return 0;
834 
835 remove_weight_file:
836 	device_remove_file(&tz->device, &dev->weight_attr);
837 remove_trip_file:
838 	device_remove_file(&tz->device, &dev->attr);
839 remove_symbol_link:
840 	sysfs_remove_link(&tz->device.kobj, dev->name);
841 release_ida:
842 	ida_free(&tz->ida, dev->id);
843 free_mem:
844 	kfree(dev);
845 	return result;
846 }
847 
848 static void thermal_instance_delete(struct thermal_instance *instance)
849 {
850 	list_del(&instance->trip_node);
851 
852 	guard(cooling_dev)(instance->cdev);
853 
854 	list_del(&instance->cdev_node);
855 }
856 
857 /**
858  * thermal_unbind_cdev_from_trip - unbind a cooling device from a thermal zone.
859  * @tz:		pointer to a struct thermal_zone_device.
860  * @td:		descriptor of the trip point to unbind @cdev from
861  * @cdev:	pointer to a struct thermal_cooling_device.
862  *
863  * This interface function unbind a thermal cooling device from the certain
864  * trip point of a thermal zone device.
865  * This function is usually called in the thermal zone device .unbind callback.
866  */
867 static void thermal_unbind_cdev_from_trip(struct thermal_zone_device *tz,
868 					  struct thermal_trip_desc *td,
869 					  struct thermal_cooling_device *cdev)
870 {
871 	struct thermal_instance *pos, *next;
872 
873 	list_for_each_entry_safe(pos, next, &td->thermal_instances, trip_node) {
874 		if (pos->cdev == cdev) {
875 			thermal_instance_delete(pos);
876 			goto unbind;
877 		}
878 	}
879 
880 	return;
881 
882 unbind:
883 	thermal_governor_update_tz(tz, THERMAL_TZ_UNBIND_CDEV);
884 
885 	device_remove_file(&tz->device, &pos->weight_attr);
886 	device_remove_file(&tz->device, &pos->attr);
887 	sysfs_remove_link(&tz->device.kobj, pos->name);
888 	ida_free(&tz->ida, pos->id);
889 	kfree(pos);
890 }
891 
892 static const struct class thermal_class = {
893 	.name = "thermal",
894 };
895 static bool thermal_class_unavailable __ro_after_init = true;
896 
897 static inline
898 void print_bind_err_msg(struct thermal_zone_device *tz,
899 			const struct thermal_trip_desc *td,
900 			struct thermal_cooling_device *cdev, int ret)
901 {
902 	dev_err(&tz->device, "binding cdev %s to trip %d failed: %d\n",
903 		cdev->type, thermal_zone_trip_id(tz, &td->trip), ret);
904 }
905 
906 static bool __thermal_zone_cdev_bind(struct thermal_zone_device *tz,
907 				     struct thermal_cooling_device *cdev)
908 {
909 	struct thermal_trip_desc *td;
910 	bool update_tz = false;
911 
912 	if (!tz->ops.should_bind)
913 		return false;
914 
915 	for_each_trip_desc(tz, td) {
916 		struct cooling_spec c = {
917 			.upper = THERMAL_NO_LIMIT,
918 			.lower = THERMAL_NO_LIMIT,
919 			.weight = THERMAL_WEIGHT_DEFAULT
920 		};
921 		int ret;
922 
923 		if (!tz->ops.should_bind(tz, &td->trip, cdev, &c))
924 			continue;
925 
926 		ret = thermal_bind_cdev_to_trip(tz, td, cdev, &c);
927 		if (ret) {
928 			print_bind_err_msg(tz, td, cdev, ret);
929 			continue;
930 		}
931 
932 		update_tz = true;
933 	}
934 
935 	return update_tz;
936 }
937 
938 static void thermal_zone_cdev_bind(struct thermal_zone_device *tz,
939 				   struct thermal_cooling_device *cdev)
940 {
941 	guard(thermal_zone)(tz);
942 
943 	if (__thermal_zone_cdev_bind(tz, cdev))
944 		__thermal_zone_device_update(tz, THERMAL_EVENT_UNSPECIFIED);
945 }
946 
947 static void thermal_cooling_device_init_complete(struct thermal_cooling_device *cdev)
948 {
949 	struct thermal_zone_device *tz;
950 
951 	guard(mutex)(&thermal_list_lock);
952 
953 	list_add(&cdev->node, &thermal_cdev_list);
954 
955 	list_for_each_entry(tz, &thermal_tz_list, node)
956 		thermal_zone_cdev_bind(tz, cdev);
957 }
958 
959 static void thermal_cdev_release(struct device *dev)
960 {
961 	struct thermal_cooling_device *cdev = to_cooling_device(dev);
962 
963 	thermal_cooling_device_destroy_sysfs(cdev);
964 	kfree_const(cdev->type);
965 	ida_free(&thermal_cdev_ida, cdev->id);
966 	kfree(cdev);
967 }
968 
969 struct thermal_cooling_device *
970 thermal_cooling_device_alloc(const char *type, const struct thermal_cooling_device_ops *ops)
971 {
972 	struct thermal_cooling_device *cdev;
973 	int ret;
974 
975 	if (!ops || !ops->get_max_state || !ops->get_cur_state ||
976 	    !ops->set_cur_state)
977 		return ERR_PTR(-EINVAL);
978 
979 	if (thermal_class_unavailable)
980 		return ERR_PTR(-ENODEV);
981 
982 	cdev = kzalloc_obj(*cdev);
983 	if (!cdev)
984 		return ERR_PTR(-ENOMEM);
985 
986 	cdev->ops = ops;
987 
988 	ret = ida_alloc(&thermal_cdev_ida, GFP_KERNEL);
989 	if (ret < 0)
990 		goto out_kfree_cdev;
991 	cdev->id = ret;
992 
993 	cdev->type = kstrdup_const(type ? type : "", GFP_KERNEL);
994 	if (!cdev->type) {
995 		ret = -ENOMEM;
996 		goto out_ida_remove;
997 	}
998 
999 	return cdev;
1000 
1001 out_ida_remove:
1002 	ida_free(&thermal_cdev_ida, cdev->id);
1003 out_kfree_cdev:
1004 	kfree(cdev);
1005 	return ERR_PTR(ret);
1006 }
1007 
1008 int thermal_cooling_device_add(struct thermal_cooling_device *cdev,
1009 			       struct device *parent, void *devdata)
1010 {
1011 	unsigned long current_state;
1012 	int ret;
1013 
1014 	mutex_init(&cdev->lock);
1015 	INIT_LIST_HEAD(&cdev->thermal_instances);
1016 	cdev->updated = false;
1017 	cdev->device.parent = parent;
1018 	cdev->device.class = &thermal_class;
1019 	cdev->device.release = thermal_cdev_release;
1020 	device_initialize(&cdev->device);
1021 	cdev->devdata = devdata;
1022 
1023 	ret = dev_set_name(&cdev->device, "cooling_device%d", cdev->id);
1024 	if (ret)
1025 		goto out_put_device;
1026 
1027 	ret = cdev->ops->get_max_state(cdev, &cdev->max_state);
1028 	if (ret)
1029 		goto out_put_device;
1030 
1031 	/*
1032 	 * The cooling device's current state is only needed for debug
1033 	 * initialization below, so a failure to get it does not cause
1034 	 * the entire cooling device initialization to fail.  However,
1035 	 * the debug will not work for the device if its initial state
1036 	 * cannot be determined and drivers are responsible for ensuring
1037 	 * that this will not happen.
1038 	 */
1039 	ret = cdev->ops->get_cur_state(cdev, &current_state);
1040 	if (ret)
1041 		current_state = ULONG_MAX;
1042 
1043 	thermal_cooling_device_setup_sysfs(cdev);
1044 
1045 	ret = device_add(&cdev->device);
1046 	if (ret)
1047 		goto out_put_device;
1048 
1049 	if (current_state <= cdev->max_state)
1050 		thermal_debug_cdev_add(cdev, current_state);
1051 
1052 	thermal_cooling_device_init_complete(cdev);
1053 
1054 	return 0;
1055 
1056 out_put_device:
1057 	/*
1058 	 * The device core will release the memory via
1059 	 * thermal_release() after put_device() is called in the error
1060 	 * path
1061 	 */
1062 	put_device(&cdev->device);
1063 	return ret;
1064 }
1065 
1066 /**
1067  * thermal_cooling_device_create() - register a new thermal cooling device
1068  * @parent:	parent device (optional).
1069  * @type:	the thermal cooling device type.
1070  * @devdata:	device private data.
1071  * @ops:	standard thermal cooling devices callbacks.
1072  *
1073  * Allocate and register a new thermal cooling device under the given parent (if
1074  * not NULL) and with the given type, device data, and operations.  During the
1075  * registration, it will be matched against all of the registered thermal zones
1076  * and it will be bound to the matching ones.
1077  *
1078  * Return: A pointer to the created struct thermal_cooling_device or an ERR_PTR.
1079  * Callers must use IS_ERR*() helpers to check the return value.
1080  */
1081 struct thermal_cooling_device *thermal_cooling_device_create(
1082 			struct device *parent, const char *type, void *devdata,
1083 			const struct thermal_cooling_device_ops *ops)
1084 {
1085 	struct thermal_cooling_device *cdev;
1086 	int ret;
1087 
1088 	cdev = thermal_cooling_device_alloc(type, ops);
1089 	if (IS_ERR(cdev))
1090 		return cdev;
1091 
1092 	ret = thermal_cooling_device_add(cdev, parent, devdata);
1093 	if (ret)
1094 		return ERR_PTR(ret);
1095 
1096 	return cdev;
1097 }
1098 EXPORT_SYMBOL_GPL(thermal_cooling_device_create);
1099 
1100 static void thermal_cooling_device_release(void *data)
1101 {
1102 	struct thermal_cooling_device *cdev = data;
1103 
1104 	thermal_cooling_device_unregister(cdev);
1105 }
1106 
1107 /**
1108  * devm_thermal_cooling_device_register() - register a thermal cooling device
1109  *
1110  * @dev:	a valid struct device pointer of a sensor device.
1111  * @type:	the thermal cooling device type.
1112  * @devdata:	device private data.
1113  * @ops:	standard thermal cooling devices callbacks.
1114  *
1115  * This function will register a cooling device. This interface
1116  * function adds a new thermal cooling device (fan/processor/...)  to
1117  * /sys/class/thermal/ folder as cooling_device[0-*]. It tries to bind
1118  * itself to all the thermal zone devices registered at the same time.
1119  *
1120  * Return: a pointer to the created struct thermal_cooling_device or an
1121  * ERR_PTR. Caller must check return value with IS_ERR*() helpers.
1122  */
1123 struct thermal_cooling_device *
1124 devm_thermal_cooling_device_register(struct device *dev, const char *type, void *devdata,
1125 				     const struct thermal_cooling_device_ops *ops)
1126 {
1127 	struct thermal_cooling_device *cdev;
1128 	int ret;
1129 
1130 	cdev = thermal_cooling_device_register(type, devdata, ops);
1131 	if (IS_ERR(cdev))
1132 		return cdev;
1133 
1134 	ret = devm_add_action_or_reset(dev, thermal_cooling_device_release, cdev);
1135 	if (ret)
1136 		return ERR_PTR(ret);
1137 
1138 	return cdev;
1139 }
1140 EXPORT_SYMBOL_GPL(devm_thermal_cooling_device_register);
1141 
1142 static bool thermal_cooling_device_present(struct thermal_cooling_device *cdev)
1143 {
1144 	struct thermal_cooling_device *pos = NULL;
1145 
1146 	list_for_each_entry(pos, &thermal_cdev_list, node) {
1147 		if (pos == cdev)
1148 			return true;
1149 	}
1150 
1151 	return false;
1152 }
1153 
1154 /**
1155  * thermal_cooling_device_update - Update a cooling device object
1156  * @cdev: Target cooling device.
1157  *
1158  * Update @cdev to reflect a change of the underlying hardware or platform.
1159  *
1160  * Must be called when the maximum cooling state of @cdev becomes invalid and so
1161  * its .get_max_state() callback needs to be run to produce the new maximum
1162  * cooling state value.
1163  */
1164 void thermal_cooling_device_update(struct thermal_cooling_device *cdev)
1165 {
1166 	struct thermal_instance *ti;
1167 	unsigned long state;
1168 
1169 	if (IS_ERR_OR_NULL(cdev))
1170 		return;
1171 
1172 	/*
1173 	 * Hold thermal_list_lock throughout the update to prevent the device
1174 	 * from going away while being updated.
1175 	 */
1176 	guard(mutex)(&thermal_list_lock);
1177 
1178 	if (!thermal_cooling_device_present(cdev))
1179 		return;
1180 
1181 	/*
1182 	 * Update under the cdev lock to prevent the state from being set beyond
1183 	 * the new limit concurrently.
1184 	 */
1185 	guard(cooling_dev)(cdev);
1186 
1187 	if (cdev->ops->get_max_state(cdev, &cdev->max_state))
1188 		return;
1189 
1190 	thermal_cooling_device_stats_reinit(cdev);
1191 
1192 	list_for_each_entry(ti, &cdev->thermal_instances, cdev_node) {
1193 		if (ti->upper == cdev->max_state)
1194 			continue;
1195 
1196 		if (ti->upper < cdev->max_state) {
1197 			if (ti->upper_no_limit)
1198 				ti->upper = cdev->max_state;
1199 
1200 			continue;
1201 		}
1202 
1203 		ti->upper = cdev->max_state;
1204 		if (ti->lower > ti->upper)
1205 			ti->lower = ti->upper;
1206 
1207 		if (ti->target == THERMAL_NO_TARGET)
1208 			continue;
1209 
1210 		if (ti->target > ti->upper)
1211 			ti->target = ti->upper;
1212 	}
1213 
1214 	if (cdev->ops->get_cur_state(cdev, &state) || state > cdev->max_state)
1215 		return;
1216 
1217 	thermal_cooling_device_stats_update(cdev, state);
1218 }
1219 EXPORT_SYMBOL_GPL(thermal_cooling_device_update);
1220 
1221 static void __thermal_zone_cdev_unbind(struct thermal_zone_device *tz,
1222 				       struct thermal_cooling_device *cdev)
1223 {
1224 	struct thermal_trip_desc *td;
1225 
1226 	for_each_trip_desc(tz, td)
1227 		thermal_unbind_cdev_from_trip(tz, td, cdev);
1228 }
1229 
1230 static void thermal_zone_cdev_unbind(struct thermal_zone_device *tz,
1231 				     struct thermal_cooling_device *cdev)
1232 {
1233 	guard(thermal_zone)(tz);
1234 
1235 	__thermal_zone_cdev_unbind(tz, cdev);
1236 }
1237 
1238 static bool thermal_cooling_device_exit(struct thermal_cooling_device *cdev)
1239 {
1240 	struct thermal_zone_device *tz;
1241 
1242 	guard(mutex)(&thermal_list_lock);
1243 
1244 	if (!thermal_cooling_device_present(cdev))
1245 		return false;
1246 
1247 	list_del(&cdev->node);
1248 
1249 	list_for_each_entry(tz, &thermal_tz_list, node)
1250 		thermal_zone_cdev_unbind(tz, cdev);
1251 
1252 	return true;
1253 }
1254 
1255 /**
1256  * thermal_cooling_device_unregister() - removes a thermal cooling device
1257  * @cdev: Thermal cooling device to remove.
1258  */
1259 void thermal_cooling_device_unregister(struct thermal_cooling_device *cdev)
1260 {
1261 	if (!cdev)
1262 		return;
1263 
1264 	thermal_debug_cdev_remove(cdev);
1265 
1266 	if (thermal_cooling_device_exit(cdev))
1267 		device_unregister(&cdev->device);
1268 }
1269 EXPORT_SYMBOL_GPL(thermal_cooling_device_unregister);
1270 
1271 int thermal_zone_get_crit_temp(struct thermal_zone_device *tz, int *temp)
1272 {
1273 	const struct thermal_trip_desc *td;
1274 	int ret = -EINVAL;
1275 
1276 	if (tz->ops.get_crit_temp)
1277 		return tz->ops.get_crit_temp(tz, temp);
1278 
1279 	guard(thermal_zone)(tz);
1280 
1281 	for_each_trip_desc(tz, td) {
1282 		const struct thermal_trip *trip = &td->trip;
1283 
1284 		if (trip->type == THERMAL_TRIP_CRITICAL) {
1285 			*temp = trip->temperature;
1286 			ret = 0;
1287 			break;
1288 		}
1289 	}
1290 
1291 	return ret;
1292 }
1293 EXPORT_SYMBOL_GPL(thermal_zone_get_crit_temp);
1294 
1295 static void thermal_zone_device_check(struct work_struct *work)
1296 {
1297 	struct thermal_zone_device *tz = container_of(work, struct
1298 						      thermal_zone_device,
1299 						      poll_queue.work);
1300 	thermal_zone_device_update(tz, THERMAL_EVENT_UNSPECIFIED);
1301 }
1302 
1303 static void thermal_zone_device_init(struct thermal_zone_device *tz)
1304 {
1305 	struct thermal_trip_desc *td, *next;
1306 
1307 	INIT_DELAYED_WORK(&tz->poll_queue, thermal_zone_device_check);
1308 
1309 	tz->temperature = THERMAL_TEMP_INIT;
1310 	tz->passive = 0;
1311 	tz->prev_low_trip = -INT_MAX;
1312 	tz->prev_high_trip = INT_MAX;
1313 	for_each_trip_desc(tz, td) {
1314 		struct thermal_instance *instance;
1315 
1316 		list_for_each_entry(instance, &td->thermal_instances, trip_node)
1317 			instance->initialized = false;
1318 	}
1319 	/*
1320 	 * At this point, all valid trips need to be moved to trips_high so that
1321 	 * mitigation can be started if the zone temperature is above them.
1322 	 */
1323 	list_for_each_entry_safe(td, next, &tz->trips_invalid, list_node) {
1324 		if (td->trip.temperature != THERMAL_TEMP_INVALID)
1325 			move_to_trips_high(tz, td);
1326 	}
1327 	/* The trips_reached list may not be empty during system resume. */
1328 	list_for_each_entry_safe(td, next, &tz->trips_reached, list_node) {
1329 		if (td->trip.temperature == THERMAL_TEMP_INVALID)
1330 			move_to_trips_invalid(tz, td);
1331 		else
1332 			move_to_trips_high(tz, td);
1333 	}
1334 }
1335 
1336 static int thermal_zone_init_governor(struct thermal_zone_device *tz)
1337 {
1338 	struct thermal_governor *governor;
1339 
1340 	guard(mutex)(&thermal_governor_lock);
1341 
1342 	if (tz->tzp)
1343 		governor = __find_governor(tz->tzp->governor_name);
1344 	else
1345 		governor = def_governor;
1346 
1347 	return thermal_set_governor(tz, governor);
1348 }
1349 
1350 static void thermal_zone_init_complete(struct thermal_zone_device *tz)
1351 {
1352 	struct thermal_cooling_device *cdev;
1353 
1354 	guard(mutex)(&thermal_list_lock);
1355 
1356 	list_add_tail(&tz->node, &thermal_tz_list);
1357 
1358 	guard(thermal_zone)(tz);
1359 
1360 	/* Bind cooling devices for this zone. */
1361 	list_for_each_entry(cdev, &thermal_cdev_list, node)
1362 		__thermal_zone_cdev_bind(tz, cdev);
1363 
1364 	tz->state &= ~TZ_STATE_FLAG_INIT;
1365 	/*
1366 	 * If system suspend or resume is in progress at this point, the
1367 	 * new thermal zone needs to be marked as suspended because
1368 	 * thermal_pm_notify() has run already.
1369 	 */
1370 	if (thermal_pm_suspended)
1371 		tz->state |= TZ_STATE_FLAG_SUSPENDED;
1372 
1373 	__thermal_zone_device_update(tz, THERMAL_EVENT_UNSPECIFIED);
1374 }
1375 
1376 static void thermal_zone_device_release(struct device *dev)
1377 {
1378 	struct thermal_zone_device *tz = to_thermal_zone(dev);
1379 
1380 	thermal_zone_destroy_device_groups(tz);
1381 	thermal_set_governor(tz, NULL);
1382 	ida_destroy(&tz->ida);
1383 	mutex_destroy(&tz->lock);
1384 	complete(&tz->removal);
1385 }
1386 
1387 /**
1388  * thermal_zone_device_register_with_trips() - register a new thermal zone device
1389  * @type:	the thermal zone device type
1390  * @trips:	a pointer to an array of thermal trips
1391  * @num_trips:	the number of trip points the thermal zone support
1392  * @devdata:	private device data
1393  * @ops:	standard thermal zone device callbacks
1394  * @tzp:	thermal zone platform parameters
1395  * @passive_delay: number of milliseconds to wait between polls when
1396  *		   performing passive cooling
1397  * @polling_delay: number of milliseconds to wait between polls when checking
1398  *		   whether trip points have been crossed (0 for interrupt
1399  *		   driven systems)
1400  *
1401  * This interface function adds a new thermal zone device (sensor) to
1402  * /sys/class/thermal folder as thermal_zone[0-*]. It tries to bind all the
1403  * thermal cooling devices registered at the same time.
1404  * thermal_zone_device_unregister() must be called when the device is no
1405  * longer needed. The passive cooling depends on the .get_trend() return value.
1406  *
1407  * Return: a pointer to the created struct thermal_zone_device or an
1408  * in case of error, an ERR_PTR. Caller must check return value with
1409  * IS_ERR*() helpers.
1410  */
1411 struct thermal_zone_device *
1412 thermal_zone_device_register_with_trips(const char *type,
1413 					const struct thermal_trip *trips,
1414 					int num_trips, void *devdata,
1415 					const struct thermal_zone_device_ops *ops,
1416 					const struct thermal_zone_params *tzp,
1417 					unsigned int passive_delay,
1418 					unsigned int polling_delay)
1419 {
1420 	const struct thermal_trip *trip = trips;
1421 	struct thermal_zone_device *tz;
1422 	struct thermal_trip_desc *td;
1423 	size_t type_len = 0;
1424 	int id;
1425 	int result;
1426 
1427 	if (type)
1428 		type_len = strnlen(type, THERMAL_NAME_LENGTH);
1429 
1430 	if (type_len == 0) {
1431 		pr_err("No thermal zone type defined\n");
1432 		return ERR_PTR(-EINVAL);
1433 	}
1434 
1435 	if (type_len == THERMAL_NAME_LENGTH) {
1436 		pr_err("Thermal zone name (%s) too long, should be under %d chars\n",
1437 		       type, THERMAL_NAME_LENGTH);
1438 		return ERR_PTR(-EINVAL);
1439 	}
1440 
1441 	if (num_trips < 0) {
1442 		pr_err("Incorrect number of thermal trips\n");
1443 		return ERR_PTR(-EINVAL);
1444 	}
1445 
1446 	if (!ops || !ops->get_temp) {
1447 		pr_err("Thermal zone device ops not defined or invalid\n");
1448 		return ERR_PTR(-EINVAL);
1449 	}
1450 
1451 	if (num_trips > 0 && !trips)
1452 		return ERR_PTR(-EINVAL);
1453 
1454 	if (polling_delay && passive_delay > polling_delay)
1455 		return ERR_PTR(-EINVAL);
1456 
1457 	if (thermal_class_unavailable)
1458 		return ERR_PTR(-ENODEV);
1459 
1460 	tz = kzalloc_flex(*tz, trips, num_trips);
1461 	if (!tz)
1462 		return ERR_PTR(-ENOMEM);
1463 
1464 	if (tzp) {
1465 		tz->tzp = kmemdup(tzp, sizeof(*tzp), GFP_KERNEL);
1466 		if (!tz->tzp) {
1467 			result = -ENOMEM;
1468 			goto free_tz;
1469 		}
1470 	}
1471 
1472 	INIT_LIST_HEAD(&tz->node);
1473 	INIT_LIST_HEAD(&tz->trips_high);
1474 	INIT_LIST_HEAD(&tz->trips_reached);
1475 	INIT_LIST_HEAD(&tz->trips_invalid);
1476 	ida_init(&tz->ida);
1477 	mutex_init(&tz->lock);
1478 	init_completion(&tz->removal);
1479 	init_completion(&tz->resume);
1480 	id = ida_alloc(&thermal_tz_ida, GFP_KERNEL);
1481 	if (id < 0) {
1482 		result = id;
1483 		goto free_tzp;
1484 	}
1485 
1486 	tz->id = id;
1487 	strscpy(tz->type, type, sizeof(tz->type));
1488 
1489 	tz->ops = *ops;
1490 	if (!tz->ops.critical)
1491 		tz->ops.critical = thermal_zone_device_critical;
1492 
1493 	tz->device.class = &thermal_class;
1494 	tz->device.release = thermal_zone_device_release;
1495 	tz->devdata = devdata;
1496 	tz->num_trips = num_trips;
1497 	for_each_trip_desc(tz, td) {
1498 		td->trip = *trip++;
1499 		INIT_LIST_HEAD(&td->thermal_instances);
1500 		INIT_LIST_HEAD(&td->list_node);
1501 		/*
1502 		 * Mark all thresholds as invalid to start with even though
1503 		 * this only matters for the trips that start as invalid and
1504 		 * become valid later.
1505 		 */
1506 		move_to_trips_invalid(tz, td);
1507 	}
1508 
1509 	tz->polling_delay_jiffies = msecs_to_jiffies(polling_delay);
1510 	tz->passive_delay_jiffies = msecs_to_jiffies(passive_delay);
1511 	tz->recheck_delay_jiffies = THERMAL_RECHECK_DELAY;
1512 
1513 	tz->state = TZ_STATE_FLAG_INIT;
1514 
1515 	result = dev_set_name(&tz->device, "thermal_zone%d", tz->id);
1516 	if (result)
1517 		goto remove_id;
1518 
1519 	thermal_zone_device_init(tz);
1520 
1521 	result = thermal_zone_init_governor(tz);
1522 	if (result)
1523 		goto remove_id;
1524 
1525 	/* sys I/F */
1526 	/* Add nodes that are always present via .groups */
1527 	result = thermal_zone_create_device_groups(tz);
1528 	if (result) {
1529 		thermal_set_governor(tz, NULL);
1530 		goto remove_id;
1531 	}
1532 
1533 	result = device_register(&tz->device);
1534 	if (result)
1535 		goto release_device;
1536 
1537 	if (!tz->tzp || !tz->tzp->no_hwmon) {
1538 		result = thermal_add_hwmon_sysfs(tz);
1539 		if (result)
1540 			goto unregister;
1541 	}
1542 
1543 	result = thermal_thresholds_init(tz);
1544 	if (result)
1545 		goto remove_hwmon;
1546 
1547 	thermal_zone_init_complete(tz);
1548 
1549 	thermal_notify_tz_create(tz);
1550 
1551 	thermal_debug_tz_add(tz);
1552 
1553 	return tz;
1554 
1555 remove_hwmon:
1556 	thermal_remove_hwmon_sysfs(tz);
1557 unregister:
1558 	device_del(&tz->device);
1559 release_device:
1560 	put_device(&tz->device);
1561 	wait_for_completion(&tz->removal);
1562 remove_id:
1563 	ida_free(&thermal_tz_ida, id);
1564 free_tzp:
1565 	kfree(tz->tzp);
1566 free_tz:
1567 	kfree(tz);
1568 	return ERR_PTR(result);
1569 }
1570 EXPORT_SYMBOL_GPL(thermal_zone_device_register_with_trips);
1571 
1572 struct thermal_zone_device *thermal_tripless_zone_device_register(
1573 					const char *type,
1574 					void *devdata,
1575 					const struct thermal_zone_device_ops *ops,
1576 					const struct thermal_zone_params *tzp)
1577 {
1578 	return thermal_zone_device_register_with_trips(type, NULL, 0, devdata,
1579 						       ops, tzp, 0, 0);
1580 }
1581 EXPORT_SYMBOL_GPL(thermal_tripless_zone_device_register);
1582 
1583 void *thermal_zone_device_priv(struct thermal_zone_device *tzd)
1584 {
1585 	return tzd->devdata;
1586 }
1587 EXPORT_SYMBOL_GPL(thermal_zone_device_priv);
1588 
1589 const char *thermal_zone_device_type(struct thermal_zone_device *tzd)
1590 {
1591 	return tzd->type;
1592 }
1593 EXPORT_SYMBOL_GPL(thermal_zone_device_type);
1594 
1595 int thermal_zone_device_id(struct thermal_zone_device *tzd)
1596 {
1597 	return tzd->id;
1598 }
1599 EXPORT_SYMBOL_GPL(thermal_zone_device_id);
1600 
1601 struct device *thermal_zone_device(struct thermal_zone_device *tzd)
1602 {
1603 	return &tzd->device;
1604 }
1605 EXPORT_SYMBOL_GPL(thermal_zone_device);
1606 
1607 static bool thermal_zone_exit(struct thermal_zone_device *tz)
1608 {
1609 	struct thermal_cooling_device *cdev;
1610 
1611 	guard(mutex)(&thermal_list_lock);
1612 
1613 	if (list_empty(&tz->node))
1614 		return false;
1615 
1616 	guard(thermal_zone)(tz);
1617 
1618 	tz->state |= TZ_STATE_FLAG_EXIT;
1619 	list_del_init(&tz->node);
1620 
1621 	/* Unbind all cdevs associated with this thermal zone. */
1622 	list_for_each_entry(cdev, &thermal_cdev_list, node)
1623 		__thermal_zone_cdev_unbind(tz, cdev);
1624 
1625 	return true;
1626 }
1627 
1628 /**
1629  * thermal_zone_device_unregister - removes the registered thermal zone device
1630  * @tz: the thermal zone device to remove
1631  */
1632 void thermal_zone_device_unregister(struct thermal_zone_device *tz)
1633 {
1634 	if (!tz)
1635 		return;
1636 
1637 	thermal_debug_tz_remove(tz);
1638 
1639 	if (!thermal_zone_exit(tz))
1640 		return;
1641 
1642 	cancel_delayed_work_sync(&tz->poll_queue);
1643 
1644 	thermal_thresholds_exit(tz);
1645 	thermal_remove_hwmon_sysfs(tz);
1646 
1647 	device_del(&tz->device);
1648 	put_device(&tz->device);
1649 
1650 	thermal_notify_tz_delete(tz);
1651 
1652 	wait_for_completion(&tz->removal);
1653 
1654 	ida_free(&thermal_tz_ida, tz->id);
1655 
1656 	kfree(tz->tzp);
1657 	kfree(tz);
1658 }
1659 EXPORT_SYMBOL_GPL(thermal_zone_device_unregister);
1660 
1661 /**
1662  * thermal_zone_get_zone_by_name() - search for a zone and returns its ref
1663  * @name: thermal zone name to fetch the temperature
1664  *
1665  * When only one zone is found with the passed name, returns a reference to it.
1666  *
1667  * Return: On success returns a reference to an unique thermal zone with
1668  * matching name equals to @name, an ERR_PTR otherwise (-EINVAL for invalid
1669  * parameters, -ENODEV for not found and -EEXIST for multiple matches).
1670  */
1671 struct thermal_zone_device *thermal_zone_get_zone_by_name(const char *name)
1672 {
1673 	struct thermal_zone_device *pos = NULL, *ref = ERR_PTR(-EINVAL);
1674 	unsigned int found = 0;
1675 
1676 	if (!name)
1677 		return ERR_PTR(-EINVAL);
1678 
1679 	guard(mutex)(&thermal_list_lock);
1680 
1681 	list_for_each_entry(pos, &thermal_tz_list, node)
1682 		if (!strncasecmp(name, pos->type, THERMAL_NAME_LENGTH)) {
1683 			found++;
1684 			ref = pos;
1685 		}
1686 
1687 	if (!found)
1688 		return ERR_PTR(-ENODEV);
1689 
1690 	/* Success only when one zone is found. */
1691 	if (found > 1)
1692 		return ERR_PTR(-EEXIST);
1693 
1694 	return ref;
1695 }
1696 EXPORT_SYMBOL_GPL(thermal_zone_get_zone_by_name);
1697 
1698 static void thermal_zone_device_resume(struct work_struct *work)
1699 {
1700 	struct thermal_zone_device *tz;
1701 
1702 	tz = container_of(work, struct thermal_zone_device, poll_queue.work);
1703 
1704 	guard(thermal_zone)(tz);
1705 
1706 	/* If the thermal zone is going away, there's nothing to do. */
1707 	if (tz->state & TZ_STATE_FLAG_EXIT)
1708 		return;
1709 
1710 	tz->state &= ~(TZ_STATE_FLAG_SUSPENDED | TZ_STATE_FLAG_RESUMING);
1711 
1712 	thermal_debug_tz_resume(tz);
1713 	thermal_zone_device_init(tz);
1714 	thermal_governor_update_tz(tz, THERMAL_TZ_RESUME);
1715 	__thermal_zone_device_update(tz, THERMAL_TZ_RESUME);
1716 
1717 	complete(&tz->resume);
1718 }
1719 
1720 static void thermal_zone_pm_prepare(struct thermal_zone_device *tz)
1721 {
1722 	guard(thermal_zone)(tz);
1723 
1724 	if (tz->state & TZ_STATE_FLAG_RESUMING) {
1725 		/*
1726 		 * thermal_zone_device_resume() queued up for this zone has not
1727 		 * acquired the lock yet, so release it to let the function run
1728 		 * and wait util it has done the work.
1729 		 */
1730 		scoped_guard(thermal_zone_reverse, tz) {
1731 			wait_for_completion(&tz->resume);
1732 		}
1733 	}
1734 
1735 	tz->state |= TZ_STATE_FLAG_SUSPENDED;
1736 
1737 	/* Prevent new work from getting to the workqueue subsequently. */
1738 	cancel_delayed_work(&tz->poll_queue);
1739 }
1740 
1741 static void __thermal_pm_prepare(void)
1742 {
1743 	struct thermal_zone_device *tz;
1744 
1745 	guard(mutex)(&thermal_list_lock);
1746 
1747 	thermal_pm_suspended = true;
1748 
1749 	list_for_each_entry(tz, &thermal_tz_list, node)
1750 		thermal_zone_pm_prepare(tz);
1751 }
1752 
1753 void thermal_pm_prepare(void)
1754 {
1755 	if (thermal_class_unavailable)
1756 		return;
1757 
1758 	__thermal_pm_prepare();
1759 	/*
1760 	 * Allow any leftover thermal work items already on the worqueue to
1761 	 * complete so they don't get in the way later.
1762 	 */
1763 	flush_workqueue(thermal_wq);
1764 }
1765 
1766 static void thermal_zone_pm_complete(struct thermal_zone_device *tz)
1767 {
1768 	guard(thermal_zone)(tz);
1769 
1770 	reinit_completion(&tz->resume);
1771 	tz->state |= TZ_STATE_FLAG_RESUMING;
1772 
1773 	/*
1774 	 * Replace the work function with the resume one, which will restore the
1775 	 * original work function and schedule the polling work if needed.
1776 	 */
1777 	INIT_DELAYED_WORK(&tz->poll_queue, thermal_zone_device_resume);
1778 	/* Queue up the work without a delay. */
1779 	mod_delayed_work(thermal_wq, &tz->poll_queue, 0);
1780 }
1781 
1782 void thermal_pm_complete(void)
1783 {
1784 	struct thermal_zone_device *tz;
1785 
1786 	if (thermal_class_unavailable)
1787 		return;
1788 
1789 	guard(mutex)(&thermal_list_lock);
1790 
1791 	thermal_pm_suspended = false;
1792 
1793 	list_for_each_entry(tz, &thermal_tz_list, node)
1794 		thermal_zone_pm_complete(tz);
1795 }
1796 
1797 static int __init thermal_init(void)
1798 {
1799 	int result;
1800 
1801 	thermal_debug_init();
1802 
1803 	result = thermal_netlink_init();
1804 	if (result)
1805 		goto error;
1806 
1807 	thermal_wq = alloc_workqueue("thermal_events", WQ_UNBOUND, 0);
1808 	if (!thermal_wq) {
1809 		result = -ENOMEM;
1810 		goto unregister_netlink;
1811 	}
1812 
1813 	result = thermal_register_governors();
1814 	if (result)
1815 		goto unregister_governors;
1816 
1817 	result = class_register(&thermal_class);
1818 	if (result)
1819 		goto unregister_governors;
1820 
1821 	thermal_class_unavailable = false;
1822 
1823 	return 0;
1824 
1825 unregister_governors:
1826 	thermal_unregister_governors();
1827 	destroy_workqueue(thermal_wq);
1828 unregister_netlink:
1829 	thermal_netlink_exit();
1830 error:
1831 	mutex_destroy(&thermal_list_lock);
1832 	mutex_destroy(&thermal_governor_lock);
1833 	return result;
1834 }
1835 postcore_initcall(thermal_init);
1836