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