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