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