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