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