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