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