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