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