xref: /linux/drivers/thermal/thermal_core.c (revision bfd5bb6f90af092aa345b15cd78143956a13c2a8)
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/module.h>
13 #include <linux/device.h>
14 #include <linux/err.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 <net/netlink.h>
23 #include <net/genetlink.h>
24 #include <linux/suspend.h>
25 
26 #define CREATE_TRACE_POINTS
27 #include <trace/events/thermal.h>
28 
29 #include "thermal_core.h"
30 #include "thermal_hwmon.h"
31 
32 MODULE_AUTHOR("Zhang Rui");
33 MODULE_DESCRIPTION("Generic thermal management sysfs support");
34 MODULE_LICENSE("GPL v2");
35 
36 static DEFINE_IDA(thermal_tz_ida);
37 static DEFINE_IDA(thermal_cdev_ida);
38 
39 static LIST_HEAD(thermal_tz_list);
40 static LIST_HEAD(thermal_cdev_list);
41 static LIST_HEAD(thermal_governor_list);
42 
43 static DEFINE_MUTEX(thermal_list_lock);
44 static DEFINE_MUTEX(thermal_governor_lock);
45 static DEFINE_MUTEX(poweroff_lock);
46 
47 static atomic_t in_suspend;
48 static bool power_off_triggered;
49 
50 static struct thermal_governor *def_governor;
51 
52 /*
53  * Governor section: set of functions to handle thermal governors
54  *
55  * Functions to help in the life cycle of thermal governors within
56  * the thermal core and by the thermal governor code.
57  */
58 
59 static struct thermal_governor *__find_governor(const char *name)
60 {
61 	struct thermal_governor *pos;
62 
63 	if (!name || !name[0])
64 		return def_governor;
65 
66 	list_for_each_entry(pos, &thermal_governor_list, governor_list)
67 		if (!strncasecmp(name, pos->name, THERMAL_NAME_LENGTH))
68 			return pos;
69 
70 	return NULL;
71 }
72 
73 /**
74  * bind_previous_governor() - bind the previous governor of the thermal zone
75  * @tz:		a valid pointer to a struct thermal_zone_device
76  * @failed_gov_name:	the name of the governor that failed to register
77  *
78  * Register the previous governor of the thermal zone after a new
79  * governor has failed to be bound.
80  */
81 static void bind_previous_governor(struct thermal_zone_device *tz,
82 				   const char *failed_gov_name)
83 {
84 	if (tz->governor && tz->governor->bind_to_tz) {
85 		if (tz->governor->bind_to_tz(tz)) {
86 			dev_err(&tz->device,
87 				"governor %s failed to bind and the previous one (%s) failed to bind again, thermal zone %s has no governor\n",
88 				failed_gov_name, tz->governor->name, tz->type);
89 			tz->governor = NULL;
90 		}
91 	}
92 }
93 
94 /**
95  * thermal_set_governor() - Switch to another governor
96  * @tz:		a valid pointer to a struct thermal_zone_device
97  * @new_gov:	pointer to the new governor
98  *
99  * Change the governor of thermal zone @tz.
100  *
101  * Return: 0 on success, an error if the new governor's bind_to_tz() failed.
102  */
103 static int thermal_set_governor(struct thermal_zone_device *tz,
104 				struct thermal_governor *new_gov)
105 {
106 	int ret = 0;
107 
108 	if (tz->governor && tz->governor->unbind_from_tz)
109 		tz->governor->unbind_from_tz(tz);
110 
111 	if (new_gov && new_gov->bind_to_tz) {
112 		ret = new_gov->bind_to_tz(tz);
113 		if (ret) {
114 			bind_previous_governor(tz, new_gov->name);
115 
116 			return ret;
117 		}
118 	}
119 
120 	tz->governor = new_gov;
121 
122 	return ret;
123 }
124 
125 int thermal_register_governor(struct thermal_governor *governor)
126 {
127 	int err;
128 	const char *name;
129 	struct thermal_zone_device *pos;
130 
131 	if (!governor)
132 		return -EINVAL;
133 
134 	mutex_lock(&thermal_governor_lock);
135 
136 	err = -EBUSY;
137 	if (!__find_governor(governor->name)) {
138 		bool match_default;
139 
140 		err = 0;
141 		list_add(&governor->governor_list, &thermal_governor_list);
142 		match_default = !strncmp(governor->name,
143 					 DEFAULT_THERMAL_GOVERNOR,
144 					 THERMAL_NAME_LENGTH);
145 
146 		if (!def_governor && match_default)
147 			def_governor = governor;
148 	}
149 
150 	mutex_lock(&thermal_list_lock);
151 
152 	list_for_each_entry(pos, &thermal_tz_list, node) {
153 		/*
154 		 * only thermal zones with specified tz->tzp->governor_name
155 		 * may run with tz->govenor unset
156 		 */
157 		if (pos->governor)
158 			continue;
159 
160 		name = pos->tzp->governor_name;
161 
162 		if (!strncasecmp(name, governor->name, THERMAL_NAME_LENGTH)) {
163 			int ret;
164 
165 			ret = thermal_set_governor(pos, governor);
166 			if (ret)
167 				dev_err(&pos->device,
168 					"Failed to set governor %s for thermal zone %s: %d\n",
169 					governor->name, pos->type, ret);
170 		}
171 	}
172 
173 	mutex_unlock(&thermal_list_lock);
174 	mutex_unlock(&thermal_governor_lock);
175 
176 	return err;
177 }
178 
179 void thermal_unregister_governor(struct thermal_governor *governor)
180 {
181 	struct thermal_zone_device *pos;
182 
183 	if (!governor)
184 		return;
185 
186 	mutex_lock(&thermal_governor_lock);
187 
188 	if (!__find_governor(governor->name))
189 		goto exit;
190 
191 	mutex_lock(&thermal_list_lock);
192 
193 	list_for_each_entry(pos, &thermal_tz_list, node) {
194 		if (!strncasecmp(pos->governor->name, governor->name,
195 				 THERMAL_NAME_LENGTH))
196 			thermal_set_governor(pos, NULL);
197 	}
198 
199 	mutex_unlock(&thermal_list_lock);
200 	list_del(&governor->governor_list);
201 exit:
202 	mutex_unlock(&thermal_governor_lock);
203 }
204 
205 int thermal_zone_device_set_policy(struct thermal_zone_device *tz,
206 				   char *policy)
207 {
208 	struct thermal_governor *gov;
209 	int ret = -EINVAL;
210 
211 	mutex_lock(&thermal_governor_lock);
212 	mutex_lock(&tz->lock);
213 
214 	gov = __find_governor(strim(policy));
215 	if (!gov)
216 		goto exit;
217 
218 	ret = thermal_set_governor(tz, gov);
219 
220 exit:
221 	mutex_unlock(&tz->lock);
222 	mutex_unlock(&thermal_governor_lock);
223 
224 	return ret;
225 }
226 
227 int thermal_build_list_of_policies(char *buf)
228 {
229 	struct thermal_governor *pos;
230 	ssize_t count = 0;
231 	ssize_t size = PAGE_SIZE;
232 
233 	mutex_lock(&thermal_governor_lock);
234 
235 	list_for_each_entry(pos, &thermal_governor_list, governor_list) {
236 		size = PAGE_SIZE - count;
237 		count += scnprintf(buf + count, size, "%s ", pos->name);
238 	}
239 	count += scnprintf(buf + count, size, "\n");
240 
241 	mutex_unlock(&thermal_governor_lock);
242 
243 	return count;
244 }
245 
246 static int __init thermal_register_governors(void)
247 {
248 	int result;
249 
250 	result = thermal_gov_step_wise_register();
251 	if (result)
252 		return result;
253 
254 	result = thermal_gov_fair_share_register();
255 	if (result)
256 		return result;
257 
258 	result = thermal_gov_bang_bang_register();
259 	if (result)
260 		return result;
261 
262 	result = thermal_gov_user_space_register();
263 	if (result)
264 		return result;
265 
266 	return thermal_gov_power_allocator_register();
267 }
268 
269 static void thermal_unregister_governors(void)
270 {
271 	thermal_gov_step_wise_unregister();
272 	thermal_gov_fair_share_unregister();
273 	thermal_gov_bang_bang_unregister();
274 	thermal_gov_user_space_unregister();
275 	thermal_gov_power_allocator_unregister();
276 }
277 
278 /*
279  * Zone update section: main control loop applied to each zone while monitoring
280  *
281  * in polling mode. The monitoring is done using a workqueue.
282  * Same update may be done on a zone by calling thermal_zone_device_update().
283  *
284  * An update means:
285  * - Non-critical trips will invoke the governor responsible for that zone;
286  * - Hot trips will produce a notification to userspace;
287  * - Critical trip point will cause a system shutdown.
288  */
289 static void thermal_zone_device_set_polling(struct thermal_zone_device *tz,
290 					    int delay)
291 {
292 	if (delay > 1000)
293 		mod_delayed_work(system_freezable_wq, &tz->poll_queue,
294 				 round_jiffies(msecs_to_jiffies(delay)));
295 	else if (delay)
296 		mod_delayed_work(system_freezable_wq, &tz->poll_queue,
297 				 msecs_to_jiffies(delay));
298 	else
299 		cancel_delayed_work(&tz->poll_queue);
300 }
301 
302 static void monitor_thermal_zone(struct thermal_zone_device *tz)
303 {
304 	mutex_lock(&tz->lock);
305 
306 	if (tz->passive)
307 		thermal_zone_device_set_polling(tz, tz->passive_delay);
308 	else if (tz->polling_delay)
309 		thermal_zone_device_set_polling(tz, tz->polling_delay);
310 	else
311 		thermal_zone_device_set_polling(tz, 0);
312 
313 	mutex_unlock(&tz->lock);
314 }
315 
316 static void handle_non_critical_trips(struct thermal_zone_device *tz,
317 				      int trip,
318 				      enum thermal_trip_type trip_type)
319 {
320 	tz->governor ? tz->governor->throttle(tz, trip) :
321 		       def_governor->throttle(tz, trip);
322 }
323 
324 /**
325  * thermal_emergency_poweroff_func - emergency poweroff work after a known delay
326  * @work: work_struct associated with the emergency poweroff function
327  *
328  * This function is called in very critical situations to force
329  * a kernel poweroff after a configurable timeout value.
330  */
331 static void thermal_emergency_poweroff_func(struct work_struct *work)
332 {
333 	/*
334 	 * We have reached here after the emergency thermal shutdown
335 	 * Waiting period has expired. This means orderly_poweroff has
336 	 * not been able to shut off the system for some reason.
337 	 * Try to shut down the system immediately using kernel_power_off
338 	 * if populated
339 	 */
340 	WARN(1, "Attempting kernel_power_off: Temperature too high\n");
341 	kernel_power_off();
342 
343 	/*
344 	 * Worst of the worst case trigger emergency restart
345 	 */
346 	WARN(1, "Attempting emergency_restart: Temperature too high\n");
347 	emergency_restart();
348 }
349 
350 static DECLARE_DELAYED_WORK(thermal_emergency_poweroff_work,
351 			    thermal_emergency_poweroff_func);
352 
353 /**
354  * thermal_emergency_poweroff - Trigger an emergency system poweroff
355  *
356  * This may be called from any critical situation to trigger a system shutdown
357  * after a known period of time. By default this is not scheduled.
358  */
359 static void thermal_emergency_poweroff(void)
360 {
361 	int poweroff_delay_ms = CONFIG_THERMAL_EMERGENCY_POWEROFF_DELAY_MS;
362 	/*
363 	 * poweroff_delay_ms must be a carefully profiled positive value.
364 	 * Its a must for thermal_emergency_poweroff_work to be scheduled
365 	 */
366 	if (poweroff_delay_ms <= 0)
367 		return;
368 	schedule_delayed_work(&thermal_emergency_poweroff_work,
369 			      msecs_to_jiffies(poweroff_delay_ms));
370 }
371 
372 static void handle_critical_trips(struct thermal_zone_device *tz,
373 				  int trip, enum thermal_trip_type trip_type)
374 {
375 	int trip_temp;
376 
377 	tz->ops->get_trip_temp(tz, trip, &trip_temp);
378 
379 	/* If we have not crossed the trip_temp, we do not care. */
380 	if (trip_temp <= 0 || tz->temperature < trip_temp)
381 		return;
382 
383 	trace_thermal_zone_trip(tz, trip, trip_type);
384 
385 	if (tz->ops->notify)
386 		tz->ops->notify(tz, trip, trip_type);
387 
388 	if (trip_type == THERMAL_TRIP_CRITICAL) {
389 		dev_emerg(&tz->device,
390 			  "critical temperature reached (%d C), shutting down\n",
391 			  tz->temperature / 1000);
392 		mutex_lock(&poweroff_lock);
393 		if (!power_off_triggered) {
394 			/*
395 			 * Queue a backup emergency shutdown in the event of
396 			 * orderly_poweroff failure
397 			 */
398 			thermal_emergency_poweroff();
399 			orderly_poweroff(true);
400 			power_off_triggered = true;
401 		}
402 		mutex_unlock(&poweroff_lock);
403 	}
404 }
405 
406 static void handle_thermal_trip(struct thermal_zone_device *tz, int trip)
407 {
408 	enum thermal_trip_type type;
409 
410 	/* Ignore disabled trip points */
411 	if (test_bit(trip, &tz->trips_disabled))
412 		return;
413 
414 	tz->ops->get_trip_type(tz, trip, &type);
415 
416 	if (type == THERMAL_TRIP_CRITICAL || type == THERMAL_TRIP_HOT)
417 		handle_critical_trips(tz, trip, type);
418 	else
419 		handle_non_critical_trips(tz, trip, type);
420 	/*
421 	 * Alright, we handled this trip successfully.
422 	 * So, start monitoring again.
423 	 */
424 	monitor_thermal_zone(tz);
425 }
426 
427 static void update_temperature(struct thermal_zone_device *tz)
428 {
429 	int temp, ret;
430 
431 	ret = thermal_zone_get_temp(tz, &temp);
432 	if (ret) {
433 		if (ret != -EAGAIN)
434 			dev_warn(&tz->device,
435 				 "failed to read out thermal zone (%d)\n",
436 				 ret);
437 		return;
438 	}
439 
440 	mutex_lock(&tz->lock);
441 	tz->last_temperature = tz->temperature;
442 	tz->temperature = temp;
443 	mutex_unlock(&tz->lock);
444 
445 	trace_thermal_temperature(tz);
446 	if (tz->last_temperature == THERMAL_TEMP_INVALID)
447 		dev_dbg(&tz->device, "last_temperature N/A, current_temperature=%d\n",
448 			tz->temperature);
449 	else
450 		dev_dbg(&tz->device, "last_temperature=%d, current_temperature=%d\n",
451 			tz->last_temperature, tz->temperature);
452 }
453 
454 static void thermal_zone_device_reset(struct thermal_zone_device *tz)
455 {
456 	struct thermal_instance *pos;
457 
458 	tz->temperature = THERMAL_TEMP_INVALID;
459 	tz->passive = 0;
460 	list_for_each_entry(pos, &tz->thermal_instances, tz_node)
461 		pos->initialized = false;
462 }
463 
464 void thermal_zone_device_update(struct thermal_zone_device *tz,
465 				enum thermal_notify_event event)
466 {
467 	int count;
468 
469 	if (atomic_read(&in_suspend))
470 		return;
471 
472 	if (!tz->ops->get_temp)
473 		return;
474 
475 	update_temperature(tz);
476 
477 	thermal_zone_set_trips(tz);
478 
479 	tz->notify_event = event;
480 
481 	for (count = 0; count < tz->trips; count++)
482 		handle_thermal_trip(tz, count);
483 }
484 EXPORT_SYMBOL_GPL(thermal_zone_device_update);
485 
486 /**
487  * thermal_notify_framework - Sensor drivers use this API to notify framework
488  * @tz:		thermal zone device
489  * @trip:	indicates which trip point has been crossed
490  *
491  * This function handles the trip events from sensor drivers. It starts
492  * throttling the cooling devices according to the policy configured.
493  * For CRITICAL and HOT trip points, this notifies the respective drivers,
494  * and does actual throttling for other trip points i.e ACTIVE and PASSIVE.
495  * The throttling policy is based on the configured platform data; if no
496  * platform data is provided, this uses the step_wise throttling policy.
497  */
498 void thermal_notify_framework(struct thermal_zone_device *tz, int trip)
499 {
500 	handle_thermal_trip(tz, trip);
501 }
502 EXPORT_SYMBOL_GPL(thermal_notify_framework);
503 
504 static void thermal_zone_device_check(struct work_struct *work)
505 {
506 	struct thermal_zone_device *tz = container_of(work, struct
507 						      thermal_zone_device,
508 						      poll_queue.work);
509 	thermal_zone_device_update(tz, THERMAL_EVENT_UNSPECIFIED);
510 }
511 
512 /*
513  * Power actor section: interface to power actors to estimate power
514  *
515  * Set of functions used to interact to cooling devices that know
516  * how to estimate their devices power consumption.
517  */
518 
519 /**
520  * power_actor_get_max_power() - get the maximum power that a cdev can consume
521  * @cdev:	pointer to &thermal_cooling_device
522  * @tz:		a valid thermal zone device pointer
523  * @max_power:	pointer in which to store the maximum power
524  *
525  * Calculate the maximum power consumption in milliwats that the
526  * cooling device can currently consume and store it in @max_power.
527  *
528  * Return: 0 on success, -EINVAL if @cdev doesn't support the
529  * power_actor API or -E* on other error.
530  */
531 int power_actor_get_max_power(struct thermal_cooling_device *cdev,
532 			      struct thermal_zone_device *tz, u32 *max_power)
533 {
534 	if (!cdev_is_power_actor(cdev))
535 		return -EINVAL;
536 
537 	return cdev->ops->state2power(cdev, tz, 0, max_power);
538 }
539 
540 /**
541  * power_actor_get_min_power() - get the mainimum power that a cdev can consume
542  * @cdev:	pointer to &thermal_cooling_device
543  * @tz:		a valid thermal zone device pointer
544  * @min_power:	pointer in which to store the minimum power
545  *
546  * Calculate the minimum power consumption in milliwatts that the
547  * cooling device can currently consume and store it in @min_power.
548  *
549  * Return: 0 on success, -EINVAL if @cdev doesn't support the
550  * power_actor API or -E* on other error.
551  */
552 int power_actor_get_min_power(struct thermal_cooling_device *cdev,
553 			      struct thermal_zone_device *tz, u32 *min_power)
554 {
555 	unsigned long max_state;
556 	int ret;
557 
558 	if (!cdev_is_power_actor(cdev))
559 		return -EINVAL;
560 
561 	ret = cdev->ops->get_max_state(cdev, &max_state);
562 	if (ret)
563 		return ret;
564 
565 	return cdev->ops->state2power(cdev, tz, max_state, min_power);
566 }
567 
568 /**
569  * power_actor_set_power() - limit the maximum power a cooling device consumes
570  * @cdev:	pointer to &thermal_cooling_device
571  * @instance:	thermal instance to update
572  * @power:	the power in milliwatts
573  *
574  * Set the cooling device to consume at most @power milliwatts. The limit is
575  * expected to be a cap at the maximum power consumption.
576  *
577  * Return: 0 on success, -EINVAL if the cooling device does not
578  * implement the power actor API or -E* for other failures.
579  */
580 int power_actor_set_power(struct thermal_cooling_device *cdev,
581 			  struct thermal_instance *instance, u32 power)
582 {
583 	unsigned long state;
584 	int ret;
585 
586 	if (!cdev_is_power_actor(cdev))
587 		return -EINVAL;
588 
589 	ret = cdev->ops->power2state(cdev, instance->tz, power, &state);
590 	if (ret)
591 		return ret;
592 
593 	instance->target = state;
594 	mutex_lock(&cdev->lock);
595 	cdev->updated = false;
596 	mutex_unlock(&cdev->lock);
597 	thermal_cdev_update(cdev);
598 
599 	return 0;
600 }
601 
602 void thermal_zone_device_rebind_exception(struct thermal_zone_device *tz,
603 					  const char *cdev_type, size_t size)
604 {
605 	struct thermal_cooling_device *cdev = NULL;
606 
607 	mutex_lock(&thermal_list_lock);
608 	list_for_each_entry(cdev, &thermal_cdev_list, node) {
609 		/* skip non matching cdevs */
610 		if (strncmp(cdev_type, cdev->type, size))
611 			continue;
612 
613 		/* re binding the exception matching the type pattern */
614 		thermal_zone_bind_cooling_device(tz, THERMAL_TRIPS_NONE, cdev,
615 						 THERMAL_NO_LIMIT,
616 						 THERMAL_NO_LIMIT,
617 						 THERMAL_WEIGHT_DEFAULT);
618 	}
619 	mutex_unlock(&thermal_list_lock);
620 }
621 
622 void thermal_zone_device_unbind_exception(struct thermal_zone_device *tz,
623 					  const char *cdev_type, size_t size)
624 {
625 	struct thermal_cooling_device *cdev = NULL;
626 
627 	mutex_lock(&thermal_list_lock);
628 	list_for_each_entry(cdev, &thermal_cdev_list, node) {
629 		/* skip non matching cdevs */
630 		if (strncmp(cdev_type, cdev->type, size))
631 			continue;
632 		/* unbinding the exception matching the type pattern */
633 		thermal_zone_unbind_cooling_device(tz, THERMAL_TRIPS_NONE,
634 						   cdev);
635 	}
636 	mutex_unlock(&thermal_list_lock);
637 }
638 
639 /*
640  * Device management section: cooling devices, zones devices, and binding
641  *
642  * Set of functions provided by the thermal core for:
643  * - cooling devices lifecycle: registration, unregistration,
644  *				binding, and unbinding.
645  * - thermal zone devices lifecycle: registration, unregistration,
646  *				     binding, and unbinding.
647  */
648 
649 /**
650  * thermal_zone_bind_cooling_device() - bind a cooling device to a thermal zone
651  * @tz:		pointer to struct thermal_zone_device
652  * @trip:	indicates which trip point the cooling devices is
653  *		associated with in this thermal zone.
654  * @cdev:	pointer to struct thermal_cooling_device
655  * @upper:	the Maximum cooling state for this trip point.
656  *		THERMAL_NO_LIMIT means no upper limit,
657  *		and the cooling device can be in max_state.
658  * @lower:	the Minimum cooling state can be used for this trip point.
659  *		THERMAL_NO_LIMIT means no lower limit,
660  *		and the cooling device can be in cooling state 0.
661  * @weight:	The weight of the cooling device to be bound to the
662  *		thermal zone. Use THERMAL_WEIGHT_DEFAULT for the
663  *		default value
664  *
665  * This interface function bind a thermal cooling device to the certain trip
666  * point of a thermal zone device.
667  * This function is usually called in the thermal zone device .bind callback.
668  *
669  * Return: 0 on success, the proper error value otherwise.
670  */
671 int thermal_zone_bind_cooling_device(struct thermal_zone_device *tz,
672 				     int trip,
673 				     struct thermal_cooling_device *cdev,
674 				     unsigned long upper, unsigned long lower,
675 				     unsigned int weight)
676 {
677 	struct thermal_instance *dev;
678 	struct thermal_instance *pos;
679 	struct thermal_zone_device *pos1;
680 	struct thermal_cooling_device *pos2;
681 	unsigned long max_state;
682 	int result, ret;
683 
684 	if (trip >= tz->trips || (trip < 0 && trip != THERMAL_TRIPS_NONE))
685 		return -EINVAL;
686 
687 	list_for_each_entry(pos1, &thermal_tz_list, node) {
688 		if (pos1 == tz)
689 			break;
690 	}
691 	list_for_each_entry(pos2, &thermal_cdev_list, node) {
692 		if (pos2 == cdev)
693 			break;
694 	}
695 
696 	if (tz != pos1 || cdev != pos2)
697 		return -EINVAL;
698 
699 	ret = cdev->ops->get_max_state(cdev, &max_state);
700 	if (ret)
701 		return ret;
702 
703 	/* lower default 0, upper default max_state */
704 	lower = lower == THERMAL_NO_LIMIT ? 0 : lower;
705 	upper = upper == THERMAL_NO_LIMIT ? max_state : upper;
706 
707 	if (lower > upper || upper > max_state)
708 		return -EINVAL;
709 
710 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
711 	if (!dev)
712 		return -ENOMEM;
713 	dev->tz = tz;
714 	dev->cdev = cdev;
715 	dev->trip = trip;
716 	dev->upper = upper;
717 	dev->lower = lower;
718 	dev->target = THERMAL_NO_TARGET;
719 	dev->weight = weight;
720 
721 	result = ida_simple_get(&tz->ida, 0, 0, GFP_KERNEL);
722 	if (result < 0)
723 		goto free_mem;
724 
725 	dev->id = result;
726 	sprintf(dev->name, "cdev%d", dev->id);
727 	result =
728 	    sysfs_create_link(&tz->device.kobj, &cdev->device.kobj, dev->name);
729 	if (result)
730 		goto release_ida;
731 
732 	sprintf(dev->attr_name, "cdev%d_trip_point", dev->id);
733 	sysfs_attr_init(&dev->attr.attr);
734 	dev->attr.attr.name = dev->attr_name;
735 	dev->attr.attr.mode = 0444;
736 	dev->attr.show = trip_point_show;
737 	result = device_create_file(&tz->device, &dev->attr);
738 	if (result)
739 		goto remove_symbol_link;
740 
741 	sprintf(dev->weight_attr_name, "cdev%d_weight", dev->id);
742 	sysfs_attr_init(&dev->weight_attr.attr);
743 	dev->weight_attr.attr.name = dev->weight_attr_name;
744 	dev->weight_attr.attr.mode = S_IWUSR | S_IRUGO;
745 	dev->weight_attr.show = weight_show;
746 	dev->weight_attr.store = weight_store;
747 	result = device_create_file(&tz->device, &dev->weight_attr);
748 	if (result)
749 		goto remove_trip_file;
750 
751 	mutex_lock(&tz->lock);
752 	mutex_lock(&cdev->lock);
753 	list_for_each_entry(pos, &tz->thermal_instances, tz_node)
754 		if (pos->tz == tz && pos->trip == trip && pos->cdev == cdev) {
755 			result = -EEXIST;
756 			break;
757 		}
758 	if (!result) {
759 		list_add_tail(&dev->tz_node, &tz->thermal_instances);
760 		list_add_tail(&dev->cdev_node, &cdev->thermal_instances);
761 		atomic_set(&tz->need_update, 1);
762 	}
763 	mutex_unlock(&cdev->lock);
764 	mutex_unlock(&tz->lock);
765 
766 	if (!result)
767 		return 0;
768 
769 	device_remove_file(&tz->device, &dev->weight_attr);
770 remove_trip_file:
771 	device_remove_file(&tz->device, &dev->attr);
772 remove_symbol_link:
773 	sysfs_remove_link(&tz->device.kobj, dev->name);
774 release_ida:
775 	ida_simple_remove(&tz->ida, dev->id);
776 free_mem:
777 	kfree(dev);
778 	return result;
779 }
780 EXPORT_SYMBOL_GPL(thermal_zone_bind_cooling_device);
781 
782 /**
783  * thermal_zone_unbind_cooling_device() - unbind a cooling device from a
784  *					  thermal zone.
785  * @tz:		pointer to a struct thermal_zone_device.
786  * @trip:	indicates which trip point the cooling devices is
787  *		associated with in this thermal zone.
788  * @cdev:	pointer to a struct thermal_cooling_device.
789  *
790  * This interface function unbind a thermal cooling device from the certain
791  * trip point of a thermal zone device.
792  * This function is usually called in the thermal zone device .unbind callback.
793  *
794  * Return: 0 on success, the proper error value otherwise.
795  */
796 int thermal_zone_unbind_cooling_device(struct thermal_zone_device *tz,
797 				       int trip,
798 				       struct thermal_cooling_device *cdev)
799 {
800 	struct thermal_instance *pos, *next;
801 
802 	mutex_lock(&tz->lock);
803 	mutex_lock(&cdev->lock);
804 	list_for_each_entry_safe(pos, next, &tz->thermal_instances, tz_node) {
805 		if (pos->tz == tz && pos->trip == trip && pos->cdev == cdev) {
806 			list_del(&pos->tz_node);
807 			list_del(&pos->cdev_node);
808 			mutex_unlock(&cdev->lock);
809 			mutex_unlock(&tz->lock);
810 			goto unbind;
811 		}
812 	}
813 	mutex_unlock(&cdev->lock);
814 	mutex_unlock(&tz->lock);
815 
816 	return -ENODEV;
817 
818 unbind:
819 	device_remove_file(&tz->device, &pos->weight_attr);
820 	device_remove_file(&tz->device, &pos->attr);
821 	sysfs_remove_link(&tz->device.kobj, pos->name);
822 	ida_simple_remove(&tz->ida, pos->id);
823 	kfree(pos);
824 	return 0;
825 }
826 EXPORT_SYMBOL_GPL(thermal_zone_unbind_cooling_device);
827 
828 static void thermal_release(struct device *dev)
829 {
830 	struct thermal_zone_device *tz;
831 	struct thermal_cooling_device *cdev;
832 
833 	if (!strncmp(dev_name(dev), "thermal_zone",
834 		     sizeof("thermal_zone") - 1)) {
835 		tz = to_thermal_zone(dev);
836 		thermal_zone_destroy_device_groups(tz);
837 		kfree(tz);
838 	} else if (!strncmp(dev_name(dev), "cooling_device",
839 			    sizeof("cooling_device") - 1)) {
840 		cdev = to_cooling_device(dev);
841 		kfree(cdev);
842 	}
843 }
844 
845 static struct class thermal_class = {
846 	.name = "thermal",
847 	.dev_release = thermal_release,
848 };
849 
850 static inline
851 void print_bind_err_msg(struct thermal_zone_device *tz,
852 			struct thermal_cooling_device *cdev, int ret)
853 {
854 	dev_err(&tz->device, "binding zone %s with cdev %s failed:%d\n",
855 		tz->type, cdev->type, ret);
856 }
857 
858 static void __bind(struct thermal_zone_device *tz, int mask,
859 		   struct thermal_cooling_device *cdev,
860 		   unsigned long *limits,
861 		   unsigned int weight)
862 {
863 	int i, ret;
864 
865 	for (i = 0; i < tz->trips; i++) {
866 		if (mask & (1 << i)) {
867 			unsigned long upper, lower;
868 
869 			upper = THERMAL_NO_LIMIT;
870 			lower = THERMAL_NO_LIMIT;
871 			if (limits) {
872 				lower = limits[i * 2];
873 				upper = limits[i * 2 + 1];
874 			}
875 			ret = thermal_zone_bind_cooling_device(tz, i, cdev,
876 							       upper, lower,
877 							       weight);
878 			if (ret)
879 				print_bind_err_msg(tz, cdev, ret);
880 		}
881 	}
882 }
883 
884 static void bind_cdev(struct thermal_cooling_device *cdev)
885 {
886 	int i, ret;
887 	const struct thermal_zone_params *tzp;
888 	struct thermal_zone_device *pos = NULL;
889 
890 	mutex_lock(&thermal_list_lock);
891 
892 	list_for_each_entry(pos, &thermal_tz_list, node) {
893 		if (!pos->tzp && !pos->ops->bind)
894 			continue;
895 
896 		if (pos->ops->bind) {
897 			ret = pos->ops->bind(pos, cdev);
898 			if (ret)
899 				print_bind_err_msg(pos, cdev, ret);
900 			continue;
901 		}
902 
903 		tzp = pos->tzp;
904 		if (!tzp || !tzp->tbp)
905 			continue;
906 
907 		for (i = 0; i < tzp->num_tbps; i++) {
908 			if (tzp->tbp[i].cdev || !tzp->tbp[i].match)
909 				continue;
910 			if (tzp->tbp[i].match(pos, cdev))
911 				continue;
912 			tzp->tbp[i].cdev = cdev;
913 			__bind(pos, tzp->tbp[i].trip_mask, cdev,
914 			       tzp->tbp[i].binding_limits,
915 			       tzp->tbp[i].weight);
916 		}
917 	}
918 
919 	mutex_unlock(&thermal_list_lock);
920 }
921 
922 /**
923  * __thermal_cooling_device_register() - register a new thermal cooling device
924  * @np:		a pointer to a device tree node.
925  * @type:	the thermal cooling device type.
926  * @devdata:	device private data.
927  * @ops:		standard thermal cooling devices callbacks.
928  *
929  * This interface function adds a new thermal cooling device (fan/processor/...)
930  * to /sys/class/thermal/ folder as cooling_device[0-*]. It tries to bind itself
931  * to all the thermal zone devices registered at the same time.
932  * It also gives the opportunity to link the cooling device to a device tree
933  * node, so that it can be bound to a thermal zone created out of device tree.
934  *
935  * Return: a pointer to the created struct thermal_cooling_device or an
936  * ERR_PTR. Caller must check return value with IS_ERR*() helpers.
937  */
938 static struct thermal_cooling_device *
939 __thermal_cooling_device_register(struct device_node *np,
940 				  char *type, void *devdata,
941 				  const struct thermal_cooling_device_ops *ops)
942 {
943 	struct thermal_cooling_device *cdev;
944 	struct thermal_zone_device *pos = NULL;
945 	int result;
946 
947 	if (type && strlen(type) >= THERMAL_NAME_LENGTH)
948 		return ERR_PTR(-EINVAL);
949 
950 	if (!ops || !ops->get_max_state || !ops->get_cur_state ||
951 	    !ops->set_cur_state)
952 		return ERR_PTR(-EINVAL);
953 
954 	cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
955 	if (!cdev)
956 		return ERR_PTR(-ENOMEM);
957 
958 	result = ida_simple_get(&thermal_cdev_ida, 0, 0, GFP_KERNEL);
959 	if (result < 0) {
960 		kfree(cdev);
961 		return ERR_PTR(result);
962 	}
963 
964 	cdev->id = result;
965 	strlcpy(cdev->type, type ? : "", sizeof(cdev->type));
966 	mutex_init(&cdev->lock);
967 	INIT_LIST_HEAD(&cdev->thermal_instances);
968 	cdev->np = np;
969 	cdev->ops = ops;
970 	cdev->updated = false;
971 	cdev->device.class = &thermal_class;
972 	cdev->devdata = devdata;
973 	thermal_cooling_device_setup_sysfs(cdev);
974 	dev_set_name(&cdev->device, "cooling_device%d", cdev->id);
975 	result = device_register(&cdev->device);
976 	if (result) {
977 		ida_simple_remove(&thermal_cdev_ida, cdev->id);
978 		kfree(cdev);
979 		return ERR_PTR(result);
980 	}
981 
982 	/* Add 'this' new cdev to the global cdev list */
983 	mutex_lock(&thermal_list_lock);
984 	list_add(&cdev->node, &thermal_cdev_list);
985 	mutex_unlock(&thermal_list_lock);
986 
987 	/* Update binding information for 'this' new cdev */
988 	bind_cdev(cdev);
989 
990 	mutex_lock(&thermal_list_lock);
991 	list_for_each_entry(pos, &thermal_tz_list, node)
992 		if (atomic_cmpxchg(&pos->need_update, 1, 0))
993 			thermal_zone_device_update(pos,
994 						   THERMAL_EVENT_UNSPECIFIED);
995 	mutex_unlock(&thermal_list_lock);
996 
997 	return cdev;
998 }
999 
1000 /**
1001  * thermal_cooling_device_register() - register a new thermal cooling device
1002  * @type:	the thermal cooling device type.
1003  * @devdata:	device private data.
1004  * @ops:		standard thermal cooling devices callbacks.
1005  *
1006  * This interface function adds a new thermal cooling device (fan/processor/...)
1007  * to /sys/class/thermal/ folder as cooling_device[0-*]. It tries to bind itself
1008  * to all the thermal zone devices registered at the same time.
1009  *
1010  * Return: a pointer to the created struct thermal_cooling_device or an
1011  * ERR_PTR. Caller must check return value with IS_ERR*() helpers.
1012  */
1013 struct thermal_cooling_device *
1014 thermal_cooling_device_register(char *type, void *devdata,
1015 				const struct thermal_cooling_device_ops *ops)
1016 {
1017 	return __thermal_cooling_device_register(NULL, type, devdata, ops);
1018 }
1019 EXPORT_SYMBOL_GPL(thermal_cooling_device_register);
1020 
1021 /**
1022  * thermal_of_cooling_device_register() - register an OF thermal cooling device
1023  * @np:		a pointer to a device tree node.
1024  * @type:	the thermal cooling device type.
1025  * @devdata:	device private data.
1026  * @ops:		standard thermal cooling devices callbacks.
1027  *
1028  * This function will register a cooling device with device tree node reference.
1029  * This interface function adds a new thermal cooling device (fan/processor/...)
1030  * to /sys/class/thermal/ folder as cooling_device[0-*]. It tries to bind itself
1031  * to all the thermal zone devices registered at the same time.
1032  *
1033  * Return: a pointer to the created struct thermal_cooling_device or an
1034  * ERR_PTR. Caller must check return value with IS_ERR*() helpers.
1035  */
1036 struct thermal_cooling_device *
1037 thermal_of_cooling_device_register(struct device_node *np,
1038 				   char *type, void *devdata,
1039 				   const struct thermal_cooling_device_ops *ops)
1040 {
1041 	return __thermal_cooling_device_register(np, type, devdata, ops);
1042 }
1043 EXPORT_SYMBOL_GPL(thermal_of_cooling_device_register);
1044 
1045 static void __unbind(struct thermal_zone_device *tz, int mask,
1046 		     struct thermal_cooling_device *cdev)
1047 {
1048 	int i;
1049 
1050 	for (i = 0; i < tz->trips; i++)
1051 		if (mask & (1 << i))
1052 			thermal_zone_unbind_cooling_device(tz, i, cdev);
1053 }
1054 
1055 /**
1056  * thermal_cooling_device_unregister - removes a thermal cooling device
1057  * @cdev:	the thermal cooling device to remove.
1058  *
1059  * thermal_cooling_device_unregister() must be called when a registered
1060  * thermal cooling device is no longer needed.
1061  */
1062 void thermal_cooling_device_unregister(struct thermal_cooling_device *cdev)
1063 {
1064 	int i;
1065 	const struct thermal_zone_params *tzp;
1066 	struct thermal_zone_device *tz;
1067 	struct thermal_cooling_device *pos = NULL;
1068 
1069 	if (!cdev)
1070 		return;
1071 
1072 	mutex_lock(&thermal_list_lock);
1073 	list_for_each_entry(pos, &thermal_cdev_list, node)
1074 		if (pos == cdev)
1075 			break;
1076 	if (pos != cdev) {
1077 		/* thermal cooling device not found */
1078 		mutex_unlock(&thermal_list_lock);
1079 		return;
1080 	}
1081 	list_del(&cdev->node);
1082 
1083 	/* Unbind all thermal zones associated with 'this' cdev */
1084 	list_for_each_entry(tz, &thermal_tz_list, node) {
1085 		if (tz->ops->unbind) {
1086 			tz->ops->unbind(tz, cdev);
1087 			continue;
1088 		}
1089 
1090 		if (!tz->tzp || !tz->tzp->tbp)
1091 			continue;
1092 
1093 		tzp = tz->tzp;
1094 		for (i = 0; i < tzp->num_tbps; i++) {
1095 			if (tzp->tbp[i].cdev == cdev) {
1096 				__unbind(tz, tzp->tbp[i].trip_mask, cdev);
1097 				tzp->tbp[i].cdev = NULL;
1098 			}
1099 		}
1100 	}
1101 
1102 	mutex_unlock(&thermal_list_lock);
1103 
1104 	ida_simple_remove(&thermal_cdev_ida, cdev->id);
1105 	device_unregister(&cdev->device);
1106 	thermal_cooling_device_destroy_sysfs(cdev);
1107 }
1108 EXPORT_SYMBOL_GPL(thermal_cooling_device_unregister);
1109 
1110 static void bind_tz(struct thermal_zone_device *tz)
1111 {
1112 	int i, ret;
1113 	struct thermal_cooling_device *pos = NULL;
1114 	const struct thermal_zone_params *tzp = tz->tzp;
1115 
1116 	if (!tzp && !tz->ops->bind)
1117 		return;
1118 
1119 	mutex_lock(&thermal_list_lock);
1120 
1121 	/* If there is ops->bind, try to use ops->bind */
1122 	if (tz->ops->bind) {
1123 		list_for_each_entry(pos, &thermal_cdev_list, node) {
1124 			ret = tz->ops->bind(tz, pos);
1125 			if (ret)
1126 				print_bind_err_msg(tz, pos, ret);
1127 		}
1128 		goto exit;
1129 	}
1130 
1131 	if (!tzp || !tzp->tbp)
1132 		goto exit;
1133 
1134 	list_for_each_entry(pos, &thermal_cdev_list, node) {
1135 		for (i = 0; i < tzp->num_tbps; i++) {
1136 			if (tzp->tbp[i].cdev || !tzp->tbp[i].match)
1137 				continue;
1138 			if (tzp->tbp[i].match(tz, pos))
1139 				continue;
1140 			tzp->tbp[i].cdev = pos;
1141 			__bind(tz, tzp->tbp[i].trip_mask, pos,
1142 			       tzp->tbp[i].binding_limits,
1143 			       tzp->tbp[i].weight);
1144 		}
1145 	}
1146 exit:
1147 	mutex_unlock(&thermal_list_lock);
1148 }
1149 
1150 /**
1151  * thermal_zone_device_register() - register a new thermal zone device
1152  * @type:	the thermal zone device type
1153  * @trips:	the number of trip points the thermal zone support
1154  * @mask:	a bit string indicating the writeablility of trip points
1155  * @devdata:	private device data
1156  * @ops:	standard thermal zone device callbacks
1157  * @tzp:	thermal zone platform parameters
1158  * @passive_delay: number of milliseconds to wait between polls when
1159  *		   performing passive cooling
1160  * @polling_delay: number of milliseconds to wait between polls when checking
1161  *		   whether trip points have been crossed (0 for interrupt
1162  *		   driven systems)
1163  *
1164  * This interface function adds a new thermal zone device (sensor) to
1165  * /sys/class/thermal folder as thermal_zone[0-*]. It tries to bind all the
1166  * thermal cooling devices registered at the same time.
1167  * thermal_zone_device_unregister() must be called when the device is no
1168  * longer needed. The passive cooling depends on the .get_trend() return value.
1169  *
1170  * Return: a pointer to the created struct thermal_zone_device or an
1171  * in case of error, an ERR_PTR. Caller must check return value with
1172  * IS_ERR*() helpers.
1173  */
1174 struct thermal_zone_device *
1175 thermal_zone_device_register(const char *type, int trips, int mask,
1176 			     void *devdata, struct thermal_zone_device_ops *ops,
1177 			     struct thermal_zone_params *tzp, int passive_delay,
1178 			     int polling_delay)
1179 {
1180 	struct thermal_zone_device *tz;
1181 	enum thermal_trip_type trip_type;
1182 	int trip_temp;
1183 	int result;
1184 	int count;
1185 	struct thermal_governor *governor;
1186 
1187 	if (!type || strlen(type) == 0)
1188 		return ERR_PTR(-EINVAL);
1189 
1190 	if (type && strlen(type) >= THERMAL_NAME_LENGTH)
1191 		return ERR_PTR(-EINVAL);
1192 
1193 	if (trips > THERMAL_MAX_TRIPS || trips < 0 || mask >> trips)
1194 		return ERR_PTR(-EINVAL);
1195 
1196 	if (!ops)
1197 		return ERR_PTR(-EINVAL);
1198 
1199 	if (trips > 0 && (!ops->get_trip_type || !ops->get_trip_temp))
1200 		return ERR_PTR(-EINVAL);
1201 
1202 	tz = kzalloc(sizeof(*tz), GFP_KERNEL);
1203 	if (!tz)
1204 		return ERR_PTR(-ENOMEM);
1205 
1206 	INIT_LIST_HEAD(&tz->thermal_instances);
1207 	ida_init(&tz->ida);
1208 	mutex_init(&tz->lock);
1209 	result = ida_simple_get(&thermal_tz_ida, 0, 0, GFP_KERNEL);
1210 	if (result < 0)
1211 		goto free_tz;
1212 
1213 	tz->id = result;
1214 	strlcpy(tz->type, type, sizeof(tz->type));
1215 	tz->ops = ops;
1216 	tz->tzp = tzp;
1217 	tz->device.class = &thermal_class;
1218 	tz->devdata = devdata;
1219 	tz->trips = trips;
1220 	tz->passive_delay = passive_delay;
1221 	tz->polling_delay = polling_delay;
1222 
1223 	/* sys I/F */
1224 	/* Add nodes that are always present via .groups */
1225 	result = thermal_zone_create_device_groups(tz, mask);
1226 	if (result)
1227 		goto remove_id;
1228 
1229 	/* A new thermal zone needs to be updated anyway. */
1230 	atomic_set(&tz->need_update, 1);
1231 
1232 	dev_set_name(&tz->device, "thermal_zone%d", tz->id);
1233 	result = device_register(&tz->device);
1234 	if (result)
1235 		goto remove_device_groups;
1236 
1237 	for (count = 0; count < trips; count++) {
1238 		if (tz->ops->get_trip_type(tz, count, &trip_type))
1239 			set_bit(count, &tz->trips_disabled);
1240 		if (tz->ops->get_trip_temp(tz, count, &trip_temp))
1241 			set_bit(count, &tz->trips_disabled);
1242 		/* Check for bogus trip points */
1243 		if (trip_temp == 0)
1244 			set_bit(count, &tz->trips_disabled);
1245 	}
1246 
1247 	/* Update 'this' zone's governor information */
1248 	mutex_lock(&thermal_governor_lock);
1249 
1250 	if (tz->tzp)
1251 		governor = __find_governor(tz->tzp->governor_name);
1252 	else
1253 		governor = def_governor;
1254 
1255 	result = thermal_set_governor(tz, governor);
1256 	if (result) {
1257 		mutex_unlock(&thermal_governor_lock);
1258 		goto unregister;
1259 	}
1260 
1261 	mutex_unlock(&thermal_governor_lock);
1262 
1263 	if (!tz->tzp || !tz->tzp->no_hwmon) {
1264 		result = thermal_add_hwmon_sysfs(tz);
1265 		if (result)
1266 			goto unregister;
1267 	}
1268 
1269 	mutex_lock(&thermal_list_lock);
1270 	list_add_tail(&tz->node, &thermal_tz_list);
1271 	mutex_unlock(&thermal_list_lock);
1272 
1273 	/* Bind cooling devices for this zone */
1274 	bind_tz(tz);
1275 
1276 	INIT_DELAYED_WORK(&tz->poll_queue, thermal_zone_device_check);
1277 
1278 	thermal_zone_device_reset(tz);
1279 	/* Update the new thermal zone and mark it as already updated. */
1280 	if (atomic_cmpxchg(&tz->need_update, 1, 0))
1281 		thermal_zone_device_update(tz, THERMAL_EVENT_UNSPECIFIED);
1282 
1283 	return tz;
1284 
1285 unregister:
1286 	ida_simple_remove(&thermal_tz_ida, tz->id);
1287 	device_unregister(&tz->device);
1288 	return ERR_PTR(result);
1289 
1290 remove_device_groups:
1291 	thermal_zone_destroy_device_groups(tz);
1292 remove_id:
1293 	ida_simple_remove(&thermal_tz_ida, tz->id);
1294 free_tz:
1295 	kfree(tz);
1296 	return ERR_PTR(result);
1297 }
1298 EXPORT_SYMBOL_GPL(thermal_zone_device_register);
1299 
1300 /**
1301  * thermal_device_unregister - removes the registered thermal zone device
1302  * @tz: the thermal zone device to remove
1303  */
1304 void thermal_zone_device_unregister(struct thermal_zone_device *tz)
1305 {
1306 	int i;
1307 	const struct thermal_zone_params *tzp;
1308 	struct thermal_cooling_device *cdev;
1309 	struct thermal_zone_device *pos = NULL;
1310 
1311 	if (!tz)
1312 		return;
1313 
1314 	tzp = tz->tzp;
1315 
1316 	mutex_lock(&thermal_list_lock);
1317 	list_for_each_entry(pos, &thermal_tz_list, node)
1318 		if (pos == tz)
1319 			break;
1320 	if (pos != tz) {
1321 		/* thermal zone device not found */
1322 		mutex_unlock(&thermal_list_lock);
1323 		return;
1324 	}
1325 	list_del(&tz->node);
1326 
1327 	/* Unbind all cdevs associated with 'this' thermal zone */
1328 	list_for_each_entry(cdev, &thermal_cdev_list, node) {
1329 		if (tz->ops->unbind) {
1330 			tz->ops->unbind(tz, cdev);
1331 			continue;
1332 		}
1333 
1334 		if (!tzp || !tzp->tbp)
1335 			break;
1336 
1337 		for (i = 0; i < tzp->num_tbps; i++) {
1338 			if (tzp->tbp[i].cdev == cdev) {
1339 				__unbind(tz, tzp->tbp[i].trip_mask, cdev);
1340 				tzp->tbp[i].cdev = NULL;
1341 			}
1342 		}
1343 	}
1344 
1345 	mutex_unlock(&thermal_list_lock);
1346 
1347 	thermal_zone_device_set_polling(tz, 0);
1348 
1349 	thermal_set_governor(tz, NULL);
1350 
1351 	thermal_remove_hwmon_sysfs(tz);
1352 	ida_simple_remove(&thermal_tz_ida, tz->id);
1353 	ida_destroy(&tz->ida);
1354 	mutex_destroy(&tz->lock);
1355 	device_unregister(&tz->device);
1356 }
1357 EXPORT_SYMBOL_GPL(thermal_zone_device_unregister);
1358 
1359 /**
1360  * thermal_zone_get_zone_by_name() - search for a zone and returns its ref
1361  * @name: thermal zone name to fetch the temperature
1362  *
1363  * When only one zone is found with the passed name, returns a reference to it.
1364  *
1365  * Return: On success returns a reference to an unique thermal zone with
1366  * matching name equals to @name, an ERR_PTR otherwise (-EINVAL for invalid
1367  * paramenters, -ENODEV for not found and -EEXIST for multiple matches).
1368  */
1369 struct thermal_zone_device *thermal_zone_get_zone_by_name(const char *name)
1370 {
1371 	struct thermal_zone_device *pos = NULL, *ref = ERR_PTR(-EINVAL);
1372 	unsigned int found = 0;
1373 
1374 	if (!name)
1375 		goto exit;
1376 
1377 	mutex_lock(&thermal_list_lock);
1378 	list_for_each_entry(pos, &thermal_tz_list, node)
1379 		if (!strncasecmp(name, pos->type, THERMAL_NAME_LENGTH)) {
1380 			found++;
1381 			ref = pos;
1382 		}
1383 	mutex_unlock(&thermal_list_lock);
1384 
1385 	/* nothing has been found, thus an error code for it */
1386 	if (found == 0)
1387 		ref = ERR_PTR(-ENODEV);
1388 	else if (found > 1)
1389 	/* Success only when an unique zone is found */
1390 		ref = ERR_PTR(-EEXIST);
1391 
1392 exit:
1393 	return ref;
1394 }
1395 EXPORT_SYMBOL_GPL(thermal_zone_get_zone_by_name);
1396 
1397 #ifdef CONFIG_NET
1398 static const struct genl_multicast_group thermal_event_mcgrps[] = {
1399 	{ .name = THERMAL_GENL_MCAST_GROUP_NAME, },
1400 };
1401 
1402 static struct genl_family thermal_event_genl_family __ro_after_init = {
1403 	.module = THIS_MODULE,
1404 	.name = THERMAL_GENL_FAMILY_NAME,
1405 	.version = THERMAL_GENL_VERSION,
1406 	.maxattr = THERMAL_GENL_ATTR_MAX,
1407 	.mcgrps = thermal_event_mcgrps,
1408 	.n_mcgrps = ARRAY_SIZE(thermal_event_mcgrps),
1409 };
1410 
1411 int thermal_generate_netlink_event(struct thermal_zone_device *tz,
1412 				   enum events event)
1413 {
1414 	struct sk_buff *skb;
1415 	struct nlattr *attr;
1416 	struct thermal_genl_event *thermal_event;
1417 	void *msg_header;
1418 	int size;
1419 	int result;
1420 	static unsigned int thermal_event_seqnum;
1421 
1422 	if (!tz)
1423 		return -EINVAL;
1424 
1425 	/* allocate memory */
1426 	size = nla_total_size(sizeof(struct thermal_genl_event)) +
1427 	       nla_total_size(0);
1428 
1429 	skb = genlmsg_new(size, GFP_ATOMIC);
1430 	if (!skb)
1431 		return -ENOMEM;
1432 
1433 	/* add the genetlink message header */
1434 	msg_header = genlmsg_put(skb, 0, thermal_event_seqnum++,
1435 				 &thermal_event_genl_family, 0,
1436 				 THERMAL_GENL_CMD_EVENT);
1437 	if (!msg_header) {
1438 		nlmsg_free(skb);
1439 		return -ENOMEM;
1440 	}
1441 
1442 	/* fill the data */
1443 	attr = nla_reserve(skb, THERMAL_GENL_ATTR_EVENT,
1444 			   sizeof(struct thermal_genl_event));
1445 
1446 	if (!attr) {
1447 		nlmsg_free(skb);
1448 		return -EINVAL;
1449 	}
1450 
1451 	thermal_event = nla_data(attr);
1452 	if (!thermal_event) {
1453 		nlmsg_free(skb);
1454 		return -EINVAL;
1455 	}
1456 
1457 	memset(thermal_event, 0, sizeof(struct thermal_genl_event));
1458 
1459 	thermal_event->orig = tz->id;
1460 	thermal_event->event = event;
1461 
1462 	/* send multicast genetlink message */
1463 	genlmsg_end(skb, msg_header);
1464 
1465 	result = genlmsg_multicast(&thermal_event_genl_family, skb, 0,
1466 				   0, GFP_ATOMIC);
1467 	if (result)
1468 		dev_err(&tz->device, "Failed to send netlink event:%d", result);
1469 
1470 	return result;
1471 }
1472 EXPORT_SYMBOL_GPL(thermal_generate_netlink_event);
1473 
1474 static int __init genetlink_init(void)
1475 {
1476 	return genl_register_family(&thermal_event_genl_family);
1477 }
1478 
1479 static void genetlink_exit(void)
1480 {
1481 	genl_unregister_family(&thermal_event_genl_family);
1482 }
1483 #else /* !CONFIG_NET */
1484 static inline int genetlink_init(void) { return 0; }
1485 static inline void genetlink_exit(void) {}
1486 #endif /* !CONFIG_NET */
1487 
1488 static int thermal_pm_notify(struct notifier_block *nb,
1489 			     unsigned long mode, void *_unused)
1490 {
1491 	struct thermal_zone_device *tz;
1492 
1493 	switch (mode) {
1494 	case PM_HIBERNATION_PREPARE:
1495 	case PM_RESTORE_PREPARE:
1496 	case PM_SUSPEND_PREPARE:
1497 		atomic_set(&in_suspend, 1);
1498 		break;
1499 	case PM_POST_HIBERNATION:
1500 	case PM_POST_RESTORE:
1501 	case PM_POST_SUSPEND:
1502 		atomic_set(&in_suspend, 0);
1503 		list_for_each_entry(tz, &thermal_tz_list, node) {
1504 			thermal_zone_device_reset(tz);
1505 			thermal_zone_device_update(tz,
1506 						   THERMAL_EVENT_UNSPECIFIED);
1507 		}
1508 		break;
1509 	default:
1510 		break;
1511 	}
1512 	return 0;
1513 }
1514 
1515 static struct notifier_block thermal_pm_nb = {
1516 	.notifier_call = thermal_pm_notify,
1517 };
1518 
1519 static int __init thermal_init(void)
1520 {
1521 	int result;
1522 
1523 	mutex_init(&poweroff_lock);
1524 	result = thermal_register_governors();
1525 	if (result)
1526 		goto error;
1527 
1528 	result = class_register(&thermal_class);
1529 	if (result)
1530 		goto unregister_governors;
1531 
1532 	result = genetlink_init();
1533 	if (result)
1534 		goto unregister_class;
1535 
1536 	result = of_parse_thermal_zones();
1537 	if (result)
1538 		goto exit_netlink;
1539 
1540 	result = register_pm_notifier(&thermal_pm_nb);
1541 	if (result)
1542 		pr_warn("Thermal: Can not register suspend notifier, return %d\n",
1543 			result);
1544 
1545 	return 0;
1546 
1547 exit_netlink:
1548 	genetlink_exit();
1549 unregister_class:
1550 	class_unregister(&thermal_class);
1551 unregister_governors:
1552 	thermal_unregister_governors();
1553 error:
1554 	ida_destroy(&thermal_tz_ida);
1555 	ida_destroy(&thermal_cdev_ida);
1556 	mutex_destroy(&thermal_list_lock);
1557 	mutex_destroy(&thermal_governor_lock);
1558 	mutex_destroy(&poweroff_lock);
1559 	return result;
1560 }
1561 
1562 static void __exit thermal_exit(void)
1563 {
1564 	unregister_pm_notifier(&thermal_pm_nb);
1565 	of_thermal_destroy_zones();
1566 	genetlink_exit();
1567 	class_unregister(&thermal_class);
1568 	thermal_unregister_governors();
1569 	ida_destroy(&thermal_tz_ida);
1570 	ida_destroy(&thermal_cdev_ida);
1571 	mutex_destroy(&thermal_list_lock);
1572 	mutex_destroy(&thermal_governor_lock);
1573 }
1574 
1575 fs_initcall(thermal_init);
1576 module_exit(thermal_exit);
1577