xref: /freebsd/sys/dev/acpica/acpi.c (revision 3ff369fed2a08f32dda232c10470b949bef9489f)
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/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mutex.h>
39 #include <sys/bus.h>
40 #include <sys/conf.h>
41 #include <sys/ioccom.h>
42 #include <sys/reboot.h>
43 #include <sys/sysctl.h>
44 #include <sys/ctype.h>
45 #include <sys/linker.h>
46 #include <sys/power.h>
47 
48 #include <machine/clock.h>
49 #include <machine/resource.h>
50 
51 #include <isa/isavar.h>
52 
53 #include "acpi.h"
54 
55 #include <dev/acpica/acpica_support.h>
56 
57 #include <dev/acpica/acpivar.h>
58 #include <dev/acpica/acpiio.h>
59 
60 MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
61 
62 /*
63  * Hooks for the ACPI CA debugging infrastructure
64  */
65 #define _COMPONENT	ACPI_BUS
66 ACPI_MODULE_NAME("ACPI")
67 
68 /*
69  * Character device
70  */
71 
72 static d_open_t		acpiopen;
73 static d_close_t	acpiclose;
74 static d_ioctl_t	acpiioctl;
75 
76 #define CDEV_MAJOR 152
77 static struct cdevsw acpi_cdevsw = {
78     acpiopen,
79     acpiclose,
80     noread,
81     nowrite,
82     acpiioctl,
83     nopoll,
84     nommap,
85     nostrategy,
86     "acpi",
87     CDEV_MAJOR,
88     nodump,
89     nopsize,
90     0
91 };
92 
93 static const char* sleep_state_names[] = {
94     "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
95 
96 /* this has to be static, as the softc is gone when we need it */
97 static int acpi_off_state = ACPI_STATE_S5;
98 
99 struct mtx	acpi_mutex;
100 
101 static int	acpi_modevent(struct module *mod, int event, void *junk);
102 static void	acpi_identify(driver_t *driver, device_t parent);
103 static int	acpi_probe(device_t dev);
104 static int	acpi_attach(device_t dev);
105 static device_t	acpi_add_child(device_t bus, int order, const char *name, int unit);
106 static int	acpi_print_resources(struct resource_list *rl, const char *name, int type,
107 				     const char *format);
108 static int	acpi_print_child(device_t bus, device_t child);
109 static int	acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result);
110 static int	acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value);
111 static int	acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start,
112 				  u_long count);
113 static int	acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp,
114 				  u_long *countp);
115 static struct resource *acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
116 					    u_long start, u_long end, u_long count, u_int flags);
117 static int	acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r);
118 static u_int32_t acpi_isa_get_logicalid(device_t dev);
119 static int	acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids);
120 
121 static void	acpi_probe_children(device_t bus);
122 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status);
123 
124 static void	acpi_shutdown_pre_sync(void *arg, int howto);
125 static void	acpi_shutdown_final(void *arg, int howto);
126 
127 static void	acpi_enable_fixed_events(struct acpi_softc *sc);
128 
129 static void	acpi_system_eventhandler_sleep(void *arg, int state);
130 static void	acpi_system_eventhandler_wakeup(void *arg, int state);
131 static int	acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
132 
133 static int	acpi_pm_func(u_long cmd, void *arg, ...);
134 
135 static device_method_t acpi_methods[] = {
136     /* Device interface */
137     DEVMETHOD(device_identify,		acpi_identify),
138     DEVMETHOD(device_probe,		acpi_probe),
139     DEVMETHOD(device_attach,		acpi_attach),
140     DEVMETHOD(device_shutdown,		bus_generic_shutdown),
141     DEVMETHOD(device_suspend,		bus_generic_suspend),
142     DEVMETHOD(device_resume,		bus_generic_resume),
143 
144     /* Bus interface */
145     DEVMETHOD(bus_add_child,		acpi_add_child),
146     DEVMETHOD(bus_print_child,		acpi_print_child),
147     DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
148     DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
149     DEVMETHOD(bus_set_resource,		acpi_set_resource),
150     DEVMETHOD(bus_get_resource,		acpi_get_resource),
151     DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
152     DEVMETHOD(bus_release_resource,	acpi_release_resource),
153     DEVMETHOD(bus_driver_added,		bus_generic_driver_added),
154     DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
155     DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
156     DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
157     DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
158 
159     /* ISA emulation */
160     DEVMETHOD(isa_pnp_probe,		acpi_isa_pnp_probe),
161 
162     {0, 0}
163 };
164 
165 static driver_t acpi_driver = {
166     "acpi",
167     acpi_methods,
168     sizeof(struct acpi_softc),
169 };
170 
171 static devclass_t acpi_devclass;
172 DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
173 MODULE_VERSION(acpi, 100);
174 
175 SYSCTL_INT(_debug, OID_AUTO, acpi_debug_layer, CTLFLAG_RW, &AcpiDbgLayer, 0, "");
176 SYSCTL_INT(_debug, OID_AUTO, acpi_debug_level, CTLFLAG_RW, &AcpiDbgLevel, 0, "");
177 static int acpi_ca_version = ACPI_CA_VERSION;
178 SYSCTL_INT(_debug, OID_AUTO, acpi_ca_version, CTLFLAG_RD, &acpi_ca_version, 0, "");
179 
180 /*
181  * ACPI can only be loaded as a module by the loader; activating it after
182  * system bootstrap time is not useful, and can be fatal to the system.
183  * It also cannot be unloaded, since the entire system bus heirarchy hangs off it.
184  */
185 static int
186 acpi_modevent(struct module *mod, int event, void *junk)
187 {
188     switch(event) {
189     case MOD_LOAD:
190 	if (!cold)
191 	    return(EPERM);
192 	break;
193     case MOD_UNLOAD:
194 	if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
195 	    return(EBUSY);
196 	break;
197     default:
198 	break;
199     }
200     return(0);
201 }
202 
203 /*
204  * Detect ACPI, perform early initialisation
205  */
206 static void
207 acpi_identify(driver_t *driver, device_t parent)
208 {
209     device_t			child;
210     int				error;
211     caddr_t			acpi_dsdt, p;
212 #ifdef ENABLE_DEBUGGER
213     char			*debugpoint;
214 #endif
215 
216     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
217 
218     if(!cold){
219 	    printf("Don't load this driver from userland!!\n");
220 	    return ;
221     }
222 
223     /*
224      * Check that we haven't been disabled with a hint.
225      */
226     if (!resource_int_value("acpi", 0, "disabled", &error) &&
227 	(error != 0))
228 	return_VOID;
229 
230     /*
231      * Make sure we're not being doubly invoked.
232      */
233     if (device_find_child(parent, "acpi", 0) != NULL)
234 	return_VOID;
235 
236     /* initialise the ACPI mutex */
237     mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
238 
239     /*
240      * Start up the ACPI CA subsystem.
241      */
242 #ifdef ENABLE_DEBUGGER
243     debugpoint = getenv("debug.acpi.debugger");
244     if (debugpoint) {
245 	if (!strcmp(debugpoint, "init"))
246 	    acpi_EnterDebugger();
247         freeenv(debugpoint);
248     }
249 #endif
250     if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
251 	printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
252 	return_VOID;
253     }
254 #ifdef ENABLE_DEBUGGER
255     debugpoint = getenv("debug.acpi.debugger");
256     if (debugpoint) {
257 	if (!strcmp(debugpoint, "tables"))
258 	    acpi_EnterDebugger();
259         freeenv(debugpoint);
260     }
261 #endif
262 
263     if ((acpi_dsdt = preload_search_by_type("acpi_dsdt")) != NULL) {
264         if ((p = preload_search_info(acpi_dsdt, MODINFO_ADDR)) != NULL) {
265 	    if (ACPI_FAILURE(error = AcpiSetDsdtTablePtr(*(void **)p))) {
266 		printf("ACPI: DSDT overriding failed: %s\n",
267 		       AcpiFormatException(error));
268 	    } else {
269 		printf("ACPI: DSDT was overridden.\n");
270 	    }
271         }
272     }
273 
274     if (ACPI_FAILURE(error = AcpiLoadTables())) {
275 	printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
276 	return_VOID;
277     }
278 
279     /*
280      * Attach the actual ACPI device.
281      */
282     if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
283 	    device_printf(parent, "ACPI: could not attach\n");
284 	    return_VOID;
285     }
286 }
287 
288 /*
289  * Fetch some descriptive data from ACPI to put in our attach message
290  */
291 static int
292 acpi_probe(device_t dev)
293 {
294     ACPI_TABLE_HEADER	th;
295     char		buf[20];
296     ACPI_STATUS		status;
297     int			error;
298 
299     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
300 
301     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
302         power_pm_get_type() != POWER_PM_TYPE_ACPI) {
303 	device_printf(dev, "Other PM system enabled.\n");
304 	return_VALUE(ENXIO);
305     }
306 
307     ACPI_LOCK;
308 
309     if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
310 	device_printf(dev, "couldn't get XSDT header: %s\n", AcpiFormatException(status));
311 	error = ENXIO;
312     } else {
313 	sprintf(buf, "%.6s %.8s", th.OemId, th.OemTableId);
314 	device_set_desc_copy(dev, buf);
315 	error = 0;
316     }
317     ACPI_UNLOCK;
318     return_VALUE(error);
319 }
320 
321 static int
322 acpi_attach(device_t dev)
323 {
324     struct acpi_softc	*sc;
325     ACPI_STATUS		status;
326     int			error;
327     UINT32		flags;
328 
329 #ifdef ENABLE_DEBUGGER
330     char		*debugpoint;
331 #endif
332 
333     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
334     ACPI_LOCK;
335     sc = device_get_softc(dev);
336     bzero(sc, sizeof(*sc));
337     sc->acpi_dev = dev;
338 
339 #ifdef ENABLE_DEBUGGER
340     debugpoint = getenv("debug.acpi.debugger");
341     if (debugpoint) {
342 	if (!strcmp(debugpoint, "spaces"))
343 	    acpi_EnterDebugger();
344         freeenv(debugpoint);
345     }
346 #endif
347 
348     /*
349      * Install the default address space handlers.
350      */
351     error = ENXIO;
352     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
353 						ACPI_ADR_SPACE_SYSTEM_MEMORY,
354 						ACPI_DEFAULT_HANDLER,
355 						NULL, NULL))) {
356 	device_printf(dev, "could not initialise SystemMemory handler: %s\n", AcpiFormatException(status));
357 	goto out;
358     }
359     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
360 						ACPI_ADR_SPACE_SYSTEM_IO,
361 						ACPI_DEFAULT_HANDLER,
362 						NULL, NULL))) {
363 	device_printf(dev, "could not initialise SystemIO handler: %s\n", AcpiFormatException(status));
364 	goto out;
365     }
366     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
367 						ACPI_ADR_SPACE_PCI_CONFIG,
368 						ACPI_DEFAULT_HANDLER,
369 						NULL, NULL))) {
370 	device_printf(dev, "could not initialise PciConfig handler: %s\n", AcpiFormatException(status));
371 	goto out;
372     }
373 
374     /*
375      * Bring ACPI fully online.
376      *
377      * Note that some systems (specifically, those with namespace evaluation issues
378      * that require the avoidance of parts of the namespace) must avoid running _INI
379      * and _STA on everything, as well as dodging the final object init pass.
380      *
381      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
382      *
383      * XXX We should arrange for the object init pass after we have attached all our
384      *     child devices, but on many systems it works here.
385      */
386 #ifdef ENABLE_DEBUGGER
387     debugpoint = getenv("debug.acpi.debugger");
388     if (debugpoint) {
389 	if (!strcmp(debugpoint, "enable"))
390 	    acpi_EnterDebugger();
391         freeenv(debugpoint);
392     }
393 #endif
394     flags = 0;
395     if (testenv("debug.acpi.avoid"))
396 	flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
397     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
398 	device_printf(dev, "could not enable ACPI: %s\n", AcpiFormatException(status));
399 	goto out;
400     }
401 
402     /*
403      * Setup our sysctl tree.
404      *
405      * XXX: This doesn't check to make sure that none of these fail.
406      */
407     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
408     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
409 			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
410 			       device_get_name(dev), CTLFLAG_RD, 0, "");
411     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
412 	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
413 	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
414     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
415 	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
416 	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
417     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
418 	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
419 	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
420     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
421 	OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
422 	&sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
423     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
424 	OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
425 	&sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
426     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
427 	OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
428 	&sc->acpi_s4bios, 0, "S4BIOS mode");
429     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
430 	OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
431 	&sc->acpi_verbose, 0, "verbose mode");
432     sc->acpi_s4bios = 1;
433     if (bootverbose)
434 	sc->acpi_verbose = 1;
435 
436     /*
437      * Dispatch the default sleep state to devices.
438      * TBD: should be configured from userland policy manager.
439      */
440     sc->acpi_power_button_sx = ACPI_POWER_BUTTON_DEFAULT_SX;
441     sc->acpi_sleep_button_sx = ACPI_SLEEP_BUTTON_DEFAULT_SX;
442     sc->acpi_lid_switch_sx = ACPI_LID_SWITCH_DEFAULT_SX;
443     sc->acpi_standby_sx = ACPI_STATE_S1;
444     sc->acpi_suspend_sx = ACPI_STATE_S3;
445 
446     acpi_enable_fixed_events(sc);
447 
448     /*
449      * Scan the namespace and attach/initialise children.
450      */
451 #ifdef ENABLE_DEBUGGER
452     debugpoint = getenv("debug.acpi.debugger");
453     if (debugpoint) {
454 	if (!strcmp(debugpoint, "probe"))
455 	    acpi_EnterDebugger();
456 	freeenv(debugpoint);
457     }
458 #endif
459     if (!acpi_disabled("bus"))
460 	acpi_probe_children(dev);
461 
462     /*
463      * Register our shutdown handlers
464      */
465     EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc, SHUTDOWN_PRI_LAST);
466     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc, SHUTDOWN_PRI_LAST);
467 
468     /*
469      * Register our acpi event handlers.
470      * XXX should be configurable eg. via userland policy manager.
471      */
472     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep, sc, ACPI_EVENT_PRI_LAST);
473     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup, sc, ACPI_EVENT_PRI_LAST);
474 
475     /*
476      * Flag our initial states.
477      */
478     sc->acpi_enabled = 1;
479     sc->acpi_sstate = ACPI_STATE_S0;
480     sc->acpi_sleep_disabled = 0;
481 
482     /*
483      * Create the control device
484      */
485     sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, 0, 5, 0660, "acpi");
486     sc->acpi_dev_t->si_drv1 = sc;
487 
488 #ifdef ENABLE_DEBUGGER
489     debugpoint = getenv("debug.acpi.debugger");
490     if (debugpoint) {
491 	if (!strcmp(debugpoint, "running"))
492 	    acpi_EnterDebugger();
493 	freeenv(debugpoint);
494     }
495 #endif
496 
497 #if defined(ACPI_MAX_THREADS) && ACPI_MAX_THREADS > 0
498     if ((error = acpi_task_thread_init())) {
499 	goto out;
500     }
501 #endif
502 
503     if ((error = acpi_machdep_init(dev))) {
504 	goto out;
505     }
506 
507     /* Register ACPI again to pass the correct argument of pm_func. */
508     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
509 
510     error = 0;
511 
512  out:
513     ACPI_UNLOCK;
514     return_VALUE(error);
515 }
516 
517 /*
518  * Handle a new device being added
519  */
520 static device_t
521 acpi_add_child(device_t bus, int order, const char *name, int unit)
522 {
523     struct acpi_device	*ad;
524     device_t		child;
525 
526     if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT)) == NULL)
527 	return(NULL);
528     bzero(ad, sizeof(*ad));
529 
530     resource_list_init(&ad->ad_rl);
531 
532     child = device_add_child_ordered(bus, order, name, unit);
533     if (child != NULL)
534 	device_set_ivars(child, ad);
535     return(child);
536 }
537 
538 /*
539  * Print child device resource usage
540  */
541 static int
542 acpi_print_resources(struct resource_list *rl, const char *name, int type, const char *format)
543 {
544     struct resource_list_entry	*rle;
545     int				printed, retval;
546 
547     printed = 0;
548     retval = 0;
549 
550     if (!SLIST_FIRST(rl))
551 	return(0);
552 
553     /* Yes, this is kinda cheating */
554     SLIST_FOREACH(rle, rl, link) {
555 	if (rle->type == type) {
556 	    if (printed == 0)
557 		retval += printf(" %s ", name);
558 	    else if (printed > 0)
559 		retval += printf(",");
560 	    printed++;
561 	    retval += printf(format, rle->start);
562 	    if (rle->count > 1) {
563 		retval += printf("-");
564 		retval += printf(format, rle->start +
565 				 rle->count - 1);
566 	    }
567 	}
568     }
569     return(retval);
570 }
571 
572 static int
573 acpi_print_child(device_t bus, device_t child)
574 {
575     struct acpi_device		*adev = device_get_ivars(child);
576     struct resource_list	*rl = &adev->ad_rl;
577     int retval = 0;
578 
579     retval += bus_print_child_header(bus, child);
580     retval += acpi_print_resources(rl, "port",  SYS_RES_IOPORT, "%#lx");
581     retval += acpi_print_resources(rl, "iomem", SYS_RES_MEMORY, "%#lx");
582     retval += acpi_print_resources(rl, "irq",   SYS_RES_IRQ,    "%ld");
583     retval += acpi_print_resources(rl, "drq",   SYS_RES_DRQ,    "%ld");
584     retval += bus_print_child_footer(bus, child);
585 
586     return(retval);
587 }
588 
589 
590 /*
591  * Handle per-device ivars
592  */
593 static int
594 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
595 {
596     struct acpi_device	*ad;
597 
598     if ((ad = device_get_ivars(child)) == NULL) {
599 	printf("device has no ivars\n");
600 	return(ENOENT);
601     }
602 
603     switch(index) {
604 	/* ACPI ivars */
605     case ACPI_IVAR_HANDLE:
606 	*(ACPI_HANDLE *)result = ad->ad_handle;
607 	break;
608     case ACPI_IVAR_MAGIC:
609 	*(int *)result = ad->ad_magic;
610 	break;
611     case ACPI_IVAR_PRIVATE:
612 	*(void **)result = ad->ad_private;
613 	break;
614 
615 	/* ISA compatibility */
616     case ISA_IVAR_VENDORID:
617     case ISA_IVAR_SERIAL:
618     case ISA_IVAR_COMPATID:
619 	*(int *)result = -1;
620 	break;
621 
622     case ISA_IVAR_LOGICALID:
623 	*(int *)result = acpi_isa_get_logicalid(child);
624 	break;
625 
626     default:
627 	panic("bad ivar read request (%d)\n", index);
628 	return(ENOENT);
629     }
630     return(0);
631 }
632 
633 static int
634 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
635 {
636     struct acpi_device	*ad;
637 
638     if ((ad = device_get_ivars(child)) == NULL) {
639 	printf("device has no ivars\n");
640 	return(ENOENT);
641     }
642 
643     switch(index) {
644 	/* ACPI ivars */
645     case ACPI_IVAR_HANDLE:
646 	ad->ad_handle = (ACPI_HANDLE)value;
647 	break;
648     case ACPI_IVAR_MAGIC:
649 	ad->ad_magic = (int )value;
650 	break;
651     case ACPI_IVAR_PRIVATE:
652 	ad->ad_private = (void *)value;
653 	break;
654 
655     default:
656 	panic("bad ivar write request (%d)\n", index);
657 	return(ENOENT);
658     }
659     return(0);
660 }
661 
662 /*
663  * Handle child resource allocation/removal
664  */
665 static int
666 acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start, u_long count)
667 {
668     struct acpi_device		*ad = device_get_ivars(child);
669     struct resource_list	*rl = &ad->ad_rl;
670 
671     resource_list_add(rl, type, rid, start, start + count -1, count);
672 
673     return(0);
674 }
675 
676 static int
677 acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp, u_long *countp)
678 {
679     struct acpi_device		*ad = device_get_ivars(child);
680     struct resource_list	*rl = &ad->ad_rl;
681     struct resource_list_entry	*rle;
682 
683     rle = resource_list_find(rl, type, rid);
684     if (!rle)
685 	return(ENOENT);
686 
687     if (startp)
688 	*startp = rle->start;
689     if (countp)
690 	*countp = rle->count;
691 
692     return(0);
693 }
694 
695 static struct resource *
696 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
697 		    u_long start, u_long end, u_long count, u_int flags)
698 {
699     struct acpi_device *ad = device_get_ivars(child);
700     struct resource_list *rl = &ad->ad_rl;
701 
702     return(resource_list_alloc(rl, bus, child, type, rid, start, end, count, flags));
703 }
704 
705 static int
706 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
707 {
708     struct acpi_device *ad = device_get_ivars(child);
709     struct resource_list *rl = &ad->ad_rl;
710 
711     return(resource_list_release(rl, bus, child, type, rid, r));
712 }
713 
714 /*
715  * Handle ISA-like devices probing for a PnP ID to match.
716  */
717 #define PNP_EISAID(s)				\
718 	((((s[0] - '@') & 0x1f) << 2)		\
719 	 | (((s[1] - '@') & 0x18) >> 3)		\
720 	 | (((s[1] - '@') & 0x07) << 13)	\
721 	 | (((s[2] - '@') & 0x1f) << 8)		\
722 	 | (PNP_HEXTONUM(s[4]) << 16)		\
723 	 | (PNP_HEXTONUM(s[3]) << 20)		\
724 	 | (PNP_HEXTONUM(s[6]) << 24)		\
725 	 | (PNP_HEXTONUM(s[5]) << 28))
726 
727 static u_int32_t
728 acpi_isa_get_logicalid(device_t dev)
729 {
730     ACPI_HANDLE		h;
731     ACPI_DEVICE_INFO	devinfo;
732     ACPI_STATUS		error;
733     u_int32_t		pnpid;
734 
735     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
736 
737     pnpid = 0;
738     ACPI_LOCK;
739 
740     /* fetch and validate the HID */
741     if ((h = acpi_get_handle(dev)) == NULL)
742 	goto out;
743     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
744 	goto out;
745     if (!(devinfo.Valid & ACPI_VALID_HID))
746 	goto out;
747 
748     pnpid = PNP_EISAID(devinfo.HardwareId);
749 out:
750     ACPI_UNLOCK;
751     return_VALUE(pnpid);
752 }
753 
754 static int
755 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
756 {
757     int			result;
758     u_int32_t		pnpid;
759 
760     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
761 
762     /*
763      * ISA-style drivers attached to ACPI may persist and
764      * probe manually if we return ENOENT.  We never want
765      * that to happen, so don't ever return it.
766      */
767     result = ENXIO;
768 
769     /* scan the supplied IDs for a match */
770     pnpid = acpi_isa_get_logicalid(child);
771     while (ids && ids->ip_id) {
772 	if (pnpid == ids->ip_id) {
773 	    result = 0;
774 	    goto out;
775 	}
776 	ids++;
777     }
778  out:
779     return_VALUE(result);
780 }
781 
782 /*
783  * Scan relevant portions of the ACPI namespace and attach child devices.
784  *
785  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and \_SB_ scopes,
786  * and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
787  */
788 static void
789 acpi_probe_children(device_t bus)
790 {
791     ACPI_HANDLE		parent;
792     static char		*scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
793     int			i;
794 
795     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
796     ACPI_ASSERTLOCK;
797 
798     /*
799      * Create any static children by calling device identify methods.
800      */
801     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
802     bus_generic_probe(bus);
803 
804     /*
805      * Scan the namespace and insert placeholders for all the devices that
806      * we find.
807      *
808      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
809      * we want to create nodes for all devices, not just those that are currently
810      * present. (This assumes that we don't want to create/remove devices as they
811      * appear, which might be smarter.)
812      */
813     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
814     for (i = 0; scopes[i] != NULL; i++)
815 	if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent)))
816 	    AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child, bus, NULL);
817 
818     /*
819      * Scan all of the child devices we have created and let them probe/attach.
820      */
821     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
822     bus_generic_attach(bus);
823 
824     /*
825      * Some of these children may have attached others as part of their attach
826      * process (eg. the root PCI bus driver), so rescan.
827      */
828     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
829     bus_generic_attach(bus);
830 
831     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
832     return_VOID;
833 }
834 
835 /*
836  * Evaluate a child device and determine whether we might attach a device to
837  * it.
838  */
839 static ACPI_STATUS
840 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
841 {
842     ACPI_OBJECT_TYPE	type;
843     device_t		child, bus = (device_t)context;
844 
845     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
846 
847     /*
848      * Skip this device if we think we'll have trouble with it.
849      */
850     if (acpi_avoid(handle))
851 	return_ACPI_STATUS(AE_OK);
852 
853     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
854 	switch(type) {
855 	case ACPI_TYPE_DEVICE:
856 	case ACPI_TYPE_PROCESSOR:
857 	case ACPI_TYPE_THERMAL:
858 	case ACPI_TYPE_POWER:
859 	    if (acpi_disabled("children"))
860 		break;
861 	    /*
862 	     * Create a placeholder device for this node.  Sort the placeholder
863 	     * so that the probe/attach passes will run breadth-first.
864 	     */
865 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", acpi_name(handle)));
866 	    child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
867 	    if (child == NULL)
868 		break;
869 	    acpi_set_handle(child, handle);
870 
871 	    /*
872 	     * Check that the device is present.  If it's not present,
873 	     * leave it disabled (so that we have a device_t attached to
874 	     * the handle, but we don't probe it).
875 	     */
876 	    if ((type == ACPI_TYPE_DEVICE) && (!acpi_DeviceIsPresent(child))) {
877 		device_disable(child);
878 		break;
879 	    }
880 
881 	    /*
882 	     * Get the device's resource settings and attach them.
883 	     * Note that if the device has _PRS but no _CRS, we need
884 	     * to decide when it's appropriate to try to configure the
885 	     * device.  Ignore the return value here; it's OK for the
886 	     * device not to have any resources.
887 	     */
888 	    acpi_parse_resources(child, handle, &acpi_res_parse_set);
889 
890 	    /* if we're debugging, probe/attach now rather than later */
891 	    ACPI_DEBUG_EXEC(device_probe_and_attach(child));
892 	    break;
893 	}
894     }
895     return_ACPI_STATUS(AE_OK);
896 }
897 
898 static void
899 acpi_shutdown_pre_sync(void *arg, int howto)
900 {
901 
902     ACPI_ASSERTLOCK;
903 
904     /*
905      * Disable all ACPI events before soft off, otherwise the system
906      * will be turned on again on some laptops.
907      *
908      * XXX this should probably be restricted to masking some events just
909      *     before powering down, since we may still need ACPI during the
910      *     shutdown process.
911      */
912     acpi_Disable((struct acpi_softc *)arg);
913 }
914 
915 static void
916 acpi_shutdown_final(void *arg, int howto)
917 {
918     ACPI_STATUS	status;
919 
920     ACPI_ASSERTLOCK;
921 
922     if (howto & RB_POWEROFF) {
923 	printf("Power system off using ACPI...\n");
924 	if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(acpi_off_state))) {
925 	    printf("AcpiEnterSleepStatePrep failed - %s\n",
926 		   AcpiFormatException(status));
927 	    return;
928 	}
929 	if (ACPI_FAILURE(status = AcpiEnterSleepState(acpi_off_state))) {
930 	    printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
931 	} else {
932 	    DELAY(1000000);
933 	    printf("ACPI power-off failed - timeout\n");
934 	}
935     } else {
936 	printf("Terminate ACPI\n");
937 	AcpiTerminate();
938     }
939 }
940 
941 static void
942 acpi_enable_fixed_events(struct acpi_softc *sc)
943 {
944     static int	first_time = 1;
945 #define MSGFORMAT "%s button is handled as a fixed feature programming model.\n"
946 
947     ACPI_ASSERTLOCK;
948 
949     /* Enable and clear fixed events and install handlers. */
950     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->PwrButton == 0)) {
951 	AcpiEnableEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED, 0);
952 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
953 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
954 				     acpi_eventhandler_power_button_for_sleep, sc);
955 	if (first_time) {
956 	    device_printf(sc->acpi_dev, MSGFORMAT, "power");
957 	}
958     }
959     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->SleepButton == 0)) {
960 	AcpiEnableEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED, 0);
961 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
962 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
963 				     acpi_eventhandler_sleep_button_for_sleep, sc);
964 	if (first_time) {
965 	    device_printf(sc->acpi_dev, MSGFORMAT, "sleep");
966 	}
967     }
968 
969     first_time = 0;
970 }
971 
972 /*
973  * Returns true if the device is actually present and should
974  * be attached to.  This requires the present, enabled, UI-visible
975  * and diagnostics-passed bits to be set.
976  */
977 BOOLEAN
978 acpi_DeviceIsPresent(device_t dev)
979 {
980     ACPI_HANDLE		h;
981     ACPI_DEVICE_INFO	devinfo;
982     ACPI_STATUS		error;
983 
984     ACPI_ASSERTLOCK;
985 
986     if ((h = acpi_get_handle(dev)) == NULL)
987 	return(FALSE);
988     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
989 	return(FALSE);
990     /* if no _STA method, must be present */
991     if (!(devinfo.Valid & ACPI_VALID_STA))
992 	return(TRUE);
993     /* return true for 'present' and 'functioning' */
994     if ((devinfo.CurrentStatus & 0x9) == 0x9)
995 	return(TRUE);
996     return(FALSE);
997 }
998 
999 /*
1000  * Returns true if the battery is actually present and inserted.
1001  */
1002 BOOLEAN
1003 acpi_BatteryIsPresent(device_t dev)
1004 {
1005     ACPI_HANDLE		h;
1006     ACPI_DEVICE_INFO	devinfo;
1007     ACPI_STATUS		error;
1008 
1009     ACPI_ASSERTLOCK;
1010 
1011     if ((h = acpi_get_handle(dev)) == NULL)
1012 	return(FALSE);
1013     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
1014 	return(FALSE);
1015     /* if no _STA method, must be present */
1016     if (!(devinfo.Valid & ACPI_VALID_STA))
1017 	return(TRUE);
1018     /* return true for 'present' and 'functioning' */
1019     if ((devinfo.CurrentStatus & 0x19) == 0x19)
1020 	return(TRUE);
1021     return(FALSE);
1022 }
1023 
1024 /*
1025  * Match a HID string against a device
1026  */
1027 BOOLEAN
1028 acpi_MatchHid(device_t dev, char *hid)
1029 {
1030     ACPI_HANDLE		h;
1031     ACPI_DEVICE_INFO	devinfo;
1032     ACPI_STATUS		error;
1033     int			cid;
1034 
1035     ACPI_ASSERTLOCK;
1036 
1037     if (hid == NULL)
1038 	return(FALSE);
1039     if ((h = acpi_get_handle(dev)) == NULL)
1040 	return(FALSE);
1041     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
1042 	return(FALSE);
1043     if ((devinfo.Valid & ACPI_VALID_HID) && !strcmp(hid, devinfo.HardwareId))
1044 	return(TRUE);
1045     if (ACPI_FAILURE(error = acpi_EvaluateInteger(h, "_CID", &cid)))
1046 	return(FALSE);
1047     if (cid == PNP_EISAID(hid))
1048 	return(TRUE);
1049     return(FALSE);
1050 }
1051 
1052 /*
1053  * Return the handle of a named object within our scope, ie. that of (parent)
1054  * or one if its parents.
1055  */
1056 ACPI_STATUS
1057 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1058 {
1059     ACPI_HANDLE		r;
1060     ACPI_STATUS		status;
1061 
1062     ACPI_ASSERTLOCK;
1063 
1064     /* walk back up the tree to the root */
1065     for (;;) {
1066 	if (ACPI_SUCCESS(status = AcpiGetHandle(parent, path, &r))) {
1067 	    *result = r;
1068 	    return(AE_OK);
1069 	}
1070 	if (status != AE_NOT_FOUND)
1071 	    return(AE_OK);
1072 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1073 	    return(AE_NOT_FOUND);
1074 	parent = r;
1075     }
1076 }
1077 
1078 /*
1079  * Allocate a buffer with a preset data size.
1080  */
1081 ACPI_BUFFER *
1082 acpi_AllocBuffer(int size)
1083 {
1084     ACPI_BUFFER	*buf;
1085 
1086     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1087 	return(NULL);
1088     buf->Length = size;
1089     buf->Pointer = (void *)(buf + 1);
1090     return(buf);
1091 }
1092 
1093 /*
1094  * Evaluate a path that should return an integer.
1095  */
1096 ACPI_STATUS
1097 acpi_EvaluateInteger(ACPI_HANDLE handle, char *path, int *number)
1098 {
1099     ACPI_STATUS	error;
1100     ACPI_BUFFER	buf;
1101     ACPI_OBJECT	param;
1102 
1103     ACPI_ASSERTLOCK;
1104 
1105     if (handle == NULL)
1106 	handle = ACPI_ROOT_OBJECT;
1107 
1108     /*
1109      * Assume that what we've been pointed at is an Integer object, or
1110      * a method that will return an Integer.
1111      */
1112     buf.Pointer = &param;
1113     buf.Length = sizeof(param);
1114     if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
1115 	if (param.Type == ACPI_TYPE_INTEGER) {
1116 	    *number = param.Integer.Value;
1117 	} else {
1118 	    error = AE_TYPE;
1119 	}
1120     }
1121 
1122     /*
1123      * In some applications, a method that's expected to return an Integer
1124      * may instead return a Buffer (probably to simplify some internal
1125      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1126      * convert it into an Integer as best we can.
1127      *
1128      * This is a hack.
1129      */
1130     if (error == AE_BUFFER_OVERFLOW) {
1131 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1132 	    error = AE_NO_MEMORY;
1133 	} else {
1134 	    if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
1135 		error = acpi_ConvertBufferToInteger(&buf, number);
1136 	    }
1137 	}
1138 	AcpiOsFree(buf.Pointer);
1139     }
1140     return(error);
1141 }
1142 
1143 ACPI_STATUS
1144 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, int *number)
1145 {
1146     ACPI_OBJECT	*p;
1147     int		i;
1148 
1149     p = (ACPI_OBJECT *)bufp->Pointer;
1150     if (p->Type == ACPI_TYPE_INTEGER) {
1151 	*number = p->Integer.Value;
1152 	return(AE_OK);
1153     }
1154     if (p->Type != ACPI_TYPE_BUFFER)
1155 	return(AE_TYPE);
1156     if (p->Buffer.Length > sizeof(int))
1157 	return(AE_BAD_DATA);
1158     *number = 0;
1159     for (i = 0; i < p->Buffer.Length; i++)
1160 	*number += (*(p->Buffer.Pointer + i) << (i * 8));
1161     return(AE_OK);
1162 }
1163 
1164 /*
1165  * Iterate over the elements of an a package object, calling the supplied
1166  * function for each element.
1167  *
1168  * XXX possible enhancement might be to abort traversal on error.
1169  */
1170 ACPI_STATUS
1171 acpi_ForeachPackageObject(ACPI_OBJECT *pkg, void (* func)(ACPI_OBJECT *comp, void *arg), void *arg)
1172 {
1173     ACPI_OBJECT	*comp;
1174     int		i;
1175 
1176     if ((pkg == NULL) || (pkg->Type != ACPI_TYPE_PACKAGE))
1177 	return(AE_BAD_PARAMETER);
1178 
1179     /* iterate over components */
1180     for (i = 0, comp = pkg->Package.Elements; i < pkg->Package.Count; i++, comp++)
1181 	func(comp, arg);
1182 
1183     return(AE_OK);
1184 }
1185 
1186 /*
1187  * Find the (index)th resource object in a set.
1188  */
1189 ACPI_STATUS
1190 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1191 {
1192     ACPI_RESOURCE	*rp;
1193     int			i;
1194 
1195     rp = (ACPI_RESOURCE *)buf->Pointer;
1196     i = index;
1197     while (i-- > 0) {
1198 	/* range check */
1199 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1200 	    return(AE_BAD_PARAMETER);
1201 	/* check for terminator */
1202 	if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1203 	    (rp->Length == 0))
1204 	    return(AE_NOT_FOUND);
1205 	rp = ACPI_RESOURCE_NEXT(rp);
1206     }
1207     if (resp != NULL)
1208 	*resp = rp;
1209     return(AE_OK);
1210 }
1211 
1212 /*
1213  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1214  *
1215  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1216  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1217  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1218  * resources.
1219  */
1220 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
1221 
1222 ACPI_STATUS
1223 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1224 {
1225     ACPI_RESOURCE	*rp;
1226     void		*newp;
1227 
1228     /*
1229      * Initialise the buffer if necessary.
1230      */
1231     if (buf->Pointer == NULL) {
1232 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1233 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1234 	    return(AE_NO_MEMORY);
1235 	rp = (ACPI_RESOURCE *)buf->Pointer;
1236 	rp->Id = ACPI_RSTYPE_END_TAG;
1237 	rp->Length = 0;
1238     }
1239     if (res == NULL)
1240 	return(AE_OK);
1241 
1242     /*
1243      * Scan the current buffer looking for the terminator.
1244      * This will either find the terminator or hit the end
1245      * of the buffer and return an error.
1246      */
1247     rp = (ACPI_RESOURCE *)buf->Pointer;
1248     for (;;) {
1249 	/* range check, don't go outside the buffer */
1250 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1251 	    return(AE_BAD_PARAMETER);
1252 	if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1253 	    (rp->Length == 0)) {
1254 	    break;
1255 	}
1256 	rp = ACPI_RESOURCE_NEXT(rp);
1257     }
1258 
1259     /*
1260      * Check the size of the buffer and expand if required.
1261      *
1262      * Required size is:
1263      *	size of existing resources before terminator +
1264      *	size of new resource and header +
1265      * 	size of terminator.
1266      *
1267      * Note that this loop should really only run once, unless
1268      * for some reason we are stuffing a *really* huge resource.
1269      */
1270     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
1271 	    res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1272 	    ACPI_RESOURCE_LENGTH) >= buf->Length) {
1273 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1274 	    return(AE_NO_MEMORY);
1275 	bcopy(buf->Pointer, newp, buf->Length);
1276         rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1277 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1278 	AcpiOsFree(buf->Pointer);
1279 	buf->Pointer = newp;
1280 	buf->Length += buf->Length;
1281     }
1282 
1283     /*
1284      * Insert the new resource.
1285      */
1286     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1287 
1288     /*
1289      * And add the terminator.
1290      */
1291     rp = ACPI_RESOURCE_NEXT(rp);
1292     rp->Id = ACPI_RSTYPE_END_TAG;
1293     rp->Length = 0;
1294 
1295     return(AE_OK);
1296 }
1297 
1298 #define ACPI_MINIMUM_AWAKETIME	5
1299 
1300 static void
1301 acpi_sleep_enable(void *arg)
1302 {
1303     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1304 }
1305 
1306 /*
1307  * Set the system sleep state
1308  *
1309  * Currently we only support S1 and S5
1310  */
1311 ACPI_STATUS
1312 acpi_SetSleepState(struct acpi_softc *sc, int state)
1313 {
1314     ACPI_STATUS	status = AE_OK;
1315     UINT8	TypeA;
1316     UINT8	TypeB;
1317 
1318     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1319     ACPI_ASSERTLOCK;
1320 
1321     if (sc->acpi_sstate != ACPI_STATE_S0)
1322 	return_ACPI_STATUS(AE_BAD_PARAMETER);	/* avoid reentry */
1323 
1324     if (sc->acpi_sleep_disabled)
1325 	return_ACPI_STATUS(AE_OK);
1326 
1327     switch (state) {
1328     case ACPI_STATE_S0:	/* XXX only for testing */
1329 	if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
1330 	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1331 	}
1332 	break;
1333 
1334     case ACPI_STATE_S1:
1335     case ACPI_STATE_S2:
1336     case ACPI_STATE_S3:
1337     case ACPI_STATE_S4:
1338 	if (ACPI_FAILURE(status = AcpiHwGetSleepTypeData((UINT8)state, &TypeA, &TypeB))) {
1339 	    device_printf(sc->acpi_dev, "AcpiHwGetSleepTypeData failed - %s\n", AcpiFormatException(status));
1340 	    break;
1341 	}
1342 
1343 	/*
1344 	 * Inform all devices that we are going to sleep.
1345 	 */
1346 	if (DEVICE_SUSPEND(root_bus) != 0) {
1347 	    /*
1348 	     * Re-wake the system.
1349 	     *
1350 	     * XXX note that a better two-pass approach with a 'veto' pass
1351 	     *     followed by a "real thing" pass would be better, but the
1352 	     *     current bus interface does not provide for this.
1353 	     */
1354 	    DEVICE_RESUME(root_bus);
1355 	    return_ACPI_STATUS(AE_ERROR);
1356 	}
1357 
1358 	if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(state))) {
1359 	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1360 			  AcpiFormatException(status));
1361 	    break;
1362 	}
1363 
1364 	sc->acpi_sstate = state;
1365 	sc->acpi_sleep_disabled = 1;
1366 
1367 	if (state != ACPI_STATE_S1) {
1368 	    acpi_sleep_machdep(sc, state);
1369 
1370 	    /* AcpiEnterSleepState() maybe incompleted, unlock here. */
1371 	    AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1372 
1373 	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1374 	    if (state == ACPI_STATE_S4) {
1375 		AcpiEnable();
1376 	    }
1377 	} else {
1378 	    if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
1379 		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1380 		break;
1381 	    }
1382 	}
1383 	AcpiLeaveSleepState((UINT8)state);
1384 	DEVICE_RESUME(root_bus);
1385 	sc->acpi_sstate = ACPI_STATE_S0;
1386 	acpi_enable_fixed_events(sc);
1387 	break;
1388 
1389     case ACPI_STATE_S5:
1390 	/*
1391 	 * Shut down cleanly and power off.  This will call us back through the
1392 	 * shutdown handlers.
1393 	 */
1394 	shutdown_nice(RB_POWEROFF);
1395 	break;
1396 
1397     default:
1398 	status = AE_BAD_PARAMETER;
1399 	break;
1400     }
1401 
1402     if (sc->acpi_sleep_disabled)
1403 	timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
1404 
1405     return_ACPI_STATUS(status);
1406 }
1407 
1408 /*
1409  * Enable/Disable ACPI
1410  */
1411 ACPI_STATUS
1412 acpi_Enable(struct acpi_softc *sc)
1413 {
1414     ACPI_STATUS	status;
1415     u_int32_t	flags;
1416 
1417     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1418     ACPI_ASSERTLOCK;
1419 
1420     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
1421             ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
1422     if (!sc->acpi_enabled) {
1423 	status = AcpiEnableSubsystem(flags);
1424     } else {
1425 	status = AE_OK;
1426     }
1427     if (status == AE_OK)
1428 	sc->acpi_enabled = 1;
1429     return_ACPI_STATUS(status);
1430 }
1431 
1432 ACPI_STATUS
1433 acpi_Disable(struct acpi_softc *sc)
1434 {
1435     ACPI_STATUS	status;
1436 
1437     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1438     ACPI_ASSERTLOCK;
1439 
1440     if (sc->acpi_enabled) {
1441 	status = AcpiDisable();
1442     } else {
1443 	status = AE_OK;
1444     }
1445     if (status == AE_OK)
1446 	sc->acpi_enabled = 0;
1447     return_ACPI_STATUS(status);
1448 }
1449 
1450 /*
1451  * ACPI Event Handlers
1452  */
1453 
1454 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1455 
1456 static void
1457 acpi_system_eventhandler_sleep(void *arg, int state)
1458 {
1459     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1460 
1461     ACPI_LOCK;
1462     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
1463 	acpi_SetSleepState((struct acpi_softc *)arg, state);
1464     ACPI_UNLOCK;
1465     return_VOID;
1466 }
1467 
1468 static void
1469 acpi_system_eventhandler_wakeup(void *arg, int state)
1470 {
1471     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1472 
1473     /* Well, what to do? :-) */
1474 
1475     ACPI_LOCK;
1476     ACPI_UNLOCK;
1477 
1478     return_VOID;
1479 }
1480 
1481 /*
1482  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1483  */
1484 UINT32
1485 acpi_eventhandler_power_button_for_sleep(void *context)
1486 {
1487     struct acpi_softc	*sc = (struct acpi_softc *)context;
1488 
1489     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1490 
1491     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1492 
1493     return_VALUE(ACPI_INTERRUPT_HANDLED);
1494 }
1495 
1496 UINT32
1497 acpi_eventhandler_power_button_for_wakeup(void *context)
1498 {
1499     struct acpi_softc	*sc = (struct acpi_softc *)context;
1500 
1501     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1502 
1503     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1504 
1505     return_VALUE(ACPI_INTERRUPT_HANDLED);
1506 }
1507 
1508 UINT32
1509 acpi_eventhandler_sleep_button_for_sleep(void *context)
1510 {
1511     struct acpi_softc	*sc = (struct acpi_softc *)context;
1512 
1513     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1514 
1515     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1516 
1517     return_VALUE(ACPI_INTERRUPT_HANDLED);
1518 }
1519 
1520 UINT32
1521 acpi_eventhandler_sleep_button_for_wakeup(void *context)
1522 {
1523     struct acpi_softc	*sc = (struct acpi_softc *)context;
1524 
1525     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1526 
1527     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1528 
1529     return_VALUE(ACPI_INTERRUPT_HANDLED);
1530 }
1531 
1532 /*
1533  * XXX This is kinda ugly, and should not be here.
1534  */
1535 struct acpi_staticbuf {
1536     ACPI_BUFFER	buffer;
1537     char	data[512];
1538 };
1539 
1540 char *
1541 acpi_name(ACPI_HANDLE handle)
1542 {
1543     static struct acpi_staticbuf	buf;
1544 
1545     ACPI_ASSERTLOCK;
1546 
1547     buf.buffer.Length = 512;
1548     buf.buffer.Pointer = &buf.data[0];
1549 
1550     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
1551 	return(buf.buffer.Pointer);
1552     return("(unknown path)");
1553 }
1554 
1555 /*
1556  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1557  * parts of the namespace.
1558  */
1559 int
1560 acpi_avoid(ACPI_HANDLE handle)
1561 {
1562     char	*cp, *env, *np;
1563     int		len;
1564 
1565     np = acpi_name(handle);
1566     if (*np == '\\')
1567 	np++;
1568     if ((env = getenv("debug.acpi.avoid")) == NULL)
1569 	return(0);
1570 
1571     /* scan the avoid list checking for a match */
1572     cp = env;
1573     for (;;) {
1574 	while ((*cp != 0) && isspace(*cp))
1575 	    cp++;
1576 	if (*cp == 0)
1577 	    break;
1578 	len = 0;
1579 	while ((cp[len] != 0) && !isspace(cp[len]))
1580 	    len++;
1581 	if (!strncmp(cp, np, len)) {
1582 	    freeenv(env);
1583 	    return(1);
1584 	}
1585 	cp += len;
1586     }
1587     freeenv(env);
1588     return(0);
1589 }
1590 
1591 /*
1592  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1593  */
1594 int
1595 acpi_disabled(char *subsys)
1596 {
1597     char	*cp, *env;
1598     int		len;
1599 
1600     if ((env = getenv("debug.acpi.disable")) == NULL)
1601 	return(0);
1602     if (!strcmp(env, "all")) {
1603 	freeenv(env);
1604 	return(1);
1605     }
1606 
1607     /* scan the disable list checking for a match */
1608     cp = env;
1609     for (;;) {
1610 	while ((*cp != 0) && isspace(*cp))
1611 	    cp++;
1612 	if (*cp == 0)
1613 	    break;
1614 	len = 0;
1615 	while ((cp[len] != 0) && !isspace(cp[len]))
1616 	    len++;
1617 	if (!strncmp(cp, subsys, len)) {
1618 	    freeenv(env);
1619 	    return(1);
1620 	}
1621 	cp += len;
1622     }
1623     freeenv(env);
1624     return(0);
1625 }
1626 
1627 /*
1628  * Control interface.
1629  *
1630  * We multiplex ioctls for all participating ACPI devices here.  Individual
1631  * drivers wanting to be accessible via /dev/acpi should use the register/deregister
1632  * interface to make their handlers visible.
1633  */
1634 struct acpi_ioctl_hook
1635 {
1636     TAILQ_ENTRY(acpi_ioctl_hook)	link;
1637     u_long				cmd;
1638     int					(* fn)(u_long cmd, caddr_t addr, void *arg);
1639     void				*arg;
1640 };
1641 
1642 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
1643 static int				acpi_ioctl_hooks_initted;
1644 
1645 /*
1646  * Register an ioctl handler.
1647  */
1648 int
1649 acpi_register_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg), void *arg)
1650 {
1651     struct acpi_ioctl_hook	*hp;
1652 
1653     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
1654 	return(ENOMEM);
1655     hp->cmd = cmd;
1656     hp->fn = fn;
1657     hp->arg = arg;
1658     if (acpi_ioctl_hooks_initted == 0) {
1659 	TAILQ_INIT(&acpi_ioctl_hooks);
1660 	acpi_ioctl_hooks_initted = 1;
1661     }
1662     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
1663     return(0);
1664 }
1665 
1666 /*
1667  * Deregister an ioctl handler.
1668  */
1669 void
1670 acpi_deregister_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg))
1671 {
1672     struct acpi_ioctl_hook	*hp;
1673 
1674     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
1675 	if ((hp->cmd == cmd) && (hp->fn == fn))
1676 	    break;
1677 
1678     if (hp != NULL) {
1679 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
1680 	free(hp, M_ACPIDEV);
1681     }
1682 }
1683 
1684 static int
1685 acpiopen(dev_t dev, int flag, int fmt, struct thread *td)
1686 {
1687     return(0);
1688 }
1689 
1690 static int
1691 acpiclose(dev_t dev, int flag, int fmt, struct thread *td)
1692 {
1693     return(0);
1694 }
1695 
1696 static int
1697 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1698 {
1699     struct acpi_softc		*sc;
1700     struct acpi_ioctl_hook	*hp;
1701     int				error, xerror, state;
1702 
1703     ACPI_LOCK;
1704 
1705     error = state = 0;
1706     sc = dev->si_drv1;
1707 
1708     /*
1709      * Scan the list of registered ioctls, looking for handlers.
1710      */
1711     if (acpi_ioctl_hooks_initted) {
1712 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
1713 	    if (hp->cmd == cmd) {
1714 		xerror = hp->fn(cmd, addr, hp->arg);
1715 		if (xerror != 0)
1716 		    error = xerror;
1717 		goto out;
1718 	    }
1719 	}
1720     }
1721 
1722     /*
1723      * Core system ioctls.
1724      */
1725     switch (cmd) {
1726     case ACPIIO_ENABLE:
1727 	if (ACPI_FAILURE(acpi_Enable(sc)))
1728 	    error = ENXIO;
1729 	break;
1730 
1731     case ACPIIO_DISABLE:
1732 	if (ACPI_FAILURE(acpi_Disable(sc)))
1733 	    error = ENXIO;
1734 	break;
1735 
1736     case ACPIIO_SETSLPSTATE:
1737 	if (!sc->acpi_enabled) {
1738 	    error = ENXIO;
1739 	    break;
1740 	}
1741 	state = *(int *)addr;
1742 	if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
1743 	    acpi_SetSleepState(sc, state);
1744 	} else {
1745 	    error = EINVAL;
1746 	}
1747 	break;
1748 
1749     default:
1750 	if (error == 0)
1751 	    error = EINVAL;
1752 	break;
1753     }
1754 
1755 out:
1756     ACPI_UNLOCK;
1757     return(error);
1758 }
1759 
1760 static int
1761 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
1762 {
1763     char sleep_state[10];
1764     int error;
1765     u_int new_state, old_state;
1766 
1767     old_state = *(u_int *)oidp->oid_arg1;
1768     if (old_state > ACPI_S_STATES_MAX+1) {
1769 	strcpy(sleep_state, "unknown");
1770     } else {
1771 	bzero(sleep_state, sizeof(sleep_state));
1772 	strncpy(sleep_state, sleep_state_names[old_state],
1773 		sizeof(sleep_state_names[old_state]));
1774     }
1775     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
1776     if (error == 0 && req->newptr != NULL) {
1777 	for (new_state = ACPI_STATE_S0; new_state <= ACPI_S_STATES_MAX+1; new_state++) {
1778 	    if (strncmp(sleep_state, sleep_state_names[new_state],
1779 			sizeof(sleep_state)) == 0)
1780 		break;
1781 	}
1782 	if (new_state <= ACPI_S_STATES_MAX+1) {
1783 	    if (new_state != old_state) {
1784 		*(u_int *)oidp->oid_arg1 = new_state;
1785 	    }
1786 	} else {
1787 	    error = EINVAL;
1788 	}
1789     }
1790     return(error);
1791 }
1792 
1793 #ifdef ACPI_DEBUG
1794 /*
1795  * Support for parsing debug options from the kernel environment.
1796  *
1797  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
1798  * by specifying the names of the bits in the debug.acpi.layer and
1799  * debug.acpi.level environment variables.  Bits may be unset by
1800  * prefixing the bit name with !.
1801  */
1802 struct debugtag
1803 {
1804     char	*name;
1805     UINT32	value;
1806 };
1807 
1808 static struct debugtag	dbg_layer[] = {
1809     {"ACPI_UTILITIES",		ACPI_UTILITIES},
1810     {"ACPI_HARDWARE",		ACPI_HARDWARE},
1811     {"ACPI_EVENTS",		ACPI_EVENTS},
1812     {"ACPI_TABLES",		ACPI_TABLES},
1813     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
1814     {"ACPI_PARSER",		ACPI_PARSER},
1815     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
1816     {"ACPI_EXECUTER",		ACPI_EXECUTER},
1817     {"ACPI_RESOURCES",		ACPI_RESOURCES},
1818     {"ACPI_DEBUGGER",		ACPI_DEBUGGER},
1819     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
1820 
1821     {"ACPI_BUS",		ACPI_BUS},
1822     {"ACPI_SYSTEM",		ACPI_SYSTEM},
1823     {"ACPI_POWER",		ACPI_POWER},
1824     {"ACPI_EC", 		ACPI_EC},
1825     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
1826     {"ACPI_BATTERY",		ACPI_BATTERY},
1827     {"ACPI_BUTTON",		ACPI_BUTTON},
1828     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
1829     {"ACPI_THERMAL",		ACPI_THERMAL},
1830     {"ACPI_FAN",		ACPI_FAN},
1831 
1832     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
1833     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
1834     {NULL, 0}
1835 };
1836 
1837 static struct debugtag dbg_level[] = {
1838     {"ACPI_LV_OK",		ACPI_LV_OK},
1839     {"ACPI_LV_INFO",		ACPI_LV_INFO},
1840     {"ACPI_LV_WARN",		ACPI_LV_WARN},
1841     {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
1842     {"ACPI_LV_FATAL",		ACPI_LV_FATAL},
1843     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
1844     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
1845     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
1846     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
1847     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
1848     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
1849     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
1850     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
1851     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
1852     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
1853     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
1854     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
1855     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
1856     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
1857     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
1858     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
1859     {"ACPI_LV_IO",		ACPI_LV_IO},
1860     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
1861     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
1862     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
1863     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
1864     {"ACPI_LV_INIT",		ACPI_LV_INIT},
1865     {"ACPI_LV_ALL",		ACPI_LV_ALL},
1866     {"ACPI_DB_AML_DISASSEMBLE",	ACPI_DB_AML_DISASSEMBLE},
1867     {"ACPI_DB_VERBOSE_INFO",	ACPI_DB_VERBOSE_INFO},
1868     {"ACPI_DB_FULL_TABLES",	ACPI_DB_FULL_TABLES},
1869     {"ACPI_DB_EVENTS",		ACPI_DB_EVENTS},
1870     {"ACPI_DB_VERBOSE",		ACPI_DB_VERBOSE},
1871     {NULL, 0}
1872 };
1873 
1874 static void
1875 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
1876 {
1877     char	*ep;
1878     int		i, l;
1879     int		set;
1880 
1881     while (*cp) {
1882 	if (isspace(*cp)) {
1883 	    cp++;
1884 	    continue;
1885 	}
1886 	ep = cp;
1887 	while (*ep && !isspace(*ep))
1888 	    ep++;
1889 	if (*cp == '!') {
1890 	    set = 0;
1891 	    cp++;
1892 	    if (cp == ep)
1893 		continue;
1894 	} else {
1895 	    set = 1;
1896 	}
1897 	l = ep - cp;
1898 	for (i = 0; tag[i].name != NULL; i++) {
1899 	    if (!strncmp(cp, tag[i].name, l)) {
1900 		if (set) {
1901 		    *flag |= tag[i].value;
1902 		} else {
1903 		    *flag &= ~tag[i].value;
1904 		}
1905 		printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
1906 	    }
1907 	}
1908 	cp = ep;
1909     }
1910 }
1911 
1912 static void
1913 acpi_set_debugging(void *junk)
1914 {
1915     char	*cp;
1916 
1917     AcpiDbgLayer = 0;
1918     AcpiDbgLevel = 0;
1919     if ((cp = getenv("debug.acpi.layer")) != NULL) {
1920 	acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
1921 	freeenv(cp);
1922     }
1923     if ((cp = getenv("debug.acpi.level")) != NULL) {
1924 	acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
1925 	freeenv(cp);
1926     }
1927 
1928     printf("ACPI debug layer 0x%x  debug level 0x%x\n", AcpiDbgLayer, AcpiDbgLevel);
1929 }
1930 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging, NULL);
1931 #endif
1932 
1933 static int
1934 acpi_pm_func(u_long cmd, void *arg, ...)
1935 {
1936 	int	state, acpi_state;
1937 	int	error;
1938 	struct	acpi_softc *sc;
1939 	va_list	ap;
1940 
1941 	error = 0;
1942 	switch (cmd) {
1943 	case POWER_CMD_SUSPEND:
1944 		sc = (struct acpi_softc *)arg;
1945 		if (sc == NULL) {
1946 			error = EINVAL;
1947 			goto out;
1948 		}
1949 
1950 		va_start(ap, arg);
1951 		state = va_arg(ap, int);
1952 		va_end(ap);
1953 
1954 		switch (state) {
1955 		case POWER_SLEEP_STATE_STANDBY:
1956 			acpi_state = sc->acpi_standby_sx;
1957 			break;
1958 		case POWER_SLEEP_STATE_SUSPEND:
1959 			acpi_state = sc->acpi_suspend_sx;
1960 			break;
1961 		case POWER_SLEEP_STATE_HIBERNATE:
1962 			acpi_state = ACPI_STATE_S4;
1963 			break;
1964 		default:
1965 			error = EINVAL;
1966 			goto out;
1967 		}
1968 
1969 		acpi_SetSleepState(sc, acpi_state);
1970 		break;
1971 
1972 	default:
1973 		error = EINVAL;
1974 		goto out;
1975 	}
1976 
1977 out:
1978 	return (error);
1979 }
1980 
1981 static void
1982 acpi_pm_register(void *arg)
1983 {
1984 
1985 	power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
1986 }
1987 
1988 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
1989 
1990