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