xref: /freebsd/sys/dev/acpica/acpi.c (revision 0fa02ea5f786ef02befd46f8f083f48c8cd9630b)
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     ACPI_LOCK;
817 
818     /* Fetch and validate the HID. */
819     if ((h = acpi_get_handle(dev)) == NULL)
820 	return (0);
821     buf.Pointer = NULL;
822     buf.Length = ACPI_ALLOCATE_BUFFER;
823     error = AcpiGetObjectInfo(h, &buf);
824     if (ACPI_FAILURE(error))
825 	return (0);
826     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
827 
828     if ((devinfo->Valid & ACPI_VALID_HID) != 0)
829 	pnpid = PNP_EISAID(devinfo->HardwareId.Value);
830 
831     AcpiOsFree(buf.Pointer);
832     ACPI_UNLOCK;
833     return_VALUE (pnpid);
834 }
835 
836 static int
837 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
838 {
839     ACPI_DEVICE_INFO	*devinfo;
840     ACPI_BUFFER		buf;
841     ACPI_HANDLE		h;
842     ACPI_STATUS		error;
843     uint32_t		*pnpid;
844     int			valid, i;
845     ACPI_LOCK_DECL;
846 
847     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
848 
849     pnpid = cids;
850     valid = 0;
851     ACPI_LOCK;
852 
853     /* Fetch and validate the CID */
854     if ((h = acpi_get_handle(dev)) == NULL)
855 	return (0);
856     buf.Pointer = NULL;
857     buf.Length = ACPI_ALLOCATE_BUFFER;
858     error = AcpiGetObjectInfo(h, &buf);
859     if (ACPI_FAILURE(error))
860 	return (0);
861     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
862     if ((devinfo->Valid & ACPI_VALID_CID) == 0)
863 	goto out;
864 
865     if (devinfo->CompatibilityId.Count < count)
866 	count = devinfo->CompatibilityId.Count;
867     for (i = 0; i < count; i++) {
868 	if (strncmp(devinfo->CompatibilityId.Id[i].Value, "PNP", 3) != 0)
869 	    continue;
870 	*pnpid++ = PNP_EISAID(devinfo->CompatibilityId.Id[i].Value);
871 	valid++;
872     }
873 
874 out:
875     AcpiOsFree(buf.Pointer);
876     ACPI_UNLOCK;
877     return_VALUE (valid);
878 }
879 
880 static int
881 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
882 {
883     int			result, cid_count, i;
884     uint32_t		lid, cids[8];
885 
886     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
887 
888     /*
889      * ISA-style drivers attached to ACPI may persist and
890      * probe manually if we return ENOENT.  We never want
891      * that to happen, so don't ever return it.
892      */
893     result = ENXIO;
894 
895     /* Scan the supplied IDs for a match */
896     lid = acpi_isa_get_logicalid(child);
897     cid_count = acpi_isa_get_compatid(child, cids, 8);
898     while (ids && ids->ip_id) {
899 	if (lid == ids->ip_id) {
900 	    result = 0;
901 	    goto out;
902 	}
903 	for (i = 0; i < cid_count; i++) {
904 	    if (cids[i] == ids->ip_id) {
905 		result = 0;
906 		goto out;
907 	    }
908 	}
909 	ids++;
910     }
911 
912  out:
913     return_VALUE (result);
914 }
915 
916 /*
917  * Scan relevant portions of the ACPI namespace and attach child devices.
918  *
919  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and
920  * \_SB_ scopes, and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
921  */
922 static void
923 acpi_probe_children(device_t bus)
924 {
925     ACPI_HANDLE	parent;
926     ACPI_STATUS	status;
927     static char	*scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
928     int		i;
929 
930     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
931     ACPI_ASSERTLOCK;
932 
933     /* Create any static children by calling device identify methods. */
934     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
935     bus_generic_probe(bus);
936 
937     /*
938      * Scan the namespace and insert placeholders for all the devices that
939      * we find.
940      *
941      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
942      * we want to create nodes for all devices, not just those that are
943      * currently present. (This assumes that we don't want to create/remove
944      * devices as they appear, which might be smarter.)
945      */
946     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
947     for (i = 0; scopes[i] != NULL; i++) {
948 	status = AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent);
949 	if (ACPI_SUCCESS(status)) {
950 	    AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child,
951 			      bus, NULL);
952 	}
953     }
954 
955     /*
956      * Scan all of the child devices we have created and let them probe/attach.
957      */
958     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
959     bus_generic_attach(bus);
960 
961     /*
962      * Some of these children may have attached others as part of their attach
963      * process (eg. the root PCI bus driver), so rescan.
964      */
965     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
966     bus_generic_attach(bus);
967 
968     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
969     return_VOID;
970 }
971 
972 /*
973  * Evaluate a child device and determine whether we might attach a device to
974  * it.
975  */
976 static ACPI_STATUS
977 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
978 {
979     ACPI_OBJECT_TYPE	type;
980     device_t		child, bus = (device_t)context;
981 
982     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
983 
984     /* Skip this device if we think we'll have trouble with it. */
985     if (acpi_avoid(handle))
986 	return_ACPI_STATUS (AE_OK);
987 
988     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
989 	switch(type) {
990 	case ACPI_TYPE_DEVICE:
991 	case ACPI_TYPE_PROCESSOR:
992 	case ACPI_TYPE_THERMAL:
993 	case ACPI_TYPE_POWER:
994 	    if (acpi_disabled("children"))
995 		break;
996 
997 	    /*
998 	     * Create a placeholder device for this node.  Sort the placeholder
999 	     * so that the probe/attach passes will run breadth-first.
1000 	     */
1001 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n",
1002 			     acpi_name(handle)));
1003 	    child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
1004 	    if (child == NULL)
1005 		break;
1006 	    acpi_set_handle(child, handle);
1007 
1008 	    /*
1009 	     * Check that the device is present.  If it's not present,
1010 	     * leave it disabled (so that we have a device_t attached to
1011 	     * the handle, but we don't probe it).
1012 	     */
1013 	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1014 		device_disable(child);
1015 		break;
1016 	    }
1017 
1018 	    /*
1019 	     * Get the device's resource settings and attach them.
1020 	     * Note that if the device has _PRS but no _CRS, we need
1021 	     * to decide when it's appropriate to try to configure the
1022 	     * device.  Ignore the return value here; it's OK for the
1023 	     * device not to have any resources.
1024 	     */
1025 	    acpi_parse_resources(child, handle, &acpi_res_parse_set);
1026 
1027 	    /* If we're debugging, probe/attach now rather than later */
1028 	    ACPI_DEBUG_EXEC(device_probe_and_attach(child));
1029 	    break;
1030 	}
1031     }
1032 
1033     return_ACPI_STATUS (AE_OK);
1034 }
1035 
1036 static void
1037 acpi_shutdown_pre_sync(void *arg, int howto)
1038 {
1039     struct acpi_softc *sc = arg;
1040 
1041     ACPI_ASSERTLOCK;
1042 
1043     /*
1044      * Disable all ACPI events before soft off, otherwise the system
1045      * will be turned on again on some laptops.
1046      *
1047      * XXX this should probably be restricted to masking some events just
1048      *     before powering down, since we may still need ACPI during the
1049      *     shutdown process.
1050      */
1051     if (sc->acpi_disable_on_poweroff)
1052 	acpi_Disable(sc);
1053 }
1054 
1055 static void
1056 acpi_shutdown_final(void *arg, int howto)
1057 {
1058     ACPI_STATUS	status;
1059 
1060     ACPI_ASSERTLOCK;
1061 
1062     if ((howto & RB_POWEROFF) != 0) {
1063 	printf("Powering system off using ACPI\n");
1064 	status = AcpiEnterSleepStatePrep(acpi_off_state);
1065 	if (ACPI_FAILURE(status)) {
1066 	    printf("AcpiEnterSleepStatePrep failed - %s\n",
1067 		   AcpiFormatException(status));
1068 	    return;
1069 	}
1070 	ACPI_DISABLE_IRQS();
1071 	status = AcpiEnterSleepState(acpi_off_state);
1072 	if (ACPI_FAILURE(status)) {
1073 	    printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
1074 	} else {
1075 	    DELAY(1000000);
1076 	    printf("ACPI power-off failed - timeout\n");
1077 	}
1078     } else {
1079 	printf("Shutting down ACPI\n");
1080 	AcpiTerminate();
1081     }
1082 }
1083 
1084 static void
1085 acpi_enable_fixed_events(struct acpi_softc *sc)
1086 {
1087     static int	first_time = 1;
1088 
1089     ACPI_ASSERTLOCK;
1090 
1091     /* Enable and clear fixed events and install handlers. */
1092     if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->PwrButton == 0) {
1093 	AcpiEnableEvent(ACPI_EVENT_POWER_BUTTON, 0);
1094 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
1095 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
1096 				     acpi_eventhandler_power_button_for_sleep,
1097 				     sc);
1098 	if (first_time)
1099 	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
1100     }
1101     if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->SleepButton == 0) {
1102 	AcpiEnableEvent(ACPI_EVENT_SLEEP_BUTTON, 0);
1103 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
1104 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
1105 				     acpi_eventhandler_sleep_button_for_sleep,
1106 				     sc);
1107 	if (first_time)
1108 	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
1109     }
1110 
1111     first_time = 0;
1112 }
1113 
1114 /*
1115  * Returns true if the device is actually present and should
1116  * be attached to.  This requires the present, enabled, UI-visible
1117  * and diagnostics-passed bits to be set.
1118  */
1119 BOOLEAN
1120 acpi_DeviceIsPresent(device_t dev)
1121 {
1122     ACPI_DEVICE_INFO	*devinfo;
1123     ACPI_HANDLE		h;
1124     ACPI_BUFFER		buf;
1125     ACPI_STATUS		error;
1126     int			ret;
1127 
1128     ACPI_ASSERTLOCK;
1129 
1130     ret = FALSE;
1131     if ((h = acpi_get_handle(dev)) == NULL)
1132 	return (FALSE);
1133     buf.Pointer = NULL;
1134     buf.Length = ACPI_ALLOCATE_BUFFER;
1135     error = AcpiGetObjectInfo(h, &buf);
1136     if (ACPI_FAILURE(error))
1137 	return (FALSE);
1138     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1139 
1140     /* If no _STA method, must be present */
1141     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1142 	ret = TRUE;
1143 
1144     /* Return true for 'present' and 'functioning' */
1145     if ((devinfo->CurrentStatus & 0x9) == 0x9)
1146 	ret = TRUE;
1147 
1148     AcpiOsFree(buf.Pointer);
1149     return (ret);
1150 }
1151 
1152 /*
1153  * Returns true if the battery is actually present and inserted.
1154  */
1155 BOOLEAN
1156 acpi_BatteryIsPresent(device_t dev)
1157 {
1158     ACPI_DEVICE_INFO	*devinfo;
1159     ACPI_HANDLE		h;
1160     ACPI_BUFFER		buf;
1161     ACPI_STATUS		error;
1162     int			ret;
1163 
1164     ACPI_ASSERTLOCK;
1165 
1166     ret = FALSE;
1167     if ((h = acpi_get_handle(dev)) == NULL)
1168 	return (FALSE);
1169     buf.Pointer = NULL;
1170     buf.Length = ACPI_ALLOCATE_BUFFER;
1171     error = AcpiGetObjectInfo(h, &buf);
1172     if (ACPI_FAILURE(error))
1173 	return (FALSE);
1174     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1175 
1176     /* If no _STA method, must be present */
1177     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1178 	ret = TRUE;
1179 
1180     /* Return true for 'present' and 'functioning' */
1181     if ((devinfo->CurrentStatus & 0x19) == 0x19)
1182 	ret = TRUE;
1183 
1184     AcpiOsFree(buf.Pointer);
1185     return (ret);
1186 }
1187 
1188 /*
1189  * Match a HID string against a device
1190  */
1191 BOOLEAN
1192 acpi_MatchHid(device_t dev, char *hid)
1193 {
1194     ACPI_DEVICE_INFO	*devinfo;
1195     ACPI_HANDLE		h;
1196     ACPI_BUFFER		buf;
1197     ACPI_STATUS		error;
1198     int			ret, i;
1199 
1200     ACPI_ASSERTLOCK;
1201 
1202     ret = FALSE;
1203     if (hid == NULL)
1204 	return (FALSE);
1205     if ((h = acpi_get_handle(dev)) == NULL)
1206 	return (FALSE);
1207     buf.Pointer = NULL;
1208     buf.Length = ACPI_ALLOCATE_BUFFER;
1209     error = AcpiGetObjectInfo(h, &buf);
1210     if (ACPI_FAILURE(error))
1211 	return (FALSE);
1212     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1213 
1214     if ((devinfo->Valid & ACPI_VALID_HID) != 0) {
1215 	if (strcmp(hid, devinfo->HardwareId.Value) == 0)
1216 	    ret = TRUE;
1217     } else if ((devinfo->Valid & ACPI_VALID_CID) != 0) {
1218 	for (i = 0; i < devinfo->CompatibilityId.Count; i++) {
1219 	    if (strcmp(hid, devinfo->CompatibilityId.Id[i].Value) == 0) {
1220 		ret = TRUE;
1221 		break;
1222 	    }
1223 	}
1224     }
1225 
1226     AcpiOsFree(buf.Pointer);
1227     return (ret);
1228 }
1229 
1230 /*
1231  * Return the handle of a named object within our scope, ie. that of (parent)
1232  * or one if its parents.
1233  */
1234 ACPI_STATUS
1235 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1236 {
1237     ACPI_HANDLE		r;
1238     ACPI_STATUS		status;
1239 
1240     ACPI_ASSERTLOCK;
1241 
1242     /* Walk back up the tree to the root */
1243     for (;;) {
1244 	status = AcpiGetHandle(parent, path, &r);
1245 	if (ACPI_SUCCESS(status)) {
1246 	    *result = r;
1247 	    return (AE_OK);
1248 	}
1249 	if (status != AE_NOT_FOUND)
1250 	    return (AE_OK);
1251 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1252 	    return (AE_NOT_FOUND);
1253 	parent = r;
1254     }
1255 }
1256 
1257 /*
1258  * Allocate a buffer with a preset data size.
1259  */
1260 ACPI_BUFFER *
1261 acpi_AllocBuffer(int size)
1262 {
1263     ACPI_BUFFER	*buf;
1264 
1265     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1266 	return (NULL);
1267     buf->Length = size;
1268     buf->Pointer = (void *)(buf + 1);
1269     return (buf);
1270 }
1271 
1272 /*
1273  * Evaluate a path that should return an integer.
1274  */
1275 ACPI_STATUS
1276 acpi_EvaluateInteger(ACPI_HANDLE handle, char *path, int *number)
1277 {
1278     ACPI_STATUS	status;
1279     ACPI_BUFFER	buf;
1280     ACPI_OBJECT	param;
1281 
1282     ACPI_ASSERTLOCK;
1283 
1284     if (handle == NULL)
1285 	handle = ACPI_ROOT_OBJECT;
1286 
1287     /*
1288      * Assume that what we've been pointed at is an Integer object, or
1289      * a method that will return an Integer.
1290      */
1291     buf.Pointer = &param;
1292     buf.Length = sizeof(param);
1293     status = AcpiEvaluateObject(handle, path, NULL, &buf);
1294     if (ACPI_SUCCESS(status)) {
1295 	if (param.Type == ACPI_TYPE_INTEGER)
1296 	    *number = param.Integer.Value;
1297 	else
1298 	    status = AE_TYPE;
1299     }
1300 
1301     /*
1302      * In some applications, a method that's expected to return an Integer
1303      * may instead return a Buffer (probably to simplify some internal
1304      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1305      * convert it into an Integer as best we can.
1306      *
1307      * This is a hack.
1308      */
1309     if (status == AE_BUFFER_OVERFLOW) {
1310 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1311 	    status = AE_NO_MEMORY;
1312 	} else {
1313 	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1314 	    if (ACPI_SUCCESS(status))
1315 		status = acpi_ConvertBufferToInteger(&buf, number);
1316 	    AcpiOsFree(buf.Pointer);
1317 	}
1318     }
1319     return (status);
1320 }
1321 
1322 ACPI_STATUS
1323 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, int *number)
1324 {
1325     ACPI_OBJECT	*p;
1326     int		i;
1327 
1328     p = (ACPI_OBJECT *)bufp->Pointer;
1329     if (p->Type == ACPI_TYPE_INTEGER) {
1330 	*number = p->Integer.Value;
1331 	return (AE_OK);
1332     }
1333     if (p->Type != ACPI_TYPE_BUFFER)
1334 	return (AE_TYPE);
1335     if (p->Buffer.Length > sizeof(int))
1336 	return (AE_BAD_DATA);
1337 
1338     *number = 0;
1339     for (i = 0; i < p->Buffer.Length; i++)
1340 	*number += (*(p->Buffer.Pointer + i) << (i * 8));
1341     return (AE_OK);
1342 }
1343 
1344 /*
1345  * Iterate over the elements of an a package object, calling the supplied
1346  * function for each element.
1347  *
1348  * XXX possible enhancement might be to abort traversal on error.
1349  */
1350 ACPI_STATUS
1351 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
1352 	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
1353 {
1354     ACPI_OBJECT	*comp;
1355     int		i;
1356 
1357     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
1358 	return (AE_BAD_PARAMETER);
1359 
1360     /* Iterate over components */
1361     i = 0;
1362     comp = pkg->Package.Elements;
1363     for (; i < pkg->Package.Count; i++, comp++)
1364 	func(comp, arg);
1365 
1366     return (AE_OK);
1367 }
1368 
1369 /*
1370  * Find the (index)th resource object in a set.
1371  */
1372 ACPI_STATUS
1373 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1374 {
1375     ACPI_RESOURCE	*rp;
1376     int			i;
1377 
1378     rp = (ACPI_RESOURCE *)buf->Pointer;
1379     i = index;
1380     while (i-- > 0) {
1381 	/* Range check */
1382 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1383 	    return (AE_BAD_PARAMETER);
1384 
1385 	/* Check for terminator */
1386 	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1387 	    return (AE_NOT_FOUND);
1388 	rp = ACPI_RESOURCE_NEXT(rp);
1389     }
1390     if (resp != NULL)
1391 	*resp = rp;
1392 
1393     return (AE_OK);
1394 }
1395 
1396 /*
1397  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1398  *
1399  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1400  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1401  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1402  * resources.
1403  */
1404 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
1405 
1406 ACPI_STATUS
1407 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1408 {
1409     ACPI_RESOURCE	*rp;
1410     void		*newp;
1411 
1412     /* Initialise the buffer if necessary. */
1413     if (buf->Pointer == NULL) {
1414 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1415 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1416 	    return (AE_NO_MEMORY);
1417 	rp = (ACPI_RESOURCE *)buf->Pointer;
1418 	rp->Id = ACPI_RSTYPE_END_TAG;
1419 	rp->Length = 0;
1420     }
1421     if (res == NULL)
1422 	return (AE_OK);
1423 
1424     /*
1425      * Scan the current buffer looking for the terminator.
1426      * This will either find the terminator or hit the end
1427      * of the buffer and return an error.
1428      */
1429     rp = (ACPI_RESOURCE *)buf->Pointer;
1430     for (;;) {
1431 	/* Range check, don't go outside the buffer */
1432 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1433 	    return (AE_BAD_PARAMETER);
1434 	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1435 	    break;
1436 	rp = ACPI_RESOURCE_NEXT(rp);
1437     }
1438 
1439     /*
1440      * Check the size of the buffer and expand if required.
1441      *
1442      * Required size is:
1443      *	size of existing resources before terminator +
1444      *	size of new resource and header +
1445      * 	size of terminator.
1446      *
1447      * Note that this loop should really only run once, unless
1448      * for some reason we are stuffing a *really* huge resource.
1449      */
1450     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
1451 	    res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1452 	    ACPI_RESOURCE_LENGTH) >= buf->Length) {
1453 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1454 	    return (AE_NO_MEMORY);
1455 	bcopy(buf->Pointer, newp, buf->Length);
1456 	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1457 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1458 	AcpiOsFree(buf->Pointer);
1459 	buf->Pointer = newp;
1460 	buf->Length += buf->Length;
1461     }
1462 
1463     /* Insert the new resource. */
1464     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1465 
1466     /* And add the terminator. */
1467     rp = ACPI_RESOURCE_NEXT(rp);
1468     rp->Id = ACPI_RSTYPE_END_TAG;
1469     rp->Length = 0;
1470 
1471     return (AE_OK);
1472 }
1473 
1474 /*
1475  * Set interrupt model.
1476  */
1477 ACPI_STATUS
1478 acpi_SetIntrModel(int model)
1479 {
1480     ACPI_OBJECT_LIST ArgList;
1481     ACPI_OBJECT Arg;
1482 
1483     Arg.Type = ACPI_TYPE_INTEGER;
1484     Arg.Integer.Value = model;
1485     ArgList.Count = 1;
1486     ArgList.Pointer = &Arg;
1487     return (AcpiEvaluateObject(ACPI_ROOT_OBJECT, "_PIC", &ArgList, NULL));
1488 }
1489 
1490 #define ACPI_MINIMUM_AWAKETIME	5
1491 
1492 static void
1493 acpi_sleep_enable(void *arg)
1494 {
1495     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1496 }
1497 
1498 /*
1499  * Set the system sleep state
1500  *
1501  * Currently we support S1-S5 but S4 is only S4BIOS
1502  */
1503 ACPI_STATUS
1504 acpi_SetSleepState(struct acpi_softc *sc, int state)
1505 {
1506     ACPI_STATUS	status = AE_OK;
1507     UINT8	TypeA;
1508     UINT8	TypeB;
1509 
1510     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1511     ACPI_ASSERTLOCK;
1512 
1513     /* Avoid reentry if already attempting to suspend. */
1514     if (sc->acpi_sstate != ACPI_STATE_S0)
1515 	return_ACPI_STATUS (AE_BAD_PARAMETER);
1516 
1517     /* We recently woke up so don't suspend again for a while. */
1518     if (sc->acpi_sleep_disabled)
1519 	return_ACPI_STATUS (AE_OK);
1520 
1521     switch (state) {
1522     case ACPI_STATE_S1:
1523     case ACPI_STATE_S2:
1524     case ACPI_STATE_S3:
1525     case ACPI_STATE_S4:
1526 	status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB);
1527 	if (status == AE_NOT_FOUND) {
1528 	    device_printf(sc->acpi_dev,
1529 			  "Sleep state S%d not supported by BIOS\n", state);
1530 	    break;
1531 	} else if (ACPI_FAILURE(status)) {
1532 	    device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n",
1533 			  AcpiFormatException(status));
1534 	    break;
1535 	}
1536 
1537 	sc->acpi_sstate = state;
1538 	sc->acpi_sleep_disabled = 1;
1539 
1540 	/* Inform all devices that we are going to sleep. */
1541 	if (DEVICE_SUSPEND(root_bus) != 0) {
1542 	    /*
1543 	     * Re-wake the system.
1544 	     *
1545 	     * XXX note that a better two-pass approach with a 'veto' pass
1546 	     *     followed by a "real thing" pass would be better, but the
1547 	     *     current bus interface does not provide for this.
1548 	     */
1549 	    DEVICE_RESUME(root_bus);
1550 	    return_ACPI_STATUS (AE_ERROR);
1551 	}
1552 
1553 	status = AcpiEnterSleepStatePrep(state);
1554 	if (ACPI_FAILURE(status)) {
1555 	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1556 			  AcpiFormatException(status));
1557 	    break;
1558 	}
1559 
1560 	if (sc->acpi_sleep_delay > 0)
1561 	    DELAY(sc->acpi_sleep_delay * 1000000);
1562 
1563 	if (state != ACPI_STATE_S1) {
1564 	    acpi_sleep_machdep(sc, state);
1565 
1566 	    /* AcpiEnterSleepState() may be incomplete, unlock if locked. */
1567 	    if (AcpiGbl_MutexInfo[ACPI_MTX_HARDWARE].OwnerId !=
1568 		ACPI_MUTEX_NOT_ACQUIRED) {
1569 
1570 		AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1571 	    }
1572 
1573 	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1574 	    if (state == ACPI_STATE_S4)
1575 		AcpiEnable();
1576 	} else {
1577 	    status = AcpiEnterSleepState((UINT8)state);
1578 	    if (ACPI_FAILURE(status)) {
1579 		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
1580 			      AcpiFormatException(status));
1581 		break;
1582 	    }
1583 	}
1584 	AcpiLeaveSleepState((UINT8)state);
1585 	DEVICE_RESUME(root_bus);
1586 	sc->acpi_sstate = ACPI_STATE_S0;
1587 	acpi_enable_fixed_events(sc);
1588 	break;
1589     case ACPI_STATE_S5:
1590 	/*
1591 	 * Shut down cleanly and power off.  This will call us back through the
1592 	 * shutdown handlers.
1593 	 */
1594 	shutdown_nice(RB_POWEROFF);
1595 	break;
1596     case ACPI_STATE_S0:
1597     default:
1598 	status = AE_BAD_PARAMETER;
1599 	break;
1600     }
1601 
1602     /* Disable a second sleep request for a short period */
1603     if (sc->acpi_sleep_disabled)
1604 	timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
1605 
1606     return_ACPI_STATUS (status);
1607 }
1608 
1609 /*
1610  * Enable/Disable ACPI
1611  */
1612 ACPI_STATUS
1613 acpi_Enable(struct acpi_softc *sc)
1614 {
1615     ACPI_STATUS	status;
1616     u_int32_t	flags;
1617 
1618     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1619     ACPI_ASSERTLOCK;
1620 
1621     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
1622 	    ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
1623     if (!sc->acpi_enabled)
1624 	status = AcpiEnableSubsystem(flags);
1625     else
1626 	status = AE_OK;
1627 
1628     if (status == AE_OK)
1629 	sc->acpi_enabled = 1;
1630 
1631     return_ACPI_STATUS (status);
1632 }
1633 
1634 ACPI_STATUS
1635 acpi_Disable(struct acpi_softc *sc)
1636 {
1637     ACPI_STATUS	status;
1638 
1639     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1640     ACPI_ASSERTLOCK;
1641 
1642     if (sc->acpi_enabled)
1643 	status = AcpiDisable();
1644     else
1645 	status = AE_OK;
1646 
1647     if (status == AE_OK)
1648 	sc->acpi_enabled = 0;
1649 
1650     return_ACPI_STATUS (status);
1651 }
1652 
1653 /*
1654  * ACPI Event Handlers
1655  */
1656 
1657 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1658 
1659 static void
1660 acpi_system_eventhandler_sleep(void *arg, int state)
1661 {
1662     ACPI_LOCK_DECL;
1663     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1664 
1665     ACPI_LOCK;
1666     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
1667 	acpi_SetSleepState((struct acpi_softc *)arg, state);
1668     ACPI_UNLOCK;
1669     return_VOID;
1670 }
1671 
1672 static void
1673 acpi_system_eventhandler_wakeup(void *arg, int state)
1674 {
1675     ACPI_LOCK_DECL;
1676     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1677 
1678     /* Well, what to do? :-) */
1679 
1680     ACPI_LOCK;
1681     ACPI_UNLOCK;
1682 
1683     return_VOID;
1684 }
1685 
1686 /*
1687  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1688  */
1689 UINT32
1690 acpi_eventhandler_power_button_for_sleep(void *context)
1691 {
1692     struct acpi_softc	*sc = (struct acpi_softc *)context;
1693 
1694     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1695 
1696     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1697 
1698     return_VALUE (ACPI_INTERRUPT_HANDLED);
1699 }
1700 
1701 UINT32
1702 acpi_eventhandler_power_button_for_wakeup(void *context)
1703 {
1704     struct acpi_softc	*sc = (struct acpi_softc *)context;
1705 
1706     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1707 
1708     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1709 
1710     return_VALUE (ACPI_INTERRUPT_HANDLED);
1711 }
1712 
1713 UINT32
1714 acpi_eventhandler_sleep_button_for_sleep(void *context)
1715 {
1716     struct acpi_softc	*sc = (struct acpi_softc *)context;
1717 
1718     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1719 
1720     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1721 
1722     return_VALUE (ACPI_INTERRUPT_HANDLED);
1723 }
1724 
1725 UINT32
1726 acpi_eventhandler_sleep_button_for_wakeup(void *context)
1727 {
1728     struct acpi_softc	*sc = (struct acpi_softc *)context;
1729 
1730     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1731 
1732     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1733 
1734     return_VALUE (ACPI_INTERRUPT_HANDLED);
1735 }
1736 
1737 /*
1738  * XXX This is kinda ugly, and should not be here.
1739  */
1740 struct acpi_staticbuf {
1741     ACPI_BUFFER	buffer;
1742     char	data[512];
1743 };
1744 
1745 char *
1746 acpi_name(ACPI_HANDLE handle)
1747 {
1748     static struct acpi_staticbuf	buf;
1749 
1750     ACPI_ASSERTLOCK;
1751 
1752     buf.buffer.Length = 512;
1753     buf.buffer.Pointer = &buf.data[0];
1754 
1755     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
1756 	return (buf.buffer.Pointer);
1757 
1758     return ("(unknown path)");
1759 }
1760 
1761 /*
1762  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1763  * parts of the namespace.
1764  */
1765 int
1766 acpi_avoid(ACPI_HANDLE handle)
1767 {
1768     char	*cp, *env, *np;
1769     int		len;
1770 
1771     np = acpi_name(handle);
1772     if (*np == '\\')
1773 	np++;
1774     if ((env = getenv("debug.acpi.avoid")) == NULL)
1775 	return (0);
1776 
1777     /* Scan the avoid list checking for a match */
1778     cp = env;
1779     for (;;) {
1780 	while ((*cp != 0) && isspace(*cp))
1781 	    cp++;
1782 	if (*cp == 0)
1783 	    break;
1784 	len = 0;
1785 	while ((cp[len] != 0) && !isspace(cp[len]))
1786 	    len++;
1787 	if (!strncmp(cp, np, len)) {
1788 	    freeenv(env);
1789 	    return(1);
1790 	}
1791 	cp += len;
1792     }
1793     freeenv(env);
1794 
1795     return (0);
1796 }
1797 
1798 /*
1799  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1800  */
1801 int
1802 acpi_disabled(char *subsys)
1803 {
1804     char	*cp, *env;
1805     int		len;
1806 
1807     if ((env = getenv("debug.acpi.disable")) == NULL)
1808 	return (0);
1809     if (!strcmp(env, "all")) {
1810 	freeenv(env);
1811 	return (1);
1812     }
1813 
1814     /* scan the disable list checking for a match */
1815     cp = env;
1816     for (;;) {
1817 	while ((*cp != 0) && isspace(*cp))
1818 	    cp++;
1819 	if (*cp == 0)
1820 	    break;
1821 	len = 0;
1822 	while ((cp[len] != 0) && !isspace(cp[len]))
1823 	    len++;
1824 	if (!strncmp(cp, subsys, len)) {
1825 	    freeenv(env);
1826 	    return (1);
1827 	}
1828 	cp += len;
1829     }
1830     freeenv(env);
1831 
1832     return (0);
1833 }
1834 
1835 /*
1836  * Device wake capability enable/disable.
1837  */
1838 void
1839 acpi_device_enable_wake_capability(ACPI_HANDLE h, int enable)
1840 {
1841     ACPI_OBJECT_LIST		ArgList;
1842     ACPI_OBJECT			Arg;
1843 
1844     /*
1845      * TBD: All Power Resources referenced by elements 2 through N
1846      *      of the _PRW object are put into the ON state.
1847      */
1848 
1849     ArgList.Count = 1;
1850     ArgList.Pointer = &Arg;
1851 
1852     Arg.Type = ACPI_TYPE_INTEGER;
1853     Arg.Integer.Value = enable;
1854 
1855     (void)AcpiEvaluateObject(h, "_PSW", &ArgList, NULL);
1856 }
1857 
1858 void
1859 acpi_device_enable_wake_event(ACPI_HANDLE h)
1860 {
1861     struct acpi_softc		*sc;
1862     ACPI_STATUS			status;
1863     ACPI_BUFFER			prw_buffer;
1864     ACPI_OBJECT			*res;
1865 
1866     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1867 
1868     sc = devclass_get_softc(acpi_devclass, 0);
1869     if (sc == NULL)
1870 	return;
1871 
1872     /*
1873      * _PRW object is only required for devices that have the ability
1874      * to wake the system from a system sleeping state.
1875      */
1876     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
1877     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
1878     if (ACPI_FAILURE(status))
1879 	return;
1880 
1881     res = (ACPI_OBJECT *)prw_buffer.Pointer;
1882     if (res == NULL)
1883 	return;
1884 
1885     if ((res->Type != ACPI_TYPE_PACKAGE) || (res->Package.Count < 2)) {
1886 	goto out;
1887     }
1888 
1889     /*
1890      * The element 1 of the _PRW object:
1891      * The lowest power system sleeping state that can be entered
1892      * while still providing wake functionality.
1893      * The sleeping state being entered must be greater or equal to
1894      * the power state declared in element 1 of the _PRW object.
1895      */
1896     if (res->Package.Elements[1].Type != ACPI_TYPE_INTEGER)
1897 	goto out;
1898 
1899     if (sc->acpi_sstate > res->Package.Elements[1].Integer.Value)
1900 	goto out;
1901 
1902     /*
1903      * The element 0 of the _PRW object:
1904      */
1905     switch(res->Package.Elements[0].Type) {
1906     case ACPI_TYPE_INTEGER:
1907 	/*
1908 	 * If the data type of this package element is numeric, then this
1909 	 * _PRW package element is the bit index in the GPEx_EN, in the
1910 	 * GPE blocks described in the FADT, of the enable bit that is
1911 	 * enabled for the wake event.
1912 	 */
1913 
1914 	status = AcpiEnableGpe(NULL, res->Package.Elements[0].Integer.Value,
1915 			       ACPI_EVENT_WAKE_ENABLE);
1916 	if (ACPI_FAILURE(status))
1917 	    printf("%s: EnableEvent Failed\n", __func__);
1918 	break;
1919     case ACPI_TYPE_PACKAGE:
1920 	/*
1921 	 * XXX TBD
1922 	 *
1923 	 * If the data type of this package element is a package, then this
1924 	 * _PRW package element is itself a package containing two
1925 	 * elements. The first is an object reference to the GPE Block
1926 	 * device that contains the GPE that will be triggered by the wake
1927 	 * event. The second element is numeric and it contains the bit
1928 	 * index in the GPEx_EN, in the GPE Block referenced by the
1929 	 * first element in the package, of the enable bit that is enabled for
1930 	 * the wake event.
1931 	 * For example, if this field is a package then it is of the form:
1932 	 * Package() {\_SB.PCI0.ISA.GPE, 2}
1933 	 */
1934 	break;
1935     default:
1936 	break;
1937     }
1938 
1939 out:
1940     if (prw_buffer.Pointer != NULL)
1941 	AcpiOsFree(prw_buffer.Pointer);
1942 }
1943 
1944 /*
1945  * Control interface.
1946  *
1947  * We multiplex ioctls for all participating ACPI devices here.  Individual
1948  * drivers wanting to be accessible via /dev/acpi should use the
1949  * register/deregister interface to make their handlers visible.
1950  */
1951 struct acpi_ioctl_hook
1952 {
1953     TAILQ_ENTRY(acpi_ioctl_hook) link;
1954     u_long			 cmd;
1955     acpi_ioctl_fn		 fn;
1956     void			 *arg;
1957 };
1958 
1959 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
1960 static int				acpi_ioctl_hooks_initted;
1961 
1962 /*
1963  * Register an ioctl handler.
1964  */
1965 int
1966 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
1967 {
1968     struct acpi_ioctl_hook	*hp;
1969 
1970     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
1971 	return (ENOMEM);
1972     hp->cmd = cmd;
1973     hp->fn = fn;
1974     hp->arg = arg;
1975     if (acpi_ioctl_hooks_initted == 0) {
1976 	TAILQ_INIT(&acpi_ioctl_hooks);
1977 	acpi_ioctl_hooks_initted = 1;
1978     }
1979     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
1980     return (0);
1981 }
1982 
1983 /*
1984  * Deregister an ioctl handler.
1985  */
1986 void
1987 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
1988 {
1989     struct acpi_ioctl_hook	*hp;
1990 
1991     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
1992 	if ((hp->cmd == cmd) && (hp->fn == fn))
1993 	    break;
1994 
1995     if (hp != NULL) {
1996 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
1997 	free(hp, M_ACPIDEV);
1998     }
1999 }
2000 
2001 static int
2002 acpiopen(dev_t dev, int flag, int fmt, d_thread_t *td)
2003 {
2004     return (0);
2005 }
2006 
2007 static int
2008 acpiclose(dev_t dev, int flag, int fmt, d_thread_t *td)
2009 {
2010     return (0);
2011 }
2012 
2013 static int
2014 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
2015 {
2016     struct acpi_softc		*sc;
2017     struct acpi_ioctl_hook	*hp;
2018     int				error, xerror, state;
2019     ACPI_LOCK_DECL;
2020 
2021     ACPI_LOCK;
2022 
2023     error = state = 0;
2024     sc = dev->si_drv1;
2025 
2026     /*
2027      * Scan the list of registered ioctls, looking for handlers.
2028      */
2029     if (acpi_ioctl_hooks_initted) {
2030 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
2031 	    if (hp->cmd == cmd) {
2032 		xerror = hp->fn(cmd, addr, hp->arg);
2033 		if (xerror != 0)
2034 		    error = xerror;
2035 		goto out;
2036 	    }
2037 	}
2038     }
2039 
2040     /*
2041      * Core ioctls are not permitted for non-writable user.
2042      * Currently, other ioctls just fetch information.
2043      * Not changing system behavior.
2044      */
2045     if((flag & FWRITE) == 0)
2046 	return (EPERM);
2047 
2048     /* Core system ioctls. */
2049     switch (cmd) {
2050     case ACPIIO_ENABLE:
2051 	if (ACPI_FAILURE(acpi_Enable(sc)))
2052 	    error = ENXIO;
2053 	break;
2054     case ACPIIO_DISABLE:
2055 	if (ACPI_FAILURE(acpi_Disable(sc)))
2056 	    error = ENXIO;
2057 	break;
2058     case ACPIIO_SETSLPSTATE:
2059 	if (!sc->acpi_enabled) {
2060 	    error = ENXIO;
2061 	    break;
2062 	}
2063 	state = *(int *)addr;
2064 	if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
2065 	    if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
2066 		error = EINVAL;
2067 	} else {
2068 	    error = EINVAL;
2069 	}
2070 	break;
2071     default:
2072 	if (error == 0)
2073 	    error = EINVAL;
2074 	break;
2075     }
2076 
2077 out:
2078     ACPI_UNLOCK;
2079     return (error);
2080 }
2081 
2082 static int
2083 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2084 {
2085     char sleep_state[4];
2086     char buf[16];
2087     int error;
2088     UINT8 state, TypeA, TypeB;
2089 
2090     buf[0] = '\0';
2091     for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX+1; state++) {
2092 	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
2093 	    sprintf(sleep_state, "S%d ", state);
2094 	    strcat(buf, sleep_state);
2095 	}
2096     }
2097     error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2098     return (error);
2099 }
2100 
2101 static int
2102 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2103 {
2104     char sleep_state[10];
2105     int error;
2106     u_int new_state, old_state;
2107 
2108     old_state = *(u_int *)oidp->oid_arg1;
2109     if (old_state > ACPI_S_STATES_MAX+1) {
2110 	strcpy(sleep_state, "unknown");
2111     } else {
2112 	bzero(sleep_state, sizeof(sleep_state));
2113 	strncpy(sleep_state, sleep_state_names[old_state],
2114 		sizeof(sleep_state_names[old_state]));
2115     }
2116     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
2117     if (error == 0 && req->newptr != NULL) {
2118 	new_state = ACPI_STATE_S0;
2119 	for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++) {
2120 	    if (strncmp(sleep_state, sleep_state_names[new_state],
2121 			sizeof(sleep_state)) == 0)
2122 		break;
2123 	}
2124 	if (new_state <= ACPI_S_STATES_MAX + 1) {
2125 	    if (new_state != old_state)
2126 		*(u_int *)oidp->oid_arg1 = new_state;
2127 	} else {
2128 	    error = EINVAL;
2129 	}
2130     }
2131 
2132     return (error);
2133 }
2134 
2135 /* Inform devctl(4) when we receive a Notify. */
2136 void
2137 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
2138 {
2139     char		notify_buf[16];
2140     ACPI_BUFFER		handle_buf;
2141     ACPI_STATUS		status;
2142 
2143     if (subsystem == NULL)
2144 	return;
2145 
2146     handle_buf.Pointer = NULL;
2147     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
2148     status = AcpiNsHandleToPathname(h, &handle_buf);
2149     if (ACPI_FAILURE(status))
2150 	return;
2151     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
2152     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
2153     AcpiOsFree(handle_buf.Pointer);
2154 }
2155 
2156 #ifdef ACPI_DEBUG
2157 /*
2158  * Support for parsing debug options from the kernel environment.
2159  *
2160  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
2161  * by specifying the names of the bits in the debug.acpi.layer and
2162  * debug.acpi.level environment variables.  Bits may be unset by
2163  * prefixing the bit name with !.
2164  */
2165 struct debugtag
2166 {
2167     char	*name;
2168     UINT32	value;
2169 };
2170 
2171 static struct debugtag	dbg_layer[] = {
2172     {"ACPI_UTILITIES",		ACPI_UTILITIES},
2173     {"ACPI_HARDWARE",		ACPI_HARDWARE},
2174     {"ACPI_EVENTS",		ACPI_EVENTS},
2175     {"ACPI_TABLES",		ACPI_TABLES},
2176     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
2177     {"ACPI_PARSER",		ACPI_PARSER},
2178     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
2179     {"ACPI_EXECUTER",		ACPI_EXECUTER},
2180     {"ACPI_RESOURCES",		ACPI_RESOURCES},
2181     {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
2182     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
2183     {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
2184     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
2185 
2186     {"ACPI_BUS",		ACPI_BUS},
2187     {"ACPI_SYSTEM",		ACPI_SYSTEM},
2188     {"ACPI_POWER",		ACPI_POWER},
2189     {"ACPI_EC", 		ACPI_EC},
2190     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
2191     {"ACPI_BATTERY",		ACPI_BATTERY},
2192     {"ACPI_BUTTON",		ACPI_BUTTON},
2193     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
2194     {"ACPI_THERMAL",		ACPI_THERMAL},
2195     {"ACPI_FAN",		ACPI_FAN},
2196     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
2197     {NULL, 0}
2198 };
2199 
2200 static struct debugtag dbg_level[] = {
2201     {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
2202     {"ACPI_LV_WARN",		ACPI_LV_WARN},
2203     {"ACPI_LV_INIT",		ACPI_LV_INIT},
2204     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
2205     {"ACPI_LV_INFO",		ACPI_LV_INFO},
2206     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
2207 
2208     /* Trace verbosity level 1 [Standard Trace Level] */
2209     {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
2210     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
2211     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
2212     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
2213     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
2214     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
2215     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
2216     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
2217     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
2218     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
2219     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
2220     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
2221     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
2222     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
2223     {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
2224 
2225     /* Trace verbosity level 2 [Function tracing and memory allocation] */
2226     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
2227     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
2228     {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
2229     {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
2230     {"ACPI_LV_ALL",		ACPI_LV_ALL},
2231 
2232     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2233     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
2234     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
2235     {"ACPI_LV_IO",		ACPI_LV_IO},
2236     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
2237     {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
2238 
2239     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2240     {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
2241     {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
2242     {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
2243     {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
2244     {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
2245     {NULL, 0}
2246 };
2247 
2248 static void
2249 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2250 {
2251     char	*ep;
2252     int		i, l;
2253     int		set;
2254 
2255     while (*cp) {
2256 	if (isspace(*cp)) {
2257 	    cp++;
2258 	    continue;
2259 	}
2260 	ep = cp;
2261 	while (*ep && !isspace(*ep))
2262 	    ep++;
2263 	if (*cp == '!') {
2264 	    set = 0;
2265 	    cp++;
2266 	    if (cp == ep)
2267 		continue;
2268 	} else {
2269 	    set = 1;
2270 	}
2271 	l = ep - cp;
2272 	for (i = 0; tag[i].name != NULL; i++) {
2273 	    if (!strncmp(cp, tag[i].name, l)) {
2274 		if (set)
2275 		    *flag |= tag[i].value;
2276 		else
2277 		    *flag &= ~tag[i].value;
2278 		printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
2279 	    }
2280 	}
2281 	cp = ep;
2282     }
2283 }
2284 
2285 static void
2286 acpi_set_debugging(void *junk)
2287 {
2288     char	*cp;
2289 
2290     if (cold) {
2291 	AcpiDbgLayer = 0;
2292 	AcpiDbgLevel = 0;
2293     }
2294 
2295     if ((cp = getenv("debug.acpi.layer")) != NULL) {
2296 	acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
2297 	freeenv(cp);
2298     }
2299     if ((cp = getenv("debug.acpi.level")) != NULL) {
2300 	acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
2301 	freeenv(cp);
2302     }
2303 
2304     if (cold) {
2305 	printf("ACPI debug layer 0x%x debug level 0x%x\n",
2306 	       AcpiDbgLayer, AcpiDbgLevel);
2307     }
2308 }
2309 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
2310 	NULL);
2311 
2312 static int
2313 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
2314 {
2315     int		 error, *dbg;
2316     struct	 debugtag *tag;
2317     struct	 sbuf sb;
2318 
2319     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
2320 	return (ENOMEM);
2321     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
2322 	tag = &dbg_layer[0];
2323 	dbg = &AcpiDbgLayer;
2324     } else {
2325 	tag = &dbg_level[0];
2326 	dbg = &AcpiDbgLevel;
2327     }
2328 
2329     /* Get old values if this is a get request. */
2330     if (*dbg == 0) {
2331 	sbuf_cpy(&sb, "NONE");
2332     } else if (req->newptr == NULL) {
2333 	for (; tag->name != NULL; tag++) {
2334 	    if ((*dbg & tag->value) == tag->value)
2335 		sbuf_printf(&sb, "%s ", tag->name);
2336 	}
2337     }
2338     sbuf_trim(&sb);
2339     sbuf_finish(&sb);
2340 
2341     error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
2342     sbuf_delete(&sb);
2343 
2344     /* If the user is setting a string, parse it. */
2345     if (error == 0 && req->newptr != NULL) {
2346 	*dbg = 0;
2347 	setenv((char *)oidp->oid_arg1, (char *)req->newptr);
2348 	acpi_set_debugging(NULL);
2349     }
2350 
2351     return (error);
2352 }
2353 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
2354 	    "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
2355 SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
2356 	    "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
2357 #endif
2358 
2359 static int
2360 acpi_pm_func(u_long cmd, void *arg, ...)
2361 {
2362 	int	state, acpi_state;
2363 	int	error;
2364 	struct	acpi_softc *sc;
2365 	va_list	ap;
2366 
2367 	error = 0;
2368 	switch (cmd) {
2369 	case POWER_CMD_SUSPEND:
2370 		sc = (struct acpi_softc *)arg;
2371 		if (sc == NULL) {
2372 			error = EINVAL;
2373 			goto out;
2374 		}
2375 
2376 		va_start(ap, arg);
2377 		state = va_arg(ap, int);
2378 		va_end(ap);
2379 
2380 		switch (state) {
2381 		case POWER_SLEEP_STATE_STANDBY:
2382 			acpi_state = sc->acpi_standby_sx;
2383 			break;
2384 		case POWER_SLEEP_STATE_SUSPEND:
2385 			acpi_state = sc->acpi_suspend_sx;
2386 			break;
2387 		case POWER_SLEEP_STATE_HIBERNATE:
2388 			acpi_state = ACPI_STATE_S4;
2389 			break;
2390 		default:
2391 			error = EINVAL;
2392 			goto out;
2393 		}
2394 
2395 		acpi_SetSleepState(sc, acpi_state);
2396 		break;
2397 	default:
2398 		error = EINVAL;
2399 		goto out;
2400 	}
2401 
2402 out:
2403 	return (error);
2404 }
2405 
2406 static void
2407 acpi_pm_register(void *arg)
2408 {
2409     if (!cold || resource_disabled("acpi", 0))
2410 	return;
2411 
2412     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2413 }
2414 
2415 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
2416