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