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