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