xref: /freebsd/sys/dev/acpica/acpi.c (revision 0f8f86b71f022b803e99151c19db81b280f245dc)
1 /*-
2  * Copyright (c) 2000 Takanori Watanabe <takawata@jp.freebsd.org>
3  * Copyright (c) 2000 Mitsuru IWASAKI <iwasaki@jp.freebsd.org>
4  * Copyright (c) 2000, 2001 Michael Smith
5  * Copyright (c) 2000 BSDi
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	$FreeBSD$
30  */
31 
32 #include "opt_acpi.h"
33 #include <sys/param.h>
34 #include <sys/kernel.h>
35 #include <sys/proc.h>
36 #include <sys/fcntl.h>
37 #include <sys/malloc.h>
38 #include <sys/bus.h>
39 #include <sys/conf.h>
40 #include <sys/ioccom.h>
41 #include <sys/reboot.h>
42 #include <sys/sysctl.h>
43 #include <sys/ctype.h>
44 #include <sys/linker.h>
45 #include <sys/power.h>
46 #include <sys/sbuf.h>
47 #include <sys/smp.h>
48 
49 #include <machine/clock.h>
50 #include <machine/resource.h>
51 #include <machine/bus.h>
52 #include <sys/rman.h>
53 #include <isa/isavar.h>
54 
55 #include "acpi.h"
56 #include <dev/acpica/acpivar.h>
57 #include <dev/acpica/acpiio.h>
58 #include <contrib/dev/acpica/acnamesp.h>
59 
60 MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
61 
62 /* Hooks for the ACPI CA debugging infrastructure */
63 #define _COMPONENT	ACPI_BUS
64 ACPI_MODULE_NAME("ACPI")
65 
66 static d_open_t		acpiopen;
67 static d_close_t	acpiclose;
68 static d_ioctl_t	acpiioctl;
69 
70 static struct cdevsw acpi_cdevsw = {
71 	.d_version =	D_VERSION,
72 	.d_flags =	D_NEEDGIANT,
73 	.d_open =	acpiopen,
74 	.d_close =	acpiclose,
75 	.d_ioctl =	acpiioctl,
76 	.d_name =	"acpi",
77 };
78 
79 static const char* sleep_state_names[] = {
80     "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
81 
82 /* this has to be static, as the softc is gone when we need it */
83 static int acpi_off_state = ACPI_STATE_S5;
84 
85 #if __FreeBSD_version >= 500000
86 struct mtx	acpi_mutex;
87 #endif
88 
89 struct acpi_quirks {
90     char	*OemId;
91     uint32_t	OemRevision;
92     char	*value;
93 };
94 
95 #define ACPI_OEM_REV_ANY	0
96 
97 static struct acpi_quirks acpi_quirks_table[] = {
98 #ifdef notyet
99     /* Bad PCI routing table.  Used on some SuperMicro boards. */
100     { "PTLTD ", 0x06040000, "pci_link" },
101 #endif
102 
103     { NULL, 0, NULL }
104 };
105 
106 static int	acpi_modevent(struct module *mod, int event, void *junk);
107 static void	acpi_identify(driver_t *driver, device_t parent);
108 static int	acpi_probe(device_t dev);
109 static int	acpi_attach(device_t dev);
110 static void	acpi_quirks_set(void);
111 static device_t	acpi_add_child(device_t bus, int order, const char *name,
112 			int unit);
113 static int	acpi_print_child(device_t bus, device_t child);
114 static int	acpi_read_ivar(device_t dev, device_t child, int index,
115 			uintptr_t *result);
116 static int	acpi_write_ivar(device_t dev, device_t child, int index,
117 			uintptr_t value);
118 static int	acpi_set_resource(device_t dev, device_t child, int type,
119 			int rid, u_long start, u_long count);
120 static int	acpi_get_resource(device_t dev, device_t child, int type,
121 			int rid, u_long *startp, u_long *countp);
122 static struct resource *acpi_alloc_resource(device_t bus, device_t child,
123 			int type, int *rid, u_long start, u_long end,
124 			u_long count, u_int flags);
125 static int	acpi_release_resource(device_t bus, device_t child, int type,
126 			int rid, struct resource *r);
127 static uint32_t	acpi_isa_get_logicalid(device_t dev);
128 static int	acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
129 static int	acpi_isa_pnp_probe(device_t bus, device_t child,
130 			struct isa_pnp_id *ids);
131 static void	acpi_probe_children(device_t bus);
132 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
133 			void *context, void **status);
134 static void	acpi_shutdown_pre_sync(void *arg, int howto);
135 static void	acpi_shutdown_final(void *arg, int howto);
136 static void	acpi_shutdown_poweroff(void *arg);
137 static void	acpi_enable_fixed_events(struct acpi_softc *sc);
138 static void	acpi_system_eventhandler_sleep(void *arg, int state);
139 static void	acpi_system_eventhandler_wakeup(void *arg, int state);
140 static int	acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
141 static int	acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
142 static int	acpi_pm_func(u_long cmd, void *arg, ...);
143 
144 static device_method_t acpi_methods[] = {
145     /* Device interface */
146     DEVMETHOD(device_identify,		acpi_identify),
147     DEVMETHOD(device_probe,		acpi_probe),
148     DEVMETHOD(device_attach,		acpi_attach),
149     DEVMETHOD(device_detach,		bus_generic_detach),
150     DEVMETHOD(device_shutdown,		bus_generic_shutdown),
151     DEVMETHOD(device_suspend,		bus_generic_suspend),
152     DEVMETHOD(device_resume,		bus_generic_resume),
153 
154     /* Bus interface */
155     DEVMETHOD(bus_add_child,		acpi_add_child),
156     DEVMETHOD(bus_print_child,		acpi_print_child),
157     DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
158     DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
159     DEVMETHOD(bus_set_resource,		acpi_set_resource),
160     DEVMETHOD(bus_get_resource,		acpi_get_resource),
161     DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
162     DEVMETHOD(bus_release_resource,	acpi_release_resource),
163     DEVMETHOD(bus_driver_added,		bus_generic_driver_added),
164     DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
165     DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
166     DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
167     DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
168 
169     /* ISA emulation */
170     DEVMETHOD(isa_pnp_probe,		acpi_isa_pnp_probe),
171 
172     {0, 0}
173 };
174 
175 static driver_t acpi_driver = {
176     "acpi",
177     acpi_methods,
178     sizeof(struct acpi_softc),
179 };
180 
181 static devclass_t acpi_devclass;
182 DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
183 MODULE_VERSION(acpi, 100);
184 
185 SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RW, NULL, "ACPI debugging");
186 static char acpi_ca_version[12];
187 SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
188 	      acpi_ca_version, 0, "Version of Intel ACPI-CA");
189 
190 /*
191  * Allow override of whether methods execute in parallel or not.
192  * Default to serial behavior as this fixes some AE_ALREADY_EXISTS errors
193  * and matches the MS interpreter.
194  */
195 static int acpi_serialize_methods = 1;
196 TUNABLE_INT("hw.acpi.serialize_methods", &acpi_serialize_methods);
197 
198 /* Allow override of whether to support the _OSI method. */
199 static int acpi_osi_method;
200 TUNABLE_INT("hw.acpi.osi_method", &acpi_osi_method);
201 
202 /*
203  * ACPI can only be loaded as a module by the loader; activating it after
204  * system bootstrap time is not useful, and can be fatal to the system.
205  * It also cannot be unloaded, since the entire system bus heirarchy hangs
206  * off it.
207  */
208 static int
209 acpi_modevent(struct module *mod, int event, void *junk)
210 {
211     switch(event) {
212     case MOD_LOAD:
213 	if (!cold) {
214 	    printf("The ACPI driver cannot be loaded after boot.\n");
215 	    return (EPERM);
216 	}
217 	break;
218     case MOD_UNLOAD:
219 	if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
220 	    return (EBUSY);
221 	break;
222     default:
223 	break;
224     }
225     return (0);
226 }
227 
228 /*
229  * Perform early initialization.
230  */
231 ACPI_STATUS
232 acpi_Startup(void)
233 {
234 #ifdef ACPI_DEBUGGER
235     char *debugpoint;
236 #endif
237     static int error, started = 0;
238 
239     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
240 
241     if (started)
242 	return_VALUE (error);
243     started = 1;
244 
245 #if __FreeBSD_version >= 500000
246     /* Initialise the ACPI mutex */
247     mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
248 #endif
249 
250     /*
251      * Set the globals from our tunables.  This is needed because ACPI-CA
252      * uses UINT8 for some values and we have no tunable_uint8.
253      */
254     AcpiGbl_AllMethodsSerialized = acpi_serialize_methods;
255     AcpiGbl_CreateOsiMethod = acpi_osi_method;
256 
257     /* Start up the ACPI CA subsystem. */
258 #ifdef ACPI_DEBUGGER
259     debugpoint = getenv("debug.acpi.debugger");
260     if (debugpoint) {
261 	if (!strcmp(debugpoint, "init"))
262 	    acpi_EnterDebugger();
263 	freeenv(debugpoint);
264     }
265 #endif
266     if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
267 	printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
268 	return_VALUE (error);
269     }
270 #ifdef ACPI_DEBUGGER
271     debugpoint = getenv("debug.acpi.debugger");
272     if (debugpoint) {
273 	if (!strcmp(debugpoint, "tables"))
274 	    acpi_EnterDebugger();
275 	freeenv(debugpoint);
276     }
277 #endif
278 
279     if (ACPI_FAILURE(error = AcpiLoadTables())) {
280 	printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
281 	return_VALUE(error);
282     }
283 
284     /* Set up any quirks we have for this XSDT. */
285     acpi_quirks_set();
286     if (acpi_disabled("acpi"))
287 	return_VALUE (AE_ERROR);
288 
289     return_VALUE (AE_OK);
290 }
291 
292 /*
293  * Detect ACPI, perform early initialisation
294  */
295 static void
296 acpi_identify(driver_t *driver, device_t parent)
297 {
298     device_t	child;
299 
300     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
301 
302     if (!cold)
303 	return_VOID;
304 
305     /* Check that we haven't been disabled with a hint. */
306     if (resource_disabled("acpi", 0))
307 	return_VOID;
308 
309     /* Make sure we're not being doubly invoked. */
310     if (device_find_child(parent, "acpi", 0) != NULL)
311 	return_VOID;
312 
313     /* Initialize ACPI-CA. */
314     if (ACPI_FAILURE(acpi_Startup()))
315 	return_VOID;
316 
317     snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%#x", ACPI_CA_VERSION);
318 
319     /* Attach the actual ACPI device. */
320     if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
321 	device_printf(parent, "ACPI: could not attach\n");
322 	return_VOID;
323     }
324 }
325 
326 /*
327  * Fetch some descriptive data from ACPI to put in our attach message
328  */
329 static int
330 acpi_probe(device_t dev)
331 {
332     ACPI_TABLE_HEADER	th;
333     char		buf[20];
334     int			error;
335     struct sbuf		sb;
336     ACPI_STATUS		status;
337     ACPI_LOCK_DECL;
338 
339     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
340 
341     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
342 	power_pm_get_type() != POWER_PM_TYPE_ACPI) {
343 
344 	device_printf(dev, "Other PM system enabled.\n");
345 	return_VALUE(ENXIO);
346     }
347 
348     ACPI_LOCK;
349 
350     if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
351 	device_printf(dev, "couldn't get XSDT header: %s\n",
352 		      AcpiFormatException(status));
353 	error = ENXIO;
354     } else {
355 	sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
356 	sbuf_bcat(&sb, th.OemId, 6);
357 	sbuf_trim(&sb);
358 	sbuf_putc(&sb, ' ');
359 	sbuf_bcat(&sb, th.OemTableId, 8);
360 	sbuf_trim(&sb);
361 	sbuf_finish(&sb);
362 	device_set_desc_copy(dev, sbuf_data(&sb));
363 	sbuf_delete(&sb);
364 	error = 0;
365     }
366     ACPI_UNLOCK;
367     return_VALUE(error);
368 }
369 
370 static int
371 acpi_attach(device_t dev)
372 {
373     struct acpi_softc	*sc;
374     ACPI_STATUS		status;
375     int			error;
376     UINT32		flags;
377     char		*env;
378 #ifdef ACPI_DEBUGGER
379     char		*debugpoint;
380 #endif
381     ACPI_LOCK_DECL;
382 
383     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
384     ACPI_LOCK;
385     sc = device_get_softc(dev);
386     bzero(sc, sizeof(*sc));
387     sc->acpi_dev = dev;
388 
389 #ifdef ACPI_DEBUGGER
390     debugpoint = getenv("debug.acpi.debugger");
391     if (debugpoint) {
392 	if (!strcmp(debugpoint, "spaces"))
393 	    acpi_EnterDebugger();
394 	freeenv(debugpoint);
395     }
396 #endif
397 
398     /* Install the default address space handlers. */
399     error = ENXIO;
400     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
401 		ACPI_ADR_SPACE_SYSTEM_MEMORY, ACPI_DEFAULT_HANDLER, NULL, NULL);
402     if (ACPI_FAILURE(status)) {
403 	device_printf(dev, "Could not initialise SystemMemory handler: %s\n",
404 		      AcpiFormatException(status));
405 	goto out;
406     }
407     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
408 		ACPI_ADR_SPACE_SYSTEM_IO, ACPI_DEFAULT_HANDLER, NULL, NULL);
409     if (ACPI_FAILURE(status)) {
410 	device_printf(dev, "Could not initialise SystemIO handler: %s\n",
411 		      AcpiFormatException(status));
412 	goto out;
413     }
414     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
415 		ACPI_ADR_SPACE_PCI_CONFIG, ACPI_DEFAULT_HANDLER, NULL, NULL);
416     if (ACPI_FAILURE(status)) {
417 	device_printf(dev, "could not initialise PciConfig handler: %s\n",
418 		      AcpiFormatException(status));
419 	goto out;
420     }
421 
422     /*
423      * Bring ACPI fully online.
424      *
425      * Note that some systems (specifically, those with namespace evaluation
426      * issues that require the avoidance of parts of the namespace) must
427      * avoid running _INI and _STA on everything, as well as dodging the final
428      * object init pass.
429      *
430      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
431      *
432      * XXX We should arrange for the object init pass after we have attached
433      *     all our child devices, but on many systems it works here.
434      */
435 #ifdef ACPI_DEBUGGER
436     debugpoint = getenv("debug.acpi.debugger");
437     if (debugpoint) {
438 	if (!strcmp(debugpoint, "enable"))
439 	    acpi_EnterDebugger();
440 	freeenv(debugpoint);
441     }
442 #endif
443     flags = 0;
444     if (testenv("debug.acpi.avoid"))
445 	flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
446     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
447 	device_printf(dev, "Could not enable ACPI: %s\n",
448 		      AcpiFormatException(status));
449 	goto out;
450     }
451 
452     /*
453      * Call the ECDT probe function to provide EC functionality before
454      * the namespace has been evaluated.
455      */
456     acpi_ec_ecdt_probe(dev);
457 
458     if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
459 	device_printf(dev, "Could not initialize ACPI objects: %s\n",
460 		      AcpiFormatException(status));
461 	goto out;
462     }
463 
464     /*
465      * Setup our sysctl tree.
466      *
467      * XXX: This doesn't check to make sure that none of these fail.
468      */
469     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
470     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
471 			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
472 			       device_get_name(dev), CTLFLAG_RD, 0, "");
473     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
474 	OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
475 	0, 0, acpi_supported_sleep_state_sysctl, "A", "");
476     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
477 	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
478 	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
479     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
480 	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
481 	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
482     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
483 	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
484 	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
485     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
486 	OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
487 	&sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
488     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
489 	OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
490 	&sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
491     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
492 	OID_AUTO, "sleep_delay", CTLFLAG_RD | CTLFLAG_RW,
493 	&sc->acpi_sleep_delay, 0, "sleep delay");
494     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
495 	OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
496 	&sc->acpi_s4bios, 0, "S4BIOS mode");
497     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
498 	OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
499 	&sc->acpi_verbose, 0, "verbose mode");
500     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
501 	OID_AUTO, "disable_on_poweroff", CTLFLAG_RD | CTLFLAG_RW,
502 	&sc->acpi_disable_on_poweroff, 0, "ACPI subsystem disable on poweroff");
503 
504     /*
505      * Default to 5 seconds before sleeping to give some machines time to
506      * stabilize.
507      */
508     sc->acpi_sleep_delay = 5;
509     sc->acpi_disable_on_poweroff = 1;
510     if (bootverbose)
511 	sc->acpi_verbose = 1;
512     if ((env = getenv("hw.acpi.verbose")) && strcmp(env, "0")) {
513 	sc->acpi_verbose = 1;
514 	freeenv(env);
515     }
516 
517     /* Only enable S4BIOS by default if the FACS says it is available. */
518     if (AcpiGbl_FACS->S4Bios_f != 0)
519 	    sc->acpi_s4bios = 1;
520 
521     /*
522      * Dispatch the default sleep state to devices.
523      * TBD: should be configured from userland policy manager.
524      */
525     sc->acpi_power_button_sx = ACPI_POWER_BUTTON_DEFAULT_SX;
526     sc->acpi_sleep_button_sx = ACPI_SLEEP_BUTTON_DEFAULT_SX;
527     sc->acpi_lid_switch_sx = ACPI_LID_SWITCH_DEFAULT_SX;
528     sc->acpi_standby_sx = ACPI_STATE_S1;
529     sc->acpi_suspend_sx = ACPI_STATE_S3;
530 
531     acpi_enable_fixed_events(sc);
532 
533     /*
534      * Scan the namespace and attach/initialise children.
535      */
536 #ifdef ACPI_DEBUGGER
537     debugpoint = getenv("debug.acpi.debugger");
538     if (debugpoint) {
539 	if (!strcmp(debugpoint, "probe"))
540 	    acpi_EnterDebugger();
541 	freeenv(debugpoint);
542     }
543 #endif
544 
545     /* Register our shutdown handlers */
546     EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc,
547 	SHUTDOWN_PRI_LAST);
548     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
549 	SHUTDOWN_PRI_LAST);
550 
551     /*
552      * Register our acpi event handlers.
553      * XXX should be configurable eg. via userland policy manager.
554      */
555     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
556 	sc, ACPI_EVENT_PRI_LAST);
557     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
558 	sc, ACPI_EVENT_PRI_LAST);
559 
560     /* Flag our initial states. */
561     sc->acpi_enabled = 1;
562     sc->acpi_sstate = ACPI_STATE_S0;
563     sc->acpi_sleep_disabled = 0;
564 
565     /* Create the control device */
566     sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_WHEEL, 0644,
567 			      "acpi");
568     sc->acpi_dev_t->si_drv1 = sc;
569 
570 #ifdef ACPI_DEBUGGER
571     debugpoint = getenv("debug.acpi.debugger");
572     if (debugpoint) {
573 	if (strcmp(debugpoint, "running") == 0)
574 	    acpi_EnterDebugger();
575 	freeenv(debugpoint);
576     }
577 #endif
578 
579 #ifdef ACPI_USE_THREADS
580     if ((error = acpi_task_thread_init()))
581 	goto out;
582 #endif
583 
584     if ((error = acpi_machdep_init(dev)))
585 	goto out;
586 
587     /* Register ACPI again to pass the correct argument of pm_func. */
588     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
589 
590     if (!acpi_disabled("bus"))
591 	acpi_probe_children(dev);
592 
593     error = 0;
594 
595  out:
596     ACPI_UNLOCK;
597     return_VALUE (error);
598 }
599 
600 static void
601 acpi_quirks_set()
602 {
603     XSDT_DESCRIPTOR *xsdt;
604     struct acpi_quirks *quirk;
605     char *env, *tmp;
606     int len;
607 
608     /*
609      * If the user loaded a custom table or disabled "quirks", leave
610      * the settings alone.
611      */
612     len = 0;
613     if ((env = getenv("acpi_dsdt_load")) != NULL) {
614 	/* XXX No strcasecmp but this is good enough. */
615 	if (*env == 'Y' || *env == 'y')
616 	    goto out;
617 	freeenv(env);
618     }
619     if ((env = getenv("debug.acpi.disabled")) != NULL) {
620 	if (strstr("quirks", env) != NULL)
621 	    goto out;
622 	len = strlen(env);
623     }
624 
625     /*
626      * Search through our quirk table and concatenate the disabled
627      * values with whatever we find.
628      */
629     xsdt = AcpiGbl_XSDT;
630     for (quirk = acpi_quirks_table; quirk->OemId; quirk++) {
631 	if (!strncmp(xsdt->OemId, quirk->OemId, strlen(quirk->OemId)) &&
632 	    (xsdt->OemRevision == quirk->OemRevision ||
633 	    quirk->OemRevision == ACPI_OEM_REV_ANY)) {
634 		len += strlen(quirk->value) + 2;
635 		if ((tmp = malloc(len, M_TEMP, M_NOWAIT)) == NULL)
636 		    goto out;
637 		sprintf(tmp, "%s %s", env ? env : "", quirk->value);
638 		setenv("debug.acpi.disabled", tmp);
639 		free(tmp, M_TEMP);
640 		break;
641 	}
642     }
643 
644 out:
645     if (env)
646 	freeenv(env);
647 }
648 
649 /*
650  * Handle a new device being added
651  */
652 static device_t
653 acpi_add_child(device_t bus, int order, const char *name, int unit)
654 {
655     struct acpi_device	*ad;
656     device_t		child;
657 
658     if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT | M_ZERO)) == NULL)
659 	return (NULL);
660 
661     resource_list_init(&ad->ad_rl);
662 
663     child = device_add_child_ordered(bus, order, name, unit);
664     if (child != NULL)
665 	device_set_ivars(child, ad);
666     return (child);
667 }
668 
669 static int
670 acpi_print_child(device_t bus, device_t child)
671 {
672     struct acpi_device	 *adev = device_get_ivars(child);
673     struct resource_list *rl = &adev->ad_rl;
674     int retval = 0;
675 
676     retval += bus_print_child_header(bus, child);
677     retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
678     retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
679     retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
680     retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
681     retval += bus_print_child_footer(bus, child);
682 
683     return (retval);
684 }
685 
686 /*
687  * Handle per-device ivars
688  */
689 static int
690 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
691 {
692     struct acpi_device	*ad;
693 
694     if ((ad = device_get_ivars(child)) == NULL) {
695 	printf("device has no ivars\n");
696 	return (ENOENT);
697     }
698 
699     /* ACPI and ISA compatibility ivars */
700     switch(index) {
701     case ACPI_IVAR_HANDLE:
702 	*(ACPI_HANDLE *)result = ad->ad_handle;
703 	break;
704     case ACPI_IVAR_MAGIC:
705 	*(int *)result = ad->ad_magic;
706 	break;
707     case ACPI_IVAR_PRIVATE:
708 	*(void **)result = ad->ad_private;
709 	break;
710     case ISA_IVAR_VENDORID:
711     case ISA_IVAR_SERIAL:
712     case ISA_IVAR_COMPATID:
713 	*(int *)result = -1;
714 	break;
715     case ISA_IVAR_LOGICALID:
716 	*(int *)result = acpi_isa_get_logicalid(child);
717 	break;
718     default:
719 	return (ENOENT);
720     }
721 
722     return (0);
723 }
724 
725 static int
726 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
727 {
728     struct acpi_device	*ad;
729 
730     if ((ad = device_get_ivars(child)) == NULL) {
731 	printf("device has no ivars\n");
732 	return (ENOENT);
733     }
734 
735     switch(index) {
736     case ACPI_IVAR_HANDLE:
737 	ad->ad_handle = (ACPI_HANDLE)value;
738 	break;
739     case ACPI_IVAR_MAGIC:
740 	ad->ad_magic = (int)value;
741 	break;
742     case ACPI_IVAR_PRIVATE:
743 	ad->ad_private = (void *)value;
744 	break;
745     default:
746 	panic("bad ivar write request (%d)", index);
747 	return (ENOENT);
748     }
749 
750     return (0);
751 }
752 
753 ACPI_HANDLE
754 acpi_get_handle(device_t dev)
755 {
756     uintptr_t up;
757     ACPI_HANDLE	h;
758 
759     if (BUS_READ_IVAR(device_get_parent(dev), dev, ACPI_IVAR_HANDLE, &up))
760 	return(NULL);
761     h = (ACPI_HANDLE)up;
762     return (h);
763 }
764 
765 int
766 acpi_set_handle(device_t dev, ACPI_HANDLE h)
767 {
768     uintptr_t up;
769 
770     up = (uintptr_t)h;
771     return (BUS_WRITE_IVAR(device_get_parent(dev), dev, ACPI_IVAR_HANDLE, up));
772 }
773 
774 int
775 acpi_get_magic(device_t dev)
776 {
777     uintptr_t up;
778     int	m;
779 
780     if (BUS_READ_IVAR(device_get_parent(dev), dev, ACPI_IVAR_MAGIC, &up))
781 	return(0);
782     m = (int)up;
783     return (m);
784 }
785 
786 int
787 acpi_set_magic(device_t dev, int m)
788 {
789     uintptr_t up;
790 
791     up = (uintptr_t)m;
792     return (BUS_WRITE_IVAR(device_get_parent(dev), dev, ACPI_IVAR_MAGIC, up));
793 }
794 
795 void *
796 acpi_get_private(device_t dev)
797 {
798     uintptr_t up;
799     void *p;
800 
801     if (BUS_READ_IVAR(device_get_parent(dev), dev, ACPI_IVAR_PRIVATE, &up))
802 	return (NULL);
803     p = (void *)up;
804     return (p);
805 }
806 
807 int
808 acpi_set_private(device_t dev, void *p)
809 {
810     uintptr_t up;
811 
812     up = (uintptr_t)p;
813     return (BUS_WRITE_IVAR(device_get_parent(dev), dev, ACPI_IVAR_PRIVATE, up));
814 }
815 
816 ACPI_OBJECT_TYPE
817 acpi_get_type(device_t dev)
818 {
819     ACPI_HANDLE		h;
820     ACPI_OBJECT_TYPE	t;
821 
822     if ((h = acpi_get_handle(dev)) == NULL)
823 	return (ACPI_TYPE_NOT_FOUND);
824     if (AcpiGetType(h, &t) != AE_OK)
825 	return (ACPI_TYPE_NOT_FOUND);
826     return (t);
827 }
828 
829 /*
830  * Handle child resource allocation/removal
831  */
832 static int
833 acpi_set_resource(device_t dev, device_t child, int type, int rid,
834 		  u_long start, u_long count)
835 {
836     struct acpi_device		*ad = device_get_ivars(child);
837     struct resource_list	*rl = &ad->ad_rl;
838 
839     resource_list_add(rl, type, rid, start, start + count -1, count);
840 
841     return(0);
842 }
843 
844 static int
845 acpi_get_resource(device_t dev, device_t child, int type, int rid,
846 		  u_long *startp, u_long *countp)
847 {
848     struct acpi_device		*ad = device_get_ivars(child);
849     struct resource_list	*rl = &ad->ad_rl;
850     struct resource_list_entry	*rle;
851 
852     rle = resource_list_find(rl, type, rid);
853     if (!rle)
854 	return(ENOENT);
855 
856     if (startp)
857 	*startp = rle->start;
858     if (countp)
859 	*countp = rle->count;
860 
861     return (0);
862 }
863 
864 static struct resource *
865 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
866 		    u_long start, u_long end, u_long count, u_int flags)
867 {
868     struct acpi_device *ad = device_get_ivars(child);
869     struct resource_list *rl = &ad->ad_rl;
870 
871     return (resource_list_alloc(rl, bus, child, type, rid, start, end, count,
872 	    flags));
873 }
874 
875 static int
876 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
877 {
878     struct acpi_device *ad = device_get_ivars(child);
879     struct resource_list *rl = &ad->ad_rl;
880 
881     return (resource_list_release(rl, bus, child, type, rid, r));
882 }
883 
884 /* Allocate an IO port or memory resource, given its GAS. */
885 struct resource *
886 acpi_bus_alloc_gas(device_t dev, int *rid, ACPI_GENERIC_ADDRESS *gas)
887 {
888     int type;
889 
890     if (gas == NULL || !ACPI_VALID_ADDRESS(gas->Address) ||
891 	gas->RegisterBitWidth < 8)
892 	return (NULL);
893 
894     switch (gas->AddressSpaceId) {
895     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
896 	type = SYS_RES_MEMORY;
897 	break;
898     case ACPI_ADR_SPACE_SYSTEM_IO:
899 	type = SYS_RES_IOPORT;
900 	break;
901     default:
902 	return (NULL);
903     }
904 
905     bus_set_resource(dev, type, *rid, gas->Address, gas->RegisterBitWidth / 8);
906     return (bus_alloc_resource_any(dev, type, rid, RF_ACTIVE));
907 }
908 
909 /*
910  * Handle ISA-like devices probing for a PnP ID to match.
911  */
912 #define PNP_EISAID(s)				\
913 	((((s[0] - '@') & 0x1f) << 2)		\
914 	 | (((s[1] - '@') & 0x18) >> 3)		\
915 	 | (((s[1] - '@') & 0x07) << 13)	\
916 	 | (((s[2] - '@') & 0x1f) << 8)		\
917 	 | (PNP_HEXTONUM(s[4]) << 16)		\
918 	 | (PNP_HEXTONUM(s[3]) << 20)		\
919 	 | (PNP_HEXTONUM(s[6]) << 24)		\
920 	 | (PNP_HEXTONUM(s[5]) << 28))
921 
922 static uint32_t
923 acpi_isa_get_logicalid(device_t dev)
924 {
925     ACPI_DEVICE_INFO	*devinfo;
926     ACPI_BUFFER		buf;
927     ACPI_HANDLE		h;
928     ACPI_STATUS		error;
929     u_int32_t		pnpid;
930     ACPI_LOCK_DECL;
931 
932     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
933 
934     pnpid = 0;
935     buf.Pointer = NULL;
936     buf.Length = ACPI_ALLOCATE_BUFFER;
937 
938     ACPI_LOCK;
939 
940     /* Fetch and validate the HID. */
941     if ((h = acpi_get_handle(dev)) == NULL)
942 	goto out;
943     error = AcpiGetObjectInfo(h, &buf);
944     if (ACPI_FAILURE(error))
945 	goto out;
946     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
947 
948     if ((devinfo->Valid & ACPI_VALID_HID) != 0)
949 	pnpid = PNP_EISAID(devinfo->HardwareId.Value);
950 
951 out:
952     if (buf.Pointer != NULL)
953 	AcpiOsFree(buf.Pointer);
954     ACPI_UNLOCK;
955     return_VALUE (pnpid);
956 }
957 
958 static int
959 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
960 {
961     ACPI_DEVICE_INFO	*devinfo;
962     ACPI_BUFFER		buf;
963     ACPI_HANDLE		h;
964     ACPI_STATUS		error;
965     uint32_t		*pnpid;
966     int			valid, i;
967     ACPI_LOCK_DECL;
968 
969     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
970 
971     pnpid = cids;
972     valid = 0;
973     buf.Pointer = NULL;
974     buf.Length = ACPI_ALLOCATE_BUFFER;
975 
976     ACPI_LOCK;
977 
978     /* Fetch and validate the CID */
979     if ((h = acpi_get_handle(dev)) == NULL)
980 	goto out;
981     error = AcpiGetObjectInfo(h, &buf);
982     if (ACPI_FAILURE(error))
983 	goto out;
984     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
985     if ((devinfo->Valid & ACPI_VALID_CID) == 0)
986 	goto out;
987 
988     if (devinfo->CompatibilityId.Count < count)
989 	count = devinfo->CompatibilityId.Count;
990     for (i = 0; i < count; i++) {
991 	if (strncmp(devinfo->CompatibilityId.Id[i].Value, "PNP", 3) != 0)
992 	    continue;
993 	*pnpid++ = PNP_EISAID(devinfo->CompatibilityId.Id[i].Value);
994 	valid++;
995     }
996 
997 out:
998     if (buf.Pointer != NULL)
999 	AcpiOsFree(buf.Pointer);
1000     ACPI_UNLOCK;
1001     return_VALUE (valid);
1002 }
1003 
1004 static int
1005 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
1006 {
1007     int			result, cid_count, i;
1008     uint32_t		lid, cids[8];
1009 
1010     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1011 
1012     /*
1013      * ISA-style drivers attached to ACPI may persist and
1014      * probe manually if we return ENOENT.  We never want
1015      * that to happen, so don't ever return it.
1016      */
1017     result = ENXIO;
1018 
1019     /* Scan the supplied IDs for a match */
1020     lid = acpi_isa_get_logicalid(child);
1021     cid_count = acpi_isa_get_compatid(child, cids, 8);
1022     while (ids && ids->ip_id) {
1023 	if (lid == ids->ip_id) {
1024 	    result = 0;
1025 	    goto out;
1026 	}
1027 	for (i = 0; i < cid_count; i++) {
1028 	    if (cids[i] == ids->ip_id) {
1029 		result = 0;
1030 		goto out;
1031 	    }
1032 	}
1033 	ids++;
1034     }
1035 
1036  out:
1037     return_VALUE (result);
1038 }
1039 
1040 /*
1041  * Scan relevant portions of the ACPI namespace and attach child devices.
1042  *
1043  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and
1044  * \_SB_ scopes, and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
1045  */
1046 static void
1047 acpi_probe_children(device_t bus)
1048 {
1049     ACPI_HANDLE	parent;
1050     ACPI_STATUS	status;
1051     static char	*scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
1052     int		i;
1053 
1054     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1055     ACPI_ASSERTLOCK;
1056 
1057     /* Create any static children by calling device identify methods. */
1058     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
1059     bus_generic_probe(bus);
1060 
1061     /*
1062      * Scan the namespace and insert placeholders for all the devices that
1063      * we find.
1064      *
1065      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
1066      * we want to create nodes for all devices, not just those that are
1067      * currently present. (This assumes that we don't want to create/remove
1068      * devices as they appear, which might be smarter.)
1069      */
1070     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
1071     for (i = 0; scopes[i] != NULL; i++) {
1072 	status = AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent);
1073 	if (ACPI_SUCCESS(status)) {
1074 	    AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child,
1075 			      bus, NULL);
1076 	}
1077     }
1078 
1079     /*
1080      * Scan all of the child devices we have created and let them probe/attach.
1081      */
1082     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
1083     bus_generic_attach(bus);
1084 
1085     /*
1086      * Some of these children may have attached others as part of their attach
1087      * process (eg. the root PCI bus driver), so rescan.
1088      */
1089     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
1090     bus_generic_attach(bus);
1091 
1092     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
1093     return_VOID;
1094 }
1095 
1096 /*
1097  * Evaluate a child device and determine whether we might attach a device to
1098  * it.
1099  */
1100 static ACPI_STATUS
1101 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
1102 {
1103     ACPI_OBJECT_TYPE	type;
1104     device_t		child, bus = (device_t)context;
1105 
1106     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1107 
1108     /* Skip this device if we think we'll have trouble with it. */
1109     if (acpi_avoid(handle))
1110 	return_ACPI_STATUS (AE_OK);
1111 
1112     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
1113 	switch(type) {
1114 	case ACPI_TYPE_DEVICE:
1115 	case ACPI_TYPE_PROCESSOR:
1116 	case ACPI_TYPE_THERMAL:
1117 	case ACPI_TYPE_POWER:
1118 	    if (acpi_disabled("children"))
1119 		break;
1120 
1121 	    /*
1122 	     * Create a placeholder device for this node.  Sort the placeholder
1123 	     * so that the probe/attach passes will run breadth-first.
1124 	     */
1125 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n",
1126 			     acpi_name(handle)));
1127 	    child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
1128 	    if (child == NULL)
1129 		break;
1130 	    acpi_set_handle(child, handle);
1131 
1132 	    /*
1133 	     * Check that the device is present.  If it's not present,
1134 	     * leave it disabled (so that we have a device_t attached to
1135 	     * the handle, but we don't probe it).
1136 	     */
1137 	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1138 		device_disable(child);
1139 		break;
1140 	    }
1141 
1142 	    /*
1143 	     * Get the device's resource settings and attach them.
1144 	     * Note that if the device has _PRS but no _CRS, we need
1145 	     * to decide when it's appropriate to try to configure the
1146 	     * device.  Ignore the return value here; it's OK for the
1147 	     * device not to have any resources.
1148 	     */
1149 	    acpi_parse_resources(child, handle, &acpi_res_parse_set);
1150 
1151 	    /* If we're debugging, probe/attach now rather than later */
1152 	    ACPI_DEBUG_EXEC(device_probe_and_attach(child));
1153 	    break;
1154 	}
1155     }
1156 
1157     return_ACPI_STATUS (AE_OK);
1158 }
1159 
1160 static void
1161 acpi_shutdown_pre_sync(void *arg, int howto)
1162 {
1163     struct acpi_softc *sc = arg;
1164 
1165     ACPI_ASSERTLOCK;
1166 
1167     /*
1168      * Disable all ACPI events before soft off, otherwise the system
1169      * will be turned on again on some laptops.
1170      *
1171      * XXX this should probably be restricted to masking some events just
1172      *     before powering down, since we may still need ACPI during the
1173      *     shutdown process.
1174      */
1175     if (sc->acpi_disable_on_poweroff)
1176 	acpi_Disable(sc);
1177 }
1178 
1179 static void
1180 acpi_shutdown_final(void *arg, int howto)
1181 {
1182 
1183     ACPI_ASSERTLOCK;
1184 
1185     /*
1186      * If powering off, run the actual shutdown code on each processor.
1187      * It will only perform the shutdown on the BSP.  Some chipsets do
1188      * not power off the system correctly if called from an AP.
1189      */
1190     if ((howto & RB_POWEROFF) != 0) {
1191 	printf("Powering system off using ACPI\n");
1192 	smp_rendezvous(NULL, acpi_shutdown_poweroff, NULL, NULL);
1193     } else {
1194 	printf("Shutting down ACPI\n");
1195 	AcpiTerminate();
1196     }
1197 }
1198 
1199 static void
1200 acpi_shutdown_poweroff(void *arg)
1201 {
1202     ACPI_STATUS	status;
1203 
1204     ACPI_ASSERTLOCK;
1205 
1206     /* Only attempt to power off if this is the BSP (cpuid 0). */
1207     if (PCPU_GET(cpuid) != 0)
1208 	return;
1209 
1210     status = AcpiEnterSleepStatePrep(acpi_off_state);
1211     if (ACPI_FAILURE(status)) {
1212 	printf("AcpiEnterSleepStatePrep failed - %s\n",
1213 	       AcpiFormatException(status));
1214 	return;
1215     }
1216     ACPI_DISABLE_IRQS();
1217     status = AcpiEnterSleepState(acpi_off_state);
1218     if (ACPI_FAILURE(status)) {
1219 	printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
1220     } else {
1221 	DELAY(1000000);
1222 	printf("ACPI power-off failed - timeout\n");
1223     }
1224 }
1225 
1226 static void
1227 acpi_enable_fixed_events(struct acpi_softc *sc)
1228 {
1229     static int	first_time = 1;
1230 
1231     ACPI_ASSERTLOCK;
1232 
1233     /* Enable and clear fixed events and install handlers. */
1234     if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->PwrButton == 0) {
1235 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
1236 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
1237 				     acpi_event_power_button_sleep, sc);
1238 	if (first_time)
1239 	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
1240     }
1241     if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->SleepButton == 0) {
1242 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
1243 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
1244 				     acpi_event_sleep_button_sleep, sc);
1245 	if (first_time)
1246 	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
1247     }
1248 
1249     first_time = 0;
1250 }
1251 
1252 /*
1253  * Returns true if the device is actually present and should
1254  * be attached to.  This requires the present, enabled, UI-visible
1255  * and diagnostics-passed bits to be set.
1256  */
1257 BOOLEAN
1258 acpi_DeviceIsPresent(device_t dev)
1259 {
1260     ACPI_DEVICE_INFO	*devinfo;
1261     ACPI_HANDLE		h;
1262     ACPI_BUFFER		buf;
1263     ACPI_STATUS		error;
1264     int			ret;
1265 
1266     ACPI_ASSERTLOCK;
1267 
1268     ret = FALSE;
1269     if ((h = acpi_get_handle(dev)) == NULL)
1270 	return (FALSE);
1271     buf.Pointer = NULL;
1272     buf.Length = ACPI_ALLOCATE_BUFFER;
1273     error = AcpiGetObjectInfo(h, &buf);
1274     if (ACPI_FAILURE(error))
1275 	return (FALSE);
1276     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1277 
1278     /* If no _STA method, must be present */
1279     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1280 	ret = TRUE;
1281 
1282     /* Return true for 'present' and 'functioning' */
1283     if ((devinfo->CurrentStatus & 0x9) == 0x9)
1284 	ret = TRUE;
1285 
1286     AcpiOsFree(buf.Pointer);
1287     return (ret);
1288 }
1289 
1290 /*
1291  * Returns true if the battery is actually present and inserted.
1292  */
1293 BOOLEAN
1294 acpi_BatteryIsPresent(device_t dev)
1295 {
1296     ACPI_DEVICE_INFO	*devinfo;
1297     ACPI_HANDLE		h;
1298     ACPI_BUFFER		buf;
1299     ACPI_STATUS		error;
1300     int			ret;
1301 
1302     ACPI_ASSERTLOCK;
1303 
1304     ret = FALSE;
1305     if ((h = acpi_get_handle(dev)) == NULL)
1306 	return (FALSE);
1307     buf.Pointer = NULL;
1308     buf.Length = ACPI_ALLOCATE_BUFFER;
1309     error = AcpiGetObjectInfo(h, &buf);
1310     if (ACPI_FAILURE(error))
1311 	return (FALSE);
1312     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1313 
1314     /* If no _STA method, must be present */
1315     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1316 	ret = TRUE;
1317 
1318     /* Return true for 'present' and 'functioning' */
1319     if ((devinfo->CurrentStatus & 0x19) == 0x19)
1320 	ret = TRUE;
1321 
1322     AcpiOsFree(buf.Pointer);
1323     return (ret);
1324 }
1325 
1326 /*
1327  * Match a HID string against a device
1328  */
1329 BOOLEAN
1330 acpi_MatchHid(device_t dev, char *hid)
1331 {
1332     ACPI_DEVICE_INFO	*devinfo;
1333     ACPI_HANDLE		h;
1334     ACPI_BUFFER		buf;
1335     ACPI_STATUS		error;
1336     int			ret, i;
1337 
1338     ACPI_ASSERTLOCK;
1339 
1340     ret = FALSE;
1341     if (hid == NULL)
1342 	return (FALSE);
1343     if ((h = acpi_get_handle(dev)) == NULL)
1344 	return (FALSE);
1345     buf.Pointer = NULL;
1346     buf.Length = ACPI_ALLOCATE_BUFFER;
1347     error = AcpiGetObjectInfo(h, &buf);
1348     if (ACPI_FAILURE(error))
1349 	return (FALSE);
1350     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1351 
1352     if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
1353 	strcmp(hid, devinfo->HardwareId.Value) == 0)
1354 	    ret = TRUE;
1355     else if ((devinfo->Valid & ACPI_VALID_CID) != 0) {
1356 	for (i = 0; i < devinfo->CompatibilityId.Count; i++) {
1357 	    if (strcmp(hid, devinfo->CompatibilityId.Id[i].Value) == 0) {
1358 		ret = TRUE;
1359 		break;
1360 	    }
1361 	}
1362     }
1363 
1364     AcpiOsFree(buf.Pointer);
1365     return (ret);
1366 }
1367 
1368 /*
1369  * Return the handle of a named object within our scope, ie. that of (parent)
1370  * or one if its parents.
1371  */
1372 ACPI_STATUS
1373 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1374 {
1375     ACPI_HANDLE		r;
1376     ACPI_STATUS		status;
1377 
1378     ACPI_ASSERTLOCK;
1379 
1380     /* Walk back up the tree to the root */
1381     for (;;) {
1382 	status = AcpiGetHandle(parent, path, &r);
1383 	if (ACPI_SUCCESS(status)) {
1384 	    *result = r;
1385 	    return (AE_OK);
1386 	}
1387 	if (status != AE_NOT_FOUND)
1388 	    return (AE_OK);
1389 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1390 	    return (AE_NOT_FOUND);
1391 	parent = r;
1392     }
1393 }
1394 
1395 /*
1396  * Allocate a buffer with a preset data size.
1397  */
1398 ACPI_BUFFER *
1399 acpi_AllocBuffer(int size)
1400 {
1401     ACPI_BUFFER	*buf;
1402 
1403     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1404 	return (NULL);
1405     buf->Length = size;
1406     buf->Pointer = (void *)(buf + 1);
1407     return (buf);
1408 }
1409 
1410 ACPI_STATUS
1411 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
1412 {
1413     ACPI_OBJECT arg1;
1414     ACPI_OBJECT_LIST args;
1415 
1416     ACPI_ASSERTLOCK;
1417 
1418     arg1.Type = ACPI_TYPE_INTEGER;
1419     arg1.Integer.Value = number;
1420     args.Count = 1;
1421     args.Pointer = &arg1;
1422 
1423     return (AcpiEvaluateObject(handle, path, &args, NULL));
1424 }
1425 
1426 /*
1427  * Evaluate a path that should return an integer.
1428  */
1429 ACPI_STATUS
1430 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
1431 {
1432     ACPI_STATUS	status;
1433     ACPI_BUFFER	buf;
1434     ACPI_OBJECT	param;
1435 
1436     ACPI_ASSERTLOCK;
1437 
1438     if (handle == NULL)
1439 	handle = ACPI_ROOT_OBJECT;
1440 
1441     /*
1442      * Assume that what we've been pointed at is an Integer object, or
1443      * a method that will return an Integer.
1444      */
1445     buf.Pointer = &param;
1446     buf.Length = sizeof(param);
1447     status = AcpiEvaluateObject(handle, path, NULL, &buf);
1448     if (ACPI_SUCCESS(status)) {
1449 	if (param.Type == ACPI_TYPE_INTEGER)
1450 	    *number = param.Integer.Value;
1451 	else
1452 	    status = AE_TYPE;
1453     }
1454 
1455     /*
1456      * In some applications, a method that's expected to return an Integer
1457      * may instead return a Buffer (probably to simplify some internal
1458      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1459      * convert it into an Integer as best we can.
1460      *
1461      * This is a hack.
1462      */
1463     if (status == AE_BUFFER_OVERFLOW) {
1464 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1465 	    status = AE_NO_MEMORY;
1466 	} else {
1467 	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1468 	    if (ACPI_SUCCESS(status))
1469 		status = acpi_ConvertBufferToInteger(&buf, number);
1470 	    AcpiOsFree(buf.Pointer);
1471 	}
1472     }
1473     return (status);
1474 }
1475 
1476 ACPI_STATUS
1477 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
1478 {
1479     ACPI_OBJECT	*p;
1480     UINT8	*val;
1481     int		i;
1482 
1483     p = (ACPI_OBJECT *)bufp->Pointer;
1484     if (p->Type == ACPI_TYPE_INTEGER) {
1485 	*number = p->Integer.Value;
1486 	return (AE_OK);
1487     }
1488     if (p->Type != ACPI_TYPE_BUFFER)
1489 	return (AE_TYPE);
1490     if (p->Buffer.Length > sizeof(int))
1491 	return (AE_BAD_DATA);
1492 
1493     *number = 0;
1494     val = p->Buffer.Pointer;
1495     for (i = 0; i < p->Buffer.Length; i++)
1496 	*number += val[i] << (i * 8);
1497     return (AE_OK);
1498 }
1499 
1500 /*
1501  * Iterate over the elements of an a package object, calling the supplied
1502  * function for each element.
1503  *
1504  * XXX possible enhancement might be to abort traversal on error.
1505  */
1506 ACPI_STATUS
1507 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
1508 	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
1509 {
1510     ACPI_OBJECT	*comp;
1511     int		i;
1512 
1513     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
1514 	return (AE_BAD_PARAMETER);
1515 
1516     /* Iterate over components */
1517     i = 0;
1518     comp = pkg->Package.Elements;
1519     for (; i < pkg->Package.Count; i++, comp++)
1520 	func(comp, arg);
1521 
1522     return (AE_OK);
1523 }
1524 
1525 /*
1526  * Find the (index)th resource object in a set.
1527  */
1528 ACPI_STATUS
1529 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1530 {
1531     ACPI_RESOURCE	*rp;
1532     int			i;
1533 
1534     rp = (ACPI_RESOURCE *)buf->Pointer;
1535     i = index;
1536     while (i-- > 0) {
1537 	/* Range check */
1538 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1539 	    return (AE_BAD_PARAMETER);
1540 
1541 	/* Check for terminator */
1542 	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1543 	    return (AE_NOT_FOUND);
1544 	rp = ACPI_NEXT_RESOURCE(rp);
1545     }
1546     if (resp != NULL)
1547 	*resp = rp;
1548 
1549     return (AE_OK);
1550 }
1551 
1552 /*
1553  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1554  *
1555  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1556  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1557  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1558  * resources.
1559  */
1560 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
1561 
1562 ACPI_STATUS
1563 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1564 {
1565     ACPI_RESOURCE	*rp;
1566     void		*newp;
1567 
1568     /* Initialise the buffer if necessary. */
1569     if (buf->Pointer == NULL) {
1570 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1571 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1572 	    return (AE_NO_MEMORY);
1573 	rp = (ACPI_RESOURCE *)buf->Pointer;
1574 	rp->Id = ACPI_RSTYPE_END_TAG;
1575 	rp->Length = 0;
1576     }
1577     if (res == NULL)
1578 	return (AE_OK);
1579 
1580     /*
1581      * Scan the current buffer looking for the terminator.
1582      * This will either find the terminator or hit the end
1583      * of the buffer and return an error.
1584      */
1585     rp = (ACPI_RESOURCE *)buf->Pointer;
1586     for (;;) {
1587 	/* Range check, don't go outside the buffer */
1588 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1589 	    return (AE_BAD_PARAMETER);
1590 	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1591 	    break;
1592 	rp = ACPI_NEXT_RESOURCE(rp);
1593     }
1594 
1595     /*
1596      * Check the size of the buffer and expand if required.
1597      *
1598      * Required size is:
1599      *	size of existing resources before terminator +
1600      *	size of new resource and header +
1601      * 	size of terminator.
1602      *
1603      * Note that this loop should really only run once, unless
1604      * for some reason we are stuffing a *really* huge resource.
1605      */
1606     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
1607 	    res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1608 	    ACPI_RESOURCE_LENGTH) >= buf->Length) {
1609 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1610 	    return (AE_NO_MEMORY);
1611 	bcopy(buf->Pointer, newp, buf->Length);
1612 	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1613 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1614 	AcpiOsFree(buf->Pointer);
1615 	buf->Pointer = newp;
1616 	buf->Length += buf->Length;
1617     }
1618 
1619     /* Insert the new resource. */
1620     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1621 
1622     /* And add the terminator. */
1623     rp = ACPI_NEXT_RESOURCE(rp);
1624     rp->Id = ACPI_RSTYPE_END_TAG;
1625     rp->Length = 0;
1626 
1627     return (AE_OK);
1628 }
1629 
1630 /*
1631  * Set interrupt model.
1632  */
1633 ACPI_STATUS
1634 acpi_SetIntrModel(int model)
1635 {
1636 
1637     return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
1638 }
1639 
1640 #define ACPI_MINIMUM_AWAKETIME	5
1641 
1642 static void
1643 acpi_sleep_enable(void *arg)
1644 {
1645     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1646 }
1647 
1648 /*
1649  * Set the system sleep state
1650  *
1651  * Currently we support S1-S5 but S4 is only S4BIOS
1652  */
1653 ACPI_STATUS
1654 acpi_SetSleepState(struct acpi_softc *sc, int state)
1655 {
1656     ACPI_STATUS	status = AE_OK;
1657     UINT8	TypeA;
1658     UINT8	TypeB;
1659 
1660     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1661     ACPI_ASSERTLOCK;
1662 
1663     /* Avoid reentry if already attempting to suspend. */
1664     if (sc->acpi_sstate != ACPI_STATE_S0)
1665 	return_ACPI_STATUS (AE_BAD_PARAMETER);
1666 
1667     /* We recently woke up so don't suspend again for a while. */
1668     if (sc->acpi_sleep_disabled)
1669 	return_ACPI_STATUS (AE_OK);
1670 
1671     switch (state) {
1672     case ACPI_STATE_S1:
1673     case ACPI_STATE_S2:
1674     case ACPI_STATE_S3:
1675     case ACPI_STATE_S4:
1676 	status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB);
1677 	if (status == AE_NOT_FOUND) {
1678 	    device_printf(sc->acpi_dev,
1679 			  "Sleep state S%d not supported by BIOS\n", state);
1680 	    break;
1681 	} else if (ACPI_FAILURE(status)) {
1682 	    device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n",
1683 			  AcpiFormatException(status));
1684 	    break;
1685 	}
1686 
1687 	sc->acpi_sstate = state;
1688 	sc->acpi_sleep_disabled = 1;
1689 
1690 	/* Inform all devices that we are going to sleep. */
1691 	if (DEVICE_SUSPEND(root_bus) != 0) {
1692 	    /*
1693 	     * Re-wake the system.
1694 	     *
1695 	     * XXX note that a better two-pass approach with a 'veto' pass
1696 	     *     followed by a "real thing" pass would be better, but the
1697 	     *     current bus interface does not provide for this.
1698 	     */
1699 	    DEVICE_RESUME(root_bus);
1700 	    return_ACPI_STATUS (AE_ERROR);
1701 	}
1702 
1703 	status = AcpiEnterSleepStatePrep(state);
1704 	if (ACPI_FAILURE(status)) {
1705 	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1706 			  AcpiFormatException(status));
1707 	    break;
1708 	}
1709 
1710 	if (sc->acpi_sleep_delay > 0)
1711 	    DELAY(sc->acpi_sleep_delay * 1000000);
1712 
1713 	if (state != ACPI_STATE_S1) {
1714 	    acpi_sleep_machdep(sc, state);
1715 
1716 	    /* AcpiEnterSleepState() may be incomplete, unlock if locked. */
1717 	    if (AcpiGbl_MutexInfo[ACPI_MTX_HARDWARE].OwnerId !=
1718 		ACPI_MUTEX_NOT_ACQUIRED) {
1719 
1720 		AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1721 	    }
1722 
1723 	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1724 	    if (state == ACPI_STATE_S4)
1725 		AcpiEnable();
1726 	} else {
1727 	    status = AcpiEnterSleepState((UINT8)state);
1728 	    if (ACPI_FAILURE(status)) {
1729 		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
1730 			      AcpiFormatException(status));
1731 		break;
1732 	    }
1733 	}
1734 	AcpiLeaveSleepState((UINT8)state);
1735 	DEVICE_RESUME(root_bus);
1736 	sc->acpi_sstate = ACPI_STATE_S0;
1737 	acpi_enable_fixed_events(sc);
1738 	break;
1739     case ACPI_STATE_S5:
1740 	/*
1741 	 * Shut down cleanly and power off.  This will call us back through the
1742 	 * shutdown handlers.
1743 	 */
1744 	shutdown_nice(RB_POWEROFF);
1745 	break;
1746     case ACPI_STATE_S0:
1747     default:
1748 	status = AE_BAD_PARAMETER;
1749 	break;
1750     }
1751 
1752     /* Disable a second sleep request for a short period */
1753     if (sc->acpi_sleep_disabled)
1754 	timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
1755 
1756     return_ACPI_STATUS (status);
1757 }
1758 
1759 /*
1760  * Enable/Disable ACPI
1761  */
1762 ACPI_STATUS
1763 acpi_Enable(struct acpi_softc *sc)
1764 {
1765     ACPI_STATUS	status;
1766     u_int32_t	flags;
1767 
1768     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1769     ACPI_ASSERTLOCK;
1770 
1771     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
1772 	    ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
1773     if (!sc->acpi_enabled)
1774 	status = AcpiEnableSubsystem(flags);
1775     else
1776 	status = AE_OK;
1777 
1778     if (status == AE_OK)
1779 	sc->acpi_enabled = 1;
1780 
1781     return_ACPI_STATUS (status);
1782 }
1783 
1784 ACPI_STATUS
1785 acpi_Disable(struct acpi_softc *sc)
1786 {
1787     ACPI_STATUS	status;
1788 
1789     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1790     ACPI_ASSERTLOCK;
1791 
1792     if (sc->acpi_enabled)
1793 	status = AcpiDisable();
1794     else
1795 	status = AE_OK;
1796 
1797     if (status == AE_OK)
1798 	sc->acpi_enabled = 0;
1799 
1800     return_ACPI_STATUS (status);
1801 }
1802 
1803 /*
1804  * ACPI Event Handlers
1805  */
1806 
1807 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1808 
1809 static void
1810 acpi_system_eventhandler_sleep(void *arg, int state)
1811 {
1812     ACPI_LOCK_DECL;
1813     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1814 
1815     ACPI_LOCK;
1816     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
1817 	acpi_SetSleepState((struct acpi_softc *)arg, state);
1818     ACPI_UNLOCK;
1819     return_VOID;
1820 }
1821 
1822 static void
1823 acpi_system_eventhandler_wakeup(void *arg, int state)
1824 {
1825     ACPI_LOCK_DECL;
1826     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1827 
1828     /* Well, what to do? :-) */
1829 
1830     ACPI_LOCK;
1831     ACPI_UNLOCK;
1832 
1833     return_VOID;
1834 }
1835 
1836 /*
1837  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1838  */
1839 UINT32
1840 acpi_event_power_button_sleep(void *context)
1841 {
1842     struct acpi_softc	*sc = (struct acpi_softc *)context;
1843 
1844     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1845 
1846     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1847 
1848     return_VALUE (ACPI_INTERRUPT_HANDLED);
1849 }
1850 
1851 UINT32
1852 acpi_event_power_button_wake(void *context)
1853 {
1854     struct acpi_softc	*sc = (struct acpi_softc *)context;
1855 
1856     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1857 
1858     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1859 
1860     return_VALUE (ACPI_INTERRUPT_HANDLED);
1861 }
1862 
1863 UINT32
1864 acpi_event_sleep_button_sleep(void *context)
1865 {
1866     struct acpi_softc	*sc = (struct acpi_softc *)context;
1867 
1868     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1869 
1870     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1871 
1872     return_VALUE (ACPI_INTERRUPT_HANDLED);
1873 }
1874 
1875 UINT32
1876 acpi_event_sleep_button_wake(void *context)
1877 {
1878     struct acpi_softc	*sc = (struct acpi_softc *)context;
1879 
1880     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1881 
1882     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1883 
1884     return_VALUE (ACPI_INTERRUPT_HANDLED);
1885 }
1886 
1887 /*
1888  * XXX This is kinda ugly, and should not be here.
1889  */
1890 struct acpi_staticbuf {
1891     ACPI_BUFFER	buffer;
1892     char	data[512];
1893 };
1894 
1895 char *
1896 acpi_name(ACPI_HANDLE handle)
1897 {
1898     static struct acpi_staticbuf	buf;
1899 
1900     ACPI_ASSERTLOCK;
1901 
1902     buf.buffer.Length = 512;
1903     buf.buffer.Pointer = &buf.data[0];
1904 
1905     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
1906 	return (buf.buffer.Pointer);
1907 
1908     return ("(unknown path)");
1909 }
1910 
1911 /*
1912  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1913  * parts of the namespace.
1914  */
1915 int
1916 acpi_avoid(ACPI_HANDLE handle)
1917 {
1918     char	*cp, *env, *np;
1919     int		len;
1920 
1921     np = acpi_name(handle);
1922     if (*np == '\\')
1923 	np++;
1924     if ((env = getenv("debug.acpi.avoid")) == NULL)
1925 	return (0);
1926 
1927     /* Scan the avoid list checking for a match */
1928     cp = env;
1929     for (;;) {
1930 	while ((*cp != 0) && isspace(*cp))
1931 	    cp++;
1932 	if (*cp == 0)
1933 	    break;
1934 	len = 0;
1935 	while ((cp[len] != 0) && !isspace(cp[len]))
1936 	    len++;
1937 	if (!strncmp(cp, np, len)) {
1938 	    freeenv(env);
1939 	    return(1);
1940 	}
1941 	cp += len;
1942     }
1943     freeenv(env);
1944 
1945     return (0);
1946 }
1947 
1948 /*
1949  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1950  */
1951 int
1952 acpi_disabled(char *subsys)
1953 {
1954     char	*cp, *env;
1955     int		len;
1956 
1957     if ((env = getenv("debug.acpi.disabled")) == NULL)
1958 	return (0);
1959     if (strcmp(env, "all") == 0) {
1960 	freeenv(env);
1961 	return (1);
1962     }
1963 
1964     /* Scan the disable list, checking for a match. */
1965     cp = env;
1966     for (;;) {
1967 	while (*cp != '\0' && isspace(*cp))
1968 	    cp++;
1969 	if (*cp == '\0')
1970 	    break;
1971 	len = 0;
1972 	while (cp[len] != '\0' && !isspace(cp[len]))
1973 	    len++;
1974 	if (strncmp(cp, subsys, len) == 0) {
1975 	    freeenv(env);
1976 	    return (1);
1977 	}
1978 	cp += len;
1979     }
1980     freeenv(env);
1981 
1982     return (0);
1983 }
1984 
1985 /*
1986  * Device wake capability enable/disable.
1987  */
1988 void
1989 acpi_device_enable_wake_capability(ACPI_HANDLE h, int enable)
1990 {
1991     /*
1992      * TBD: All Power Resources referenced by elements 2 through N
1993      *      of the _PRW object are put into the ON state.
1994      */
1995 
1996     (void)acpi_SetInteger(h, "_PSW", enable);
1997 }
1998 
1999 void
2000 acpi_device_enable_wake_event(ACPI_HANDLE h)
2001 {
2002     struct acpi_softc		*sc;
2003     ACPI_STATUS			status;
2004     ACPI_BUFFER			prw_buffer;
2005     ACPI_OBJECT			*res;
2006 
2007     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2008 
2009     sc = devclass_get_softc(acpi_devclass, 0);
2010     if (sc == NULL)
2011 	return;
2012 
2013     /*
2014      * _PRW object is only required for devices that have the ability
2015      * to wake the system from a system sleeping state.
2016      */
2017     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
2018     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
2019     if (ACPI_FAILURE(status))
2020 	return;
2021 
2022     res = (ACPI_OBJECT *)prw_buffer.Pointer;
2023     if (res == NULL)
2024 	return;
2025 
2026     if ((res->Type != ACPI_TYPE_PACKAGE) || (res->Package.Count < 2)) {
2027 	goto out;
2028     }
2029 
2030     /*
2031      * The element 1 of the _PRW object:
2032      * The lowest power system sleeping state that can be entered
2033      * while still providing wake functionality.
2034      * The sleeping state being entered must be greater or equal to
2035      * the power state declared in element 1 of the _PRW object.
2036      */
2037     if (res->Package.Elements[1].Type != ACPI_TYPE_INTEGER)
2038 	goto out;
2039 
2040     if (sc->acpi_sstate > res->Package.Elements[1].Integer.Value)
2041 	goto out;
2042 
2043     /*
2044      * The element 0 of the _PRW object:
2045      */
2046     switch(res->Package.Elements[0].Type) {
2047     case ACPI_TYPE_INTEGER:
2048 	/*
2049 	 * If the data type of this package element is numeric, then this
2050 	 * _PRW package element is the bit index in the GPEx_EN, in the
2051 	 * GPE blocks described in the FADT, of the enable bit that is
2052 	 * enabled for the wake event.
2053 	 */
2054 
2055 	status = AcpiEnableGpe(NULL, res->Package.Elements[0].Integer.Value,
2056 			       ACPI_EVENT_WAKE_ENABLE);
2057 	if (ACPI_FAILURE(status))
2058 	    printf("%s: EnableEvent Failed\n", __func__);
2059 	break;
2060     case ACPI_TYPE_PACKAGE:
2061 	/*
2062 	 * XXX TBD
2063 	 *
2064 	 * If the data type of this package element is a package, then this
2065 	 * _PRW package element is itself a package containing two
2066 	 * elements. The first is an object reference to the GPE Block
2067 	 * device that contains the GPE that will be triggered by the wake
2068 	 * event. The second element is numeric and it contains the bit
2069 	 * index in the GPEx_EN, in the GPE Block referenced by the
2070 	 * first element in the package, of the enable bit that is enabled for
2071 	 * the wake event.
2072 	 * For example, if this field is a package then it is of the form:
2073 	 * Package() {\_SB.PCI0.ISA.GPE, 2}
2074 	 */
2075 	break;
2076     default:
2077 	break;
2078     }
2079 
2080 out:
2081     if (prw_buffer.Pointer != NULL)
2082 	AcpiOsFree(prw_buffer.Pointer);
2083 }
2084 
2085 /*
2086  * Control interface.
2087  *
2088  * We multiplex ioctls for all participating ACPI devices here.  Individual
2089  * drivers wanting to be accessible via /dev/acpi should use the
2090  * register/deregister interface to make their handlers visible.
2091  */
2092 struct acpi_ioctl_hook
2093 {
2094     TAILQ_ENTRY(acpi_ioctl_hook) link;
2095     u_long			 cmd;
2096     acpi_ioctl_fn		 fn;
2097     void			 *arg;
2098 };
2099 
2100 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
2101 static int				acpi_ioctl_hooks_initted;
2102 
2103 /*
2104  * Register an ioctl handler.
2105  */
2106 int
2107 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
2108 {
2109     struct acpi_ioctl_hook	*hp;
2110 
2111     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
2112 	return (ENOMEM);
2113     hp->cmd = cmd;
2114     hp->fn = fn;
2115     hp->arg = arg;
2116     if (acpi_ioctl_hooks_initted == 0) {
2117 	TAILQ_INIT(&acpi_ioctl_hooks);
2118 	acpi_ioctl_hooks_initted = 1;
2119     }
2120     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
2121     return (0);
2122 }
2123 
2124 /*
2125  * Deregister an ioctl handler.
2126  */
2127 void
2128 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
2129 {
2130     struct acpi_ioctl_hook	*hp;
2131 
2132     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
2133 	if ((hp->cmd == cmd) && (hp->fn == fn))
2134 	    break;
2135 
2136     if (hp != NULL) {
2137 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
2138 	free(hp, M_ACPIDEV);
2139     }
2140 }
2141 
2142 static int
2143 acpiopen(dev_t dev, int flag, int fmt, d_thread_t *td)
2144 {
2145     return (0);
2146 }
2147 
2148 static int
2149 acpiclose(dev_t dev, int flag, int fmt, d_thread_t *td)
2150 {
2151     return (0);
2152 }
2153 
2154 static int
2155 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
2156 {
2157     struct acpi_softc		*sc;
2158     struct acpi_ioctl_hook	*hp;
2159     int				error, xerror, state;
2160     ACPI_LOCK_DECL;
2161 
2162     ACPI_LOCK;
2163 
2164     error = state = 0;
2165     sc = dev->si_drv1;
2166 
2167     /*
2168      * Scan the list of registered ioctls, looking for handlers.
2169      */
2170     if (acpi_ioctl_hooks_initted) {
2171 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
2172 	    if (hp->cmd == cmd) {
2173 		xerror = hp->fn(cmd, addr, hp->arg);
2174 		if (xerror != 0)
2175 		    error = xerror;
2176 		goto out;
2177 	    }
2178 	}
2179     }
2180 
2181     /*
2182      * Core ioctls are not permitted for non-writable user.
2183      * Currently, other ioctls just fetch information.
2184      * Not changing system behavior.
2185      */
2186     if((flag & FWRITE) == 0)
2187 	return (EPERM);
2188 
2189     /* Core system ioctls. */
2190     switch (cmd) {
2191     case ACPIIO_ENABLE:
2192 	if (ACPI_FAILURE(acpi_Enable(sc)))
2193 	    error = ENXIO;
2194 	break;
2195     case ACPIIO_DISABLE:
2196 	if (ACPI_FAILURE(acpi_Disable(sc)))
2197 	    error = ENXIO;
2198 	break;
2199     case ACPIIO_SETSLPSTATE:
2200 	if (!sc->acpi_enabled) {
2201 	    error = ENXIO;
2202 	    break;
2203 	}
2204 	state = *(int *)addr;
2205 	if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
2206 	    if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
2207 		error = EINVAL;
2208 	} else {
2209 	    error = EINVAL;
2210 	}
2211 	break;
2212     default:
2213 	if (error == 0)
2214 	    error = EINVAL;
2215 	break;
2216     }
2217 
2218 out:
2219     ACPI_UNLOCK;
2220     return (error);
2221 }
2222 
2223 static int
2224 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2225 {
2226     char sleep_state[4];
2227     char buf[16];
2228     int error;
2229     UINT8 state, TypeA, TypeB;
2230 
2231     buf[0] = '\0';
2232     for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX+1; state++) {
2233 	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
2234 	    sprintf(sleep_state, "S%d ", state);
2235 	    strcat(buf, sleep_state);
2236 	}
2237     }
2238     error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2239     return (error);
2240 }
2241 
2242 static int
2243 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2244 {
2245     char sleep_state[10];
2246     int error;
2247     u_int new_state, old_state;
2248 
2249     old_state = *(u_int *)oidp->oid_arg1;
2250     if (old_state > ACPI_S_STATES_MAX+1) {
2251 	strcpy(sleep_state, "unknown");
2252     } else {
2253 	bzero(sleep_state, sizeof(sleep_state));
2254 	strncpy(sleep_state, sleep_state_names[old_state],
2255 		sizeof(sleep_state_names[old_state]));
2256     }
2257     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
2258     if (error == 0 && req->newptr != NULL) {
2259 	new_state = ACPI_STATE_S0;
2260 	for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++) {
2261 	    if (strncmp(sleep_state, sleep_state_names[new_state],
2262 			sizeof(sleep_state)) == 0)
2263 		break;
2264 	}
2265 	if (new_state <= ACPI_S_STATES_MAX + 1) {
2266 	    if (new_state != old_state)
2267 		*(u_int *)oidp->oid_arg1 = new_state;
2268 	} else {
2269 	    error = EINVAL;
2270 	}
2271     }
2272 
2273     return (error);
2274 }
2275 
2276 /* Inform devctl(4) when we receive a Notify. */
2277 void
2278 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
2279 {
2280     char		notify_buf[16];
2281     ACPI_BUFFER		handle_buf;
2282     ACPI_STATUS		status;
2283 
2284     if (subsystem == NULL)
2285 	return;
2286 
2287     handle_buf.Pointer = NULL;
2288     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
2289     status = AcpiNsHandleToPathname(h, &handle_buf);
2290     if (ACPI_FAILURE(status))
2291 	return;
2292     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
2293     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
2294     AcpiOsFree(handle_buf.Pointer);
2295 }
2296 
2297 #ifdef ACPI_DEBUG
2298 /*
2299  * Support for parsing debug options from the kernel environment.
2300  *
2301  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
2302  * by specifying the names of the bits in the debug.acpi.layer and
2303  * debug.acpi.level environment variables.  Bits may be unset by
2304  * prefixing the bit name with !.
2305  */
2306 struct debugtag
2307 {
2308     char	*name;
2309     UINT32	value;
2310 };
2311 
2312 static struct debugtag	dbg_layer[] = {
2313     {"ACPI_UTILITIES",		ACPI_UTILITIES},
2314     {"ACPI_HARDWARE",		ACPI_HARDWARE},
2315     {"ACPI_EVENTS",		ACPI_EVENTS},
2316     {"ACPI_TABLES",		ACPI_TABLES},
2317     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
2318     {"ACPI_PARSER",		ACPI_PARSER},
2319     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
2320     {"ACPI_EXECUTER",		ACPI_EXECUTER},
2321     {"ACPI_RESOURCES",		ACPI_RESOURCES},
2322     {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
2323     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
2324     {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
2325     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
2326 
2327     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
2328     {"ACPI_BATTERY",		ACPI_BATTERY},
2329     {"ACPI_BUS",		ACPI_BUS},
2330     {"ACPI_BUTTON",		ACPI_BUTTON},
2331     {"ACPI_EC", 		ACPI_EC},
2332     {"ACPI_FAN",		ACPI_FAN},
2333     {"ACPI_POWERRES",		ACPI_POWERRES},
2334     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
2335     {"ACPI_THERMAL",		ACPI_THERMAL},
2336     {"ACPI_TIMER",		ACPI_TIMER},
2337     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
2338     {NULL, 0}
2339 };
2340 
2341 static struct debugtag dbg_level[] = {
2342     {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
2343     {"ACPI_LV_WARN",		ACPI_LV_WARN},
2344     {"ACPI_LV_INIT",		ACPI_LV_INIT},
2345     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
2346     {"ACPI_LV_INFO",		ACPI_LV_INFO},
2347     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
2348 
2349     /* Trace verbosity level 1 [Standard Trace Level] */
2350     {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
2351     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
2352     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
2353     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
2354     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
2355     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
2356     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
2357     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
2358     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
2359     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
2360     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
2361     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
2362     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
2363     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
2364     {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
2365 
2366     /* Trace verbosity level 2 [Function tracing and memory allocation] */
2367     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
2368     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
2369     {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
2370     {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
2371     {"ACPI_LV_ALL",		ACPI_LV_ALL},
2372 
2373     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2374     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
2375     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
2376     {"ACPI_LV_IO",		ACPI_LV_IO},
2377     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
2378     {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
2379 
2380     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2381     {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
2382     {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
2383     {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
2384     {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
2385     {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
2386     {NULL, 0}
2387 };
2388 
2389 static void
2390 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2391 {
2392     char	*ep;
2393     int		i, l;
2394     int		set;
2395 
2396     while (*cp) {
2397 	if (isspace(*cp)) {
2398 	    cp++;
2399 	    continue;
2400 	}
2401 	ep = cp;
2402 	while (*ep && !isspace(*ep))
2403 	    ep++;
2404 	if (*cp == '!') {
2405 	    set = 0;
2406 	    cp++;
2407 	    if (cp == ep)
2408 		continue;
2409 	} else {
2410 	    set = 1;
2411 	}
2412 	l = ep - cp;
2413 	for (i = 0; tag[i].name != NULL; i++) {
2414 	    if (!strncmp(cp, tag[i].name, l)) {
2415 		if (set)
2416 		    *flag |= tag[i].value;
2417 		else
2418 		    *flag &= ~tag[i].value;
2419 		printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
2420 	    }
2421 	}
2422 	cp = ep;
2423     }
2424 }
2425 
2426 static void
2427 acpi_set_debugging(void *junk)
2428 {
2429     char	*cp;
2430 
2431     if (cold) {
2432 	AcpiDbgLayer = 0;
2433 	AcpiDbgLevel = 0;
2434     }
2435 
2436     if ((cp = getenv("debug.acpi.layer")) != NULL) {
2437 	acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
2438 	freeenv(cp);
2439     }
2440     if ((cp = getenv("debug.acpi.level")) != NULL) {
2441 	acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
2442 	freeenv(cp);
2443     }
2444 
2445     if (cold) {
2446 	printf("ACPI debug layer 0x%x debug level 0x%x\n",
2447 	       AcpiDbgLayer, AcpiDbgLevel);
2448     }
2449 }
2450 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
2451 	NULL);
2452 
2453 static int
2454 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
2455 {
2456     int		 error, *dbg;
2457     struct	 debugtag *tag;
2458     struct	 sbuf sb;
2459 
2460     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
2461 	return (ENOMEM);
2462     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
2463 	tag = &dbg_layer[0];
2464 	dbg = &AcpiDbgLayer;
2465     } else {
2466 	tag = &dbg_level[0];
2467 	dbg = &AcpiDbgLevel;
2468     }
2469 
2470     /* Get old values if this is a get request. */
2471     if (*dbg == 0) {
2472 	sbuf_cpy(&sb, "NONE");
2473     } else if (req->newptr == NULL) {
2474 	for (; tag->name != NULL; tag++) {
2475 	    if ((*dbg & tag->value) == tag->value)
2476 		sbuf_printf(&sb, "%s ", tag->name);
2477 	}
2478     }
2479     sbuf_trim(&sb);
2480     sbuf_finish(&sb);
2481 
2482     error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
2483     sbuf_delete(&sb);
2484 
2485     /* If the user is setting a string, parse it. */
2486     if (error == 0 && req->newptr != NULL) {
2487 	*dbg = 0;
2488 	setenv((char *)oidp->oid_arg1, (char *)req->newptr);
2489 	acpi_set_debugging(NULL);
2490     }
2491 
2492     return (error);
2493 }
2494 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
2495 	    "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
2496 SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
2497 	    "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
2498 #endif
2499 
2500 static int
2501 acpi_pm_func(u_long cmd, void *arg, ...)
2502 {
2503 	int	state, acpi_state;
2504 	int	error;
2505 	struct	acpi_softc *sc;
2506 	va_list	ap;
2507 
2508 	error = 0;
2509 	switch (cmd) {
2510 	case POWER_CMD_SUSPEND:
2511 		sc = (struct acpi_softc *)arg;
2512 		if (sc == NULL) {
2513 			error = EINVAL;
2514 			goto out;
2515 		}
2516 
2517 		va_start(ap, arg);
2518 		state = va_arg(ap, int);
2519 		va_end(ap);
2520 
2521 		switch (state) {
2522 		case POWER_SLEEP_STATE_STANDBY:
2523 			acpi_state = sc->acpi_standby_sx;
2524 			break;
2525 		case POWER_SLEEP_STATE_SUSPEND:
2526 			acpi_state = sc->acpi_suspend_sx;
2527 			break;
2528 		case POWER_SLEEP_STATE_HIBERNATE:
2529 			acpi_state = ACPI_STATE_S4;
2530 			break;
2531 		default:
2532 			error = EINVAL;
2533 			goto out;
2534 		}
2535 
2536 		acpi_SetSleepState(sc, acpi_state);
2537 		break;
2538 	default:
2539 		error = EINVAL;
2540 		goto out;
2541 	}
2542 
2543 out:
2544 	return (error);
2545 }
2546 
2547 static void
2548 acpi_pm_register(void *arg)
2549 {
2550     if (!cold || resource_disabled("acpi", 0))
2551 	return;
2552 
2553     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2554 }
2555 
2556 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
2557