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