xref: /freebsd/sys/dev/acpica/acpi.c (revision ba54cdcdda639bebc917b1796ecbc35a83ff8625)
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 all of the ACPI namespace and attach child devices.
1396  *
1397  * We should only expect to find devices in the \_PR, \_TZ, \_SI, and
1398  * \_SB scopes, and \_PR and \_TZ became obsolete in the ACPI 2.0 spec.
1399  * However, in violation of the spec, some systems place their PCI link
1400  * devices in \, so we have to walk the whole namespace.  We check the
1401  * type of namespace nodes, so this should be ok.
1402  */
1403 static void
1404 acpi_probe_children(device_t bus)
1405 {
1406 
1407     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1408 
1409     /*
1410      * Scan the namespace and insert placeholders for all the devices that
1411      * we find.  We also probe/attach any early devices.
1412      *
1413      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
1414      * we want to create nodes for all devices, not just those that are
1415      * currently present. (This assumes that we don't want to create/remove
1416      * devices as they appear, which might be smarter.)
1417      */
1418     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
1419     AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, 100, acpi_probe_child,
1420 	bus, NULL);
1421 
1422     /* Pre-allocate resources for our rman from any sysresource devices. */
1423     acpi_sysres_alloc(bus);
1424 
1425     /* Create any static children by calling device identify methods. */
1426     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
1427     bus_generic_probe(bus);
1428 
1429     /* Probe/attach all children, created staticly and from the namespace. */
1430     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
1431     bus_generic_attach(bus);
1432 
1433     /*
1434      * Some of these children may have attached others as part of their attach
1435      * process (eg. the root PCI bus driver), so rescan.
1436      */
1437     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
1438     bus_generic_attach(bus);
1439 
1440     /* Attach wake sysctls. */
1441     acpi_wake_sysctl_walk(bus);
1442 
1443     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
1444     return_VOID;
1445 }
1446 
1447 /*
1448  * Determine the probe order for a given device and return non-zero if it
1449  * should be attached immediately.
1450  */
1451 static int
1452 acpi_probe_order(ACPI_HANDLE handle, int *order)
1453 {
1454     int ret;
1455 
1456     /*
1457      * 1. I/O port and memory system resource holders
1458      * 2. Embedded controllers (to handle early accesses)
1459      */
1460     ret = 0;
1461     if (acpi_MatchHid(handle, "PNP0C01") || acpi_MatchHid(handle, "PNP0C02")) {
1462 	*order = 1;
1463 	ret = 1;
1464     } else if (acpi_MatchHid(handle, "PNP0C09")) {
1465 	*order = 2;
1466 	ret = 1;
1467     }
1468 
1469     return (ret);
1470 }
1471 
1472 /*
1473  * Evaluate a child device and determine whether we might attach a device to
1474  * it.
1475  */
1476 static ACPI_STATUS
1477 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
1478 {
1479     ACPI_OBJECT_TYPE type;
1480     device_t bus, child;
1481     int order, probe_now;
1482     char *handle_str, **search;
1483     static char *scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI_", "\\_SB_", NULL};
1484 
1485     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1486 
1487     /* Skip this device if we think we'll have trouble with it. */
1488     if (acpi_avoid(handle))
1489 	return_ACPI_STATUS (AE_OK);
1490 
1491     bus = (device_t)context;
1492     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
1493 	switch (type) {
1494 	case ACPI_TYPE_DEVICE:
1495 	case ACPI_TYPE_PROCESSOR:
1496 	case ACPI_TYPE_THERMAL:
1497 	case ACPI_TYPE_POWER:
1498 	    if (acpi_disabled("children"))
1499 		break;
1500 
1501 	    /*
1502 	     * Since we scan from \, be sure to skip system scope objects.
1503 	     * At least \_SB and \_TZ are detected as devices (ACPI-CA bug?)
1504 	     */
1505 	    handle_str = acpi_name(handle);
1506 	    for (search = scopes; *search != NULL; search++) {
1507 		if (strcmp(handle_str, *search) == 0)
1508 		    break;
1509 	    }
1510 	    if (*search != NULL)
1511 		break;
1512 
1513 	    /*
1514 	     * Create a placeholder device for this node.  Sort the placeholder
1515 	     * so that the probe/attach passes will run breadth-first.  Orders
1516 	     * less than 10 are reserved for special objects (i.e., system
1517 	     * resources).  Larger values are used for all other devices.
1518 	     */
1519 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
1520 	    order = (level + 1) * 10;
1521 	    probe_now = acpi_probe_order(handle, &order);
1522 	    child = BUS_ADD_CHILD(bus, order, NULL, -1);
1523 	    if (child == NULL)
1524 		break;
1525 
1526 	    /* Associate the handle with the device_t and vice versa. */
1527 	    acpi_set_handle(child, handle);
1528 	    AcpiAttachData(handle, acpi_fake_objhandler, child);
1529 
1530 	    /*
1531 	     * Check that the device is present.  If it's not present,
1532 	     * leave it disabled (so that we have a device_t attached to
1533 	     * the handle, but we don't probe it).
1534 	     */
1535 	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1536 		device_disable(child);
1537 		break;
1538 	    }
1539 
1540 	    /*
1541 	     * Get the device's resource settings and attach them.
1542 	     * Note that if the device has _PRS but no _CRS, we need
1543 	     * to decide when it's appropriate to try to configure the
1544 	     * device.  Ignore the return value here; it's OK for the
1545 	     * device not to have any resources.
1546 	     */
1547 	    acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
1548 
1549 	    /* If order was overridden, probe/attach now rather than later. */
1550 	    if (probe_now)
1551 		device_probe_and_attach(child);
1552 	    break;
1553 	}
1554     }
1555 
1556     return_ACPI_STATUS (AE_OK);
1557 }
1558 
1559 /*
1560  * AcpiAttachData() requires an object handler but never uses it.  This is a
1561  * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
1562  */
1563 void
1564 acpi_fake_objhandler(ACPI_HANDLE h, UINT32 fn, void *data)
1565 {
1566 }
1567 
1568 static void
1569 acpi_shutdown_final(void *arg, int howto)
1570 {
1571     ACPI_STATUS	status;
1572 
1573     /*
1574      * XXX Shutdown code should only run on the BSP (cpuid 0).
1575      * Some chipsets do not power off the system correctly if called from
1576      * an AP.
1577      */
1578     if ((howto & RB_POWEROFF) != 0) {
1579 	status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
1580 	if (ACPI_FAILURE(status)) {
1581 	    printf("AcpiEnterSleepStatePrep failed - %s\n",
1582 		   AcpiFormatException(status));
1583 	    return;
1584 	}
1585 	printf("Powering system off using ACPI\n");
1586 	ACPI_DISABLE_IRQS();
1587 	status = AcpiEnterSleepState(ACPI_STATE_S5);
1588 	if (ACPI_FAILURE(status)) {
1589 	    printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
1590 	} else {
1591 	    DELAY(1000000);
1592 	    printf("ACPI power-off failed - timeout\n");
1593 	}
1594     } else if (panicstr == NULL) {
1595 	printf("Shutting down ACPI\n");
1596 	AcpiTerminate();
1597     }
1598 }
1599 
1600 static void
1601 acpi_enable_fixed_events(struct acpi_softc *sc)
1602 {
1603     static int	first_time = 1;
1604 
1605     /* Enable and clear fixed events and install handlers. */
1606     if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->PwrButton == 0) {
1607 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
1608 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
1609 				     acpi_event_power_button_sleep, sc);
1610 	if (first_time)
1611 	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
1612     }
1613     if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->SleepButton == 0) {
1614 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
1615 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
1616 				     acpi_event_sleep_button_sleep, sc);
1617 	if (first_time)
1618 	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
1619     }
1620 
1621     first_time = 0;
1622 }
1623 
1624 /*
1625  * Returns true if the device is actually present and should
1626  * be attached to.  This requires the present, enabled, UI-visible
1627  * and diagnostics-passed bits to be set.
1628  */
1629 BOOLEAN
1630 acpi_DeviceIsPresent(device_t dev)
1631 {
1632     ACPI_DEVICE_INFO	*devinfo;
1633     ACPI_HANDLE		h;
1634     ACPI_BUFFER		buf;
1635     ACPI_STATUS		error;
1636     int			ret;
1637 
1638     ret = FALSE;
1639     if ((h = acpi_get_handle(dev)) == NULL)
1640 	return (FALSE);
1641     buf.Pointer = NULL;
1642     buf.Length = ACPI_ALLOCATE_BUFFER;
1643     error = AcpiGetObjectInfo(h, &buf);
1644     if (ACPI_FAILURE(error))
1645 	return (FALSE);
1646     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1647 
1648     /* If no _STA method, must be present */
1649     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1650 	ret = TRUE;
1651 
1652     /* Return true for 'present' and 'functioning' */
1653     if (ACPI_DEVICE_PRESENT(devinfo->CurrentStatus))
1654 	ret = TRUE;
1655 
1656     AcpiOsFree(buf.Pointer);
1657     return (ret);
1658 }
1659 
1660 /*
1661  * Returns true if the battery is actually present and inserted.
1662  */
1663 BOOLEAN
1664 acpi_BatteryIsPresent(device_t dev)
1665 {
1666     ACPI_DEVICE_INFO	*devinfo;
1667     ACPI_HANDLE		h;
1668     ACPI_BUFFER		buf;
1669     ACPI_STATUS		error;
1670     int			ret;
1671 
1672     ret = FALSE;
1673     if ((h = acpi_get_handle(dev)) == NULL)
1674 	return (FALSE);
1675     buf.Pointer = NULL;
1676     buf.Length = ACPI_ALLOCATE_BUFFER;
1677     error = AcpiGetObjectInfo(h, &buf);
1678     if (ACPI_FAILURE(error))
1679 	return (FALSE);
1680     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1681 
1682     /* If no _STA method, must be present */
1683     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1684 	ret = TRUE;
1685 
1686     /* Return true for 'present', 'battery present', and 'functioning' */
1687     if (ACPI_BATTERY_PRESENT(devinfo->CurrentStatus))
1688 	ret = TRUE;
1689 
1690     AcpiOsFree(buf.Pointer);
1691     return (ret);
1692 }
1693 
1694 /*
1695  * Match a HID string against a handle
1696  */
1697 static BOOLEAN
1698 acpi_MatchHid(ACPI_HANDLE h, const char *hid)
1699 {
1700     ACPI_DEVICE_INFO	*devinfo;
1701     ACPI_BUFFER		buf;
1702     ACPI_STATUS		error;
1703     int			ret, i;
1704 
1705     ret = FALSE;
1706     if (hid == NULL || h == NULL)
1707 	return (ret);
1708     buf.Pointer = NULL;
1709     buf.Length = ACPI_ALLOCATE_BUFFER;
1710     error = AcpiGetObjectInfo(h, &buf);
1711     if (ACPI_FAILURE(error))
1712 	return (ret);
1713     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1714 
1715     if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
1716 	strcmp(hid, devinfo->HardwareId.Value) == 0)
1717 	    ret = TRUE;
1718     else if ((devinfo->Valid & ACPI_VALID_CID) != 0) {
1719 	for (i = 0; i < devinfo->CompatibilityId.Count; i++) {
1720 	    if (strcmp(hid, devinfo->CompatibilityId.Id[i].Value) == 0) {
1721 		ret = TRUE;
1722 		break;
1723 	    }
1724 	}
1725     }
1726 
1727     AcpiOsFree(buf.Pointer);
1728     return (ret);
1729 }
1730 
1731 /*
1732  * Return the handle of a named object within our scope, ie. that of (parent)
1733  * or one if its parents.
1734  */
1735 ACPI_STATUS
1736 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1737 {
1738     ACPI_HANDLE		r;
1739     ACPI_STATUS		status;
1740 
1741     /* Walk back up the tree to the root */
1742     for (;;) {
1743 	status = AcpiGetHandle(parent, path, &r);
1744 	if (ACPI_SUCCESS(status)) {
1745 	    *result = r;
1746 	    return (AE_OK);
1747 	}
1748 	/* XXX Return error here? */
1749 	if (status != AE_NOT_FOUND)
1750 	    return (AE_OK);
1751 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1752 	    return (AE_NOT_FOUND);
1753 	parent = r;
1754     }
1755 }
1756 
1757 /* Find the difference between two PM tick counts. */
1758 uint32_t
1759 acpi_TimerDelta(uint32_t end, uint32_t start)
1760 {
1761     uint32_t delta;
1762 
1763     if (end >= start)
1764 	delta = end - start;
1765     else if (AcpiGbl_FADT->TmrValExt == 0)
1766 	delta = ((0x00FFFFFF - start) + end + 1) & 0x00FFFFFF;
1767     else
1768 	delta = ((0xFFFFFFFF - start) + end + 1);
1769     return (delta);
1770 }
1771 
1772 /*
1773  * Allocate a buffer with a preset data size.
1774  */
1775 ACPI_BUFFER *
1776 acpi_AllocBuffer(int size)
1777 {
1778     ACPI_BUFFER	*buf;
1779 
1780     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1781 	return (NULL);
1782     buf->Length = size;
1783     buf->Pointer = (void *)(buf + 1);
1784     return (buf);
1785 }
1786 
1787 ACPI_STATUS
1788 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
1789 {
1790     ACPI_OBJECT arg1;
1791     ACPI_OBJECT_LIST args;
1792 
1793     arg1.Type = ACPI_TYPE_INTEGER;
1794     arg1.Integer.Value = number;
1795     args.Count = 1;
1796     args.Pointer = &arg1;
1797 
1798     return (AcpiEvaluateObject(handle, path, &args, NULL));
1799 }
1800 
1801 /*
1802  * Evaluate a path that should return an integer.
1803  */
1804 ACPI_STATUS
1805 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
1806 {
1807     ACPI_STATUS	status;
1808     ACPI_BUFFER	buf;
1809     ACPI_OBJECT	param;
1810 
1811     if (handle == NULL)
1812 	handle = ACPI_ROOT_OBJECT;
1813 
1814     /*
1815      * Assume that what we've been pointed at is an Integer object, or
1816      * a method that will return an Integer.
1817      */
1818     buf.Pointer = &param;
1819     buf.Length = sizeof(param);
1820     status = AcpiEvaluateObject(handle, path, NULL, &buf);
1821     if (ACPI_SUCCESS(status)) {
1822 	if (param.Type == ACPI_TYPE_INTEGER)
1823 	    *number = param.Integer.Value;
1824 	else
1825 	    status = AE_TYPE;
1826     }
1827 
1828     /*
1829      * In some applications, a method that's expected to return an Integer
1830      * may instead return a Buffer (probably to simplify some internal
1831      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1832      * convert it into an Integer as best we can.
1833      *
1834      * This is a hack.
1835      */
1836     if (status == AE_BUFFER_OVERFLOW) {
1837 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1838 	    status = AE_NO_MEMORY;
1839 	} else {
1840 	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1841 	    if (ACPI_SUCCESS(status))
1842 		status = acpi_ConvertBufferToInteger(&buf, number);
1843 	    AcpiOsFree(buf.Pointer);
1844 	}
1845     }
1846     return (status);
1847 }
1848 
1849 ACPI_STATUS
1850 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
1851 {
1852     ACPI_OBJECT	*p;
1853     UINT8	*val;
1854     int		i;
1855 
1856     p = (ACPI_OBJECT *)bufp->Pointer;
1857     if (p->Type == ACPI_TYPE_INTEGER) {
1858 	*number = p->Integer.Value;
1859 	return (AE_OK);
1860     }
1861     if (p->Type != ACPI_TYPE_BUFFER)
1862 	return (AE_TYPE);
1863     if (p->Buffer.Length > sizeof(int))
1864 	return (AE_BAD_DATA);
1865 
1866     *number = 0;
1867     val = p->Buffer.Pointer;
1868     for (i = 0; i < p->Buffer.Length; i++)
1869 	*number += val[i] << (i * 8);
1870     return (AE_OK);
1871 }
1872 
1873 /*
1874  * Iterate over the elements of an a package object, calling the supplied
1875  * function for each element.
1876  *
1877  * XXX possible enhancement might be to abort traversal on error.
1878  */
1879 ACPI_STATUS
1880 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
1881 	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
1882 {
1883     ACPI_OBJECT	*comp;
1884     int		i;
1885 
1886     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
1887 	return (AE_BAD_PARAMETER);
1888 
1889     /* Iterate over components */
1890     i = 0;
1891     comp = pkg->Package.Elements;
1892     for (; i < pkg->Package.Count; i++, comp++)
1893 	func(comp, arg);
1894 
1895     return (AE_OK);
1896 }
1897 
1898 /*
1899  * Find the (index)th resource object in a set.
1900  */
1901 ACPI_STATUS
1902 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1903 {
1904     ACPI_RESOURCE	*rp;
1905     int			i;
1906 
1907     rp = (ACPI_RESOURCE *)buf->Pointer;
1908     i = index;
1909     while (i-- > 0) {
1910 	/* Range check */
1911 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1912 	    return (AE_BAD_PARAMETER);
1913 
1914 	/* Check for terminator */
1915 	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1916 	    return (AE_NOT_FOUND);
1917 	rp = ACPI_NEXT_RESOURCE(rp);
1918     }
1919     if (resp != NULL)
1920 	*resp = rp;
1921 
1922     return (AE_OK);
1923 }
1924 
1925 /*
1926  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1927  *
1928  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1929  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1930  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1931  * resources.
1932  */
1933 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
1934 
1935 ACPI_STATUS
1936 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1937 {
1938     ACPI_RESOURCE	*rp;
1939     void		*newp;
1940 
1941     /* Initialise the buffer if necessary. */
1942     if (buf->Pointer == NULL) {
1943 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1944 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1945 	    return (AE_NO_MEMORY);
1946 	rp = (ACPI_RESOURCE *)buf->Pointer;
1947 	rp->Id = ACPI_RSTYPE_END_TAG;
1948 	rp->Length = 0;
1949     }
1950     if (res == NULL)
1951 	return (AE_OK);
1952 
1953     /*
1954      * Scan the current buffer looking for the terminator.
1955      * This will either find the terminator or hit the end
1956      * of the buffer and return an error.
1957      */
1958     rp = (ACPI_RESOURCE *)buf->Pointer;
1959     for (;;) {
1960 	/* Range check, don't go outside the buffer */
1961 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1962 	    return (AE_BAD_PARAMETER);
1963 	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1964 	    break;
1965 	rp = ACPI_NEXT_RESOURCE(rp);
1966     }
1967 
1968     /*
1969      * Check the size of the buffer and expand if required.
1970      *
1971      * Required size is:
1972      *	size of existing resources before terminator +
1973      *	size of new resource and header +
1974      * 	size of terminator.
1975      *
1976      * Note that this loop should really only run once, unless
1977      * for some reason we are stuffing a *really* huge resource.
1978      */
1979     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
1980 	    res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1981 	    ACPI_RESOURCE_LENGTH) >= buf->Length) {
1982 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1983 	    return (AE_NO_MEMORY);
1984 	bcopy(buf->Pointer, newp, buf->Length);
1985 	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1986 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1987 	AcpiOsFree(buf->Pointer);
1988 	buf->Pointer = newp;
1989 	buf->Length += buf->Length;
1990     }
1991 
1992     /* Insert the new resource. */
1993     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1994 
1995     /* And add the terminator. */
1996     rp = ACPI_NEXT_RESOURCE(rp);
1997     rp->Id = ACPI_RSTYPE_END_TAG;
1998     rp->Length = 0;
1999 
2000     return (AE_OK);
2001 }
2002 
2003 /*
2004  * Set interrupt model.
2005  */
2006 ACPI_STATUS
2007 acpi_SetIntrModel(int model)
2008 {
2009 
2010     return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
2011 }
2012 
2013 static void
2014 acpi_sleep_enable(void *arg)
2015 {
2016 
2017     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
2018 }
2019 
2020 enum acpi_sleep_state {
2021     ACPI_SS_NONE,
2022     ACPI_SS_GPE_SET,
2023     ACPI_SS_DEV_SUSPEND,
2024     ACPI_SS_SLP_PREP,
2025     ACPI_SS_SLEPT,
2026 };
2027 
2028 /*
2029  * Set the system sleep state
2030  *
2031  * Currently we support S1-S5 but S4 is only S4BIOS
2032  */
2033 ACPI_STATUS
2034 acpi_SetSleepState(struct acpi_softc *sc, int state)
2035 {
2036     ACPI_STATUS	status;
2037     UINT8	TypeA;
2038     UINT8	TypeB;
2039     enum acpi_sleep_state slp_state;
2040 
2041     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2042 
2043     status = AE_OK;
2044     ACPI_LOCK(acpi);
2045     if (sc->acpi_sleep_disabled) {
2046 	if (sc->acpi_sstate != ACPI_STATE_S0)
2047 	    status = AE_ERROR;
2048 	ACPI_UNLOCK(acpi);
2049 	printf("acpi: suspend request ignored (not ready yet)\n");
2050 	return (status);
2051     }
2052     sc->acpi_sleep_disabled = 1;
2053     ACPI_UNLOCK(acpi);
2054 
2055     /*
2056      * Be sure to hold Giant across DEVICE_SUSPEND/RESUME since non-MPSAFE
2057      * drivers need this.
2058      */
2059     mtx_lock(&Giant);
2060     slp_state = ACPI_SS_NONE;
2061     switch (state) {
2062     case ACPI_STATE_S1:
2063     case ACPI_STATE_S2:
2064     case ACPI_STATE_S3:
2065     case ACPI_STATE_S4:
2066 	status = AcpiGetSleepTypeData(state, &TypeA, &TypeB);
2067 	if (status == AE_NOT_FOUND) {
2068 	    device_printf(sc->acpi_dev,
2069 			  "Sleep state S%d not supported by BIOS\n", state);
2070 	    break;
2071 	} else if (ACPI_FAILURE(status)) {
2072 	    device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n",
2073 			  AcpiFormatException(status));
2074 	    break;
2075 	}
2076 
2077 	sc->acpi_sstate = state;
2078 
2079 	/* Enable any GPEs as appropriate and requested by the user. */
2080 	acpi_wake_prep_walk(state);
2081 	slp_state = ACPI_SS_GPE_SET;
2082 
2083 	/*
2084 	 * Inform all devices that we are going to sleep.  If at least one
2085 	 * device fails, DEVICE_SUSPEND() automatically resumes the tree.
2086 	 *
2087 	 * XXX Note that a better two-pass approach with a 'veto' pass
2088 	 * followed by a "real thing" pass would be better, but the current
2089 	 * bus interface does not provide for this.
2090 	 */
2091 	if (DEVICE_SUSPEND(root_bus) != 0) {
2092 	    device_printf(sc->acpi_dev, "device_suspend failed\n");
2093 	    break;
2094 	}
2095 	slp_state = ACPI_SS_DEV_SUSPEND;
2096 
2097 	status = AcpiEnterSleepStatePrep(state);
2098 	if (ACPI_FAILURE(status)) {
2099 	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
2100 			  AcpiFormatException(status));
2101 	    break;
2102 	}
2103 	slp_state = ACPI_SS_SLP_PREP;
2104 
2105 	if (sc->acpi_sleep_delay > 0)
2106 	    DELAY(sc->acpi_sleep_delay * 1000000);
2107 
2108 	if (state != ACPI_STATE_S1) {
2109 	    acpi_sleep_machdep(sc, state);
2110 
2111 	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
2112 	    if (state == ACPI_STATE_S4)
2113 		AcpiEnable();
2114 	} else {
2115 	    ACPI_DISABLE_IRQS();
2116 	    status = AcpiEnterSleepState(state);
2117 	    if (ACPI_FAILURE(status)) {
2118 		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
2119 			      AcpiFormatException(status));
2120 		break;
2121 	    }
2122 	}
2123 	slp_state = ACPI_SS_SLEPT;
2124 	break;
2125     case ACPI_STATE_S5:
2126 	/*
2127 	 * Shut down cleanly and power off.  This will call us back through the
2128 	 * shutdown handlers.
2129 	 */
2130 	shutdown_nice(RB_POWEROFF);
2131 	break;
2132     case ACPI_STATE_S0:
2133     default:
2134 	status = AE_BAD_PARAMETER;
2135 	break;
2136     }
2137 
2138     /*
2139      * Back out state according to how far along we got in the suspend
2140      * process.  This handles both the error and success cases.
2141      */
2142     if (slp_state >= ACPI_SS_GPE_SET) {
2143 	acpi_wake_prep_walk(state);
2144 	sc->acpi_sstate = ACPI_STATE_S0;
2145     }
2146     if (slp_state >= ACPI_SS_SLP_PREP)
2147 	AcpiLeaveSleepState(state);
2148     if (slp_state >= ACPI_SS_DEV_SUSPEND)
2149 	DEVICE_RESUME(root_bus);
2150     if (slp_state >= ACPI_SS_SLEPT)
2151 	acpi_enable_fixed_events(sc);
2152 
2153     /* Allow another sleep request after a while. */
2154     if (state != ACPI_STATE_S5)
2155 	timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
2156 
2157     mtx_unlock(&Giant);
2158     return_ACPI_STATUS (status);
2159 }
2160 
2161 /* Initialize a device's wake GPE. */
2162 int
2163 acpi_wake_init(device_t dev, int type)
2164 {
2165     struct acpi_prw_data prw;
2166 
2167     /* Evaluate _PRW to find the GPE. */
2168     if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
2169 	return (ENXIO);
2170 
2171     /* Set the requested type for the GPE (runtime, wake, or both). */
2172     if (ACPI_FAILURE(AcpiSetGpeType(prw.gpe_handle, prw.gpe_bit, type))) {
2173 	device_printf(dev, "set GPE type failed\n");
2174 	return (ENXIO);
2175     }
2176 
2177     return (0);
2178 }
2179 
2180 /* Enable or disable the device's wake GPE. */
2181 int
2182 acpi_wake_set_enable(device_t dev, int enable)
2183 {
2184     struct acpi_prw_data prw;
2185     ACPI_HANDLE handle;
2186     ACPI_STATUS status;
2187     int flags;
2188 
2189     /* Make sure the device supports waking the system and get the GPE. */
2190     handle = acpi_get_handle(dev);
2191     if (acpi_parse_prw(handle, &prw) != 0)
2192 	return (ENXIO);
2193 
2194     flags = acpi_get_flags(dev);
2195     if (enable) {
2196 	status = AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2197 	if (ACPI_FAILURE(status)) {
2198 	    device_printf(dev, "enable wake failed\n");
2199 	    return (ENXIO);
2200 	}
2201 	acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
2202     } else {
2203 	status = AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2204 	if (ACPI_FAILURE(status)) {
2205 	    device_printf(dev, "disable wake failed\n");
2206 	    return (ENXIO);
2207 	}
2208 	acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
2209     }
2210 
2211     return (0);
2212 }
2213 
2214 static int
2215 acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate)
2216 {
2217     struct acpi_prw_data prw;
2218     device_t dev;
2219 
2220     /* Check that this is a wake-capable device and get its GPE. */
2221     if (acpi_parse_prw(handle, &prw) != 0)
2222 	return (ENXIO);
2223     dev = acpi_get_device(handle);
2224 
2225     /*
2226      * The destination sleep state must be less than (i.e., higher power)
2227      * or equal to the value specified by _PRW.  If this GPE cannot be
2228      * enabled for the next sleep state, then disable it.  If it can and
2229      * the user requested it be enabled, turn on any required power resources
2230      * and set _PSW.
2231      */
2232     if (sstate > prw.lowest_wake) {
2233 	AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2234 	if (bootverbose)
2235 	    device_printf(dev, "wake_prep disabled wake for %s (S%d)\n",
2236 		acpi_name(handle), sstate);
2237     } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
2238 	acpi_pwr_wake_enable(handle, 1);
2239 	acpi_SetInteger(handle, "_PSW", 1);
2240 	if (bootverbose)
2241 	    device_printf(dev, "wake_prep enabled for %s (S%d)\n",
2242 		acpi_name(handle), sstate);
2243     }
2244 
2245     return (0);
2246 }
2247 
2248 static int
2249 acpi_wake_run_prep(ACPI_HANDLE handle, int sstate)
2250 {
2251     struct acpi_prw_data prw;
2252     device_t dev;
2253 
2254     /*
2255      * Check that this is a wake-capable device and get its GPE.  Return
2256      * now if the user didn't enable this device for wake.
2257      */
2258     if (acpi_parse_prw(handle, &prw) != 0)
2259 	return (ENXIO);
2260     dev = acpi_get_device(handle);
2261     if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
2262 	return (0);
2263 
2264     /*
2265      * If this GPE couldn't be enabled for the previous sleep state, it was
2266      * disabled before going to sleep so re-enable it.  If it was enabled,
2267      * clear _PSW and turn off any power resources it used.
2268      */
2269     if (sstate > prw.lowest_wake) {
2270 	AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2271 	if (bootverbose)
2272 	    device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
2273     } else {
2274 	acpi_SetInteger(handle, "_PSW", 0);
2275 	acpi_pwr_wake_enable(handle, 0);
2276 	if (bootverbose)
2277 	    device_printf(dev, "run_prep cleaned up for %s\n",
2278 		acpi_name(handle));
2279     }
2280 
2281     return (0);
2282 }
2283 
2284 static ACPI_STATUS
2285 acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2286 {
2287     int sstate;
2288 
2289     /* If suspending, run the sleep prep function, otherwise wake. */
2290     sstate = *(int *)context;
2291     if (AcpiGbl_SystemAwakeAndRunning)
2292 	acpi_wake_sleep_prep(handle, sstate);
2293     else
2294 	acpi_wake_run_prep(handle, sstate);
2295     return (AE_OK);
2296 }
2297 
2298 /* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
2299 static int
2300 acpi_wake_prep_walk(int sstate)
2301 {
2302     ACPI_HANDLE sb_handle;
2303 
2304     if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2305 	AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
2306 	    acpi_wake_prep, &sstate, NULL);
2307     return (0);
2308 }
2309 
2310 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
2311 static int
2312 acpi_wake_sysctl_walk(device_t dev)
2313 {
2314     int error, i, numdevs;
2315     device_t *devlist;
2316     device_t child;
2317     ACPI_STATUS status;
2318 
2319     error = device_get_children(dev, &devlist, &numdevs);
2320     if (error != 0 || numdevs == 0)
2321 	return (error);
2322     for (i = 0; i < numdevs; i++) {
2323 	child = devlist[i];
2324 	acpi_wake_sysctl_walk(child);
2325 	if (!device_is_attached(child))
2326 	    continue;
2327 	status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
2328 	if (ACPI_SUCCESS(status)) {
2329 	    SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
2330 		SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
2331 		"wake", CTLTYPE_INT | CTLFLAG_RW, child, 0,
2332 		acpi_wake_set_sysctl, "I", "Device set to wake the system");
2333 	}
2334     }
2335     free(devlist, M_TEMP);
2336 
2337     return (0);
2338 }
2339 
2340 /* Enable or disable wake from userland. */
2341 static int
2342 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
2343 {
2344     int enable, error;
2345     device_t dev;
2346 
2347     dev = (device_t)arg1;
2348     enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
2349 
2350     error = sysctl_handle_int(oidp, &enable, 0, req);
2351     if (error != 0 || req->newptr == NULL)
2352 	return (error);
2353     if (enable != 0 && enable != 1)
2354 	return (EINVAL);
2355 
2356     return (acpi_wake_set_enable(dev, enable));
2357 }
2358 
2359 /* Parse a device's _PRW into a structure. */
2360 int
2361 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
2362 {
2363     ACPI_STATUS			status;
2364     ACPI_BUFFER			prw_buffer;
2365     ACPI_OBJECT			*res, *res2;
2366     int				error, i, power_count;
2367 
2368     if (h == NULL || prw == NULL)
2369 	return (EINVAL);
2370 
2371     /*
2372      * The _PRW object (7.2.9) is only required for devices that have the
2373      * ability to wake the system from a sleeping state.
2374      */
2375     error = EINVAL;
2376     prw_buffer.Pointer = NULL;
2377     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
2378     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
2379     if (ACPI_FAILURE(status))
2380 	return (ENOENT);
2381     res = (ACPI_OBJECT *)prw_buffer.Pointer;
2382     if (res == NULL)
2383 	return (ENOENT);
2384     if (!ACPI_PKG_VALID(res, 2))
2385 	goto out;
2386 
2387     /*
2388      * Element 1 of the _PRW object:
2389      * The lowest power system sleeping state that can be entered while still
2390      * providing wake functionality.  The sleeping state being entered must
2391      * be less than (i.e., higher power) or equal to this value.
2392      */
2393     if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
2394 	goto out;
2395 
2396     /*
2397      * Element 0 of the _PRW object:
2398      */
2399     switch (res->Package.Elements[0].Type) {
2400     case ACPI_TYPE_INTEGER:
2401 	/*
2402 	 * If the data type of this package element is numeric, then this
2403 	 * _PRW package element is the bit index in the GPEx_EN, in the
2404 	 * GPE blocks described in the FADT, of the enable bit that is
2405 	 * enabled for the wake event.
2406 	 */
2407 	prw->gpe_handle = NULL;
2408 	prw->gpe_bit = res->Package.Elements[0].Integer.Value;
2409 	error = 0;
2410 	break;
2411     case ACPI_TYPE_PACKAGE:
2412 	/*
2413 	 * If the data type of this package element is a package, then this
2414 	 * _PRW package element is itself a package containing two
2415 	 * elements.  The first is an object reference to the GPE Block
2416 	 * device that contains the GPE that will be triggered by the wake
2417 	 * event.  The second element is numeric and it contains the bit
2418 	 * index in the GPEx_EN, in the GPE Block referenced by the
2419 	 * first element in the package, of the enable bit that is enabled for
2420 	 * the wake event.
2421 	 *
2422 	 * For example, if this field is a package then it is of the form:
2423 	 * Package() {\_SB.PCI0.ISA.GPE, 2}
2424 	 */
2425 	res2 = &res->Package.Elements[0];
2426 	if (!ACPI_PKG_VALID(res2, 2))
2427 	    goto out;
2428 	prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
2429 	if (prw->gpe_handle == NULL)
2430 	    goto out;
2431 	if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
2432 	    goto out;
2433 	error = 0;
2434 	break;
2435     default:
2436 	goto out;
2437     }
2438 
2439     /* Elements 2 to N of the _PRW object are power resources. */
2440     power_count = res->Package.Count - 2;
2441     if (power_count > ACPI_PRW_MAX_POWERRES) {
2442 	printf("ACPI device %s has too many power resources\n", acpi_name(h));
2443 	power_count = 0;
2444     }
2445     prw->power_res_count = power_count;
2446     for (i = 0; i < power_count; i++)
2447 	prw->power_res[i] = res->Package.Elements[i];
2448 
2449 out:
2450     if (prw_buffer.Pointer != NULL)
2451 	AcpiOsFree(prw_buffer.Pointer);
2452     return (error);
2453 }
2454 
2455 /*
2456  * ACPI Event Handlers
2457  */
2458 
2459 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
2460 
2461 static void
2462 acpi_system_eventhandler_sleep(void *arg, int state)
2463 {
2464 
2465     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2466 
2467     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
2468 	acpi_SetSleepState((struct acpi_softc *)arg, state);
2469 
2470     return_VOID;
2471 }
2472 
2473 static void
2474 acpi_system_eventhandler_wakeup(void *arg, int state)
2475 {
2476 
2477     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2478 
2479     /* Currently, nothing to do for wakeup. */
2480 
2481     return_VOID;
2482 }
2483 
2484 /*
2485  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
2486  */
2487 UINT32
2488 acpi_event_power_button_sleep(void *context)
2489 {
2490     struct acpi_softc	*sc = (struct acpi_softc *)context;
2491 
2492     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2493 
2494     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
2495 
2496     return_VALUE (ACPI_INTERRUPT_HANDLED);
2497 }
2498 
2499 UINT32
2500 acpi_event_power_button_wake(void *context)
2501 {
2502     struct acpi_softc	*sc = (struct acpi_softc *)context;
2503 
2504     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2505 
2506     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
2507 
2508     return_VALUE (ACPI_INTERRUPT_HANDLED);
2509 }
2510 
2511 UINT32
2512 acpi_event_sleep_button_sleep(void *context)
2513 {
2514     struct acpi_softc	*sc = (struct acpi_softc *)context;
2515 
2516     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2517 
2518     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
2519 
2520     return_VALUE (ACPI_INTERRUPT_HANDLED);
2521 }
2522 
2523 UINT32
2524 acpi_event_sleep_button_wake(void *context)
2525 {
2526     struct acpi_softc	*sc = (struct acpi_softc *)context;
2527 
2528     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2529 
2530     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
2531 
2532     return_VALUE (ACPI_INTERRUPT_HANDLED);
2533 }
2534 
2535 /*
2536  * XXX This static buffer is suboptimal.  There is no locking so only
2537  * use this for single-threaded callers.
2538  */
2539 char *
2540 acpi_name(ACPI_HANDLE handle)
2541 {
2542     ACPI_BUFFER buf;
2543     static char data[256];
2544 
2545     buf.Length = sizeof(data);
2546     buf.Pointer = data;
2547 
2548     if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
2549 	return (data);
2550     return ("(unknown)");
2551 }
2552 
2553 /*
2554  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
2555  * parts of the namespace.
2556  */
2557 int
2558 acpi_avoid(ACPI_HANDLE handle)
2559 {
2560     char	*cp, *env, *np;
2561     int		len;
2562 
2563     np = acpi_name(handle);
2564     if (*np == '\\')
2565 	np++;
2566     if ((env = getenv("debug.acpi.avoid")) == NULL)
2567 	return (0);
2568 
2569     /* Scan the avoid list checking for a match */
2570     cp = env;
2571     for (;;) {
2572 	while (*cp != 0 && isspace(*cp))
2573 	    cp++;
2574 	if (*cp == 0)
2575 	    break;
2576 	len = 0;
2577 	while (cp[len] != 0 && !isspace(cp[len]))
2578 	    len++;
2579 	if (!strncmp(cp, np, len)) {
2580 	    freeenv(env);
2581 	    return(1);
2582 	}
2583 	cp += len;
2584     }
2585     freeenv(env);
2586 
2587     return (0);
2588 }
2589 
2590 /*
2591  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
2592  */
2593 int
2594 acpi_disabled(char *subsys)
2595 {
2596     char	*cp, *env;
2597     int		len;
2598 
2599     if ((env = getenv("debug.acpi.disabled")) == NULL)
2600 	return (0);
2601     if (strcmp(env, "all") == 0) {
2602 	freeenv(env);
2603 	return (1);
2604     }
2605 
2606     /* Scan the disable list, checking for a match. */
2607     cp = env;
2608     for (;;) {
2609 	while (*cp != '\0' && isspace(*cp))
2610 	    cp++;
2611 	if (*cp == '\0')
2612 	    break;
2613 	len = 0;
2614 	while (cp[len] != '\0' && !isspace(cp[len]))
2615 	    len++;
2616 	if (strncmp(cp, subsys, len) == 0) {
2617 	    freeenv(env);
2618 	    return (1);
2619 	}
2620 	cp += len;
2621     }
2622     freeenv(env);
2623 
2624     return (0);
2625 }
2626 
2627 /*
2628  * Control interface.
2629  *
2630  * We multiplex ioctls for all participating ACPI devices here.  Individual
2631  * drivers wanting to be accessible via /dev/acpi should use the
2632  * register/deregister interface to make their handlers visible.
2633  */
2634 struct acpi_ioctl_hook
2635 {
2636     TAILQ_ENTRY(acpi_ioctl_hook) link;
2637     u_long			 cmd;
2638     acpi_ioctl_fn		 fn;
2639     void			 *arg;
2640 };
2641 
2642 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
2643 static int				acpi_ioctl_hooks_initted;
2644 
2645 int
2646 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
2647 {
2648     struct acpi_ioctl_hook	*hp;
2649 
2650     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
2651 	return (ENOMEM);
2652     hp->cmd = cmd;
2653     hp->fn = fn;
2654     hp->arg = arg;
2655 
2656     ACPI_LOCK(acpi);
2657     if (acpi_ioctl_hooks_initted == 0) {
2658 	TAILQ_INIT(&acpi_ioctl_hooks);
2659 	acpi_ioctl_hooks_initted = 1;
2660     }
2661     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
2662     ACPI_UNLOCK(acpi);
2663 
2664     return (0);
2665 }
2666 
2667 void
2668 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
2669 {
2670     struct acpi_ioctl_hook	*hp;
2671 
2672     ACPI_LOCK(acpi);
2673     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
2674 	if (hp->cmd == cmd && hp->fn == fn)
2675 	    break;
2676 
2677     if (hp != NULL) {
2678 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
2679 	free(hp, M_ACPIDEV);
2680     }
2681     ACPI_UNLOCK(acpi);
2682 }
2683 
2684 static int
2685 acpiopen(struct cdev *dev, int flag, int fmt, d_thread_t *td)
2686 {
2687     return (0);
2688 }
2689 
2690 static int
2691 acpiclose(struct cdev *dev, int flag, int fmt, d_thread_t *td)
2692 {
2693     return (0);
2694 }
2695 
2696 static int
2697 acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
2698 {
2699     struct acpi_softc		*sc;
2700     struct acpi_ioctl_hook	*hp;
2701     int				error, state;
2702 
2703     error = 0;
2704     hp = NULL;
2705     sc = dev->si_drv1;
2706 
2707     /*
2708      * Scan the list of registered ioctls, looking for handlers.
2709      */
2710     ACPI_LOCK(acpi);
2711     if (acpi_ioctl_hooks_initted)
2712 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
2713 	    if (hp->cmd == cmd)
2714 		break;
2715 	}
2716     ACPI_UNLOCK(acpi);
2717     if (hp)
2718 	return (hp->fn(cmd, addr, hp->arg));
2719 
2720     /*
2721      * Core ioctls are not permitted for non-writable user.
2722      * Currently, other ioctls just fetch information.
2723      * Not changing system behavior.
2724      */
2725     if ((flag & FWRITE) == 0)
2726 	return (EPERM);
2727 
2728     /* Core system ioctls. */
2729     switch (cmd) {
2730     case ACPIIO_SETSLPSTATE:
2731 	error = EINVAL;
2732 	state = *(int *)addr;
2733 	if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
2734 	    if (ACPI_SUCCESS(acpi_SetSleepState(sc, state)))
2735 		error = 0;
2736 	break;
2737     default:
2738 	error = ENXIO;
2739 	break;
2740     }
2741 
2742     return (error);
2743 }
2744 
2745 static int
2746 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2747 {
2748     int error;
2749     struct sbuf sb;
2750     UINT8 state, TypeA, TypeB;
2751 
2752     sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
2753     for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX + 1; state++)
2754 	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB)))
2755 	    sbuf_printf(&sb, "S%d ", state);
2756     sbuf_trim(&sb);
2757     sbuf_finish(&sb);
2758     error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
2759     sbuf_delete(&sb);
2760     return (error);
2761 }
2762 
2763 static int
2764 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2765 {
2766     char sleep_state[10];
2767     int error;
2768     u_int new_state, old_state;
2769 
2770     old_state = *(u_int *)oidp->oid_arg1;
2771     if (old_state > ACPI_S_STATES_MAX + 1)
2772 	strlcpy(sleep_state, "unknown", sizeof(sleep_state));
2773     else
2774 	strlcpy(sleep_state, sleep_state_names[old_state], sizeof(sleep_state));
2775     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
2776     if (error == 0 && req->newptr != NULL) {
2777 	new_state = ACPI_STATE_S0;
2778 	for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++)
2779 	    if (strcmp(sleep_state, sleep_state_names[new_state]) == 0)
2780 		break;
2781 	if (new_state <= ACPI_S_STATES_MAX + 1) {
2782 	    if (new_state != old_state)
2783 		*(u_int *)oidp->oid_arg1 = new_state;
2784 	} else
2785 	    error = EINVAL;
2786     }
2787 
2788     return (error);
2789 }
2790 
2791 /* Inform devctl(4) when we receive a Notify. */
2792 void
2793 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
2794 {
2795     char		notify_buf[16];
2796     ACPI_BUFFER		handle_buf;
2797     ACPI_STATUS		status;
2798 
2799     if (subsystem == NULL)
2800 	return;
2801 
2802     handle_buf.Pointer = NULL;
2803     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
2804     status = AcpiNsHandleToPathname(h, &handle_buf);
2805     if (ACPI_FAILURE(status))
2806 	return;
2807     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
2808     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
2809     AcpiOsFree(handle_buf.Pointer);
2810 }
2811 
2812 #ifdef ACPI_DEBUG
2813 /*
2814  * Support for parsing debug options from the kernel environment.
2815  *
2816  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
2817  * by specifying the names of the bits in the debug.acpi.layer and
2818  * debug.acpi.level environment variables.  Bits may be unset by
2819  * prefixing the bit name with !.
2820  */
2821 struct debugtag
2822 {
2823     char	*name;
2824     UINT32	value;
2825 };
2826 
2827 static struct debugtag	dbg_layer[] = {
2828     {"ACPI_UTILITIES",		ACPI_UTILITIES},
2829     {"ACPI_HARDWARE",		ACPI_HARDWARE},
2830     {"ACPI_EVENTS",		ACPI_EVENTS},
2831     {"ACPI_TABLES",		ACPI_TABLES},
2832     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
2833     {"ACPI_PARSER",		ACPI_PARSER},
2834     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
2835     {"ACPI_EXECUTER",		ACPI_EXECUTER},
2836     {"ACPI_RESOURCES",		ACPI_RESOURCES},
2837     {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
2838     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
2839     {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
2840     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
2841 
2842     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
2843     {"ACPI_BATTERY",		ACPI_BATTERY},
2844     {"ACPI_BUS",		ACPI_BUS},
2845     {"ACPI_BUTTON",		ACPI_BUTTON},
2846     {"ACPI_EC", 		ACPI_EC},
2847     {"ACPI_FAN",		ACPI_FAN},
2848     {"ACPI_POWERRES",		ACPI_POWERRES},
2849     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
2850     {"ACPI_THERMAL",		ACPI_THERMAL},
2851     {"ACPI_TIMER",		ACPI_TIMER},
2852     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
2853     {NULL, 0}
2854 };
2855 
2856 static struct debugtag dbg_level[] = {
2857     {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
2858     {"ACPI_LV_WARN",		ACPI_LV_WARN},
2859     {"ACPI_LV_INIT",		ACPI_LV_INIT},
2860     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
2861     {"ACPI_LV_INFO",		ACPI_LV_INFO},
2862     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
2863 
2864     /* Trace verbosity level 1 [Standard Trace Level] */
2865     {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
2866     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
2867     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
2868     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
2869     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
2870     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
2871     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
2872     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
2873     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
2874     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
2875     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
2876     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
2877     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
2878     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
2879     {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
2880 
2881     /* Trace verbosity level 2 [Function tracing and memory allocation] */
2882     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
2883     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
2884     {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
2885     {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
2886     {"ACPI_LV_ALL",		ACPI_LV_ALL},
2887 
2888     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2889     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
2890     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
2891     {"ACPI_LV_IO",		ACPI_LV_IO},
2892     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
2893     {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
2894 
2895     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2896     {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
2897     {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
2898     {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
2899     {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
2900     {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
2901     {NULL, 0}
2902 };
2903 
2904 static void
2905 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2906 {
2907     char	*ep;
2908     int		i, l;
2909     int		set;
2910 
2911     while (*cp) {
2912 	if (isspace(*cp)) {
2913 	    cp++;
2914 	    continue;
2915 	}
2916 	ep = cp;
2917 	while (*ep && !isspace(*ep))
2918 	    ep++;
2919 	if (*cp == '!') {
2920 	    set = 0;
2921 	    cp++;
2922 	    if (cp == ep)
2923 		continue;
2924 	} else {
2925 	    set = 1;
2926 	}
2927 	l = ep - cp;
2928 	for (i = 0; tag[i].name != NULL; i++) {
2929 	    if (!strncmp(cp, tag[i].name, l)) {
2930 		if (set)
2931 		    *flag |= tag[i].value;
2932 		else
2933 		    *flag &= ~tag[i].value;
2934 	    }
2935 	}
2936 	cp = ep;
2937     }
2938 }
2939 
2940 static void
2941 acpi_set_debugging(void *junk)
2942 {
2943     char	*layer, *level;
2944 
2945     if (cold) {
2946 	AcpiDbgLayer = 0;
2947 	AcpiDbgLevel = 0;
2948     }
2949 
2950     layer = getenv("debug.acpi.layer");
2951     level = getenv("debug.acpi.level");
2952     if (layer == NULL && level == NULL)
2953 	return;
2954 
2955     printf("ACPI set debug");
2956     if (layer != NULL) {
2957 	if (strcmp("NONE", layer) != 0)
2958 	    printf(" layer '%s'", layer);
2959 	acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
2960 	freeenv(layer);
2961     }
2962     if (level != NULL) {
2963 	if (strcmp("NONE", level) != 0)
2964 	    printf(" level '%s'", level);
2965 	acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
2966 	freeenv(level);
2967     }
2968     printf("\n");
2969 }
2970 
2971 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
2972 	NULL);
2973 
2974 static int
2975 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
2976 {
2977     int		 error, *dbg;
2978     struct	 debugtag *tag;
2979     struct	 sbuf sb;
2980 
2981     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
2982 	return (ENOMEM);
2983     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
2984 	tag = &dbg_layer[0];
2985 	dbg = &AcpiDbgLayer;
2986     } else {
2987 	tag = &dbg_level[0];
2988 	dbg = &AcpiDbgLevel;
2989     }
2990 
2991     /* Get old values if this is a get request. */
2992     ACPI_SERIAL_BEGIN(acpi);
2993     if (*dbg == 0) {
2994 	sbuf_cpy(&sb, "NONE");
2995     } else if (req->newptr == NULL) {
2996 	for (; tag->name != NULL; tag++) {
2997 	    if ((*dbg & tag->value) == tag->value)
2998 		sbuf_printf(&sb, "%s ", tag->name);
2999 	}
3000     }
3001     sbuf_trim(&sb);
3002     sbuf_finish(&sb);
3003 
3004     /* Copy out the old values to the user. */
3005     error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
3006     sbuf_delete(&sb);
3007 
3008     /* If the user is setting a string, parse it. */
3009     if (error == 0 && req->newptr != NULL) {
3010 	*dbg = 0;
3011 	setenv((char *)oidp->oid_arg1, (char *)req->newptr);
3012 	acpi_set_debugging(NULL);
3013     }
3014     ACPI_SERIAL_END(acpi);
3015 
3016     return (error);
3017 }
3018 
3019 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
3020 	    "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
3021 SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
3022 	    "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
3023 #endif /* ACPI_DEBUG */
3024 
3025 static int
3026 acpi_pm_func(u_long cmd, void *arg, ...)
3027 {
3028 	int	state, acpi_state;
3029 	int	error;
3030 	struct	acpi_softc *sc;
3031 	va_list	ap;
3032 
3033 	error = 0;
3034 	switch (cmd) {
3035 	case POWER_CMD_SUSPEND:
3036 		sc = (struct acpi_softc *)arg;
3037 		if (sc == NULL) {
3038 			error = EINVAL;
3039 			goto out;
3040 		}
3041 
3042 		va_start(ap, arg);
3043 		state = va_arg(ap, int);
3044 		va_end(ap);
3045 
3046 		switch (state) {
3047 		case POWER_SLEEP_STATE_STANDBY:
3048 			acpi_state = sc->acpi_standby_sx;
3049 			break;
3050 		case POWER_SLEEP_STATE_SUSPEND:
3051 			acpi_state = sc->acpi_suspend_sx;
3052 			break;
3053 		case POWER_SLEEP_STATE_HIBERNATE:
3054 			acpi_state = ACPI_STATE_S4;
3055 			break;
3056 		default:
3057 			error = EINVAL;
3058 			goto out;
3059 		}
3060 
3061 		acpi_SetSleepState(sc, acpi_state);
3062 		break;
3063 	default:
3064 		error = EINVAL;
3065 		goto out;
3066 	}
3067 
3068 out:
3069 	return (error);
3070 }
3071 
3072 static void
3073 acpi_pm_register(void *arg)
3074 {
3075     if (!cold || resource_disabled("acpi", 0))
3076 	return;
3077 
3078     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
3079 }
3080 
3081 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
3082