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