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