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