Merge branch 'vendor/GCC50' - gcc 5.0 snapshot 1 FEB 2015
[dragonfly.git] / sys / dev / acpica / acpi_thermal.c
1 /*-
2  * Copyright (c) 2000, 2001 Michael Smith
3  * Copyright (c) 2000 BSDi
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD: head/sys/dev/acpica/acpi_thermal.c 255077 2013-08-30 19:21:12Z dumbbell $
28  */
29
30 #include "opt_acpi.h"
31 #include <sys/param.h>
32 #include <sys/kernel.h>
33 #include <sys/bus.h>
34 #include <sys/kthread.h>
35 #include <sys/malloc.h>
36 #include <sys/module.h>
37 #include <sys/proc.h>
38 #include <sys/reboot.h>
39 #include <sys/sysctl.h>
40 #include <sys/unistd.h>
41 #include <sys/power.h>
42 #include <sys/sensors.h>
43
44 #include <sys/mplock2.h>
45
46 #include "acpi.h"
47 #include "accommon.h"
48
49 #include <dev/acpica/acpivar.h>
50
51 /* Hooks for the ACPICA debugging infrastructure */
52 #define _COMPONENT      ACPI_THERMAL
53 ACPI_MODULE_NAME("THERMAL")
54
55 #define TZ_ZEROC        2732
56 #define TZ_KELVTOC(x)   (((x) - TZ_ZEROC) / 10), abs(((x) - TZ_ZEROC) % 10)
57
58 #define TZ_NOTIFY_TEMPERATURE   0x80 /* Temperature changed. */
59 #define TZ_NOTIFY_LEVELS        0x81 /* Cooling levels changed. */
60 #define TZ_NOTIFY_DEVICES       0x82 /* Device lists changed. */
61 #define TZ_NOTIFY_CRITICAL      0xcc /* Fake notify that _CRT/_HOT reached. */
62
63 /* Check for temperature changes every 10 seconds by default */
64 #define TZ_POLLRATE     10
65
66 /* Make sure the reported temperature is valid for this number of polls. */
67 #define TZ_VALIDCHECKS  3
68
69 /* Notify the user we will be shutting down in one more poll cycle. */
70 #define TZ_NOTIFYCOUNT  (TZ_VALIDCHECKS - 1)
71
72 /* ACPI spec defines this */
73 #define TZ_NUMLEVELS    10
74 struct acpi_tz_zone {
75     int         ac[TZ_NUMLEVELS];
76     ACPI_BUFFER al[TZ_NUMLEVELS];
77     int         crt;
78     int         hot;
79     ACPI_BUFFER psl;
80     int         psv;
81     int         tc1;
82     int         tc2;
83     int         tsp;
84     int         tzp;
85 };
86
87 struct acpi_tz_softc {
88     device_t                    tz_dev;
89     ACPI_HANDLE                 tz_handle;      /*Thermal zone handle*/
90     int                         tz_temperature; /*Current temperature*/
91     int                         tz_active;      /*Current active cooling*/
92 #define TZ_ACTIVE_NONE          -1
93 #define TZ_ACTIVE_UNKNOWN       -2
94     int                         tz_requested;   /*Minimum active cooling*/
95     int                         tz_thflags;     /*Current temp-related flags*/
96 #define TZ_THFLAG_NONE          0
97 #define TZ_THFLAG_PSV           (1<<0)
98 #define TZ_THFLAG_HOT           (1<<2)
99 #define TZ_THFLAG_CRT           (1<<3)
100     int                         tz_flags;
101 #define TZ_FLAG_NO_SCP          (1<<0)          /*No _SCP method*/
102 #define TZ_FLAG_GETPROFILE      (1<<1)          /*Get power_profile in timeout*/
103 #define TZ_FLAG_GETSETTINGS     (1<<2)          /*Get devs/setpoints*/
104     struct timespec             tz_cooling_started;
105                                         /*Current cooling starting time*/
106
107     struct sysctl_ctx_list      tz_sysctl_ctx;
108     struct sysctl_oid           *tz_sysctl_tree;
109     eventhandler_tag            tz_event;
110
111     struct acpi_tz_zone         tz_zone;        /*Thermal zone parameters*/
112     int                         tz_validchecks;
113     int                         tz_insane_tmp_notified;
114
115     /* passive cooling */
116     struct thread               *tz_cooling_proc;
117     int                         tz_cooling_proc_running;
118     int                         tz_cooling_enabled;
119     int                         tz_cooling_active;
120     int                         tz_cooling_updated;
121     int                         tz_cooling_saved_freq;
122     /* sensors(9) related */
123     struct ksensordev           sensordev;
124     struct ksensor              sensor;
125 };
126
127 #define TZ_ACTIVE_LEVEL(act)    ((act) >= 0 ? (act) : TZ_NUMLEVELS)
128
129 #define CPUFREQ_MAX_LEVELS      64 /* XXX cpufreq should export this */
130
131 static int      acpi_tz_probe(device_t dev);
132 static int      acpi_tz_attach(device_t dev);
133 static int      acpi_tz_establish(struct acpi_tz_softc *sc);
134 static void     acpi_tz_monitor(void *Context);
135 static void     acpi_tz_switch_cooler_off(ACPI_OBJECT *obj, void *arg);
136 static void     acpi_tz_switch_cooler_on(ACPI_OBJECT *obj, void *arg);
137 static void     acpi_tz_getparam(struct acpi_tz_softc *sc, char *node,
138                                  int *data);
139 static void     acpi_tz_sanity(struct acpi_tz_softc *sc, int *val, char *what);
140 static int      acpi_tz_active_sysctl(SYSCTL_HANDLER_ARGS);
141 static int      acpi_tz_cooling_sysctl(SYSCTL_HANDLER_ARGS);
142 static int      acpi_tz_temp_sysctl(SYSCTL_HANDLER_ARGS);
143 static int      acpi_tz_passive_sysctl(SYSCTL_HANDLER_ARGS);
144 static void     acpi_tz_notify_handler(ACPI_HANDLE h, UINT32 notify,
145                                        void *context);
146 static void     acpi_tz_signal(struct acpi_tz_softc *sc, int flags);
147 static void     acpi_tz_timeout(struct acpi_tz_softc *sc, int flags);
148 static void     acpi_tz_power_profile(void *arg);
149 static void     acpi_tz_thread(void *arg);
150 static int      acpi_tz_cooling_is_available(struct acpi_tz_softc *sc);
151 static int      acpi_tz_cooling_thread_start(struct acpi_tz_softc *sc);
152
153 static device_method_t acpi_tz_methods[] = {
154     /* Device interface */
155     DEVMETHOD(device_probe,     acpi_tz_probe),
156     DEVMETHOD(device_attach,    acpi_tz_attach),
157
158     DEVMETHOD_END
159 };
160
161 static driver_t acpi_tz_driver = {
162     "acpi_tz",
163     acpi_tz_methods,
164     sizeof(struct acpi_tz_softc),
165 };
166
167 static char *acpi_tz_tmp_name = "_TMP";
168
169 static devclass_t acpi_tz_devclass;
170 DRIVER_MODULE(acpi_tz, acpi, acpi_tz_driver, acpi_tz_devclass, NULL, NULL);
171 MODULE_DEPEND(acpi_tz, acpi, 1, 1, 1);
172
173 static struct sysctl_ctx_list   acpi_tz_sysctl_ctx;
174 static struct sysctl_oid        *acpi_tz_sysctl_tree;
175
176 /* Minimum cooling run time */
177 static int                      acpi_tz_min_runtime;
178 static int                      acpi_tz_polling_rate = TZ_POLLRATE;
179 static int                      acpi_tz_override;
180
181 /* Timezone polling thread */
182 static struct thread            *acpi_tz_td;
183 ACPI_LOCK_DECL(thermal, "ACPI thermal zone");
184
185 static int                      acpi_tz_cooling_unit = -1;
186
187 static int
188 acpi_tz_probe(device_t dev)
189 {
190     int         result;
191
192     if (acpi_get_type(dev) == ACPI_TYPE_THERMAL && !acpi_disabled("thermal")) {
193         device_set_desc(dev, "Thermal Zone");
194         result = -10;
195     } else
196         result = ENXIO;
197     return (result);
198 }
199
200 static int
201 acpi_tz_attach(device_t dev)
202 {
203     struct acpi_tz_softc        *sc;
204     struct acpi_softc           *acpi_sc;
205     int                         error;
206     char                        oidname[8];
207
208     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
209     if (device_get_unit(dev) == 0)
210         ACPI_LOCK_INIT(thermal, "acpitz");
211
212     sc = device_get_softc(dev);
213     sc->tz_dev = dev;
214     sc->tz_handle = acpi_get_handle(dev);
215     sc->tz_requested = TZ_ACTIVE_NONE;
216     sc->tz_active = TZ_ACTIVE_UNKNOWN;
217     sc->tz_thflags = TZ_THFLAG_NONE;
218     sc->tz_cooling_proc = NULL;
219     sc->tz_cooling_proc_running = FALSE;
220     sc->tz_cooling_active = FALSE;
221     sc->tz_cooling_updated = FALSE;
222     sc->tz_cooling_enabled = FALSE;
223
224     /*
225      * Parse the current state of the thermal zone and build control
226      * structures.  We don't need to worry about interference with the
227      * control thread since we haven't fully attached this device yet.
228      */
229     if ((error = acpi_tz_establish(sc)) != 0)
230         return (error);
231
232     /*
233      * Register for any Notify events sent to this zone.
234      */
235     AcpiInstallNotifyHandler(sc->tz_handle, ACPI_DEVICE_NOTIFY,
236                              acpi_tz_notify_handler, sc);
237
238     /*
239      * Create our sysctl nodes.
240      *
241      * XXX we need a mechanism for adding nodes under ACPI.
242      */
243     if (device_get_unit(dev) == 0) {
244         acpi_sc = acpi_device_get_parent_softc(dev);
245         sysctl_ctx_init(&acpi_tz_sysctl_ctx);
246         acpi_tz_sysctl_tree = SYSCTL_ADD_NODE(&acpi_tz_sysctl_ctx,
247                               SYSCTL_CHILDREN(acpi_sc->acpi_sysctl_tree),
248                               OID_AUTO, "thermal", CTLFLAG_RD, 0, "");
249         SYSCTL_ADD_INT(&acpi_tz_sysctl_ctx,
250                        SYSCTL_CHILDREN(acpi_tz_sysctl_tree),
251                        OID_AUTO, "min_runtime", CTLFLAG_RW,
252                        &acpi_tz_min_runtime, 0,
253                        "minimum cooling run time in sec");
254         SYSCTL_ADD_INT(&acpi_tz_sysctl_ctx,
255                        SYSCTL_CHILDREN(acpi_tz_sysctl_tree),
256                        OID_AUTO, "polling_rate", CTLFLAG_RW,
257                        &acpi_tz_polling_rate, 0, "monitor polling interval in seconds");
258         SYSCTL_ADD_INT(&acpi_tz_sysctl_ctx,
259                        SYSCTL_CHILDREN(acpi_tz_sysctl_tree), OID_AUTO,
260                        "user_override", CTLFLAG_RW, &acpi_tz_override, 0,
261                        "allow override of thermal settings");
262     }
263     sysctl_ctx_init(&sc->tz_sysctl_ctx);
264     ksprintf(oidname, "tz%d", device_get_unit(dev));
265     sc->tz_sysctl_tree = SYSCTL_ADD_NODE(&sc->tz_sysctl_ctx,
266                                          SYSCTL_CHILDREN(acpi_tz_sysctl_tree),
267                                          OID_AUTO, oidname, CTLFLAG_RD, 0, "");
268     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
269                     OID_AUTO, "temperature", CTLTYPE_INT | CTLFLAG_RD,
270                     &sc->tz_temperature, 0, sysctl_handle_int,
271                     "IK", "current thermal zone temperature");
272     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
273                     OID_AUTO, "active", CTLTYPE_INT | CTLFLAG_RW,
274                     sc, 0, acpi_tz_active_sysctl, "I", "cooling is active");
275     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
276                     OID_AUTO, "passive_cooling", CTLTYPE_INT | CTLFLAG_RW,
277                     sc, 0, acpi_tz_cooling_sysctl, "I",
278                     "enable passive (speed reduction) cooling");
279
280     SYSCTL_ADD_INT(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
281                    OID_AUTO, "thermal_flags", CTLFLAG_RD,
282                    &sc->tz_thflags, 0, "thermal zone flags");
283     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
284                     OID_AUTO, "_PSV", CTLTYPE_INT | CTLFLAG_RW,
285                     sc, offsetof(struct acpi_tz_softc, tz_zone.psv),
286                     acpi_tz_temp_sysctl, "IK", "passive cooling temp setpoint");
287     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
288                     OID_AUTO, "_HOT", CTLTYPE_INT | CTLFLAG_RW,
289                     sc, offsetof(struct acpi_tz_softc, tz_zone.hot),
290                     acpi_tz_temp_sysctl, "IK",
291                     "too hot temp setpoint (suspend now)");
292     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
293                     OID_AUTO, "_CRT", CTLTYPE_INT | CTLFLAG_RW,
294                     sc, offsetof(struct acpi_tz_softc, tz_zone.crt),
295                     acpi_tz_temp_sysctl, "IK",
296                     "critical temp setpoint (shutdown now)");
297     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
298                     OID_AUTO, "_ACx", CTLTYPE_INT | CTLFLAG_RD,
299                     &sc->tz_zone.ac, sizeof(sc->tz_zone.ac),
300                     sysctl_handle_opaque, "IK", "");
301     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
302                     OID_AUTO, "_TC1", CTLTYPE_INT | CTLFLAG_RW,
303                     sc, offsetof(struct acpi_tz_softc, tz_zone.tc1),
304                     acpi_tz_passive_sysctl, "I",
305                     "thermal constant 1 for passive cooling");
306     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
307                     OID_AUTO, "_TC2", CTLTYPE_INT | CTLFLAG_RW,
308                     sc, offsetof(struct acpi_tz_softc, tz_zone.tc2),
309                     acpi_tz_passive_sysctl, "I",
310                     "thermal constant 2 for passive cooling");
311     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
312                     OID_AUTO, "_TSP", CTLTYPE_INT | CTLFLAG_RW,
313                     sc, offsetof(struct acpi_tz_softc, tz_zone.tsp),
314                     acpi_tz_passive_sysctl, "I",
315                     "thermal sampling period for passive cooling");
316
317     /*
318      * Create thread to service all of the thermal zones.  Register
319      * our power profile event handler.
320      */
321     sc->tz_event = EVENTHANDLER_REGISTER(power_profile_change,
322         acpi_tz_power_profile, sc, 0);
323     if (acpi_tz_td == NULL) {
324         error = kthread_create(acpi_tz_thread, NULL, &acpi_tz_td,
325             "acpi_thermal");
326         if (error != 0) {
327             device_printf(sc->tz_dev, "could not create thread - %d", error);
328             goto out;
329         }
330     }
331
332     /*
333      * Create a thread to handle passive cooling for 1st zone which
334      * has _PSV, _TSP, _TC1 and _TC2.  Users can enable it for other
335      * zones manually for now.
336      *
337      * XXX We enable only one zone to avoid multiple zones conflict
338      * with each other since cpufreq currently sets all CPUs to the
339      * given frequency whereas it's possible for different thermal
340      * zones to specify independent settings for multiple CPUs.
341      */
342     if (acpi_tz_cooling_unit < 0 && acpi_tz_cooling_is_available(sc))
343         sc->tz_cooling_enabled = TRUE;
344     if (sc->tz_cooling_enabled) {
345         error = acpi_tz_cooling_thread_start(sc);
346         if (error != 0) {
347             sc->tz_cooling_enabled = FALSE;
348             goto out;
349         }
350         acpi_tz_cooling_unit = device_get_unit(dev);
351     }
352
353     /*
354      * Flag the event handler for a manual invocation by our timeout.
355      * We defer it like this so that the rest of the subsystem has time
356      * to come up.  Don't bother evaluating/printing the temperature at
357      * this point; on many systems it'll be bogus until the EC is running.
358      */
359     sc->tz_flags |= TZ_FLAG_GETPROFILE;
360
361     /* Attach sensors(9). */
362     strlcpy(sc->sensordev.xname, device_get_nameunit(sc->tz_dev),
363         sizeof(sc->sensordev.xname));
364
365     sc->sensor.type = SENSOR_TEMP;
366     sensor_attach(&sc->sensordev, &sc->sensor);
367
368     sensordev_install(&sc->sensordev);
369
370 out:
371     if (error != 0) {
372         EVENTHANDLER_DEREGISTER(power_profile_change, sc->tz_event);
373         AcpiRemoveNotifyHandler(sc->tz_handle, ACPI_DEVICE_NOTIFY,
374             acpi_tz_notify_handler);
375         sysctl_ctx_free(&sc->tz_sysctl_ctx);
376     }
377     return_VALUE (error);
378 }
379
380 /*
381  * Parse the current state of this thermal zone and set up to use it.
382  *
383  * Note that we may have previous state, which will have to be discarded.
384  */
385 static int
386 acpi_tz_establish(struct acpi_tz_softc *sc)
387 {
388     ACPI_OBJECT *obj;
389     int         i;
390     char        nbuf[8];
391
392     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
393
394     /* Erase any existing state. */
395     for (i = 0; i < TZ_NUMLEVELS; i++)
396         if (sc->tz_zone.al[i].Pointer != NULL)
397             AcpiOsFree(sc->tz_zone.al[i].Pointer);
398     if (sc->tz_zone.psl.Pointer != NULL)
399         AcpiOsFree(sc->tz_zone.psl.Pointer);
400
401     /*
402      * XXX: We initialize only ACPI_BUFFER to avoid race condition
403      * with passive cooling thread which refers psv, tc1, tc2 and tsp.
404      */
405     bzero(sc->tz_zone.ac, sizeof(sc->tz_zone.ac));
406     bzero(sc->tz_zone.al, sizeof(sc->tz_zone.al));
407     bzero(&sc->tz_zone.psl, sizeof(sc->tz_zone.psl));
408
409     /* Evaluate thermal zone parameters. */
410     for (i = 0; i < TZ_NUMLEVELS; i++) {
411         ksprintf(nbuf, "_AC%d", i);
412         acpi_tz_getparam(sc, nbuf, &sc->tz_zone.ac[i]);
413         ksprintf(nbuf, "_AL%d", i);
414         sc->tz_zone.al[i].Length = ACPI_ALLOCATE_BUFFER;
415         sc->tz_zone.al[i].Pointer = NULL;
416         AcpiEvaluateObject(sc->tz_handle, nbuf, NULL, &sc->tz_zone.al[i]);
417         obj = (ACPI_OBJECT *)sc->tz_zone.al[i].Pointer;
418         if (obj != NULL) {
419             /* Should be a package containing a list of power objects */
420             if (obj->Type != ACPI_TYPE_PACKAGE) {
421                 device_printf(sc->tz_dev, "%s has unknown type %d, rejecting\n",
422                               nbuf, obj->Type);
423                 return_VALUE (ENXIO);
424             }
425         }
426     }
427     acpi_tz_getparam(sc, "_CRT", &sc->tz_zone.crt);
428     acpi_tz_getparam(sc, "_HOT", &sc->tz_zone.hot);
429     sc->tz_zone.psl.Length = ACPI_ALLOCATE_BUFFER;
430     sc->tz_zone.psl.Pointer = NULL;
431     AcpiEvaluateObject(sc->tz_handle, "_PSL", NULL, &sc->tz_zone.psl);
432     acpi_tz_getparam(sc, "_PSV", &sc->tz_zone.psv);
433     acpi_tz_getparam(sc, "_TC1", &sc->tz_zone.tc1);
434     acpi_tz_getparam(sc, "_TC2", &sc->tz_zone.tc2);
435     acpi_tz_getparam(sc, "_TSP", &sc->tz_zone.tsp);
436     acpi_tz_getparam(sc, "_TZP", &sc->tz_zone.tzp);
437
438     /*
439      * Sanity-check the values we've been given.
440      *
441      * XXX what do we do about systems that give us the same value for
442      *     more than one of these setpoints?
443      */
444     acpi_tz_sanity(sc, &sc->tz_zone.crt, "_CRT");
445     acpi_tz_sanity(sc, &sc->tz_zone.hot, "_HOT");
446     acpi_tz_sanity(sc, &sc->tz_zone.psv, "_PSV");
447     for (i = 0; i < TZ_NUMLEVELS; i++)
448         acpi_tz_sanity(sc, &sc->tz_zone.ac[i], "_ACx");
449
450     return_VALUE (0);
451 }
452
453 static char *aclevel_string[] = {
454     "NONE", "_AC0", "_AC1", "_AC2", "_AC3", "_AC4",
455     "_AC5", "_AC6", "_AC7", "_AC8", "_AC9"
456 };
457
458 static __inline const char *
459 acpi_tz_aclevel_string(int active)
460 {
461     if (active < -1 || active >= TZ_NUMLEVELS)
462         return (aclevel_string[0]);
463
464     return (aclevel_string[active + 1]);
465 }
466
467 /*
468  * Get the current temperature.
469  */
470 static int
471 acpi_tz_get_temperature(struct acpi_tz_softc *sc)
472 {
473     int         temp;
474     ACPI_STATUS status;
475
476     ACPI_FUNCTION_NAME ("acpi_tz_get_temperature");
477
478     /* Evaluate the thermal zone's _TMP method. */
479     status = acpi_GetInteger(sc->tz_handle, acpi_tz_tmp_name, &temp);
480     if (ACPI_FAILURE(status)) {
481         ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
482             "error fetching current temperature -- %s\n",
483              AcpiFormatException(status));
484         return (FALSE);
485     }
486
487     /* Check it for validity. */
488     acpi_tz_sanity(sc, &temp, acpi_tz_tmp_name);
489     if (temp == -1)
490         return (FALSE);
491
492     ACPI_DEBUG_PRINT((ACPI_DB_VALUES, "got %d.%dC\n", TZ_KELVTOC(temp)));
493     sc->tz_temperature = temp;
494     /* Update sensor */
495     if(sc->tz_temperature == -1)
496         sc->sensor.flags &= ~SENSOR_FINVALID;
497     sc->sensor.value = sc->tz_temperature * 100000 - 50000;
498     return (TRUE);
499 }
500
501 /*
502  * Evaluate the condition of a thermal zone, take appropriate actions.
503  */
504 static void
505 acpi_tz_monitor(void *Context)
506 {
507     struct acpi_tz_softc *sc;
508     struct      timespec curtime;
509     int         temp;
510     int         i;
511     int         newactive, newflags;
512
513     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
514
515     sc = (struct acpi_tz_softc *)Context;
516
517     /* Get the current temperature. */
518     if (!acpi_tz_get_temperature(sc)) {
519         /* XXX disable zone? go to max cooling? */
520         return_VOID;
521     }
522     temp = sc->tz_temperature;
523
524     /*
525      * Work out what we ought to be doing right now.
526      *
527      * Note that the _ACx levels sort from hot to cold.
528      */
529     newactive = TZ_ACTIVE_NONE;
530     for (i = TZ_NUMLEVELS - 1; i >= 0; i--) {
531         if (sc->tz_zone.ac[i] != -1 && temp >= sc->tz_zone.ac[i])
532             newactive = i;
533     }
534
535     /*
536      * We are going to get _ACx level down (colder side), but give a guaranteed
537      * minimum cooling run time if requested.
538      */
539     if (acpi_tz_min_runtime > 0 && sc->tz_active != TZ_ACTIVE_NONE &&
540         sc->tz_active != TZ_ACTIVE_UNKNOWN &&
541         (newactive == TZ_ACTIVE_NONE || newactive > sc->tz_active)) {
542
543         getnanotime(&curtime);
544         timespecsub(&curtime, &sc->tz_cooling_started);
545         if (curtime.tv_sec < acpi_tz_min_runtime)
546             newactive = sc->tz_active;
547     }
548
549     /* Handle user override of active mode */
550     if (sc->tz_requested != TZ_ACTIVE_NONE && (newactive == TZ_ACTIVE_NONE
551         || sc->tz_requested < newactive))
552         newactive = sc->tz_requested;
553
554     /* update temperature-related flags */
555     newflags = TZ_THFLAG_NONE;
556     if (sc->tz_zone.psv != -1 && temp >= sc->tz_zone.psv)
557         newflags |= TZ_THFLAG_PSV;
558     if (sc->tz_zone.hot != -1 && temp >= sc->tz_zone.hot)
559         newflags |= TZ_THFLAG_HOT;
560     if (sc->tz_zone.crt != -1 && temp >= sc->tz_zone.crt)
561         newflags |= TZ_THFLAG_CRT;
562
563     /* If the active cooling state has changed, we have to switch things. */
564     if (sc->tz_active == TZ_ACTIVE_UNKNOWN) {
565         /*
566          * We don't know which cooling device is on or off,
567          * so stop them all, because we now know which
568          * should be on (if any).
569          */
570         for (i = 0; i < TZ_NUMLEVELS; i++) {
571             if (sc->tz_zone.al[i].Pointer != NULL) {
572                 acpi_ForeachPackageObject(
573                     (ACPI_OBJECT *)sc->tz_zone.al[i].Pointer,
574                     acpi_tz_switch_cooler_off, sc);
575             }
576         }
577         /* now we know that all devices are off */
578         sc->tz_active = TZ_ACTIVE_NONE;
579     }
580
581     if (newactive != sc->tz_active) {
582         /* Turn off unneeded cooling devices that are on, if any are */
583         for (i = TZ_ACTIVE_LEVEL(sc->tz_active);
584              i < TZ_ACTIVE_LEVEL(newactive); i++) {
585             acpi_ForeachPackageObject(
586                 (ACPI_OBJECT *)sc->tz_zone.al[i].Pointer,
587                 acpi_tz_switch_cooler_off, sc);
588         }
589         /* Turn on cooling devices that are required, if any are */
590         for (i = TZ_ACTIVE_LEVEL(sc->tz_active) - 1;
591              i >= TZ_ACTIVE_LEVEL(newactive); i--) {
592             acpi_ForeachPackageObject(
593                 (ACPI_OBJECT *)sc->tz_zone.al[i].Pointer,
594                 acpi_tz_switch_cooler_on, sc);
595         }
596
597         ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
598                     "switched from %s to %s: %d.%dC\n",
599                     acpi_tz_aclevel_string(sc->tz_active),
600                     acpi_tz_aclevel_string(newactive), TZ_KELVTOC(temp));
601         sc->tz_active = newactive;
602         getnanotime(&sc->tz_cooling_started);
603     }
604
605     /* XXX (de)activate any passive cooling that may be required. */
606
607     /*
608      * If the temperature is at _HOT or _CRT, increment our event count.
609      * If it has occurred enough times, shutdown the system.  This is
610      * needed because some systems will report an invalid high temperature
611      * for one poll cycle.  It is suspected this is due to the embedded
612      * controller timing out.  A typical value is 138C for one cycle on
613      * a system that is otherwise 65C.
614      *
615      * If we're almost at that threshold, notify the user through devd(8).
616      */
617     if ((newflags & (TZ_THFLAG_HOT | TZ_THFLAG_CRT)) != 0) {
618         sc->tz_validchecks++;
619         if (sc->tz_validchecks == TZ_VALIDCHECKS) {
620             device_printf(sc->tz_dev,
621                 "WARNING - current temperature (%d.%dC) exceeds safe limits\n",
622                 TZ_KELVTOC(sc->tz_temperature));
623             shutdown_nice(RB_POWEROFF);
624         } else if (sc->tz_validchecks == TZ_NOTIFYCOUNT)
625             acpi_UserNotify("Thermal", sc->tz_handle, TZ_NOTIFY_CRITICAL);
626     } else {
627         sc->tz_validchecks = 0;
628     }
629     sc->tz_thflags = newflags;
630
631     return_VOID;
632 }
633
634 /*
635  * Given an object, verify that it's a reference to a device of some sort,
636  * and try to switch it off.
637  */
638 static void
639 acpi_tz_switch_cooler_off(ACPI_OBJECT *obj, void *arg)
640 {
641     ACPI_HANDLE                 cooler;
642
643     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
644
645     cooler = acpi_GetReference(NULL, obj);
646     if (cooler == NULL) {
647         ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "can't get handle\n"));
648         return_VOID;
649     }
650
651     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "called to turn %s off\n",
652                      acpi_name(cooler)));
653     acpi_pwr_switch_consumer(cooler, ACPI_STATE_D3);
654
655     return_VOID;
656 }
657
658 /*
659  * Given an object, verify that it's a reference to a device of some sort,
660  * and try to switch it on.
661  *
662  * XXX replication of off/on function code is bad.
663  */
664 static void
665 acpi_tz_switch_cooler_on(ACPI_OBJECT *obj, void *arg)
666 {
667     struct acpi_tz_softc        *sc = (struct acpi_tz_softc *)arg;
668     ACPI_HANDLE                 cooler;
669     ACPI_STATUS                 status;
670
671     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
672
673     cooler = acpi_GetReference(NULL, obj);
674     if (cooler == NULL) {
675         ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "can't get handle\n"));
676         return_VOID;
677     }
678
679     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "called to turn %s on\n",
680                      acpi_name(cooler)));
681     status = acpi_pwr_switch_consumer(cooler, ACPI_STATE_D0);
682     if (ACPI_FAILURE(status)) {
683         ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
684                     "failed to activate %s - %s\n", acpi_name(cooler),
685                     AcpiFormatException(status));
686     }
687
688     return_VOID;
689 }
690
691 /*
692  * Read/debug-print a parameter, default it to -1.
693  */
694 static void
695 acpi_tz_getparam(struct acpi_tz_softc *sc, char *node, int *data)
696 {
697
698     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
699
700     if (ACPI_FAILURE(acpi_GetInteger(sc->tz_handle, node, data))) {
701         *data = -1;
702     } else {
703         ACPI_DEBUG_PRINT((ACPI_DB_VALUES, "%s.%s = %d\n",
704                          acpi_name(sc->tz_handle), node, *data));
705     }
706
707     return_VOID;
708 }
709
710 /*
711  * Sanity-check a temperature value.  Assume that setpoints
712  * should be between 0C and 200C.
713  */
714 static void
715 acpi_tz_sanity(struct acpi_tz_softc *sc, int *val, char *what)
716 {
717     if (*val != -1 && (*val < TZ_ZEROC || *val > TZ_ZEROC + 2000)) {
718         /*
719          * If the value we are checking is _TMP, warn the user only
720          * once. This avoids spamming messages if, for instance, the
721          * sensor is broken and always returns an invalid temperature.
722          *
723          * This is only done for _TMP; other values always emit a
724          * warning.
725          */
726         if (what != acpi_tz_tmp_name || !sc->tz_insane_tmp_notified) {
727             device_printf(sc->tz_dev, "%s value is absurd, ignored (%d.%dC)\n",
728                           what, TZ_KELVTOC(*val));
729
730             /* Don't warn the user again if the read value doesn't improve. */
731             if (what == acpi_tz_tmp_name)
732                 sc->tz_insane_tmp_notified = 1;
733         }
734         *val = -1;
735         return;
736     }
737
738     /* This value is correct. Warn if it's incorrect again. */
739     if (what == acpi_tz_tmp_name)
740         sc->tz_insane_tmp_notified = 0;
741 }
742
743 /*
744  * Respond to a sysctl on the active state node.
745  */
746 static int
747 acpi_tz_active_sysctl(SYSCTL_HANDLER_ARGS)
748 {
749     struct acpi_tz_softc        *sc;
750     int                         active;
751     int                         error;
752
753     sc = (struct acpi_tz_softc *)oidp->oid_arg1;
754     active = sc->tz_active;
755     error = sysctl_handle_int(oidp, &active, 0, req);
756
757     /* Error or no new value */
758     if (error != 0 || req->newptr == NULL)
759         return (error);
760     if (active < -1 || active >= TZ_NUMLEVELS)
761         return (EINVAL);
762
763     /* Set new preferred level and re-switch */
764     sc->tz_requested = active;
765     acpi_tz_signal(sc, 0);
766     return (0);
767 }
768
769 static int
770 acpi_tz_cooling_sysctl(SYSCTL_HANDLER_ARGS)
771 {
772     struct acpi_tz_softc *sc;
773     int enabled, error;
774
775     sc = (struct acpi_tz_softc *)oidp->oid_arg1;
776     enabled = sc->tz_cooling_enabled;
777     error = sysctl_handle_int(oidp, &enabled, 0, req);
778
779     /* Error or no new value */
780     if (error != 0 || req->newptr == NULL)
781         return (error);
782     if (enabled != TRUE && enabled != FALSE)
783         return (EINVAL);
784
785     if (enabled) {
786         if (acpi_tz_cooling_is_available(sc))
787             error = acpi_tz_cooling_thread_start(sc);
788         else
789             error = ENODEV;
790         if (error)
791             enabled = FALSE;
792     }
793     sc->tz_cooling_enabled = enabled;
794     return (error);
795 }
796
797 static int
798 acpi_tz_temp_sysctl(SYSCTL_HANDLER_ARGS)
799 {
800     struct acpi_tz_softc        *sc;
801     int                         temp, *temp_ptr;
802     int                         error;
803
804     sc = oidp->oid_arg1;
805     temp_ptr = (int *)((uintptr_t)sc + oidp->oid_arg2);
806     temp = *temp_ptr;
807     error = sysctl_handle_int(oidp, &temp, 0, req);
808
809     /* Error or no new value */
810     if (error != 0 || req->newptr == NULL)
811         return (error);
812
813     /* Only allow changing settings if override is set. */
814     if (!acpi_tz_override)
815         return (EPERM);
816
817     /* Check user-supplied value for sanity. */
818     acpi_tz_sanity(sc, &temp, "user-supplied temp");
819     if (temp == -1)
820         return (EINVAL);
821
822     *temp_ptr = temp;
823     return (0);
824 }
825
826 static int
827 acpi_tz_passive_sysctl(SYSCTL_HANDLER_ARGS)
828 {
829     struct acpi_tz_softc        *sc;
830     int                         val, *val_ptr;
831     int                         error;
832
833     sc = oidp->oid_arg1;
834     val_ptr = (int *)((uintptr_t)sc + oidp->oid_arg2);
835     val = *val_ptr;
836     error = sysctl_handle_int(oidp, &val, 0, req);
837
838     /* Error or no new value */
839     if (error != 0 || req->newptr == NULL)
840         return (error);
841
842     /* Only allow changing settings if override is set. */
843     if (!acpi_tz_override)
844         return (EPERM);
845
846     *val_ptr = val;
847     return (0);
848 }
849
850 static void
851 acpi_tz_notify_handler(ACPI_HANDLE h, UINT32 notify, void *context)
852 {
853     struct acpi_tz_softc        *sc = (struct acpi_tz_softc *)context;
854
855     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
856
857     switch (notify) {
858     case TZ_NOTIFY_TEMPERATURE:
859         /* Temperature change occurred */
860         acpi_tz_signal(sc, 0);
861         break;
862     case TZ_NOTIFY_DEVICES:
863     case TZ_NOTIFY_LEVELS:
864         /* Zone devices/setpoints changed */
865         acpi_tz_signal(sc, TZ_FLAG_GETSETTINGS);
866         break;
867     default:
868         ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
869                     "unknown Notify event 0x%x\n", notify);
870         break;
871     }
872
873     acpi_UserNotify("Thermal", h, notify);
874
875     return_VOID;
876 }
877
878 static void
879 acpi_tz_signal(struct acpi_tz_softc *sc, int flags)
880 {
881     ACPI_LOCK(thermal);
882     sc->tz_flags |= flags;
883     ACPI_UNLOCK(thermal);
884     wakeup(&acpi_tz_td);
885 }
886
887 /*
888  * Notifies can be generated asynchronously but have also been seen to be
889  * triggered by other thermal methods.  One system generates a notify of
890  * 0x81 when the fan is turned on or off.  Another generates it when _SCP
891  * is called.  To handle these situations, we check the zone via
892  * acpi_tz_monitor() before evaluating changes to setpoints or the cooling
893  * policy.
894  */
895 static void
896 acpi_tz_timeout(struct acpi_tz_softc *sc, int flags)
897 {
898
899     /* Check the current temperature and take action based on it */
900     acpi_tz_monitor(sc);
901
902     /* If requested, get the power profile settings. */
903     if (flags & TZ_FLAG_GETPROFILE)
904         acpi_tz_power_profile(sc);
905
906     /*
907      * If requested, check for new devices/setpoints.  After finding them,
908      * check if we need to switch fans based on the new values.
909      */
910     if (flags & TZ_FLAG_GETSETTINGS) {
911         acpi_tz_establish(sc);
912         acpi_tz_monitor(sc);
913     }
914
915     /* XXX passive cooling actions? */
916 }
917
918 /*
919  * System power profile may have changed; fetch and notify the
920  * thermal zone accordingly.
921  *
922  * Since this can be called from an arbitrary eventhandler, it needs
923  * to get the ACPI lock itself.
924  */
925 static void
926 acpi_tz_power_profile(void *arg)
927 {
928     ACPI_STATUS                 status;
929     struct acpi_tz_softc        *sc = (struct acpi_tz_softc *)arg;
930     int                         state;
931
932     state = power_profile_get_state();
933     if (state != POWER_PROFILE_PERFORMANCE && state != POWER_PROFILE_ECONOMY)
934         return;
935
936     /* check that we haven't decided there's no _SCP method */
937     if ((sc->tz_flags & TZ_FLAG_NO_SCP) == 0) {
938
939         /* Call _SCP to set the new profile */
940         status = acpi_SetInteger(sc->tz_handle, "_SCP",
941             (state == POWER_PROFILE_PERFORMANCE) ? 0 : 1);
942         if (ACPI_FAILURE(status)) {
943             if (status != AE_NOT_FOUND)
944                 ACPI_VPRINT(sc->tz_dev,
945                             acpi_device_get_parent_softc(sc->tz_dev),
946                             "can't evaluate %s._SCP - %s\n",
947                             acpi_name(sc->tz_handle),
948                             AcpiFormatException(status));
949             sc->tz_flags |= TZ_FLAG_NO_SCP;
950         } else {
951             /* We have to re-evaluate the entire zone now */
952             acpi_tz_signal(sc, TZ_FLAG_GETSETTINGS);
953         }
954     }
955 }
956
957 /*
958  * Thermal zone monitor thread.
959  */
960 static void
961 acpi_tz_thread(void *arg)
962 {
963     device_t    *devs;
964     int         devcount, i;
965     int         flags;
966     struct acpi_tz_softc **sc;
967
968     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
969
970     devs = NULL;
971     devcount = 0;
972     sc = NULL;
973     get_mplock();
974
975     for (;;) {
976         /* If the number of devices has changed, re-evaluate. */
977         if (devclass_get_count(acpi_tz_devclass) != devcount) {
978             if (devs != NULL) {
979                 kfree(devs, M_TEMP);
980                 kfree(sc, M_TEMP);
981             }
982             devclass_get_devices(acpi_tz_devclass, &devs, &devcount);
983             sc = kmalloc(sizeof(struct acpi_tz_softc *) * devcount, M_TEMP,
984                         M_WAITOK | M_ZERO);
985             for (i = 0; i < devcount; i++)
986                 sc[i] = device_get_softc(devs[i]);
987         }
988
989         /* Check for temperature events and act on them. */
990         for (i = 0; i < devcount; i++) {
991             ACPI_LOCK(thermal);
992             flags = sc[i]->tz_flags;
993             sc[i]->tz_flags &= TZ_FLAG_NO_SCP;
994             ACPI_UNLOCK(thermal);
995             acpi_tz_timeout(sc[i], flags);
996         }
997
998         /* If more work to do, don't go to sleep yet. */
999         ACPI_LOCK(thermal);
1000         for (i = 0; i < devcount; i++) {
1001             if (sc[i]->tz_flags & ~TZ_FLAG_NO_SCP)
1002                 break;
1003         }
1004
1005         /*
1006          * Interlocked sleep until signaled or we timeout.
1007          */
1008         if (i == devcount) {
1009             tsleep_interlock(&acpi_tz_td, 0);
1010             ACPI_UNLOCK(thermal);
1011             tsleep(&acpi_tz_td, 0, "tzpoll", hz * acpi_tz_polling_rate);
1012         } else {
1013             ACPI_UNLOCK(thermal);
1014         }
1015     }
1016     rel_mplock();
1017 }
1018
1019 #ifdef __FreeBSD__
1020 static int
1021 acpi_tz_cpufreq_restore(struct acpi_tz_softc *sc)
1022 {
1023     device_t dev;
1024     int error;
1025
1026     if (!sc->tz_cooling_updated)
1027         return (0);
1028     if ((dev = devclass_get_device(devclass_find("cpufreq"), 0)) == NULL)
1029         return (ENXIO);
1030     ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
1031         "temperature %d.%dC: resuming previous clock speed (%d MHz)\n",
1032         TZ_KELVTOC(sc->tz_temperature), sc->tz_cooling_saved_freq);
1033     error = CPUFREQ_SET(dev, NULL, CPUFREQ_PRIO_KERN);
1034     if (error == 0)
1035         sc->tz_cooling_updated = FALSE;
1036     return (error);
1037 }
1038
1039 static int
1040 acpi_tz_cpufreq_update(struct acpi_tz_softc *sc, int req)
1041 {
1042     device_t dev;
1043     struct cf_level *levels;
1044     int num_levels, error, freq, desired_freq, perf, i;
1045
1046     levels = kmalloc(CPUFREQ_MAX_LEVELS * sizeof(*levels), M_TEMP, M_NOWAIT);
1047     if (levels == NULL)
1048         return (ENOMEM);
1049
1050     /*
1051      * Find the main device, cpufreq0.  We don't yet support independent
1052      * CPU frequency control on SMP.
1053      */
1054     if ((dev = devclass_get_device(devclass_find("cpufreq"), 0)) == NULL) {
1055         error = ENXIO;
1056         goto out;
1057     }
1058
1059     /* Get the current frequency. */
1060     error = CPUFREQ_GET(dev, &levels[0]);
1061     if (error)
1062         goto out;
1063     freq = levels[0].total_set.freq;
1064
1065     /* Get the current available frequency levels. */
1066     num_levels = CPUFREQ_MAX_LEVELS;
1067     error = CPUFREQ_LEVELS(dev, levels, &num_levels);
1068     if (error) {
1069         if (error == E2BIG)
1070             printf("cpufreq: need to increase CPUFREQ_MAX_LEVELS\n");
1071         goto out;
1072     }
1073
1074     /* Calculate the desired frequency as a percent of the max frequency. */
1075     perf = 100 * freq / levels[0].total_set.freq - req;
1076     if (perf < 0)
1077         perf = 0;
1078     else if (perf > 100)
1079         perf = 100;
1080     desired_freq = levels[0].total_set.freq * perf / 100;
1081
1082     if (desired_freq < freq) {
1083         /* Find the closest available frequency, rounding down. */
1084         for (i = 0; i < num_levels; i++)
1085             if (levels[i].total_set.freq <= desired_freq)
1086                 break;
1087
1088         /* If we didn't find a relevant setting, use the lowest. */
1089         if (i == num_levels)
1090             i--;
1091     } else {
1092         /* If we didn't decrease frequency yet, don't increase it. */
1093         if (!sc->tz_cooling_updated) {
1094             sc->tz_cooling_active = FALSE;
1095             goto out;
1096         }
1097
1098         /* Use saved cpu frequency as maximum value. */
1099         if (desired_freq > sc->tz_cooling_saved_freq)
1100             desired_freq = sc->tz_cooling_saved_freq;
1101
1102         /* Find the closest available frequency, rounding up. */
1103         for (i = num_levels - 1; i >= 0; i--)
1104             if (levels[i].total_set.freq >= desired_freq)
1105                 break;
1106
1107         /* If we didn't find a relevant setting, use the highest. */
1108         if (i == -1)
1109             i++;
1110
1111         /* If we're going to the highest frequency, restore the old setting. */
1112         if (i == 0 || desired_freq == sc->tz_cooling_saved_freq) {
1113             error = acpi_tz_cpufreq_restore(sc);
1114             if (error == 0)
1115                 sc->tz_cooling_active = FALSE;
1116             goto out;
1117         }
1118     }
1119
1120     /* If we are going to a new frequency, activate it. */
1121     if (levels[i].total_set.freq != freq) {
1122         ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
1123             "temperature %d.%dC: %screasing clock speed "
1124             "from %d MHz to %d MHz\n",
1125             TZ_KELVTOC(sc->tz_temperature),
1126             (freq > levels[i].total_set.freq) ? "de" : "in",
1127             freq, levels[i].total_set.freq);
1128         error = CPUFREQ_SET(dev, &levels[i], CPUFREQ_PRIO_KERN);
1129         if (error == 0 && !sc->tz_cooling_updated) {
1130             sc->tz_cooling_saved_freq = freq;
1131             sc->tz_cooling_updated = TRUE;
1132         }
1133     }
1134
1135 out:
1136     if (levels)
1137         free(levels, M_TEMP);
1138     return (error);
1139 }
1140 #endif
1141
1142 /*
1143  * Passive cooling thread; monitors current temperature according to the
1144  * cooling interval and calculates whether to scale back CPU frequency.
1145  */
1146 static void
1147 acpi_tz_cooling_thread(void *arg)
1148 {
1149     struct acpi_tz_softc *sc;
1150     int perf, curr_temp, prev_temp;
1151 #ifdef __FreeBSD__
1152     int error;
1153 #endif
1154
1155     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1156
1157     sc = (struct acpi_tz_softc *)arg;
1158     get_mplock();
1159
1160     prev_temp = sc->tz_temperature;
1161     while (sc->tz_cooling_enabled) {
1162         if (sc->tz_cooling_active)
1163             (void)acpi_tz_get_temperature(sc);
1164         curr_temp = sc->tz_temperature;
1165         if (curr_temp >= sc->tz_zone.psv)
1166             sc->tz_cooling_active = TRUE;
1167         if (sc->tz_cooling_active) {
1168             perf = sc->tz_zone.tc1 * (curr_temp - prev_temp) +
1169                    sc->tz_zone.tc2 * (curr_temp - sc->tz_zone.psv);
1170             perf /= 10;
1171
1172             if (perf != 0) {
1173 #ifdef __FreeBSD__
1174                 error = acpi_tz_cpufreq_update(sc, perf);
1175
1176                 /*
1177                  * If error and not simply a higher priority setting was
1178                  * active, disable cooling.
1179                  */
1180                 if (error != 0 && error != EPERM) {
1181                     device_printf(sc->tz_dev,
1182                         "failed to set new freq, disabling passive cooling\n");
1183                     sc->tz_cooling_enabled = FALSE;
1184                 }
1185 #endif
1186             }
1187         }
1188         prev_temp = curr_temp;
1189         tsleep(&sc->tz_cooling_proc, 0, "cooling",
1190             hz * sc->tz_zone.tsp / 10);
1191     }
1192     if (sc->tz_cooling_active) {
1193 #ifdef __FreeBSD__
1194         acpi_tz_cpufreq_restore(sc);
1195 #endif
1196         sc->tz_cooling_active = FALSE;
1197     }
1198     sc->tz_cooling_proc = NULL;
1199     ACPI_LOCK(thermal);
1200     sc->tz_cooling_proc_running = FALSE;
1201     ACPI_UNLOCK(thermal);
1202     rel_mplock();
1203 }
1204
1205 /*
1206  * TODO: We ignore _PSL (list of cooling devices) since cpufreq enumerates
1207  * all CPUs for us.  However, it's possible in the future _PSL will
1208  * reference non-CPU devices so we may want to support it then.
1209  */
1210 static int
1211 acpi_tz_cooling_is_available(struct acpi_tz_softc *sc)
1212 {
1213     return (sc->tz_zone.tc1 != -1 && sc->tz_zone.tc2 != -1 &&
1214         sc->tz_zone.tsp != -1 && sc->tz_zone.tsp != 0 &&
1215         sc->tz_zone.psv != -1);
1216 }
1217
1218 static int
1219 acpi_tz_cooling_thread_start(struct acpi_tz_softc *sc)
1220 {
1221     int error;
1222
1223     ACPI_LOCK(thermal);
1224     if (sc->tz_cooling_proc_running) {
1225         ACPI_UNLOCK(thermal);
1226         return (0);
1227     }
1228     sc->tz_cooling_proc_running = TRUE;
1229     ACPI_UNLOCK(thermal);
1230     error = 0;
1231     if (sc->tz_cooling_proc == NULL) {
1232         error = kthread_create(acpi_tz_cooling_thread, sc,
1233             &sc->tz_cooling_proc,
1234             "acpi_cooling%d", device_get_unit(sc->tz_dev));
1235         if (error != 0) {
1236             device_printf(sc->tz_dev, "could not create thread - %d", error);
1237             ACPI_LOCK(thermal);
1238             sc->tz_cooling_proc_running = FALSE;
1239             ACPI_UNLOCK(thermal);
1240         }
1241     }
1242     return (error);
1243 }