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