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