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