xref: /freebsd/sys/dev/acpica/acpi.c (revision 10f0bcab61ef441cb5af32fb706688d8cbd55dc0)
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 int	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 and return non-zero if it
1524  * should be attached immediately.
1525  */
1526 static int
1527 acpi_probe_order(ACPI_HANDLE handle, int *order)
1528 {
1529     ACPI_OBJECT_TYPE type;
1530     u_int addr;
1531 
1532     /*
1533      * 1. I/O port and memory system resource holders
1534      * 2. Embedded controllers (to handle early accesses)
1535      * 3. PCI Link Devices
1536      * 11 - 266. Host-PCI bridges sorted by _ADR
1537      * 280. CPUs
1538      */
1539     AcpiGetType(handle, &type);
1540     if (acpi_MatchHid(handle, "PNP0C01") || acpi_MatchHid(handle, "PNP0C02"))
1541 	*order = 1;
1542     else if (acpi_MatchHid(handle, "PNP0C09"))
1543 	*order = 2;
1544     else if (acpi_MatchHid(handle, "PNP0C0F"))
1545 	*order = 3;
1546     else if (acpi_MatchHid(handle, "PNP0A03")) {
1547 	if (ACPI_SUCCESS(acpi_GetInteger(handle, "_ADR", &addr)))
1548 	    *order = 11 + ACPI_ADR_PCI_SLOT(addr) * (PCI_FUNCMAX + 1) +
1549 	       ACPI_ADR_PCI_FUNC(addr);
1550 	else
1551 	    *order = 11;
1552     } else if (type == ACPI_TYPE_PROCESSOR)
1553 	*order = 280;
1554     return (0);
1555 }
1556 
1557 /*
1558  * Evaluate a child device and determine whether we might attach a device to
1559  * it.
1560  */
1561 static ACPI_STATUS
1562 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
1563 {
1564     ACPI_OBJECT_TYPE type;
1565     ACPI_HANDLE h;
1566     device_t bus, child;
1567     int order;
1568     char *handle_str, **search;
1569     static char *scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI_", "\\_SB_", NULL};
1570 
1571     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1572 
1573     /* Skip this device if we think we'll have trouble with it. */
1574     if (acpi_avoid(handle))
1575 	return_ACPI_STATUS (AE_OK);
1576 
1577     bus = (device_t)context;
1578     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
1579 	switch (type) {
1580 	case ACPI_TYPE_DEVICE:
1581 	case ACPI_TYPE_PROCESSOR:
1582 	case ACPI_TYPE_THERMAL:
1583 	case ACPI_TYPE_POWER:
1584 	    if (acpi_disabled("children"))
1585 		break;
1586 
1587 	    /*
1588 	     * Since we scan from \, be sure to skip system scope objects.
1589 	     * At least \_SB and \_TZ are detected as devices (ACPI-CA bug?)
1590 	     */
1591 	    handle_str = acpi_name(handle);
1592 	    for (search = scopes; *search != NULL; search++) {
1593 		if (strcmp(handle_str, *search) == 0)
1594 		    break;
1595 	    }
1596 	    if (*search != NULL)
1597 		break;
1598 
1599 	    /*
1600 	     * Create a placeholder device for this node.  Sort the
1601 	     * placeholder so that the probe/attach passes will run
1602 	     * breadth-first.  Orders less than ACPI_DEV_BASE_ORDER
1603 	     * are reserved for special objects (i.e., system
1604 	     * resources).  Orders between ACPI_DEV_BASE_ORDER and 300
1605 	     * are used for Host-PCI bridges (and effectively all
1606 	     * their children) and CPUs.  Larger values are used for
1607 	     * all other devices.
1608 	     */
1609 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
1610 	    order = level * 10 + 300;
1611 	    acpi_probe_order(handle, &order);
1612 	    child = BUS_ADD_CHILD(bus, order, NULL, -1);
1613 	    if (child == NULL)
1614 		break;
1615 
1616 	    /* Associate the handle with the device_t and vice versa. */
1617 	    acpi_set_handle(child, handle);
1618 	    AcpiAttachData(handle, acpi_fake_objhandler, child);
1619 
1620 	    /*
1621 	     * Check that the device is present.  If it's not present,
1622 	     * leave it disabled (so that we have a device_t attached to
1623 	     * the handle, but we don't probe it).
1624 	     *
1625 	     * XXX PCI link devices sometimes report "present" but not
1626 	     * "functional" (i.e. if disabled).  Go ahead and probe them
1627 	     * anyway since we may enable them later.
1628 	     */
1629 	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1630 		/* Never disable PCI link devices. */
1631 		if (acpi_MatchHid(handle, "PNP0C0F"))
1632 		    break;
1633 		/*
1634 		 * Docking stations should remain enabled since the system
1635 		 * may be undocked at boot.
1636 		 */
1637 		if (ACPI_SUCCESS(AcpiGetHandle(handle, "_DCK", &h)))
1638 		    break;
1639 
1640 		device_disable(child);
1641 		break;
1642 	    }
1643 
1644 	    /*
1645 	     * Get the device's resource settings and attach them.
1646 	     * Note that if the device has _PRS but no _CRS, we need
1647 	     * to decide when it's appropriate to try to configure the
1648 	     * device.  Ignore the return value here; it's OK for the
1649 	     * device not to have any resources.
1650 	     */
1651 	    acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
1652 	    break;
1653 	}
1654     }
1655 
1656     return_ACPI_STATUS (AE_OK);
1657 }
1658 
1659 /*
1660  * AcpiAttachData() requires an object handler but never uses it.  This is a
1661  * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
1662  */
1663 void
1664 acpi_fake_objhandler(ACPI_HANDLE h, UINT32 fn, void *data)
1665 {
1666 }
1667 
1668 static void
1669 acpi_shutdown_final(void *arg, int howto)
1670 {
1671     struct acpi_softc *sc;
1672     ACPI_STATUS status;
1673 
1674     /*
1675      * XXX Shutdown code should only run on the BSP (cpuid 0).
1676      * Some chipsets do not power off the system correctly if called from
1677      * an AP.
1678      */
1679     sc = arg;
1680     if ((howto & RB_POWEROFF) != 0) {
1681 	status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
1682 	if (ACPI_FAILURE(status)) {
1683 	    printf("AcpiEnterSleepStatePrep failed - %s\n",
1684 		   AcpiFormatException(status));
1685 	    return;
1686 	}
1687 	printf("Powering system off using ACPI\n");
1688 	ACPI_DISABLE_IRQS();
1689 	status = AcpiEnterSleepState(ACPI_STATE_S5);
1690 	if (ACPI_FAILURE(status)) {
1691 	    printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
1692 	} else {
1693 	    DELAY(1000000);
1694 	    printf("ACPI power-off failed - timeout\n");
1695 	}
1696     } else if ((howto & RB_HALT) == 0 &&
1697 	(AcpiGbl_FADT.Flags & ACPI_FADT_RESET_REGISTER) &&
1698 	sc->acpi_handle_reboot) {
1699 	/* Reboot using the reset register. */
1700 	status = AcpiHwLowLevelWrite(
1701 	    AcpiGbl_FADT.ResetRegister.BitWidth,
1702 	    AcpiGbl_FADT.ResetValue, &AcpiGbl_FADT.ResetRegister);
1703 	if (ACPI_FAILURE(status)) {
1704 	    printf("ACPI reset failed - %s\n", AcpiFormatException(status));
1705 	} else {
1706 	    DELAY(1000000);
1707 	    printf("ACPI reset failed - timeout\n");
1708 	}
1709     } else if (sc->acpi_do_disable && panicstr == NULL) {
1710 	/*
1711 	 * Only disable ACPI if the user requested.  On some systems, writing
1712 	 * the disable value to SMI_CMD hangs the system.
1713 	 */
1714 	printf("Shutting down ACPI\n");
1715 	AcpiTerminate();
1716     }
1717 }
1718 
1719 static void
1720 acpi_enable_fixed_events(struct acpi_softc *sc)
1721 {
1722     static int	first_time = 1;
1723 
1724     /* Enable and clear fixed events and install handlers. */
1725     if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
1726 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
1727 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
1728 				     acpi_event_power_button_sleep, sc);
1729 	if (first_time)
1730 	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
1731     }
1732     if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
1733 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
1734 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
1735 				     acpi_event_sleep_button_sleep, sc);
1736 	if (first_time)
1737 	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
1738     }
1739 
1740     first_time = 0;
1741 }
1742 
1743 /*
1744  * Returns true if the device is actually present and should
1745  * be attached to.  This requires the present, enabled, UI-visible
1746  * and diagnostics-passed bits to be set.
1747  */
1748 BOOLEAN
1749 acpi_DeviceIsPresent(device_t dev)
1750 {
1751     ACPI_DEVICE_INFO	*devinfo;
1752     ACPI_HANDLE		h;
1753     ACPI_BUFFER		buf;
1754     ACPI_STATUS		error;
1755     int			ret;
1756 
1757     ret = FALSE;
1758     if ((h = acpi_get_handle(dev)) == NULL)
1759 	return (FALSE);
1760     buf.Pointer = NULL;
1761     buf.Length = ACPI_ALLOCATE_BUFFER;
1762     error = AcpiGetObjectInfo(h, &buf);
1763     if (ACPI_FAILURE(error))
1764 	return (FALSE);
1765     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1766 
1767     /* If no _STA method, must be present */
1768     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1769 	ret = TRUE;
1770 
1771     /* Return true for 'present' and 'functioning' */
1772     if (ACPI_DEVICE_PRESENT(devinfo->CurrentStatus))
1773 	ret = TRUE;
1774 
1775     AcpiOsFree(buf.Pointer);
1776     return (ret);
1777 }
1778 
1779 /*
1780  * Returns true if the battery is actually present and inserted.
1781  */
1782 BOOLEAN
1783 acpi_BatteryIsPresent(device_t dev)
1784 {
1785     ACPI_DEVICE_INFO	*devinfo;
1786     ACPI_HANDLE		h;
1787     ACPI_BUFFER		buf;
1788     ACPI_STATUS		error;
1789     int			ret;
1790 
1791     ret = FALSE;
1792     if ((h = acpi_get_handle(dev)) == NULL)
1793 	return (FALSE);
1794     buf.Pointer = NULL;
1795     buf.Length = ACPI_ALLOCATE_BUFFER;
1796     error = AcpiGetObjectInfo(h, &buf);
1797     if (ACPI_FAILURE(error))
1798 	return (FALSE);
1799     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1800 
1801     /* If no _STA method, must be present */
1802     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1803 	ret = TRUE;
1804 
1805     /* Return true for 'present', 'battery present', and 'functioning' */
1806     if (ACPI_BATTERY_PRESENT(devinfo->CurrentStatus))
1807 	ret = TRUE;
1808 
1809     AcpiOsFree(buf.Pointer);
1810     return (ret);
1811 }
1812 
1813 /*
1814  * Match a HID string against a handle
1815  */
1816 static BOOLEAN
1817 acpi_MatchHid(ACPI_HANDLE h, const char *hid)
1818 {
1819     ACPI_DEVICE_INFO	*devinfo;
1820     ACPI_BUFFER		buf;
1821     ACPI_STATUS		error;
1822     int			ret, i;
1823 
1824     ret = FALSE;
1825     if (hid == NULL || h == NULL)
1826 	return (ret);
1827     buf.Pointer = NULL;
1828     buf.Length = ACPI_ALLOCATE_BUFFER;
1829     error = AcpiGetObjectInfo(h, &buf);
1830     if (ACPI_FAILURE(error))
1831 	return (ret);
1832     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1833 
1834     if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
1835 	strcmp(hid, devinfo->HardwareId.Value) == 0)
1836 	    ret = TRUE;
1837     else if ((devinfo->Valid & ACPI_VALID_CID) != 0) {
1838 	for (i = 0; i < devinfo->CompatibilityId.Count; i++) {
1839 	    if (strcmp(hid, devinfo->CompatibilityId.Id[i].Value) == 0) {
1840 		ret = TRUE;
1841 		break;
1842 	    }
1843 	}
1844     }
1845 
1846     AcpiOsFree(buf.Pointer);
1847     return (ret);
1848 }
1849 
1850 /*
1851  * Return the handle of a named object within our scope, ie. that of (parent)
1852  * or one if its parents.
1853  */
1854 ACPI_STATUS
1855 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1856 {
1857     ACPI_HANDLE		r;
1858     ACPI_STATUS		status;
1859 
1860     /* Walk back up the tree to the root */
1861     for (;;) {
1862 	status = AcpiGetHandle(parent, path, &r);
1863 	if (ACPI_SUCCESS(status)) {
1864 	    *result = r;
1865 	    return (AE_OK);
1866 	}
1867 	/* XXX Return error here? */
1868 	if (status != AE_NOT_FOUND)
1869 	    return (AE_OK);
1870 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1871 	    return (AE_NOT_FOUND);
1872 	parent = r;
1873     }
1874 }
1875 
1876 /* Find the difference between two PM tick counts. */
1877 uint32_t
1878 acpi_TimerDelta(uint32_t end, uint32_t start)
1879 {
1880     uint32_t delta;
1881 
1882     if (end >= start)
1883 	delta = end - start;
1884     else if (AcpiGbl_FADT.Flags & ACPI_FADT_32BIT_TIMER)
1885 	delta = ((0xFFFFFFFF - start) + end + 1);
1886     else
1887 	delta = ((0x00FFFFFF - start) + end + 1) & 0x00FFFFFF;
1888     return (delta);
1889 }
1890 
1891 /*
1892  * Allocate a buffer with a preset data size.
1893  */
1894 ACPI_BUFFER *
1895 acpi_AllocBuffer(int size)
1896 {
1897     ACPI_BUFFER	*buf;
1898 
1899     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1900 	return (NULL);
1901     buf->Length = size;
1902     buf->Pointer = (void *)(buf + 1);
1903     return (buf);
1904 }
1905 
1906 ACPI_STATUS
1907 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
1908 {
1909     ACPI_OBJECT arg1;
1910     ACPI_OBJECT_LIST args;
1911 
1912     arg1.Type = ACPI_TYPE_INTEGER;
1913     arg1.Integer.Value = number;
1914     args.Count = 1;
1915     args.Pointer = &arg1;
1916 
1917     return (AcpiEvaluateObject(handle, path, &args, NULL));
1918 }
1919 
1920 /*
1921  * Evaluate a path that should return an integer.
1922  */
1923 ACPI_STATUS
1924 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
1925 {
1926     ACPI_STATUS	status;
1927     ACPI_BUFFER	buf;
1928     ACPI_OBJECT	param;
1929 
1930     if (handle == NULL)
1931 	handle = ACPI_ROOT_OBJECT;
1932 
1933     /*
1934      * Assume that what we've been pointed at is an Integer object, or
1935      * a method that will return an Integer.
1936      */
1937     buf.Pointer = &param;
1938     buf.Length = sizeof(param);
1939     status = AcpiEvaluateObject(handle, path, NULL, &buf);
1940     if (ACPI_SUCCESS(status)) {
1941 	if (param.Type == ACPI_TYPE_INTEGER)
1942 	    *number = param.Integer.Value;
1943 	else
1944 	    status = AE_TYPE;
1945     }
1946 
1947     /*
1948      * In some applications, a method that's expected to return an Integer
1949      * may instead return a Buffer (probably to simplify some internal
1950      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1951      * convert it into an Integer as best we can.
1952      *
1953      * This is a hack.
1954      */
1955     if (status == AE_BUFFER_OVERFLOW) {
1956 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1957 	    status = AE_NO_MEMORY;
1958 	} else {
1959 	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1960 	    if (ACPI_SUCCESS(status))
1961 		status = acpi_ConvertBufferToInteger(&buf, number);
1962 	    AcpiOsFree(buf.Pointer);
1963 	}
1964     }
1965     return (status);
1966 }
1967 
1968 ACPI_STATUS
1969 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
1970 {
1971     ACPI_OBJECT	*p;
1972     UINT8	*val;
1973     int		i;
1974 
1975     p = (ACPI_OBJECT *)bufp->Pointer;
1976     if (p->Type == ACPI_TYPE_INTEGER) {
1977 	*number = p->Integer.Value;
1978 	return (AE_OK);
1979     }
1980     if (p->Type != ACPI_TYPE_BUFFER)
1981 	return (AE_TYPE);
1982     if (p->Buffer.Length > sizeof(int))
1983 	return (AE_BAD_DATA);
1984 
1985     *number = 0;
1986     val = p->Buffer.Pointer;
1987     for (i = 0; i < p->Buffer.Length; i++)
1988 	*number += val[i] << (i * 8);
1989     return (AE_OK);
1990 }
1991 
1992 /*
1993  * Iterate over the elements of an a package object, calling the supplied
1994  * function for each element.
1995  *
1996  * XXX possible enhancement might be to abort traversal on error.
1997  */
1998 ACPI_STATUS
1999 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
2000 	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
2001 {
2002     ACPI_OBJECT	*comp;
2003     int		i;
2004 
2005     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
2006 	return (AE_BAD_PARAMETER);
2007 
2008     /* Iterate over components */
2009     i = 0;
2010     comp = pkg->Package.Elements;
2011     for (; i < pkg->Package.Count; i++, comp++)
2012 	func(comp, arg);
2013 
2014     return (AE_OK);
2015 }
2016 
2017 /*
2018  * Find the (index)th resource object in a set.
2019  */
2020 ACPI_STATUS
2021 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
2022 {
2023     ACPI_RESOURCE	*rp;
2024     int			i;
2025 
2026     rp = (ACPI_RESOURCE *)buf->Pointer;
2027     i = index;
2028     while (i-- > 0) {
2029 	/* Range check */
2030 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2031 	    return (AE_BAD_PARAMETER);
2032 
2033 	/* Check for terminator */
2034 	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2035 	    return (AE_NOT_FOUND);
2036 	rp = ACPI_NEXT_RESOURCE(rp);
2037     }
2038     if (resp != NULL)
2039 	*resp = rp;
2040 
2041     return (AE_OK);
2042 }
2043 
2044 /*
2045  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
2046  *
2047  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
2048  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
2049  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
2050  * resources.
2051  */
2052 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
2053 
2054 ACPI_STATUS
2055 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
2056 {
2057     ACPI_RESOURCE	*rp;
2058     void		*newp;
2059 
2060     /* Initialise the buffer if necessary. */
2061     if (buf->Pointer == NULL) {
2062 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
2063 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
2064 	    return (AE_NO_MEMORY);
2065 	rp = (ACPI_RESOURCE *)buf->Pointer;
2066 	rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2067 	rp->Length = 0;
2068     }
2069     if (res == NULL)
2070 	return (AE_OK);
2071 
2072     /*
2073      * Scan the current buffer looking for the terminator.
2074      * This will either find the terminator or hit the end
2075      * of the buffer and return an error.
2076      */
2077     rp = (ACPI_RESOURCE *)buf->Pointer;
2078     for (;;) {
2079 	/* Range check, don't go outside the buffer */
2080 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2081 	    return (AE_BAD_PARAMETER);
2082 	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2083 	    break;
2084 	rp = ACPI_NEXT_RESOURCE(rp);
2085     }
2086 
2087     /*
2088      * Check the size of the buffer and expand if required.
2089      *
2090      * Required size is:
2091      *	size of existing resources before terminator +
2092      *	size of new resource and header +
2093      * 	size of terminator.
2094      *
2095      * Note that this loop should really only run once, unless
2096      * for some reason we are stuffing a *really* huge resource.
2097      */
2098     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
2099 	    res->Length + ACPI_RS_SIZE_NO_DATA +
2100 	    ACPI_RS_SIZE_MIN) >= buf->Length) {
2101 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
2102 	    return (AE_NO_MEMORY);
2103 	bcopy(buf->Pointer, newp, buf->Length);
2104 	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
2105 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
2106 	AcpiOsFree(buf->Pointer);
2107 	buf->Pointer = newp;
2108 	buf->Length += buf->Length;
2109     }
2110 
2111     /* Insert the new resource. */
2112     bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
2113 
2114     /* And add the terminator. */
2115     rp = ACPI_NEXT_RESOURCE(rp);
2116     rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2117     rp->Length = 0;
2118 
2119     return (AE_OK);
2120 }
2121 
2122 /*
2123  * Set interrupt model.
2124  */
2125 ACPI_STATUS
2126 acpi_SetIntrModel(int model)
2127 {
2128 
2129     return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
2130 }
2131 
2132 /*
2133  * DEPRECATED.  This interface has serious deficiencies and will be
2134  * removed.
2135  *
2136  * Immediately enter the sleep state.  In the old model, acpiconf(8) ran
2137  * rc.suspend and rc.resume so we don't have to notify devd(8) to do this.
2138  */
2139 ACPI_STATUS
2140 acpi_SetSleepState(struct acpi_softc *sc, int state)
2141 {
2142     static int once;
2143 
2144     if (!once) {
2145 	printf(
2146 "warning: acpi_SetSleepState() deprecated, need to update your software\n");
2147 	once = 1;
2148     }
2149     return (acpi_EnterSleepState(sc, state));
2150 }
2151 
2152 static void
2153 acpi_sleep_force(void *arg)
2154 {
2155     struct acpi_softc *sc;
2156 
2157     printf("acpi: suspend request timed out, forcing sleep now\n");
2158     sc = arg;
2159     if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
2160 	printf("acpi: force sleep state S%d failed\n", sc->acpi_next_sstate);
2161 }
2162 
2163 /*
2164  * Request that the system enter the given suspend state.  All /dev/apm
2165  * devices and devd(8) will be notified.  Userland then has a chance to
2166  * save state and acknowledge the request.  The system sleeps once all
2167  * acks are in.
2168  */
2169 int
2170 acpi_ReqSleepState(struct acpi_softc *sc, int state)
2171 {
2172     struct apm_clone_data *clone;
2173 
2174     if (state < ACPI_STATE_S1 || state > ACPI_STATE_S5)
2175 	return (EINVAL);
2176 
2177     /* S5 (soft-off) should be entered directly with no waiting. */
2178     if (state == ACPI_STATE_S5) {
2179 	if (ACPI_SUCCESS(acpi_EnterSleepState(sc, state)))
2180 	    return (0);
2181 	else
2182 	    return (ENXIO);
2183     }
2184 
2185 #if !defined(__i386__)
2186     /* This platform does not support acpi suspend/resume. */
2187     return (EOPNOTSUPP);
2188 #endif
2189 
2190     /* If a suspend request is already in progress, just return. */
2191     ACPI_LOCK(acpi);
2192     if (sc->acpi_next_sstate != 0) {
2193     	ACPI_UNLOCK(acpi);
2194 	return (0);
2195     }
2196 
2197     /* Record the pending state and notify all apm devices. */
2198     sc->acpi_next_sstate = state;
2199     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
2200 	clone->notify_status = APM_EV_NONE;
2201 	if ((clone->flags & ACPI_EVF_DEVD) == 0) {
2202 	    selwakeuppri(&clone->sel_read, PZERO);
2203 	    KNOTE_UNLOCKED(&clone->sel_read.si_note, 0);
2204 	}
2205     }
2206 
2207     /* If devd(8) is not running, immediately enter the sleep state. */
2208     if (devctl_process_running() == FALSE) {
2209 	ACPI_UNLOCK(acpi);
2210 	if (ACPI_SUCCESS(acpi_EnterSleepState(sc, sc->acpi_next_sstate))) {
2211 	    return (0);
2212 	} else {
2213 	    return (ENXIO);
2214 	}
2215     }
2216 
2217     /* Now notify devd(8) also. */
2218     acpi_UserNotify("Suspend", ACPI_ROOT_OBJECT, state);
2219 
2220     /*
2221      * Set a timeout to fire if userland doesn't ack the suspend request
2222      * in time.  This way we still eventually go to sleep if we were
2223      * overheating or running low on battery, even if userland is hung.
2224      * We cancel this timeout once all userland acks are in or the
2225      * suspend request is aborted.
2226      */
2227     callout_reset(&sc->susp_force_to, 10 * hz, acpi_sleep_force, sc);
2228     ACPI_UNLOCK(acpi);
2229     return (0);
2230 }
2231 
2232 /*
2233  * Acknowledge (or reject) a pending sleep state.  The caller has
2234  * prepared for suspend and is now ready for it to proceed.  If the
2235  * error argument is non-zero, it indicates suspend should be cancelled
2236  * and gives an errno value describing why.  Once all votes are in,
2237  * we suspend the system.
2238  */
2239 int
2240 acpi_AckSleepState(struct apm_clone_data *clone, int error)
2241 {
2242     struct acpi_softc *sc;
2243     int ret, sleeping;
2244 
2245 #if !defined(__i386__)
2246     /* This platform does not support acpi suspend/resume. */
2247     return (EOPNOTSUPP);
2248 #endif
2249 
2250     /* If no pending sleep state, return an error. */
2251     ACPI_LOCK(acpi);
2252     sc = clone->acpi_sc;
2253     if (sc->acpi_next_sstate == 0) {
2254     	ACPI_UNLOCK(acpi);
2255 	return (ENXIO);
2256     }
2257 
2258     /* Caller wants to abort suspend process. */
2259     if (error) {
2260 	sc->acpi_next_sstate = 0;
2261 	callout_stop(&sc->susp_force_to);
2262 	printf("acpi: listener on %s cancelled the pending suspend\n",
2263 	    devtoname(clone->cdev));
2264     	ACPI_UNLOCK(acpi);
2265 	return (0);
2266     }
2267 
2268     /*
2269      * Mark this device as acking the suspend request.  Then, walk through
2270      * all devices, seeing if they agree yet.  We only count devices that
2271      * are writable since read-only devices couldn't ack the request.
2272      */
2273     clone->notify_status = APM_EV_ACKED;
2274     sleeping = TRUE;
2275     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
2276 	if ((clone->flags & ACPI_EVF_WRITE) != 0 &&
2277 	    clone->notify_status != APM_EV_ACKED) {
2278 	    sleeping = FALSE;
2279 	    break;
2280 	}
2281     }
2282 
2283     /* If all devices have voted "yes", we will suspend now. */
2284     if (sleeping)
2285 	callout_stop(&sc->susp_force_to);
2286     ACPI_UNLOCK(acpi);
2287     ret = 0;
2288     if (sleeping) {
2289 	if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
2290 		ret = ENODEV;
2291     }
2292 
2293     return (ret);
2294 }
2295 
2296 static void
2297 acpi_sleep_enable(void *arg)
2298 {
2299 
2300     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
2301 }
2302 
2303 enum acpi_sleep_state {
2304     ACPI_SS_NONE,
2305     ACPI_SS_GPE_SET,
2306     ACPI_SS_DEV_SUSPEND,
2307     ACPI_SS_SLP_PREP,
2308     ACPI_SS_SLEPT,
2309 };
2310 
2311 /*
2312  * Enter the desired system sleep state.
2313  *
2314  * Currently we support S1-S5 but S4 is only S4BIOS
2315  */
2316 static ACPI_STATUS
2317 acpi_EnterSleepState(struct acpi_softc *sc, int state)
2318 {
2319     ACPI_STATUS	status;
2320     UINT8	TypeA;
2321     UINT8	TypeB;
2322     enum acpi_sleep_state slp_state;
2323 
2324     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2325 
2326     /* Re-entry once we're suspending is not allowed. */
2327     status = AE_OK;
2328     ACPI_LOCK(acpi);
2329     if (sc->acpi_sleep_disabled) {
2330 	ACPI_UNLOCK(acpi);
2331 	printf("acpi: suspend request ignored (not ready yet)\n");
2332 	return (AE_ERROR);
2333     }
2334     sc->acpi_sleep_disabled = 1;
2335     ACPI_UNLOCK(acpi);
2336 
2337     /*
2338      * Be sure to hold Giant across DEVICE_SUSPEND/RESUME since non-MPSAFE
2339      * drivers need this.
2340      */
2341     mtx_lock(&Giant);
2342     slp_state = ACPI_SS_NONE;
2343     switch (state) {
2344     case ACPI_STATE_S1:
2345     case ACPI_STATE_S2:
2346     case ACPI_STATE_S3:
2347     case ACPI_STATE_S4:
2348 	status = AcpiGetSleepTypeData(state, &TypeA, &TypeB);
2349 	if (status == AE_NOT_FOUND) {
2350 	    device_printf(sc->acpi_dev,
2351 			  "Sleep state S%d not supported by BIOS\n", state);
2352 	    break;
2353 	} else if (ACPI_FAILURE(status)) {
2354 	    device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n",
2355 			  AcpiFormatException(status));
2356 	    break;
2357 	}
2358 
2359 	sc->acpi_sstate = state;
2360 
2361 	/* Enable any GPEs as appropriate and requested by the user. */
2362 	acpi_wake_prep_walk(state);
2363 	slp_state = ACPI_SS_GPE_SET;
2364 
2365 	/*
2366 	 * Inform all devices that we are going to sleep.  If at least one
2367 	 * device fails, DEVICE_SUSPEND() automatically resumes the tree.
2368 	 *
2369 	 * XXX Note that a better two-pass approach with a 'veto' pass
2370 	 * followed by a "real thing" pass would be better, but the current
2371 	 * bus interface does not provide for this.
2372 	 */
2373 	if (DEVICE_SUSPEND(root_bus) != 0) {
2374 	    device_printf(sc->acpi_dev, "device_suspend failed\n");
2375 	    break;
2376 	}
2377 	slp_state = ACPI_SS_DEV_SUSPEND;
2378 
2379 	/* If testing device suspend only, back out of everything here. */
2380 	if (acpi_susp_bounce)
2381 	    break;
2382 
2383 	status = AcpiEnterSleepStatePrep(state);
2384 	if (ACPI_FAILURE(status)) {
2385 	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
2386 			  AcpiFormatException(status));
2387 	    break;
2388 	}
2389 	slp_state = ACPI_SS_SLP_PREP;
2390 
2391 	if (sc->acpi_sleep_delay > 0)
2392 	    DELAY(sc->acpi_sleep_delay * 1000000);
2393 
2394 	if (state != ACPI_STATE_S1) {
2395 	    acpi_sleep_machdep(sc, state);
2396 
2397 	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
2398 	    if (state == ACPI_STATE_S4)
2399 		AcpiEnable();
2400 	} else {
2401 	    ACPI_DISABLE_IRQS();
2402 	    status = AcpiEnterSleepState(state);
2403 	    if (ACPI_FAILURE(status)) {
2404 		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
2405 			      AcpiFormatException(status));
2406 		break;
2407 	    }
2408 	}
2409 	slp_state = ACPI_SS_SLEPT;
2410 	break;
2411     case ACPI_STATE_S5:
2412 	/*
2413 	 * Shut down cleanly and power off.  This will call us back through the
2414 	 * shutdown handlers.
2415 	 */
2416 	shutdown_nice(RB_POWEROFF);
2417 	break;
2418     case ACPI_STATE_S0:
2419     default:
2420 	status = AE_BAD_PARAMETER;
2421 	break;
2422     }
2423 
2424     /*
2425      * Back out state according to how far along we got in the suspend
2426      * process.  This handles both the error and success cases.
2427      */
2428     sc->acpi_next_sstate = 0;
2429     if (slp_state >= ACPI_SS_GPE_SET) {
2430 	acpi_wake_prep_walk(state);
2431 	sc->acpi_sstate = ACPI_STATE_S0;
2432     }
2433     if (slp_state >= ACPI_SS_SLP_PREP)
2434 	AcpiLeaveSleepState(state);
2435     if (slp_state >= ACPI_SS_DEV_SUSPEND)
2436 	DEVICE_RESUME(root_bus);
2437     if (slp_state >= ACPI_SS_SLEPT)
2438 	acpi_enable_fixed_events(sc);
2439 
2440     /* Allow another sleep request after a while. */
2441     if (state != ACPI_STATE_S5)
2442 	timeout(acpi_sleep_enable, sc, hz * ACPI_MINIMUM_AWAKETIME);
2443 
2444     /* Run /etc/rc.resume after we are back. */
2445     acpi_UserNotify("Resume", ACPI_ROOT_OBJECT, state);
2446 
2447     mtx_unlock(&Giant);
2448     return_ACPI_STATUS (status);
2449 }
2450 
2451 /* Initialize a device's wake GPE. */
2452 int
2453 acpi_wake_init(device_t dev, int type)
2454 {
2455     struct acpi_prw_data prw;
2456 
2457     /* Evaluate _PRW to find the GPE. */
2458     if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
2459 	return (ENXIO);
2460 
2461     /* Set the requested type for the GPE (runtime, wake, or both). */
2462     if (ACPI_FAILURE(AcpiSetGpeType(prw.gpe_handle, prw.gpe_bit, type))) {
2463 	device_printf(dev, "set GPE type failed\n");
2464 	return (ENXIO);
2465     }
2466 
2467     return (0);
2468 }
2469 
2470 /* Enable or disable the device's wake GPE. */
2471 int
2472 acpi_wake_set_enable(device_t dev, int enable)
2473 {
2474     struct acpi_prw_data prw;
2475     ACPI_STATUS status;
2476     int flags;
2477 
2478     /* Make sure the device supports waking the system and get the GPE. */
2479     if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
2480 	return (ENXIO);
2481 
2482     flags = acpi_get_flags(dev);
2483     if (enable) {
2484 	status = AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2485 	if (ACPI_FAILURE(status)) {
2486 	    device_printf(dev, "enable wake failed\n");
2487 	    return (ENXIO);
2488 	}
2489 	acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
2490     } else {
2491 	status = AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2492 	if (ACPI_FAILURE(status)) {
2493 	    device_printf(dev, "disable wake failed\n");
2494 	    return (ENXIO);
2495 	}
2496 	acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
2497     }
2498 
2499     return (0);
2500 }
2501 
2502 static int
2503 acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate)
2504 {
2505     struct acpi_prw_data prw;
2506     device_t dev;
2507 
2508     /* Check that this is a wake-capable device and get its GPE. */
2509     if (acpi_parse_prw(handle, &prw) != 0)
2510 	return (ENXIO);
2511     dev = acpi_get_device(handle);
2512 
2513     /*
2514      * The destination sleep state must be less than (i.e., higher power)
2515      * or equal to the value specified by _PRW.  If this GPE cannot be
2516      * enabled for the next sleep state, then disable it.  If it can and
2517      * the user requested it be enabled, turn on any required power resources
2518      * and set _PSW.
2519      */
2520     if (sstate > prw.lowest_wake) {
2521 	AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2522 	if (bootverbose)
2523 	    device_printf(dev, "wake_prep disabled wake for %s (S%d)\n",
2524 		acpi_name(handle), sstate);
2525     } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
2526 	acpi_pwr_wake_enable(handle, 1);
2527 	acpi_SetInteger(handle, "_PSW", 1);
2528 	if (bootverbose)
2529 	    device_printf(dev, "wake_prep enabled for %s (S%d)\n",
2530 		acpi_name(handle), sstate);
2531     }
2532 
2533     return (0);
2534 }
2535 
2536 static int
2537 acpi_wake_run_prep(ACPI_HANDLE handle, int sstate)
2538 {
2539     struct acpi_prw_data prw;
2540     device_t dev;
2541 
2542     /*
2543      * Check that this is a wake-capable device and get its GPE.  Return
2544      * now if the user didn't enable this device for wake.
2545      */
2546     if (acpi_parse_prw(handle, &prw) != 0)
2547 	return (ENXIO);
2548     dev = acpi_get_device(handle);
2549     if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
2550 	return (0);
2551 
2552     /*
2553      * If this GPE couldn't be enabled for the previous sleep state, it was
2554      * disabled before going to sleep so re-enable it.  If it was enabled,
2555      * clear _PSW and turn off any power resources it used.
2556      */
2557     if (sstate > prw.lowest_wake) {
2558 	AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2559 	if (bootverbose)
2560 	    device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
2561     } else {
2562 	acpi_SetInteger(handle, "_PSW", 0);
2563 	acpi_pwr_wake_enable(handle, 0);
2564 	if (bootverbose)
2565 	    device_printf(dev, "run_prep cleaned up for %s\n",
2566 		acpi_name(handle));
2567     }
2568 
2569     return (0);
2570 }
2571 
2572 static ACPI_STATUS
2573 acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2574 {
2575     int sstate;
2576 
2577     /* If suspending, run the sleep prep function, otherwise wake. */
2578     sstate = *(int *)context;
2579     if (AcpiGbl_SystemAwakeAndRunning)
2580 	acpi_wake_sleep_prep(handle, sstate);
2581     else
2582 	acpi_wake_run_prep(handle, sstate);
2583     return (AE_OK);
2584 }
2585 
2586 /* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
2587 static int
2588 acpi_wake_prep_walk(int sstate)
2589 {
2590     ACPI_HANDLE sb_handle;
2591 
2592     if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2593 	AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
2594 	    acpi_wake_prep, &sstate, NULL);
2595     return (0);
2596 }
2597 
2598 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
2599 static int
2600 acpi_wake_sysctl_walk(device_t dev)
2601 {
2602     int error, i, numdevs;
2603     device_t *devlist;
2604     device_t child;
2605     ACPI_STATUS status;
2606 
2607     error = device_get_children(dev, &devlist, &numdevs);
2608     if (error != 0 || numdevs == 0) {
2609 	if (numdevs == 0)
2610 	    free(devlist, M_TEMP);
2611 	return (error);
2612     }
2613     for (i = 0; i < numdevs; i++) {
2614 	child = devlist[i];
2615 	acpi_wake_sysctl_walk(child);
2616 	if (!device_is_attached(child))
2617 	    continue;
2618 	status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
2619 	if (ACPI_SUCCESS(status)) {
2620 	    SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
2621 		SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
2622 		"wake", CTLTYPE_INT | CTLFLAG_RW, child, 0,
2623 		acpi_wake_set_sysctl, "I", "Device set to wake the system");
2624 	}
2625     }
2626     free(devlist, M_TEMP);
2627 
2628     return (0);
2629 }
2630 
2631 /* Enable or disable wake from userland. */
2632 static int
2633 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
2634 {
2635     int enable, error;
2636     device_t dev;
2637 
2638     dev = (device_t)arg1;
2639     enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
2640 
2641     error = sysctl_handle_int(oidp, &enable, 0, req);
2642     if (error != 0 || req->newptr == NULL)
2643 	return (error);
2644     if (enable != 0 && enable != 1)
2645 	return (EINVAL);
2646 
2647     return (acpi_wake_set_enable(dev, enable));
2648 }
2649 
2650 /* Parse a device's _PRW into a structure. */
2651 int
2652 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
2653 {
2654     ACPI_STATUS			status;
2655     ACPI_BUFFER			prw_buffer;
2656     ACPI_OBJECT			*res, *res2;
2657     int				error, i, power_count;
2658 
2659     if (h == NULL || prw == NULL)
2660 	return (EINVAL);
2661 
2662     /*
2663      * The _PRW object (7.2.9) is only required for devices that have the
2664      * ability to wake the system from a sleeping state.
2665      */
2666     error = EINVAL;
2667     prw_buffer.Pointer = NULL;
2668     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
2669     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
2670     if (ACPI_FAILURE(status))
2671 	return (ENOENT);
2672     res = (ACPI_OBJECT *)prw_buffer.Pointer;
2673     if (res == NULL)
2674 	return (ENOENT);
2675     if (!ACPI_PKG_VALID(res, 2))
2676 	goto out;
2677 
2678     /*
2679      * Element 1 of the _PRW object:
2680      * The lowest power system sleeping state that can be entered while still
2681      * providing wake functionality.  The sleeping state being entered must
2682      * be less than (i.e., higher power) or equal to this value.
2683      */
2684     if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
2685 	goto out;
2686 
2687     /*
2688      * Element 0 of the _PRW object:
2689      */
2690     switch (res->Package.Elements[0].Type) {
2691     case ACPI_TYPE_INTEGER:
2692 	/*
2693 	 * If the data type of this package element is numeric, then this
2694 	 * _PRW package element is the bit index in the GPEx_EN, in the
2695 	 * GPE blocks described in the FADT, of the enable bit that is
2696 	 * enabled for the wake event.
2697 	 */
2698 	prw->gpe_handle = NULL;
2699 	prw->gpe_bit = res->Package.Elements[0].Integer.Value;
2700 	error = 0;
2701 	break;
2702     case ACPI_TYPE_PACKAGE:
2703 	/*
2704 	 * If the data type of this package element is a package, then this
2705 	 * _PRW package element is itself a package containing two
2706 	 * elements.  The first is an object reference to the GPE Block
2707 	 * device that contains the GPE that will be triggered by the wake
2708 	 * event.  The second element is numeric and it contains the bit
2709 	 * index in the GPEx_EN, in the GPE Block referenced by the
2710 	 * first element in the package, of the enable bit that is enabled for
2711 	 * the wake event.
2712 	 *
2713 	 * For example, if this field is a package then it is of the form:
2714 	 * Package() {\_SB.PCI0.ISA.GPE, 2}
2715 	 */
2716 	res2 = &res->Package.Elements[0];
2717 	if (!ACPI_PKG_VALID(res2, 2))
2718 	    goto out;
2719 	prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
2720 	if (prw->gpe_handle == NULL)
2721 	    goto out;
2722 	if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
2723 	    goto out;
2724 	error = 0;
2725 	break;
2726     default:
2727 	goto out;
2728     }
2729 
2730     /* Elements 2 to N of the _PRW object are power resources. */
2731     power_count = res->Package.Count - 2;
2732     if (power_count > ACPI_PRW_MAX_POWERRES) {
2733 	printf("ACPI device %s has too many power resources\n", acpi_name(h));
2734 	power_count = 0;
2735     }
2736     prw->power_res_count = power_count;
2737     for (i = 0; i < power_count; i++)
2738 	prw->power_res[i] = res->Package.Elements[i];
2739 
2740 out:
2741     if (prw_buffer.Pointer != NULL)
2742 	AcpiOsFree(prw_buffer.Pointer);
2743     return (error);
2744 }
2745 
2746 /*
2747  * ACPI Event Handlers
2748  */
2749 
2750 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
2751 
2752 static void
2753 acpi_system_eventhandler_sleep(void *arg, int state)
2754 {
2755     int ret;
2756 
2757     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2758 
2759     /* Check if button action is disabled. */
2760     if (state == ACPI_S_STATES_MAX + 1)
2761 	return;
2762 
2763     /* Request that the system prepare to enter the given suspend state. */
2764     ret = acpi_ReqSleepState((struct acpi_softc *)arg, state);
2765     if (ret != 0)
2766 	printf("acpi: request to enter state S%d failed (err %d)\n",
2767 	    state, ret);
2768 
2769     return_VOID;
2770 }
2771 
2772 static void
2773 acpi_system_eventhandler_wakeup(void *arg, int state)
2774 {
2775 
2776     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2777 
2778     /* Currently, nothing to do for wakeup. */
2779 
2780     return_VOID;
2781 }
2782 
2783 /*
2784  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
2785  */
2786 UINT32
2787 acpi_event_power_button_sleep(void *context)
2788 {
2789     struct acpi_softc	*sc = (struct acpi_softc *)context;
2790 
2791     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2792 
2793     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
2794 
2795     return_VALUE (ACPI_INTERRUPT_HANDLED);
2796 }
2797 
2798 UINT32
2799 acpi_event_power_button_wake(void *context)
2800 {
2801     struct acpi_softc	*sc = (struct acpi_softc *)context;
2802 
2803     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2804 
2805     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
2806 
2807     return_VALUE (ACPI_INTERRUPT_HANDLED);
2808 }
2809 
2810 UINT32
2811 acpi_event_sleep_button_sleep(void *context)
2812 {
2813     struct acpi_softc	*sc = (struct acpi_softc *)context;
2814 
2815     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2816 
2817     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
2818 
2819     return_VALUE (ACPI_INTERRUPT_HANDLED);
2820 }
2821 
2822 UINT32
2823 acpi_event_sleep_button_wake(void *context)
2824 {
2825     struct acpi_softc	*sc = (struct acpi_softc *)context;
2826 
2827     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2828 
2829     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
2830 
2831     return_VALUE (ACPI_INTERRUPT_HANDLED);
2832 }
2833 
2834 /*
2835  * XXX This static buffer is suboptimal.  There is no locking so only
2836  * use this for single-threaded callers.
2837  */
2838 char *
2839 acpi_name(ACPI_HANDLE handle)
2840 {
2841     ACPI_BUFFER buf;
2842     static char data[256];
2843 
2844     buf.Length = sizeof(data);
2845     buf.Pointer = data;
2846 
2847     if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
2848 	return (data);
2849     return ("(unknown)");
2850 }
2851 
2852 /*
2853  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
2854  * parts of the namespace.
2855  */
2856 int
2857 acpi_avoid(ACPI_HANDLE handle)
2858 {
2859     char	*cp, *env, *np;
2860     int		len;
2861 
2862     np = acpi_name(handle);
2863     if (*np == '\\')
2864 	np++;
2865     if ((env = getenv("debug.acpi.avoid")) == NULL)
2866 	return (0);
2867 
2868     /* Scan the avoid list checking for a match */
2869     cp = env;
2870     for (;;) {
2871 	while (*cp != 0 && isspace(*cp))
2872 	    cp++;
2873 	if (*cp == 0)
2874 	    break;
2875 	len = 0;
2876 	while (cp[len] != 0 && !isspace(cp[len]))
2877 	    len++;
2878 	if (!strncmp(cp, np, len)) {
2879 	    freeenv(env);
2880 	    return(1);
2881 	}
2882 	cp += len;
2883     }
2884     freeenv(env);
2885 
2886     return (0);
2887 }
2888 
2889 /*
2890  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
2891  */
2892 int
2893 acpi_disabled(char *subsys)
2894 {
2895     char	*cp, *env;
2896     int		len;
2897 
2898     if ((env = getenv("debug.acpi.disabled")) == NULL)
2899 	return (0);
2900     if (strcmp(env, "all") == 0) {
2901 	freeenv(env);
2902 	return (1);
2903     }
2904 
2905     /* Scan the disable list, checking for a match. */
2906     cp = env;
2907     for (;;) {
2908 	while (*cp != '\0' && isspace(*cp))
2909 	    cp++;
2910 	if (*cp == '\0')
2911 	    break;
2912 	len = 0;
2913 	while (cp[len] != '\0' && !isspace(cp[len]))
2914 	    len++;
2915 	if (strncmp(cp, subsys, len) == 0) {
2916 	    freeenv(env);
2917 	    return (1);
2918 	}
2919 	cp += len;
2920     }
2921     freeenv(env);
2922 
2923     return (0);
2924 }
2925 
2926 /*
2927  * Control interface.
2928  *
2929  * We multiplex ioctls for all participating ACPI devices here.  Individual
2930  * drivers wanting to be accessible via /dev/acpi should use the
2931  * register/deregister interface to make their handlers visible.
2932  */
2933 struct acpi_ioctl_hook
2934 {
2935     TAILQ_ENTRY(acpi_ioctl_hook) link;
2936     u_long			 cmd;
2937     acpi_ioctl_fn		 fn;
2938     void			 *arg;
2939 };
2940 
2941 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
2942 static int				acpi_ioctl_hooks_initted;
2943 
2944 int
2945 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
2946 {
2947     struct acpi_ioctl_hook	*hp;
2948 
2949     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
2950 	return (ENOMEM);
2951     hp->cmd = cmd;
2952     hp->fn = fn;
2953     hp->arg = arg;
2954 
2955     ACPI_LOCK(acpi);
2956     if (acpi_ioctl_hooks_initted == 0) {
2957 	TAILQ_INIT(&acpi_ioctl_hooks);
2958 	acpi_ioctl_hooks_initted = 1;
2959     }
2960     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
2961     ACPI_UNLOCK(acpi);
2962 
2963     return (0);
2964 }
2965 
2966 void
2967 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
2968 {
2969     struct acpi_ioctl_hook	*hp;
2970 
2971     ACPI_LOCK(acpi);
2972     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
2973 	if (hp->cmd == cmd && hp->fn == fn)
2974 	    break;
2975 
2976     if (hp != NULL) {
2977 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
2978 	free(hp, M_ACPIDEV);
2979     }
2980     ACPI_UNLOCK(acpi);
2981 }
2982 
2983 static int
2984 acpiopen(struct cdev *dev, int flag, int fmt, d_thread_t *td)
2985 {
2986     return (0);
2987 }
2988 
2989 static int
2990 acpiclose(struct cdev *dev, int flag, int fmt, d_thread_t *td)
2991 {
2992     return (0);
2993 }
2994 
2995 static int
2996 acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
2997 {
2998     struct acpi_softc		*sc;
2999     struct acpi_ioctl_hook	*hp;
3000     int				error, state;
3001 
3002     error = 0;
3003     hp = NULL;
3004     sc = dev->si_drv1;
3005 
3006     /*
3007      * Scan the list of registered ioctls, looking for handlers.
3008      */
3009     ACPI_LOCK(acpi);
3010     if (acpi_ioctl_hooks_initted)
3011 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
3012 	    if (hp->cmd == cmd)
3013 		break;
3014 	}
3015     ACPI_UNLOCK(acpi);
3016     if (hp)
3017 	return (hp->fn(cmd, addr, hp->arg));
3018 
3019     /*
3020      * Core ioctls are not permitted for non-writable user.
3021      * Currently, other ioctls just fetch information.
3022      * Not changing system behavior.
3023      */
3024     if ((flag & FWRITE) == 0)
3025 	return (EPERM);
3026 
3027     /* Core system ioctls. */
3028     switch (cmd) {
3029     case ACPIIO_REQSLPSTATE:
3030 	state = *(int *)addr;
3031 	if (state != ACPI_STATE_S5)
3032 	    error = acpi_ReqSleepState(sc, state);
3033 	else {
3034 	    printf("power off via acpi ioctl not supported\n");
3035 	    error = ENXIO;
3036 	}
3037 	break;
3038     case ACPIIO_ACKSLPSTATE:
3039 	error = *(int *)addr;
3040 	error = acpi_AckSleepState(sc->acpi_clone, error);
3041 	break;
3042     case ACPIIO_SETSLPSTATE:	/* DEPRECATED */
3043 	error = EINVAL;
3044 	state = *(int *)addr;
3045 	if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
3046 	    if (ACPI_SUCCESS(acpi_SetSleepState(sc, state)))
3047 		error = 0;
3048 	break;
3049     default:
3050 	error = ENXIO;
3051 	break;
3052     }
3053 
3054     return (error);
3055 }
3056 
3057 static int
3058 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
3059 {
3060     int error;
3061     struct sbuf sb;
3062     UINT8 state, TypeA, TypeB;
3063 
3064     sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
3065     for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX + 1; state++)
3066 	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB)))
3067 	    sbuf_printf(&sb, "S%d ", state);
3068     sbuf_trim(&sb);
3069     sbuf_finish(&sb);
3070     error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
3071     sbuf_delete(&sb);
3072     return (error);
3073 }
3074 
3075 static int
3076 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
3077 {
3078     char sleep_state[10];
3079     int error;
3080     u_int new_state, old_state;
3081 
3082     old_state = *(u_int *)oidp->oid_arg1;
3083     if (old_state > ACPI_S_STATES_MAX + 1)
3084 	strlcpy(sleep_state, "unknown", sizeof(sleep_state));
3085     else
3086 	strlcpy(sleep_state, sleep_state_names[old_state], sizeof(sleep_state));
3087     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
3088     if (error == 0 && req->newptr != NULL) {
3089 	new_state = ACPI_STATE_S0;
3090 	for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++)
3091 	    if (strcmp(sleep_state, sleep_state_names[new_state]) == 0)
3092 		break;
3093 	if (new_state <= ACPI_S_STATES_MAX + 1) {
3094 	    if (new_state != old_state)
3095 		*(u_int *)oidp->oid_arg1 = new_state;
3096 	} else
3097 	    error = EINVAL;
3098     }
3099 
3100     return (error);
3101 }
3102 
3103 /* Inform devctl(4) when we receive a Notify. */
3104 void
3105 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
3106 {
3107     char		notify_buf[16];
3108     ACPI_BUFFER		handle_buf;
3109     ACPI_STATUS		status;
3110 
3111     if (subsystem == NULL)
3112 	return;
3113 
3114     handle_buf.Pointer = NULL;
3115     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
3116     status = AcpiNsHandleToPathname(h, &handle_buf);
3117     if (ACPI_FAILURE(status))
3118 	return;
3119     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
3120     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
3121     AcpiOsFree(handle_buf.Pointer);
3122 }
3123 
3124 #ifdef ACPI_DEBUG
3125 /*
3126  * Support for parsing debug options from the kernel environment.
3127  *
3128  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
3129  * by specifying the names of the bits in the debug.acpi.layer and
3130  * debug.acpi.level environment variables.  Bits may be unset by
3131  * prefixing the bit name with !.
3132  */
3133 struct debugtag
3134 {
3135     char	*name;
3136     UINT32	value;
3137 };
3138 
3139 static struct debugtag	dbg_layer[] = {
3140     {"ACPI_UTILITIES",		ACPI_UTILITIES},
3141     {"ACPI_HARDWARE",		ACPI_HARDWARE},
3142     {"ACPI_EVENTS",		ACPI_EVENTS},
3143     {"ACPI_TABLES",		ACPI_TABLES},
3144     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
3145     {"ACPI_PARSER",		ACPI_PARSER},
3146     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
3147     {"ACPI_EXECUTER",		ACPI_EXECUTER},
3148     {"ACPI_RESOURCES",		ACPI_RESOURCES},
3149     {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
3150     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
3151     {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
3152     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
3153 
3154     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
3155     {"ACPI_BATTERY",		ACPI_BATTERY},
3156     {"ACPI_BUS",		ACPI_BUS},
3157     {"ACPI_BUTTON",		ACPI_BUTTON},
3158     {"ACPI_EC", 		ACPI_EC},
3159     {"ACPI_FAN",		ACPI_FAN},
3160     {"ACPI_POWERRES",		ACPI_POWERRES},
3161     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
3162     {"ACPI_THERMAL",		ACPI_THERMAL},
3163     {"ACPI_TIMER",		ACPI_TIMER},
3164     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
3165     {NULL, 0}
3166 };
3167 
3168 static struct debugtag dbg_level[] = {
3169     {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
3170     {"ACPI_LV_WARN",		ACPI_LV_WARN},
3171     {"ACPI_LV_INIT",		ACPI_LV_INIT},
3172     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
3173     {"ACPI_LV_INFO",		ACPI_LV_INFO},
3174     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
3175 
3176     /* Trace verbosity level 1 [Standard Trace Level] */
3177     {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
3178     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
3179     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
3180     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
3181     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
3182     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
3183     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
3184     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
3185     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
3186     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
3187     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
3188     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
3189     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
3190     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
3191     {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
3192 
3193     /* Trace verbosity level 2 [Function tracing and memory allocation] */
3194     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
3195     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
3196     {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
3197     {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
3198     {"ACPI_LV_ALL",		ACPI_LV_ALL},
3199 
3200     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
3201     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
3202     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
3203     {"ACPI_LV_IO",		ACPI_LV_IO},
3204     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
3205     {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
3206 
3207     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
3208     {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
3209     {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
3210     {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
3211     {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
3212     {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
3213     {NULL, 0}
3214 };
3215 
3216 static void
3217 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
3218 {
3219     char	*ep;
3220     int		i, l;
3221     int		set;
3222 
3223     while (*cp) {
3224 	if (isspace(*cp)) {
3225 	    cp++;
3226 	    continue;
3227 	}
3228 	ep = cp;
3229 	while (*ep && !isspace(*ep))
3230 	    ep++;
3231 	if (*cp == '!') {
3232 	    set = 0;
3233 	    cp++;
3234 	    if (cp == ep)
3235 		continue;
3236 	} else {
3237 	    set = 1;
3238 	}
3239 	l = ep - cp;
3240 	for (i = 0; tag[i].name != NULL; i++) {
3241 	    if (!strncmp(cp, tag[i].name, l)) {
3242 		if (set)
3243 		    *flag |= tag[i].value;
3244 		else
3245 		    *flag &= ~tag[i].value;
3246 	    }
3247 	}
3248 	cp = ep;
3249     }
3250 }
3251 
3252 static void
3253 acpi_set_debugging(void *junk)
3254 {
3255     char	*layer, *level;
3256 
3257     if (cold) {
3258 	AcpiDbgLayer = 0;
3259 	AcpiDbgLevel = 0;
3260     }
3261 
3262     layer = getenv("debug.acpi.layer");
3263     level = getenv("debug.acpi.level");
3264     if (layer == NULL && level == NULL)
3265 	return;
3266 
3267     printf("ACPI set debug");
3268     if (layer != NULL) {
3269 	if (strcmp("NONE", layer) != 0)
3270 	    printf(" layer '%s'", layer);
3271 	acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
3272 	freeenv(layer);
3273     }
3274     if (level != NULL) {
3275 	if (strcmp("NONE", level) != 0)
3276 	    printf(" level '%s'", level);
3277 	acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
3278 	freeenv(level);
3279     }
3280     printf("\n");
3281 }
3282 
3283 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
3284 	NULL);
3285 
3286 static int
3287 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
3288 {
3289     int		 error, *dbg;
3290     struct	 debugtag *tag;
3291     struct	 sbuf sb;
3292 
3293     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
3294 	return (ENOMEM);
3295     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
3296 	tag = &dbg_layer[0];
3297 	dbg = &AcpiDbgLayer;
3298     } else {
3299 	tag = &dbg_level[0];
3300 	dbg = &AcpiDbgLevel;
3301     }
3302 
3303     /* Get old values if this is a get request. */
3304     ACPI_SERIAL_BEGIN(acpi);
3305     if (*dbg == 0) {
3306 	sbuf_cpy(&sb, "NONE");
3307     } else if (req->newptr == NULL) {
3308 	for (; tag->name != NULL; tag++) {
3309 	    if ((*dbg & tag->value) == tag->value)
3310 		sbuf_printf(&sb, "%s ", tag->name);
3311 	}
3312     }
3313     sbuf_trim(&sb);
3314     sbuf_finish(&sb);
3315 
3316     /* Copy out the old values to the user. */
3317     error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
3318     sbuf_delete(&sb);
3319 
3320     /* If the user is setting a string, parse it. */
3321     if (error == 0 && req->newptr != NULL) {
3322 	*dbg = 0;
3323 	setenv((char *)oidp->oid_arg1, (char *)req->newptr);
3324 	acpi_set_debugging(NULL);
3325     }
3326     ACPI_SERIAL_END(acpi);
3327 
3328     return (error);
3329 }
3330 
3331 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
3332 	    "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
3333 SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
3334 	    "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
3335 #endif /* ACPI_DEBUG */
3336 
3337 static int
3338 acpi_pm_func(u_long cmd, void *arg, ...)
3339 {
3340 	int	state, acpi_state;
3341 	int	error;
3342 	struct	acpi_softc *sc;
3343 	va_list	ap;
3344 
3345 	error = 0;
3346 	switch (cmd) {
3347 	case POWER_CMD_SUSPEND:
3348 		sc = (struct acpi_softc *)arg;
3349 		if (sc == NULL) {
3350 			error = EINVAL;
3351 			goto out;
3352 		}
3353 
3354 		va_start(ap, arg);
3355 		state = va_arg(ap, int);
3356 		va_end(ap);
3357 
3358 		switch (state) {
3359 		case POWER_SLEEP_STATE_STANDBY:
3360 			acpi_state = sc->acpi_standby_sx;
3361 			break;
3362 		case POWER_SLEEP_STATE_SUSPEND:
3363 			acpi_state = sc->acpi_suspend_sx;
3364 			break;
3365 		case POWER_SLEEP_STATE_HIBERNATE:
3366 			acpi_state = ACPI_STATE_S4;
3367 			break;
3368 		default:
3369 			error = EINVAL;
3370 			goto out;
3371 		}
3372 
3373 		if (ACPI_FAILURE(acpi_EnterSleepState(sc, acpi_state)))
3374 			error = ENXIO;
3375 		break;
3376 	default:
3377 		error = EINVAL;
3378 		goto out;
3379 	}
3380 
3381 out:
3382 	return (error);
3383 }
3384 
3385 static void
3386 acpi_pm_register(void *arg)
3387 {
3388     if (!cold || resource_disabled("acpi", 0))
3389 	return;
3390 
3391     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
3392 }
3393 
3394 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
3395