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