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