Merge from vendor branch DIFFUTILS:
[dragonfly.git] / sys / dev / acpica5 / 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: src/sys/dev/acpica/acpi_thermal.c,v 1.37 2004/02/03 04:18:56 njl Exp $
28  * $DragonFly: src/sys/dev/acpica5/acpi_thermal.c,v 1.1 2004/02/21 06:48:08 dillon Exp $
29  */
30
31 #include "opt_acpi.h"
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/kthread.h>
35 #include <sys/bus.h>
36 #include <sys/proc.h>
37 #include <sys/reboot.h>
38 #include <sys/sysctl.h>
39 #include <sys/unistd.h>
40 #include <sys/power.h>
41
42 #include "acpi.h"
43 #include <dev/acpica5/acpivar.h>
44
45 /* Hooks for the ACPI CA debugging infrastructure */
46 #define _COMPONENT      ACPI_THERMAL
47 ACPI_MODULE_NAME("THERMAL")
48
49 #define TZ_ZEROC        2732
50 #define TZ_KELVTOC(x)   (((x) - TZ_ZEROC) / 10), (((x) - TZ_ZEROC) % 10)
51
52 #define TZ_NOTIFY_TEMPERATURE   0x80 /* Temperature changed. */
53 #define TZ_NOTIFY_LEVELS        0x81 /* Cooling levels changed. */
54 #define TZ_NOTIFY_DEVICES       0x82 /* Device lists changed. */
55 #define TZ_NOTIFY_CRITICAL      0xcc /* Fake notify that _CRT/_HOT reached. */
56
57 /* Check for temperature changes every 10 seconds by default */
58 #define TZ_POLLRATE     10
59
60 /* Make sure the reported temperature is valid for this number of polls. */
61 #define TZ_VALIDCHECKS  3
62
63 /* Notify the user we will be shutting down in one more poll cycle. */
64 #define TZ_NOTIFYCOUNT  (TZ_VALIDCHECKS - 1)
65
66 /* ACPI spec defines this */
67 #define TZ_NUMLEVELS    10
68 struct acpi_tz_zone {
69     int         ac[TZ_NUMLEVELS];
70     ACPI_BUFFER al[TZ_NUMLEVELS];
71     int         crt;
72     int         hot;
73     ACPI_BUFFER psl;
74     int         psv;
75     int         tc1;
76     int         tc2;
77     int         tsp;
78     int         tzp;
79 };
80
81 struct acpi_tz_softc {
82     device_t                    tz_dev;
83     ACPI_HANDLE                 tz_handle;      /*Thermal zone handle*/
84     int                         tz_temperature; /*Current temperature*/
85     int                         tz_active;      /*Current active cooling*/
86 #define TZ_ACTIVE_NONE          -1
87     int                         tz_requested;   /*Minimum active cooling*/
88     int                         tz_thflags;     /*Current temp-related flags*/
89 #define TZ_THFLAG_NONE          0
90 #define TZ_THFLAG_PSV           (1<<0)
91 #define TZ_THFLAG_HOT           (1<<2)
92 #define TZ_THFLAG_CRT           (1<<3)    
93     int                         tz_flags;
94 #define TZ_FLAG_NO_SCP          (1<<0)          /*No _SCP method*/
95 #define TZ_FLAG_GETPROFILE      (1<<1)          /*Get power_profile in timeout*/
96     struct timespec             tz_cooling_started;
97                                         /*Current cooling starting time*/
98
99     struct sysctl_ctx_list      tz_sysctl_ctx;
100     struct sysctl_oid           *tz_sysctl_tree;
101     
102     struct acpi_tz_zone         tz_zone;        /*Thermal zone parameters*/
103     int                         tz_tmp_updating;
104     int                         tz_validchecks;
105 };
106
107 static int      acpi_tz_probe(device_t dev);
108 static int      acpi_tz_attach(device_t dev);
109 static int      acpi_tz_establish(struct acpi_tz_softc *sc);
110 static void     acpi_tz_monitor(void *Context);
111 static void     acpi_tz_all_off(struct acpi_tz_softc *sc);
112 static void     acpi_tz_switch_cooler_off(ACPI_OBJECT *obj, void *arg);
113 static void     acpi_tz_switch_cooler_on(ACPI_OBJECT *obj, void *arg);
114 static void     acpi_tz_getparam(struct acpi_tz_softc *sc, char *node,
115                                  int *data);
116 static void     acpi_tz_sanity(struct acpi_tz_softc *sc, int *val, char *what);
117 static int      acpi_tz_active_sysctl(SYSCTL_HANDLER_ARGS);
118 static void     acpi_tz_notify_handler(ACPI_HANDLE h, UINT32 notify,
119                                        void *context);
120 static void     acpi_tz_timeout(struct acpi_tz_softc *sc);
121 static void     acpi_tz_power_profile(void *arg);
122 static void     acpi_tz_thread(void *arg);
123
124 static device_method_t acpi_tz_methods[] = {
125     /* Device interface */
126     DEVMETHOD(device_probe,     acpi_tz_probe),
127     DEVMETHOD(device_attach,    acpi_tz_attach),
128
129     {0, 0}
130 };
131
132 static driver_t acpi_tz_driver = {
133     "acpi_tz",
134     acpi_tz_methods,
135     sizeof(struct acpi_tz_softc),
136 };
137
138 static devclass_t acpi_tz_devclass;
139 DRIVER_MODULE(acpi_tz, acpi, acpi_tz_driver, acpi_tz_devclass, 0, 0);
140
141 static struct sysctl_ctx_list   acpi_tz_sysctl_ctx;
142 static struct sysctl_oid        *acpi_tz_sysctl_tree;
143
144 /* Minimum cooling run time */
145 static int                      acpi_tz_min_runtime = 0;
146 static int                      acpi_tz_polling_rate = TZ_POLLRATE;
147
148 /* Timezone polling thread */
149 static struct thread            *acpi_tz_td;
150
151 /*
152  * Match an ACPI thermal zone.
153  */
154 static int
155 acpi_tz_probe(device_t dev)
156 {
157     int         result;
158     ACPI_LOCK_DECL;
159     
160     ACPI_LOCK;
161     
162     /* No FUNCTION_TRACE - too noisy */
163
164     if (acpi_get_type(dev) == ACPI_TYPE_THERMAL && !acpi_disabled("thermal")) {
165         device_set_desc(dev, "Thermal Zone");
166         result = -10;
167     } else {
168         result = ENXIO;
169     }
170     ACPI_UNLOCK;
171     return (result);
172 }
173
174 /*
175  * Attach to an ACPI thermal zone.
176  */
177 static int
178 acpi_tz_attach(device_t dev)
179 {
180     struct acpi_tz_softc        *sc;
181     struct acpi_softc           *acpi_sc;
182     int                         error;
183     char                        oidname[8];
184     ACPI_LOCK_DECL;
185
186     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
187
188     ACPI_LOCK;
189
190     sc = device_get_softc(dev);
191     sc->tz_dev = dev;
192     sc->tz_handle = acpi_get_handle(dev);
193     sc->tz_requested = TZ_ACTIVE_NONE;
194     sc->tz_tmp_updating = 0;
195
196     /*
197      * Parse the current state of the thermal zone and build control
198      * structures.
199      */
200     if ((error = acpi_tz_establish(sc)) != 0)
201         goto out;
202     
203     /*
204      * Register for any Notify events sent to this zone.
205      */
206     AcpiInstallNotifyHandler(sc->tz_handle, ACPI_DEVICE_NOTIFY, 
207                              acpi_tz_notify_handler, sc);
208
209     /*
210      * Create our sysctl nodes.
211      *
212      * XXX we need a mechanism for adding nodes under ACPI.
213      */
214     if (device_get_unit(dev) == 0) {
215         acpi_sc = acpi_device_get_parent_softc(dev);
216         sysctl_ctx_init(&acpi_tz_sysctl_ctx);
217         acpi_tz_sysctl_tree = SYSCTL_ADD_NODE(&acpi_tz_sysctl_ctx,
218                               SYSCTL_CHILDREN(acpi_sc->acpi_sysctl_tree),
219                               OID_AUTO, "thermal", CTLFLAG_RD, 0, "");
220         SYSCTL_ADD_INT(&acpi_tz_sysctl_ctx,
221                        SYSCTL_CHILDREN(acpi_tz_sysctl_tree),
222                        OID_AUTO, "min_runtime", CTLFLAG_RD | CTLFLAG_RW,
223                        &acpi_tz_min_runtime, 0,
224                        "minimum cooling run time in sec");
225         SYSCTL_ADD_INT(&acpi_tz_sysctl_ctx,
226                        SYSCTL_CHILDREN(acpi_tz_sysctl_tree),
227                        OID_AUTO, "polling_rate", CTLFLAG_RD | CTLFLAG_RW,
228                        &acpi_tz_polling_rate, 0, "monitor polling rate");
229     }
230     sysctl_ctx_init(&sc->tz_sysctl_ctx);
231     sprintf(oidname, "tz%d", device_get_unit(dev));
232     sc->tz_sysctl_tree = SYSCTL_ADD_NODE(&sc->tz_sysctl_ctx,
233                                          SYSCTL_CHILDREN(acpi_tz_sysctl_tree),
234                                          OID_AUTO, oidname, CTLFLAG_RD, 0, "");
235     SYSCTL_ADD_INT(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
236                    OID_AUTO, "temperature", CTLFLAG_RD,
237                    &sc->tz_temperature, 0, "current thermal zone temperature");
238     SYSCTL_ADD_PROC(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
239                     OID_AUTO, "active", CTLTYPE_INT | CTLFLAG_RW,
240                     sc, 0, acpi_tz_active_sysctl, "I", "");
241     
242     SYSCTL_ADD_INT(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
243                    OID_AUTO, "thermal_flags", CTLFLAG_RD,
244                    &sc->tz_thflags, 0, "thermal zone flags");
245     SYSCTL_ADD_INT(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
246                    OID_AUTO, "_PSV", CTLFLAG_RD,
247                    &sc->tz_zone.psv, 0, "");
248     SYSCTL_ADD_INT(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
249                    OID_AUTO, "_HOT", CTLFLAG_RD,
250                    &sc->tz_zone.hot, 0, "");
251     SYSCTL_ADD_INT(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
252                    OID_AUTO, "_CRT", CTLFLAG_RD,
253                    &sc->tz_zone.crt, 0, "");
254     SYSCTL_ADD_OPAQUE(&sc->tz_sysctl_ctx, SYSCTL_CHILDREN(sc->tz_sysctl_tree),
255                       OID_AUTO, "_ACx", CTLFLAG_RD, &sc->tz_zone.ac,
256                       sizeof(sc->tz_zone.ac), "I", "");
257
258     /*
259      * Register our power profile event handler, and flag it for a manual
260      * invocation by our timeout.  We defer it like this so that the rest
261      * of the subsystem has time to come up.
262      */
263     EVENTHANDLER_REGISTER(power_profile_change, acpi_tz_power_profile, sc, 0);
264     sc->tz_flags |= TZ_FLAG_GETPROFILE;
265
266     /*
267      * Don't bother evaluating/printing the temperature at this point;
268      * on many systems it'll be bogus until the EC is running.
269      */
270
271     /*
272      * Create our thread; we only need one, it will service all of the
273      * thermal zones.
274      */
275     if (acpi_tz_td == NULL) {
276             error = kthread_create(acpi_tz_thread, NULL, &acpi_tz_td,
277                                    RFHIGHPID, 0, "acpi_thermal");
278             if (error != 0) {
279                     device_printf(sc->tz_dev, "could not create thread - %d",
280                                   error);
281                     goto out;
282             }
283     }
284         
285  out:
286     ACPI_UNLOCK;
287
288     return_VALUE (error);
289 }
290
291 /*
292  * Parse the current state of this thermal zone and set up to use it.
293  *
294  * Note that we may have previous state, which will have to be discarded.
295  */
296 static int
297 acpi_tz_establish(struct acpi_tz_softc *sc)
298 {
299     ACPI_OBJECT *obj;
300     int         i;
301     char        nbuf[8];
302     
303     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
304
305     ACPI_ASSERTLOCK;
306
307     /* Power everything off and erase any existing state. */
308     acpi_tz_all_off(sc);
309     for (i = 0; i < TZ_NUMLEVELS; i++)
310         if (sc->tz_zone.al[i].Pointer != NULL)
311             AcpiOsFree(sc->tz_zone.al[i].Pointer);
312     if (sc->tz_zone.psl.Pointer != NULL)
313         AcpiOsFree(sc->tz_zone.psl.Pointer);
314     bzero(&sc->tz_zone, sizeof(sc->tz_zone));
315
316     /* Evaluate thermal zone parameters. */
317     for (i = 0; i < TZ_NUMLEVELS; i++) {
318         sprintf(nbuf, "_AC%d", i);
319         acpi_tz_getparam(sc, nbuf, &sc->tz_zone.ac[i]);
320         sprintf(nbuf, "_AL%d", i);
321         sc->tz_zone.al[i].Length = ACPI_ALLOCATE_BUFFER;
322         sc->tz_zone.al[i].Pointer = NULL;
323         AcpiEvaluateObject(sc->tz_handle, nbuf, NULL, &sc->tz_zone.al[i]);
324         obj = (ACPI_OBJECT *)sc->tz_zone.al[i].Pointer;
325         if (obj != NULL) {
326             /* Should be a package containing a list of power objects */
327             if (obj->Type != ACPI_TYPE_PACKAGE) {
328                 device_printf(sc->tz_dev, "%s has unknown type %d, rejecting\n",
329                               nbuf, obj->Type);
330                 return_VALUE (ENXIO);
331             }
332         }
333     }
334     acpi_tz_getparam(sc, "_CRT", &sc->tz_zone.crt);
335     acpi_tz_getparam(sc, "_HOT", &sc->tz_zone.hot);
336     sc->tz_zone.psl.Length = ACPI_ALLOCATE_BUFFER;
337     sc->tz_zone.psl.Pointer = NULL;
338     AcpiEvaluateObject(sc->tz_handle, "_PSL", NULL, &sc->tz_zone.psl);
339     acpi_tz_getparam(sc, "_PSV", &sc->tz_zone.psv);
340     acpi_tz_getparam(sc, "_TC1", &sc->tz_zone.tc1);
341     acpi_tz_getparam(sc, "_TC2", &sc->tz_zone.tc2);
342     acpi_tz_getparam(sc, "_TSP", &sc->tz_zone.tsp);
343     acpi_tz_getparam(sc, "_TZP", &sc->tz_zone.tzp);
344
345     /*
346      * Sanity-check the values we've been given.
347      *
348      * XXX what do we do about systems that give us the same value for
349      *     more than one of these setpoints?
350      */
351     acpi_tz_sanity(sc, &sc->tz_zone.crt, "_CRT");
352     acpi_tz_sanity(sc, &sc->tz_zone.hot, "_HOT");
353     acpi_tz_sanity(sc, &sc->tz_zone.psv, "_PSV");
354     for (i = 0; i < TZ_NUMLEVELS; i++)
355         acpi_tz_sanity(sc, &sc->tz_zone.ac[i], "_ACx");
356
357     /*
358      * Power off everything that we've just been given.
359      */
360     acpi_tz_all_off(sc);
361
362     return_VALUE (0);
363 }
364
365 static char     *aclevel_string[] =     {
366         "NONE", "_AC0", "_AC1", "_AC2", "_AC3", "_AC4",
367         "_AC5", "_AC6", "_AC7", "_AC8", "_AC9" };
368
369 static __inline const char *
370 acpi_tz_aclevel_string(int active)
371 {
372         if (active < -1 || active >= TZ_NUMLEVELS)
373                 return (aclevel_string[0]);
374
375         return (aclevel_string[active+1]);
376 }
377
378 /*
379  * Evaluate the condition of a thermal zone, take appropriate actions.
380  */
381 static void
382 acpi_tz_monitor(void *Context)
383 {
384     struct acpi_tz_softc *sc;
385     struct      timespec curtime;
386     int         temp;
387     int         i;
388     int         newactive, newflags;
389     ACPI_STATUS status;
390
391     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
392
393     ACPI_ASSERTLOCK;
394
395     sc = (struct acpi_tz_softc *)Context;
396     if (sc->tz_tmp_updating)
397         goto out;
398     sc->tz_tmp_updating = 1;
399
400     /* Get the current temperature. */
401     status = acpi_EvaluateInteger(sc->tz_handle, "_TMP", &temp);
402     if (ACPI_FAILURE(status)) {
403         ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
404             "error fetching current temperature -- %s\n",
405              AcpiFormatException(status));
406         /* XXX disable zone? go to max cooling? */
407         goto out;
408     }
409
410     ACPI_DEBUG_PRINT((ACPI_DB_VALUES, "got %d.%dC\n", TZ_KELVTOC(temp)));
411     sc->tz_temperature = temp;
412
413     /*
414      * Work out what we ought to be doing right now.
415      *
416      * Note that the _ACx levels sort from hot to cold.
417      */
418     newactive = TZ_ACTIVE_NONE;
419     for (i = TZ_NUMLEVELS - 1; i >= 0; i--) {
420         if ((sc->tz_zone.ac[i] != -1) && (temp >= sc->tz_zone.ac[i])) {
421             newactive = i;
422             if (sc->tz_active != newactive) {
423                 ACPI_VPRINT(sc->tz_dev,
424                             acpi_device_get_parent_softc(sc->tz_dev),
425                             "_AC%d: temperature %d.%d >= setpoint %d.%d\n", i,
426                             TZ_KELVTOC(temp), TZ_KELVTOC(sc->tz_zone.ac[i]));
427                 getnanotime(&sc->tz_cooling_started);
428             }
429         }
430     }
431
432     /*
433      * We are going to get _ACx level down (colder side), but give a guaranteed
434      * minimum cooling run time if requested.
435      */
436     if (acpi_tz_min_runtime > 0 && sc->tz_active != TZ_ACTIVE_NONE &&
437         (newactive == TZ_ACTIVE_NONE || newactive > sc->tz_active)) {
438
439         getnanotime(&curtime);
440         timespecsub(&curtime, &sc->tz_cooling_started);
441         if (curtime.tv_sec < acpi_tz_min_runtime)
442             newactive = sc->tz_active;
443     }
444
445     /* Handle user override of active mode */
446     if (sc->tz_requested > newactive)
447         newactive = sc->tz_requested;
448
449     /* update temperature-related flags */
450     newflags = TZ_THFLAG_NONE;
451     if (sc->tz_zone.psv != -1 && temp >= sc->tz_zone.psv)
452         newflags |= TZ_THFLAG_PSV;
453     if (sc->tz_zone.hot != -1 && temp >= sc->tz_zone.hot)
454         newflags |= TZ_THFLAG_HOT;
455     if (sc->tz_zone.crt != -1 && temp >= sc->tz_zone.crt)
456         newflags |= TZ_THFLAG_CRT;
457
458     /* If the active cooling state has changed, we have to switch things. */
459     if (newactive != sc->tz_active) {
460         /* Turn off the cooling devices that are on, if any are */
461         if (sc->tz_active != TZ_ACTIVE_NONE)
462             acpi_ForeachPackageObject(
463                 (ACPI_OBJECT *)sc->tz_zone.al[sc->tz_active].Pointer,
464                 acpi_tz_switch_cooler_off, sc);
465
466         /* Turn on cooling devices that are required, if any are */
467         if (newactive != TZ_ACTIVE_NONE) {
468             acpi_ForeachPackageObject(
469                 (ACPI_OBJECT *)sc->tz_zone.al[newactive].Pointer,
470                 acpi_tz_switch_cooler_on, sc);
471         }
472         ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
473                     "switched from %s to %s: %d.%dC\n",
474                     acpi_tz_aclevel_string(sc->tz_active),
475                     acpi_tz_aclevel_string(newactive), TZ_KELVTOC(temp));
476         sc->tz_active = newactive;
477     }
478
479     /* XXX (de)activate any passive cooling that may be required. */
480
481     /*
482      * If the temperature is at _HOT or _CRT, increment our event count.
483      * If it has occurred enough times, shutdown the system.  This is
484      * needed because some systems will report an invalid high temperature
485      * for one poll cycle.  It is suspected this is due to the embedded
486      * controller timing out.  A typical value is 138C for one cycle on
487      * a system that is otherwise 65C.
488      *
489      * If we're almost at that threshold, notify the user through devd(8).
490      */
491     if ((newflags & (TZ_THFLAG_HOT | TZ_THFLAG_CRT)) != 0) {
492         sc->tz_validchecks++;
493         if (sc->tz_validchecks == TZ_VALIDCHECKS) {
494             device_printf(sc->tz_dev,
495                 "WARNING - current temperature (%d.%dC) exceeds safe limits\n",
496                 TZ_KELVTOC(sc->tz_temperature));
497             shutdown_nice(RB_POWEROFF);
498         } else if (sc->tz_validchecks == TZ_NOTIFYCOUNT)
499             acpi_UserNotify("Thermal", sc->tz_handle, TZ_NOTIFY_CRITICAL);
500     } else {
501         sc->tz_validchecks = 0;
502     }
503     sc->tz_thflags = newflags;
504
505 out:
506     sc->tz_tmp_updating = 0;
507     return_VOID;
508 }
509
510 /*
511  * Turn off all the cooling devices.
512  */
513 static void
514 acpi_tz_all_off(struct acpi_tz_softc *sc)
515 {
516     int         i;
517
518     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
519
520     ACPI_ASSERTLOCK;
521     
522     /* Scan all the _ALx objects and turn them all off. */
523     for (i = 0; i < TZ_NUMLEVELS; i++) {
524         if (sc->tz_zone.al[i].Pointer == NULL)
525             continue;
526         acpi_ForeachPackageObject((ACPI_OBJECT *)sc->tz_zone.al[i].Pointer,
527                                   acpi_tz_switch_cooler_off, sc);
528     }
529
530     /*
531      * XXX revert any passive-cooling options.
532      */
533
534     sc->tz_active = TZ_ACTIVE_NONE;
535     sc->tz_thflags = TZ_THFLAG_NONE;
536
537     return_VOID;
538 }
539
540 /*
541  * Given an object, verify that it's a reference to a device of some sort, 
542  * and try to switch it off.
543  */
544 static void
545 acpi_tz_switch_cooler_off(ACPI_OBJECT *obj, void *arg)
546 {
547     ACPI_HANDLE         cooler;
548
549     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
550
551     ACPI_ASSERTLOCK;
552
553     switch(obj->Type) {
554     case ACPI_TYPE_ANY:
555         ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "called to turn %s off\n",
556                          acpi_name(obj->Reference.Handle)));
557
558         acpi_pwr_switch_consumer(obj->Reference.Handle, ACPI_STATE_D3);
559         break;
560     case ACPI_TYPE_STRING:
561         ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "called to turn %s off\n",
562                          obj->String.Pointer));
563
564         /*
565          * Find the handle for the device and turn it off.
566          * The String object here seems to contain a fully-qualified path, so we
567          * don't have to search for it in our parents.
568          *
569          * XXX This may not always be the case.
570          */
571         if (ACPI_SUCCESS(AcpiGetHandle(NULL, obj->String.Pointer, &cooler)))
572             acpi_pwr_switch_consumer(cooler, ACPI_STATE_D3);
573         break;
574     default:
575         ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS,
576                          "called to handle unsupported object type %d\n",
577                          obj->Type));
578         break;
579     }
580
581     return_VOID;
582 }
583
584 /*
585  * Given an object, verify that it's a reference to a device of some sort, 
586  * and try to switch it on.
587  *
588  * XXX replication of off/on function code is bad, mmmkay?
589  */
590 static void
591 acpi_tz_switch_cooler_on(ACPI_OBJECT *obj, void *arg)
592 {
593     struct acpi_tz_softc        *sc = (struct acpi_tz_softc *)arg;
594     ACPI_HANDLE                 cooler;
595     ACPI_STATUS                 status;
596     
597     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
598
599     ACPI_ASSERTLOCK;
600
601     switch(obj->Type) {
602     case ACPI_TYPE_ANY:
603         ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "called to turn %s on\n",
604                          acpi_name(obj->Reference.Handle)));
605
606         status = acpi_pwr_switch_consumer(obj->Reference.Handle, ACPI_STATE_D0);
607         if (ACPI_FAILURE(status)) {
608             ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
609                         "failed to activate %s - %s\n",
610                         acpi_name(obj->Reference.Handle),
611                         AcpiFormatException(status));
612         }
613         break;
614     case ACPI_TYPE_STRING:
615         ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "called to turn %s on\n",
616                          obj->String.Pointer));
617
618         /*
619          * Find the handle for the device and turn it off.
620          * The String object here seems to contain a fully-qualified path, so we
621          * don't have to search for it in our parents.
622          *
623          * XXX This may not always be the case.
624          */
625         if (ACPI_SUCCESS(AcpiGetHandle(NULL, obj->String.Pointer, &cooler))) {
626             status = acpi_pwr_switch_consumer(cooler, ACPI_STATE_D0);
627             if (ACPI_FAILURE(status)) {
628                 ACPI_VPRINT(sc->tz_dev,
629                             acpi_device_get_parent_softc(sc->tz_dev),
630                             "failed to activate %s - %s\n",
631                             obj->String.Pointer, AcpiFormatException(status));
632             }
633         } else {
634             ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
635                         "couldn't find %s\n", obj->String.Pointer);
636         }
637         break;
638     default:
639         ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "unsupported object type %d\n",
640                           obj->Type));
641         break;
642     }
643
644     return_VOID;
645 }
646
647 /*
648  * Read/debug-print a parameter, default it to -1.
649  */
650 static void
651 acpi_tz_getparam(struct acpi_tz_softc *sc, char *node, int *data)
652 {
653
654     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
655
656     ACPI_ASSERTLOCK;
657
658     if (ACPI_FAILURE(acpi_EvaluateInteger(sc->tz_handle, node, data))) {
659         *data = -1;
660     } else {
661         ACPI_DEBUG_PRINT((ACPI_DB_VALUES, "%s.%s = %d\n",
662                          acpi_name(sc->tz_handle), node, *data));
663     }
664
665     return_VOID;    
666 }
667
668 /*
669  * Sanity-check a temperature value.  Assume that setpoints
670  * should be between 0C and 150C.
671  */
672 static void
673 acpi_tz_sanity(struct acpi_tz_softc *sc, int *val, char *what)
674 {
675     if (*val != -1 && (*val < TZ_ZEROC || *val > TZ_ZEROC + 1500)) {
676         device_printf(sc->tz_dev, "%s value is absurd, ignored (%d.%dC)\n",
677                       what, TZ_KELVTOC(*val));
678         *val = -1;
679     }
680 }
681
682 /*
683  * Respond to a sysctl on the active state node.
684  */    
685 static int
686 acpi_tz_active_sysctl(SYSCTL_HANDLER_ARGS)
687 {
688     struct acpi_tz_softc        *sc;
689     int                         active;
690     int                         error;
691     ACPI_LOCK_DECL;
692
693     ACPI_LOCK;
694
695     sc = (struct acpi_tz_softc *)oidp->oid_arg1;
696     active = sc->tz_active;
697     error = sysctl_handle_int(oidp, &active, 0, req);
698
699     /* Error or no new value */
700     if (error != 0 || req->newptr == NULL)
701         goto out;
702     if (active < -1 || active >= TZ_NUMLEVELS) {
703         error = EINVAL;
704         goto out;
705     }
706
707     /* Set new preferred level and re-switch */
708     sc->tz_requested = active;
709     acpi_tz_monitor(sc);
710
711  out:
712     ACPI_UNLOCK;
713     return (error);
714 }
715
716 /*
717  * Respond to a Notify event sent to the zone.
718  */
719 static void
720 acpi_tz_notify_handler(ACPI_HANDLE h, UINT32 notify, void *context)
721 {
722     struct acpi_tz_softc        *sc = (struct acpi_tz_softc *)context;
723
724     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
725
726     ACPI_ASSERTLOCK;
727
728     switch(notify) {
729     case TZ_NOTIFY_TEMPERATURE:
730         /* Temperature change occurred */
731         AcpiOsQueueForExecution(OSD_PRIORITY_HIGH, acpi_tz_monitor, sc);
732         break;
733     case TZ_NOTIFY_DEVICES:
734     case TZ_NOTIFY_LEVELS:
735         /* Zone devices/setpoints changed */
736         AcpiOsQueueForExecution(OSD_PRIORITY_HIGH,
737                                 (OSD_EXECUTION_CALLBACK)acpi_tz_establish, sc);
738         break;
739     default:
740         ACPI_VPRINT(sc->tz_dev, acpi_device_get_parent_softc(sc->tz_dev),
741                     "unknown Notify event 0x%x\n", notify);
742         break;
743     }
744
745     acpi_UserNotify("Thermal", h, notify);
746
747     return_VOID;
748 }
749
750 /*
751  * Poll the thermal zone.
752  */
753 static void
754 acpi_tz_timeout(struct acpi_tz_softc *sc)
755 {
756     /* Do we need to get the power profile settings? */
757     if (sc->tz_flags & TZ_FLAG_GETPROFILE) {
758         acpi_tz_power_profile((void *)sc);
759         sc->tz_flags &= ~TZ_FLAG_GETPROFILE;
760     }
761
762     ACPI_ASSERTLOCK;
763
764     /* Check the current temperature and take action based on it */
765     acpi_tz_monitor(sc);
766
767     /* XXX passive cooling actions? */
768 }
769
770 /*
771  * System power profile may have changed; fetch and notify the
772  * thermal zone accordingly.
773  *
774  * Since this can be called from an arbitrary eventhandler, it needs
775  * to get the ACPI lock itself.
776  */
777 static void
778 acpi_tz_power_profile(void *arg)
779 {
780     ACPI_OBJECT_LIST            args;
781     ACPI_OBJECT                 obj;
782     ACPI_STATUS                 status;
783     struct acpi_tz_softc        *sc = (struct acpi_tz_softc *)arg;
784     int                         state;
785     ACPI_LOCK_DECL;
786
787     state = power_profile_get_state();
788     if (state != POWER_PROFILE_PERFORMANCE && state != POWER_PROFILE_ECONOMY)
789         return;
790
791     ACPI_LOCK;
792
793     /* check that we haven't decided there's no _SCP method */
794     if ((sc->tz_flags & TZ_FLAG_NO_SCP) == 0) {
795
796         /* Call _SCP to set the new profile */
797         obj.Type = ACPI_TYPE_INTEGER;
798         obj.Integer.Value = (state == POWER_PROFILE_PERFORMANCE) ? 0 : 1;
799         args.Count = 1;
800         args.Pointer = &obj;
801         status = AcpiEvaluateObject(sc->tz_handle, "_SCP", &args, NULL);
802         if (ACPI_FAILURE(status)) {
803             if (status != AE_NOT_FOUND)
804                 ACPI_VPRINT(sc->tz_dev,
805                             acpi_device_get_parent_softc(sc->tz_dev),
806                             "can't evaluate %s._SCP - %s\n",
807                             acpi_name(sc->tz_handle),
808                             AcpiFormatException(status));
809             sc->tz_flags |= TZ_FLAG_NO_SCP;
810         } else {
811             /* We have to re-evaluate the entire zone now */
812             AcpiOsQueueForExecution(OSD_PRIORITY_HIGH,
813                                     (OSD_EXECUTION_CALLBACK)acpi_tz_establish,
814                                     sc);
815         }
816     }
817
818     ACPI_UNLOCK;
819 }
820
821 /*
822  * Thermal zone monitor thread.
823  */
824 static void
825 acpi_tz_thread(void *arg)
826 {
827     device_t    *devs;
828     int         devcount, i;
829     ACPI_LOCK_DECL;
830
831     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
832
833     devs = NULL;
834     devcount = 0;
835
836     for (;;) {
837         tsleep(&acpi_tz_td, 0, "tzpoll", hz * acpi_tz_polling_rate);
838
839 #if __FreeBSD_version >= 500000
840         mtx_lock(&Giant);
841 #endif
842
843         if (devcount == 0)
844             devclass_get_devices(acpi_tz_devclass, &devs, &devcount);
845
846         ACPI_LOCK;
847         for (i = 0; i < devcount; i++)
848             acpi_tz_timeout(device_get_softc(devs[i]));
849         ACPI_UNLOCK;
850
851 #if __FreeBSD_version >= 500000
852         mtx_unlock(&Giant);
853 #endif
854     }
855 }