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