xref: /freebsd/sys/dev/acpica/acpi.c (revision 7be9a3b45356747f9fcb6d69a722c1c95f8060bf)
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_MPSAFE, 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_MPSAFE,
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_MPSAFE,
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_MPSAFE,
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_MPSAFE,
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_MPSAFE,
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_MPSAFE,
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     bus_topo_assert();
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     bus_topo_assert();
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     bus_topo_assert();
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, &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 	default:
1854 		return (0);
1855 	}
1856 }
1857 
1858 int
1859 acpi_device_pwr_for_sleep(device_t bus, device_t dev, int *dstate)
1860 {
1861     struct acpi_softc *sc;
1862     ACPI_HANDLE handle;
1863     ACPI_STATUS status;
1864     char sxd[8];
1865 
1866     handle = acpi_get_handle(dev);
1867 
1868     /*
1869      * XXX If we find these devices, don't try to power them down.
1870      * The serial and IRDA ports on my T23 hang the system when
1871      * set to D3 and it appears that such legacy devices may
1872      * need special handling in their drivers.
1873      */
1874     if (dstate == NULL || handle == NULL ||
1875 	acpi_MatchHid(handle, "PNP0500") ||
1876 	acpi_MatchHid(handle, "PNP0501") ||
1877 	acpi_MatchHid(handle, "PNP0502") ||
1878 	acpi_MatchHid(handle, "PNP0510") ||
1879 	acpi_MatchHid(handle, "PNP0511"))
1880 	return (ENXIO);
1881 
1882     /*
1883      * Override next state with the value from _SxD, if present.
1884      * Note illegal _S0D is evaluated because some systems expect this.
1885      */
1886     sc = device_get_softc(bus);
1887     snprintf(sxd, sizeof(sxd), "_S%dD", sc->acpi_sstate);
1888     status = acpi_GetInteger(handle, sxd, dstate);
1889     if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
1890 	    device_printf(dev, "failed to get %s on %s: %s\n", sxd,
1891 		acpi_name(handle), AcpiFormatException(status));
1892 	    return (ENXIO);
1893     }
1894 
1895     return (0);
1896 }
1897 
1898 /* Callback arg for our implementation of walking the namespace. */
1899 struct acpi_device_scan_ctx {
1900     acpi_scan_cb_t	user_fn;
1901     void		*arg;
1902     ACPI_HANDLE		parent;
1903 };
1904 
1905 static ACPI_STATUS
1906 acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level, void *arg, void **retval)
1907 {
1908     struct acpi_device_scan_ctx *ctx;
1909     device_t dev, old_dev;
1910     ACPI_STATUS status;
1911     ACPI_OBJECT_TYPE type;
1912 
1913     /*
1914      * Skip this device if we think we'll have trouble with it or it is
1915      * the parent where the scan began.
1916      */
1917     ctx = (struct acpi_device_scan_ctx *)arg;
1918     if (acpi_avoid(h) || h == ctx->parent)
1919 	return (AE_OK);
1920 
1921     /* If this is not a valid device type (e.g., a method), skip it. */
1922     if (ACPI_FAILURE(AcpiGetType(h, &type)))
1923 	return (AE_OK);
1924     if (type != ACPI_TYPE_DEVICE && type != ACPI_TYPE_PROCESSOR &&
1925 	type != ACPI_TYPE_THERMAL && type != ACPI_TYPE_POWER)
1926 	return (AE_OK);
1927 
1928     /*
1929      * Call the user function with the current device.  If it is unchanged
1930      * afterwards, return.  Otherwise, we update the handle to the new dev.
1931      */
1932     old_dev = acpi_get_device(h);
1933     dev = old_dev;
1934     status = ctx->user_fn(h, &dev, level, ctx->arg);
1935     if (ACPI_FAILURE(status) || old_dev == dev)
1936 	return (status);
1937 
1938     /* Remove the old child and its connection to the handle. */
1939     if (old_dev != NULL)
1940 	device_delete_child(device_get_parent(old_dev), old_dev);
1941 
1942     /* Recreate the handle association if the user created a device. */
1943     if (dev != NULL)
1944 	AcpiAttachData(h, acpi_fake_objhandler, dev);
1945 
1946     return (AE_OK);
1947 }
1948 
1949 static ACPI_STATUS
1950 acpi_device_scan_children(device_t bus, device_t dev, int max_depth,
1951     acpi_scan_cb_t user_fn, void *arg)
1952 {
1953     ACPI_HANDLE h;
1954     struct acpi_device_scan_ctx ctx;
1955 
1956     if (acpi_disabled("children"))
1957 	return (AE_OK);
1958 
1959     if (dev == NULL)
1960 	h = ACPI_ROOT_OBJECT;
1961     else if ((h = acpi_get_handle(dev)) == NULL)
1962 	return (AE_BAD_PARAMETER);
1963     ctx.user_fn = user_fn;
1964     ctx.arg = arg;
1965     ctx.parent = h;
1966     return (AcpiWalkNamespace(ACPI_TYPE_ANY, h, max_depth,
1967 	acpi_device_scan_cb, NULL, &ctx, NULL));
1968 }
1969 
1970 /*
1971  * Even though ACPI devices are not PCI, we use the PCI approach for setting
1972  * device power states since it's close enough to ACPI.
1973  */
1974 int
1975 acpi_set_powerstate(device_t child, int state)
1976 {
1977     ACPI_HANDLE h;
1978     ACPI_STATUS status;
1979 
1980     h = acpi_get_handle(child);
1981     if (state < ACPI_STATE_D0 || state > ACPI_D_STATES_MAX)
1982 	return (EINVAL);
1983     if (h == NULL)
1984 	return (0);
1985 
1986     /* Ignore errors if the power methods aren't present. */
1987     status = acpi_pwr_switch_consumer(h, state);
1988     if (ACPI_SUCCESS(status)) {
1989 	if (bootverbose)
1990 	    device_printf(child, "set ACPI power state D%d on %s\n",
1991 		state, acpi_name(h));
1992     } else if (status != AE_NOT_FOUND)
1993 	device_printf(child,
1994 	    "failed to set ACPI power state D%d on %s: %s\n", state,
1995 	    acpi_name(h), AcpiFormatException(status));
1996 
1997     return (0);
1998 }
1999 
2000 static int
2001 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
2002 {
2003     int			result, cid_count, i;
2004     uint32_t		lid, cids[8];
2005 
2006     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2007 
2008     /*
2009      * ISA-style drivers attached to ACPI may persist and
2010      * probe manually if we return ENOENT.  We never want
2011      * that to happen, so don't ever return it.
2012      */
2013     result = ENXIO;
2014 
2015     /* Scan the supplied IDs for a match */
2016     lid = acpi_isa_get_logicalid(child);
2017     cid_count = acpi_isa_get_compatid(child, cids, 8);
2018     while (ids && ids->ip_id) {
2019 	if (lid == ids->ip_id) {
2020 	    result = 0;
2021 	    goto out;
2022 	}
2023 	for (i = 0; i < cid_count; i++) {
2024 	    if (cids[i] == ids->ip_id) {
2025 		result = 0;
2026 		goto out;
2027 	    }
2028 	}
2029 	ids++;
2030     }
2031 
2032  out:
2033     if (result == 0 && ids->ip_desc)
2034 	device_set_desc(child, ids->ip_desc);
2035 
2036     return_VALUE (result);
2037 }
2038 
2039 /*
2040  * Look for a MCFG table.  If it is present, use the settings for
2041  * domain (segment) 0 to setup PCI config space access via the memory
2042  * map.
2043  *
2044  * On non-x86 architectures (arm64 for now), this will be done from the
2045  * PCI host bridge driver.
2046  */
2047 static void
2048 acpi_enable_pcie(void)
2049 {
2050 #if defined(__i386__) || defined(__amd64__)
2051 	ACPI_TABLE_HEADER *hdr;
2052 	ACPI_MCFG_ALLOCATION *alloc, *end;
2053 	ACPI_STATUS status;
2054 
2055 	status = AcpiGetTable(ACPI_SIG_MCFG, 1, &hdr);
2056 	if (ACPI_FAILURE(status))
2057 		return;
2058 
2059 	end = (ACPI_MCFG_ALLOCATION *)((char *)hdr + hdr->Length);
2060 	alloc = (ACPI_MCFG_ALLOCATION *)((ACPI_TABLE_MCFG *)hdr + 1);
2061 	while (alloc < end) {
2062 		if (alloc->PciSegment == 0) {
2063 			pcie_cfgregopen(alloc->Address, alloc->StartBusNumber,
2064 			    alloc->EndBusNumber);
2065 			return;
2066 		}
2067 		alloc++;
2068 	}
2069 #endif
2070 }
2071 
2072 static void
2073 acpi_platform_osc(device_t dev)
2074 {
2075 	ACPI_HANDLE sb_handle;
2076 	ACPI_STATUS status;
2077 	uint32_t cap_set[2];
2078 
2079 	/* 0811B06E-4A27-44F9-8D60-3CBBC22E7B48 */
2080 	static uint8_t acpi_platform_uuid[ACPI_UUID_LENGTH] = {
2081 		0x6e, 0xb0, 0x11, 0x08, 0x27, 0x4a, 0xf9, 0x44,
2082 		0x8d, 0x60, 0x3c, 0xbb, 0xc2, 0x2e, 0x7b, 0x48
2083 	};
2084 
2085 	if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2086 		return;
2087 
2088 	cap_set[1] = 0x10;	/* APEI Support */
2089 	status = acpi_EvaluateOSC(sb_handle, acpi_platform_uuid, 1,
2090 	    nitems(cap_set), cap_set, cap_set, false);
2091 	if (ACPI_FAILURE(status)) {
2092 		if (status == AE_NOT_FOUND)
2093 			return;
2094 		device_printf(dev, "_OSC failed: %s\n",
2095 		    AcpiFormatException(status));
2096 		return;
2097 	}
2098 }
2099 
2100 /*
2101  * Scan all of the ACPI namespace and attach child devices.
2102  *
2103  * We should only expect to find devices in the \_PR, \_TZ, \_SI, and
2104  * \_SB scopes, and \_PR and \_TZ became obsolete in the ACPI 2.0 spec.
2105  * However, in violation of the spec, some systems place their PCI link
2106  * devices in \, so we have to walk the whole namespace.  We check the
2107  * type of namespace nodes, so this should be ok.
2108  */
2109 static void
2110 acpi_probe_children(device_t bus)
2111 {
2112 
2113     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2114 
2115     /*
2116      * Scan the namespace and insert placeholders for all the devices that
2117      * we find.  We also probe/attach any early devices.
2118      *
2119      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
2120      * we want to create nodes for all devices, not just those that are
2121      * currently present. (This assumes that we don't want to create/remove
2122      * devices as they appear, which might be smarter.)
2123      */
2124     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
2125     AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, 100, acpi_probe_child,
2126 	NULL, bus, NULL);
2127 
2128     /* Pre-allocate resources for our rman from any sysresource devices. */
2129     acpi_sysres_alloc(bus);
2130 
2131     /* Reserve resources already allocated to children. */
2132     acpi_reserve_resources(bus);
2133 
2134     /* Create any static children by calling device identify methods. */
2135     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
2136     bus_generic_probe(bus);
2137 
2138     /* Probe/attach all children, created statically and from the namespace. */
2139     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "acpi bus_generic_attach\n"));
2140     bus_generic_attach(bus);
2141 
2142     /* Attach wake sysctls. */
2143     acpi_wake_sysctl_walk(bus);
2144 
2145     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
2146     return_VOID;
2147 }
2148 
2149 /*
2150  * Determine the probe order for a given device.
2151  */
2152 static void
2153 acpi_probe_order(ACPI_HANDLE handle, int *order)
2154 {
2155 	ACPI_OBJECT_TYPE type;
2156 
2157 	/*
2158 	 * 0. CPUs
2159 	 * 1. I/O port and memory system resource holders
2160 	 * 2. Clocks and timers (to handle early accesses)
2161 	 * 3. Embedded controllers (to handle early accesses)
2162 	 * 4. PCI Link Devices
2163 	 */
2164 	AcpiGetType(handle, &type);
2165 	if (type == ACPI_TYPE_PROCESSOR)
2166 		*order = 0;
2167 	else if (acpi_MatchHid(handle, "PNP0C01") ||
2168 	    acpi_MatchHid(handle, "PNP0C02"))
2169 		*order = 1;
2170 	else if (acpi_MatchHid(handle, "PNP0100") ||
2171 	    acpi_MatchHid(handle, "PNP0103") ||
2172 	    acpi_MatchHid(handle, "PNP0B00"))
2173 		*order = 2;
2174 	else if (acpi_MatchHid(handle, "PNP0C09"))
2175 		*order = 3;
2176 	else if (acpi_MatchHid(handle, "PNP0C0F"))
2177 		*order = 4;
2178 }
2179 
2180 /*
2181  * Evaluate a child device and determine whether we might attach a device to
2182  * it.
2183  */
2184 static ACPI_STATUS
2185 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2186 {
2187     ACPI_DEVICE_INFO *devinfo;
2188     struct acpi_device	*ad;
2189     struct acpi_prw_data prw;
2190     ACPI_OBJECT_TYPE type;
2191     ACPI_HANDLE h;
2192     device_t bus, child;
2193     char *handle_str;
2194     int order;
2195 
2196     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2197 
2198     if (acpi_disabled("children"))
2199 	return_ACPI_STATUS (AE_OK);
2200 
2201     /* Skip this device if we think we'll have trouble with it. */
2202     if (acpi_avoid(handle))
2203 	return_ACPI_STATUS (AE_OK);
2204 
2205     bus = (device_t)context;
2206     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
2207 	handle_str = acpi_name(handle);
2208 	switch (type) {
2209 	case ACPI_TYPE_DEVICE:
2210 	    /*
2211 	     * Since we scan from \, be sure to skip system scope objects.
2212 	     * \_SB_ and \_TZ_ are defined in ACPICA as devices to work around
2213 	     * BIOS bugs.  For example, \_SB_ is to allow \_SB_._INI to be run
2214 	     * during the initialization and \_TZ_ is to support Notify() on it.
2215 	     */
2216 	    if (strcmp(handle_str, "\\_SB_") == 0 ||
2217 		strcmp(handle_str, "\\_TZ_") == 0)
2218 		break;
2219 	    if (acpi_parse_prw(handle, &prw) == 0)
2220 		AcpiSetupGpeForWake(handle, prw.gpe_handle, prw.gpe_bit);
2221 
2222 	    /*
2223 	     * Ignore devices that do not have a _HID or _CID.  They should
2224 	     * be discovered by other buses (e.g. the PCI bus driver).
2225 	     */
2226 	    if (!acpi_has_hid(handle))
2227 		break;
2228 	    /* FALLTHROUGH */
2229 	case ACPI_TYPE_PROCESSOR:
2230 	case ACPI_TYPE_THERMAL:
2231 	case ACPI_TYPE_POWER:
2232 	    /*
2233 	     * Create a placeholder device for this node.  Sort the
2234 	     * placeholder so that the probe/attach passes will run
2235 	     * breadth-first.  Orders less than ACPI_DEV_BASE_ORDER
2236 	     * are reserved for special objects (i.e., system
2237 	     * resources).
2238 	     */
2239 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
2240 	    order = level * 10 + ACPI_DEV_BASE_ORDER;
2241 	    acpi_probe_order(handle, &order);
2242 	    child = BUS_ADD_CHILD(bus, order, NULL, -1);
2243 	    if (child == NULL)
2244 		break;
2245 
2246 	    /* Associate the handle with the device_t and vice versa. */
2247 	    acpi_set_handle(child, handle);
2248 	    AcpiAttachData(handle, acpi_fake_objhandler, child);
2249 
2250 	    /*
2251 	     * Check that the device is present.  If it's not present,
2252 	     * leave it disabled (so that we have a device_t attached to
2253 	     * the handle, but we don't probe it).
2254 	     *
2255 	     * XXX PCI link devices sometimes report "present" but not
2256 	     * "functional" (i.e. if disabled).  Go ahead and probe them
2257 	     * anyway since we may enable them later.
2258 	     */
2259 	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
2260 		/* Never disable PCI link devices. */
2261 		if (acpi_MatchHid(handle, "PNP0C0F"))
2262 		    break;
2263 
2264 		/*
2265 		 * RTC Device should be enabled for CMOS register space
2266 		 * unless FADT indicate it is not present.
2267 		 * (checked in RTC probe routine.)
2268 		 */
2269 		if (acpi_MatchHid(handle, "PNP0B00"))
2270 		    break;
2271 
2272 		/*
2273 		 * Docking stations should remain enabled since the system
2274 		 * may be undocked at boot.
2275 		 */
2276 		if (ACPI_SUCCESS(AcpiGetHandle(handle, "_DCK", &h)))
2277 		    break;
2278 
2279 		device_disable(child);
2280 		break;
2281 	    }
2282 
2283 	    /*
2284 	     * Get the device's resource settings and attach them.
2285 	     * Note that if the device has _PRS but no _CRS, we need
2286 	     * to decide when it's appropriate to try to configure the
2287 	     * device.  Ignore the return value here; it's OK for the
2288 	     * device not to have any resources.
2289 	     */
2290 	    acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
2291 
2292 	    ad = device_get_ivars(child);
2293 	    ad->ad_cls_class = 0xffffff;
2294 	    if (ACPI_SUCCESS(AcpiGetObjectInfo(handle, &devinfo))) {
2295 		if ((devinfo->Valid & ACPI_VALID_CLS) != 0 &&
2296 		    devinfo->ClassCode.Length >= ACPI_PCICLS_STRING_SIZE) {
2297 		    ad->ad_cls_class = strtoul(devinfo->ClassCode.String,
2298 			NULL, 16);
2299 		}
2300 		AcpiOsFree(devinfo);
2301 	    }
2302 	    break;
2303 	}
2304     }
2305 
2306     return_ACPI_STATUS (AE_OK);
2307 }
2308 
2309 /*
2310  * AcpiAttachData() requires an object handler but never uses it.  This is a
2311  * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
2312  */
2313 void
2314 acpi_fake_objhandler(ACPI_HANDLE h, void *data)
2315 {
2316 }
2317 
2318 static void
2319 acpi_shutdown_final(void *arg, int howto)
2320 {
2321     struct acpi_softc *sc = (struct acpi_softc *)arg;
2322     register_t intr;
2323     ACPI_STATUS status;
2324 
2325     /*
2326      * XXX Shutdown code should only run on the BSP (cpuid 0).
2327      * Some chipsets do not power off the system correctly if called from
2328      * an AP.
2329      */
2330     if ((howto & RB_POWEROFF) != 0) {
2331 	status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
2332 	if (ACPI_FAILURE(status)) {
2333 	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
2334 		AcpiFormatException(status));
2335 	    return;
2336 	}
2337 	device_printf(sc->acpi_dev, "Powering system off\n");
2338 	intr = intr_disable();
2339 	status = AcpiEnterSleepState(ACPI_STATE_S5);
2340 	if (ACPI_FAILURE(status)) {
2341 	    intr_restore(intr);
2342 	    device_printf(sc->acpi_dev, "power-off failed - %s\n",
2343 		AcpiFormatException(status));
2344 	} else {
2345 	    DELAY(1000000);
2346 	    intr_restore(intr);
2347 	    device_printf(sc->acpi_dev, "power-off failed - timeout\n");
2348 	}
2349     } else if ((howto & RB_HALT) == 0 && sc->acpi_handle_reboot) {
2350 	/* Reboot using the reset register. */
2351 	status = AcpiReset();
2352 	if (ACPI_SUCCESS(status)) {
2353 	    DELAY(1000000);
2354 	    device_printf(sc->acpi_dev, "reset failed - timeout\n");
2355 	} else if (status != AE_NOT_EXIST)
2356 	    device_printf(sc->acpi_dev, "reset failed - %s\n",
2357 		AcpiFormatException(status));
2358     } else if (sc->acpi_do_disable && !KERNEL_PANICKED()) {
2359 	/*
2360 	 * Only disable ACPI if the user requested.  On some systems, writing
2361 	 * the disable value to SMI_CMD hangs the system.
2362 	 */
2363 	device_printf(sc->acpi_dev, "Shutting down\n");
2364 	AcpiTerminate();
2365     }
2366 }
2367 
2368 static void
2369 acpi_enable_fixed_events(struct acpi_softc *sc)
2370 {
2371     static int	first_time = 1;
2372 
2373     /* Enable and clear fixed events and install handlers. */
2374     if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
2375 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
2376 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
2377 				     acpi_event_power_button_sleep, sc);
2378 	if (first_time)
2379 	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
2380     }
2381     if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
2382 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
2383 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
2384 				     acpi_event_sleep_button_sleep, sc);
2385 	if (first_time)
2386 	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
2387     }
2388 
2389     first_time = 0;
2390 }
2391 
2392 /*
2393  * Returns true if the device is actually present and should
2394  * be attached to.  This requires the present, enabled, UI-visible
2395  * and diagnostics-passed bits to be set.
2396  */
2397 BOOLEAN
2398 acpi_DeviceIsPresent(device_t dev)
2399 {
2400 	ACPI_HANDLE h;
2401 	UINT32 s;
2402 	ACPI_STATUS status;
2403 
2404 	h = acpi_get_handle(dev);
2405 	if (h == NULL)
2406 		return (FALSE);
2407 
2408 #ifdef ACPI_EARLY_EPYC_WAR
2409 	/*
2410 	 * Certain Treadripper boards always returns 0 for FreeBSD because it
2411 	 * only returns non-zero for the OS string "Windows 2015". Otherwise it
2412 	 * will return zero. Force them to always be treated as present.
2413 	 * Beata versions were worse: they always returned 0.
2414 	 */
2415 	if (acpi_MatchHid(h, "AMDI0020") || acpi_MatchHid(h, "AMDI0010"))
2416 		return (TRUE);
2417 #endif
2418 
2419 	status = acpi_GetInteger(h, "_STA", &s);
2420 
2421 	/*
2422 	 * If no _STA method or if it failed, then assume that
2423 	 * the device is present.
2424 	 */
2425 	if (ACPI_FAILURE(status))
2426 		return (TRUE);
2427 
2428 	return (ACPI_DEVICE_PRESENT(s) ? TRUE : FALSE);
2429 }
2430 
2431 /*
2432  * Returns true if the battery is actually present and inserted.
2433  */
2434 BOOLEAN
2435 acpi_BatteryIsPresent(device_t dev)
2436 {
2437 	ACPI_HANDLE h;
2438 	UINT32 s;
2439 	ACPI_STATUS status;
2440 
2441 	h = acpi_get_handle(dev);
2442 	if (h == NULL)
2443 		return (FALSE);
2444 	status = acpi_GetInteger(h, "_STA", &s);
2445 
2446 	/*
2447 	 * If no _STA method or if it failed, then assume that
2448 	 * the device is present.
2449 	 */
2450 	if (ACPI_FAILURE(status))
2451 		return (TRUE);
2452 
2453 	return (ACPI_BATTERY_PRESENT(s) ? TRUE : FALSE);
2454 }
2455 
2456 /*
2457  * Returns true if a device has at least one valid device ID.
2458  */
2459 BOOLEAN
2460 acpi_has_hid(ACPI_HANDLE h)
2461 {
2462     ACPI_DEVICE_INFO	*devinfo;
2463     BOOLEAN		ret;
2464 
2465     if (h == NULL ||
2466 	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2467 	return (FALSE);
2468 
2469     ret = FALSE;
2470     if ((devinfo->Valid & ACPI_VALID_HID) != 0)
2471 	ret = TRUE;
2472     else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2473 	if (devinfo->CompatibleIdList.Count > 0)
2474 	    ret = TRUE;
2475 
2476     AcpiOsFree(devinfo);
2477     return (ret);
2478 }
2479 
2480 /*
2481  * Match a HID string against a handle
2482  * returns ACPI_MATCHHID_HID if _HID match
2483  *         ACPI_MATCHHID_CID if _CID match and not _HID match.
2484  *         ACPI_MATCHHID_NOMATCH=0 if no match.
2485  */
2486 int
2487 acpi_MatchHid(ACPI_HANDLE h, const char *hid)
2488 {
2489     ACPI_DEVICE_INFO	*devinfo;
2490     BOOLEAN		ret;
2491     int			i;
2492 
2493     if (hid == NULL || h == NULL ||
2494 	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2495 	return (ACPI_MATCHHID_NOMATCH);
2496 
2497     ret = ACPI_MATCHHID_NOMATCH;
2498     if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
2499 	strcmp(hid, devinfo->HardwareId.String) == 0)
2500 	    ret = ACPI_MATCHHID_HID;
2501     else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2502 	for (i = 0; i < devinfo->CompatibleIdList.Count; i++) {
2503 	    if (strcmp(hid, devinfo->CompatibleIdList.Ids[i].String) == 0) {
2504 		ret = ACPI_MATCHHID_CID;
2505 		break;
2506 	    }
2507 	}
2508 
2509     AcpiOsFree(devinfo);
2510     return (ret);
2511 }
2512 
2513 /*
2514  * Return the handle of a named object within our scope, ie. that of (parent)
2515  * or one if its parents.
2516  */
2517 ACPI_STATUS
2518 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
2519 {
2520     ACPI_HANDLE		r;
2521     ACPI_STATUS		status;
2522 
2523     /* Walk back up the tree to the root */
2524     for (;;) {
2525 	status = AcpiGetHandle(parent, path, &r);
2526 	if (ACPI_SUCCESS(status)) {
2527 	    *result = r;
2528 	    return (AE_OK);
2529 	}
2530 	/* XXX Return error here? */
2531 	if (status != AE_NOT_FOUND)
2532 	    return (AE_OK);
2533 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
2534 	    return (AE_NOT_FOUND);
2535 	parent = r;
2536     }
2537 }
2538 
2539 ACPI_STATUS
2540 acpi_GetProperty(device_t dev, ACPI_STRING propname,
2541     const ACPI_OBJECT **value)
2542 {
2543 	device_t bus = device_get_parent(dev);
2544 
2545 	return (ACPI_GET_PROPERTY(bus, dev, propname, value));
2546 }
2547 
2548 /*
2549  * Allocate a buffer with a preset data size.
2550  */
2551 ACPI_BUFFER *
2552 acpi_AllocBuffer(int size)
2553 {
2554     ACPI_BUFFER	*buf;
2555 
2556     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
2557 	return (NULL);
2558     buf->Length = size;
2559     buf->Pointer = (void *)(buf + 1);
2560     return (buf);
2561 }
2562 
2563 ACPI_STATUS
2564 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
2565 {
2566     ACPI_OBJECT arg1;
2567     ACPI_OBJECT_LIST args;
2568 
2569     arg1.Type = ACPI_TYPE_INTEGER;
2570     arg1.Integer.Value = number;
2571     args.Count = 1;
2572     args.Pointer = &arg1;
2573 
2574     return (AcpiEvaluateObject(handle, path, &args, NULL));
2575 }
2576 
2577 /*
2578  * Evaluate a path that should return an integer.
2579  */
2580 ACPI_STATUS
2581 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
2582 {
2583     ACPI_STATUS	status;
2584     ACPI_BUFFER	buf;
2585     ACPI_OBJECT	param;
2586 
2587     if (handle == NULL)
2588 	handle = ACPI_ROOT_OBJECT;
2589 
2590     /*
2591      * Assume that what we've been pointed at is an Integer object, or
2592      * a method that will return an Integer.
2593      */
2594     buf.Pointer = &param;
2595     buf.Length = sizeof(param);
2596     status = AcpiEvaluateObject(handle, path, NULL, &buf);
2597     if (ACPI_SUCCESS(status)) {
2598 	if (param.Type == ACPI_TYPE_INTEGER)
2599 	    *number = param.Integer.Value;
2600 	else
2601 	    status = AE_TYPE;
2602     }
2603 
2604     /*
2605      * In some applications, a method that's expected to return an Integer
2606      * may instead return a Buffer (probably to simplify some internal
2607      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
2608      * convert it into an Integer as best we can.
2609      *
2610      * This is a hack.
2611      */
2612     if (status == AE_BUFFER_OVERFLOW) {
2613 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
2614 	    status = AE_NO_MEMORY;
2615 	} else {
2616 	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
2617 	    if (ACPI_SUCCESS(status))
2618 		status = acpi_ConvertBufferToInteger(&buf, number);
2619 	    AcpiOsFree(buf.Pointer);
2620 	}
2621     }
2622     return (status);
2623 }
2624 
2625 ACPI_STATUS
2626 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
2627 {
2628     ACPI_OBJECT	*p;
2629     UINT8	*val;
2630     int		i;
2631 
2632     p = (ACPI_OBJECT *)bufp->Pointer;
2633     if (p->Type == ACPI_TYPE_INTEGER) {
2634 	*number = p->Integer.Value;
2635 	return (AE_OK);
2636     }
2637     if (p->Type != ACPI_TYPE_BUFFER)
2638 	return (AE_TYPE);
2639     if (p->Buffer.Length > sizeof(int))
2640 	return (AE_BAD_DATA);
2641 
2642     *number = 0;
2643     val = p->Buffer.Pointer;
2644     for (i = 0; i < p->Buffer.Length; i++)
2645 	*number += val[i] << (i * 8);
2646     return (AE_OK);
2647 }
2648 
2649 /*
2650  * Iterate over the elements of an a package object, calling the supplied
2651  * function for each element.
2652  *
2653  * XXX possible enhancement might be to abort traversal on error.
2654  */
2655 ACPI_STATUS
2656 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
2657 	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
2658 {
2659     ACPI_OBJECT	*comp;
2660     int		i;
2661 
2662     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
2663 	return (AE_BAD_PARAMETER);
2664 
2665     /* Iterate over components */
2666     i = 0;
2667     comp = pkg->Package.Elements;
2668     for (; i < pkg->Package.Count; i++, comp++)
2669 	func(comp, arg);
2670 
2671     return (AE_OK);
2672 }
2673 
2674 /*
2675  * Find the (index)th resource object in a set.
2676  */
2677 ACPI_STATUS
2678 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
2679 {
2680     ACPI_RESOURCE	*rp;
2681     int			i;
2682 
2683     rp = (ACPI_RESOURCE *)buf->Pointer;
2684     i = index;
2685     while (i-- > 0) {
2686 	/* Range check */
2687 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2688 	    return (AE_BAD_PARAMETER);
2689 
2690 	/* Check for terminator */
2691 	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2692 	    return (AE_NOT_FOUND);
2693 	rp = ACPI_NEXT_RESOURCE(rp);
2694     }
2695     if (resp != NULL)
2696 	*resp = rp;
2697 
2698     return (AE_OK);
2699 }
2700 
2701 /*
2702  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
2703  *
2704  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
2705  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
2706  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
2707  * resources.
2708  */
2709 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
2710 
2711 ACPI_STATUS
2712 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
2713 {
2714     ACPI_RESOURCE	*rp;
2715     void		*newp;
2716 
2717     /* Initialise the buffer if necessary. */
2718     if (buf->Pointer == NULL) {
2719 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
2720 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
2721 	    return (AE_NO_MEMORY);
2722 	rp = (ACPI_RESOURCE *)buf->Pointer;
2723 	rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2724 	rp->Length = ACPI_RS_SIZE_MIN;
2725     }
2726     if (res == NULL)
2727 	return (AE_OK);
2728 
2729     /*
2730      * Scan the current buffer looking for the terminator.
2731      * This will either find the terminator or hit the end
2732      * of the buffer and return an error.
2733      */
2734     rp = (ACPI_RESOURCE *)buf->Pointer;
2735     for (;;) {
2736 	/* Range check, don't go outside the buffer */
2737 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2738 	    return (AE_BAD_PARAMETER);
2739 	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2740 	    break;
2741 	rp = ACPI_NEXT_RESOURCE(rp);
2742     }
2743 
2744     /*
2745      * Check the size of the buffer and expand if required.
2746      *
2747      * Required size is:
2748      *	size of existing resources before terminator +
2749      *	size of new resource and header +
2750      * 	size of terminator.
2751      *
2752      * Note that this loop should really only run once, unless
2753      * for some reason we are stuffing a *really* huge resource.
2754      */
2755     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
2756 	    res->Length + ACPI_RS_SIZE_NO_DATA +
2757 	    ACPI_RS_SIZE_MIN) >= buf->Length) {
2758 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
2759 	    return (AE_NO_MEMORY);
2760 	bcopy(buf->Pointer, newp, buf->Length);
2761 	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
2762 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
2763 	AcpiOsFree(buf->Pointer);
2764 	buf->Pointer = newp;
2765 	buf->Length += buf->Length;
2766     }
2767 
2768     /* Insert the new resource. */
2769     bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
2770 
2771     /* And add the terminator. */
2772     rp = ACPI_NEXT_RESOURCE(rp);
2773     rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2774     rp->Length = ACPI_RS_SIZE_MIN;
2775 
2776     return (AE_OK);
2777 }
2778 
2779 UINT64
2780 acpi_DSMQuery(ACPI_HANDLE h, const uint8_t *uuid, int revision)
2781 {
2782     /*
2783      * ACPI spec 9.1.1 defines this.
2784      *
2785      * "Arg2: Function Index Represents a specific function whose meaning is
2786      * specific to the UUID and Revision ID. Function indices should start
2787      * with 1. Function number zero is a query function (see the special
2788      * return code defined below)."
2789      */
2790     ACPI_BUFFER buf;
2791     ACPI_OBJECT *obj;
2792     UINT64 ret = 0;
2793     int i;
2794 
2795     if (!ACPI_SUCCESS(acpi_EvaluateDSM(h, uuid, revision, 0, NULL, &buf))) {
2796 	ACPI_INFO(("Failed to enumerate DSM functions\n"));
2797 	return (0);
2798     }
2799 
2800     obj = (ACPI_OBJECT *)buf.Pointer;
2801     KASSERT(obj, ("Object not allowed to be NULL\n"));
2802 
2803     /*
2804      * From ACPI 6.2 spec 9.1.1:
2805      * If Function Index = 0, a Buffer containing a function index bitfield.
2806      * Otherwise, the return value and type depends on the UUID and revision
2807      * ID (see below).
2808      */
2809     switch (obj->Type) {
2810     case ACPI_TYPE_BUFFER:
2811 	for (i = 0; i < MIN(obj->Buffer.Length, sizeof(ret)); i++)
2812 	    ret |= (((uint64_t)obj->Buffer.Pointer[i]) << (i * 8));
2813 	break;
2814     case ACPI_TYPE_INTEGER:
2815 	ACPI_BIOS_WARNING((AE_INFO,
2816 	    "Possibly buggy BIOS with ACPI_TYPE_INTEGER for function enumeration\n"));
2817 	ret = obj->Integer.Value;
2818 	break;
2819     default:
2820 	ACPI_WARNING((AE_INFO, "Unexpected return type %u\n", obj->Type));
2821     };
2822 
2823     AcpiOsFree(obj);
2824     return ret;
2825 }
2826 
2827 /*
2828  * DSM may return multiple types depending on the function. It is therefore
2829  * unsafe to use the typed evaluation. It is highly recommended that the caller
2830  * check the type of the returned object.
2831  */
2832 ACPI_STATUS
2833 acpi_EvaluateDSM(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
2834     UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf)
2835 {
2836 	return (acpi_EvaluateDSMTyped(handle, uuid, revision, function,
2837 	    package, out_buf, ACPI_TYPE_ANY));
2838 }
2839 
2840 ACPI_STATUS
2841 acpi_EvaluateDSMTyped(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
2842     UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf,
2843     ACPI_OBJECT_TYPE type)
2844 {
2845     ACPI_OBJECT arg[4];
2846     ACPI_OBJECT_LIST arglist;
2847     ACPI_BUFFER buf;
2848     ACPI_STATUS status;
2849 
2850     if (out_buf == NULL)
2851 	return (AE_NO_MEMORY);
2852 
2853     arg[0].Type = ACPI_TYPE_BUFFER;
2854     arg[0].Buffer.Length = ACPI_UUID_LENGTH;
2855     arg[0].Buffer.Pointer = __DECONST(uint8_t *, uuid);
2856     arg[1].Type = ACPI_TYPE_INTEGER;
2857     arg[1].Integer.Value = revision;
2858     arg[2].Type = ACPI_TYPE_INTEGER;
2859     arg[2].Integer.Value = function;
2860     if (package) {
2861 	arg[3] = *package;
2862     } else {
2863 	arg[3].Type = ACPI_TYPE_PACKAGE;
2864 	arg[3].Package.Count = 0;
2865 	arg[3].Package.Elements = NULL;
2866     }
2867 
2868     arglist.Pointer = arg;
2869     arglist.Count = 4;
2870     buf.Pointer = NULL;
2871     buf.Length = ACPI_ALLOCATE_BUFFER;
2872     status = AcpiEvaluateObjectTyped(handle, "_DSM", &arglist, &buf, type);
2873     if (ACPI_FAILURE(status))
2874 	return (status);
2875 
2876     KASSERT(ACPI_SUCCESS(status), ("Unexpected status"));
2877 
2878     *out_buf = buf;
2879     return (status);
2880 }
2881 
2882 ACPI_STATUS
2883 acpi_EvaluateOSC(ACPI_HANDLE handle, uint8_t *uuid, int revision, int count,
2884     uint32_t *caps_in, uint32_t *caps_out, bool query)
2885 {
2886 	ACPI_OBJECT arg[4], *ret;
2887 	ACPI_OBJECT_LIST arglist;
2888 	ACPI_BUFFER buf;
2889 	ACPI_STATUS status;
2890 
2891 	arglist.Pointer = arg;
2892 	arglist.Count = 4;
2893 	arg[0].Type = ACPI_TYPE_BUFFER;
2894 	arg[0].Buffer.Length = ACPI_UUID_LENGTH;
2895 	arg[0].Buffer.Pointer = uuid;
2896 	arg[1].Type = ACPI_TYPE_INTEGER;
2897 	arg[1].Integer.Value = revision;
2898 	arg[2].Type = ACPI_TYPE_INTEGER;
2899 	arg[2].Integer.Value = count;
2900 	arg[3].Type = ACPI_TYPE_BUFFER;
2901 	arg[3].Buffer.Length = count * sizeof(*caps_in);
2902 	arg[3].Buffer.Pointer = (uint8_t *)caps_in;
2903 	caps_in[0] = query ? 1 : 0;
2904 	buf.Pointer = NULL;
2905 	buf.Length = ACPI_ALLOCATE_BUFFER;
2906 	status = AcpiEvaluateObjectTyped(handle, "_OSC", &arglist, &buf,
2907 	    ACPI_TYPE_BUFFER);
2908 	if (ACPI_FAILURE(status))
2909 		return (status);
2910 	if (caps_out != NULL) {
2911 		ret = buf.Pointer;
2912 		if (ret->Buffer.Length != count * sizeof(*caps_out)) {
2913 			AcpiOsFree(buf.Pointer);
2914 			return (AE_BUFFER_OVERFLOW);
2915 		}
2916 		bcopy(ret->Buffer.Pointer, caps_out, ret->Buffer.Length);
2917 	}
2918 	AcpiOsFree(buf.Pointer);
2919 	return (status);
2920 }
2921 
2922 /*
2923  * Set interrupt model.
2924  */
2925 ACPI_STATUS
2926 acpi_SetIntrModel(int model)
2927 {
2928 
2929     return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
2930 }
2931 
2932 /*
2933  * Walk subtables of a table and call a callback routine for each
2934  * subtable.  The caller should provide the first subtable and a
2935  * pointer to the end of the table.  This can be used to walk tables
2936  * such as MADT and SRAT that use subtable entries.
2937  */
2938 void
2939 acpi_walk_subtables(void *first, void *end, acpi_subtable_handler *handler,
2940     void *arg)
2941 {
2942     ACPI_SUBTABLE_HEADER *entry;
2943 
2944     for (entry = first; (void *)entry < end; ) {
2945 	/* Avoid an infinite loop if we hit a bogus entry. */
2946 	if (entry->Length < sizeof(ACPI_SUBTABLE_HEADER))
2947 	    return;
2948 
2949 	handler(entry, arg);
2950 	entry = ACPI_ADD_PTR(ACPI_SUBTABLE_HEADER, entry, entry->Length);
2951     }
2952 }
2953 
2954 /*
2955  * DEPRECATED.  This interface has serious deficiencies and will be
2956  * removed.
2957  *
2958  * Immediately enter the sleep state.  In the old model, acpiconf(8) ran
2959  * rc.suspend and rc.resume so we don't have to notify devd(8) to do this.
2960  */
2961 ACPI_STATUS
2962 acpi_SetSleepState(struct acpi_softc *sc, int state)
2963 {
2964     static int once;
2965 
2966     if (!once) {
2967 	device_printf(sc->acpi_dev,
2968 "warning: acpi_SetSleepState() deprecated, need to update your software\n");
2969 	once = 1;
2970     }
2971     return (acpi_EnterSleepState(sc, state));
2972 }
2973 
2974 #if defined(__amd64__) || defined(__i386__)
2975 static void
2976 acpi_sleep_force_task(void *context)
2977 {
2978     struct acpi_softc *sc = (struct acpi_softc *)context;
2979 
2980     if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
2981 	device_printf(sc->acpi_dev, "force sleep state S%d failed\n",
2982 	    sc->acpi_next_sstate);
2983 }
2984 
2985 static void
2986 acpi_sleep_force(void *arg)
2987 {
2988     struct acpi_softc *sc = (struct acpi_softc *)arg;
2989 
2990     device_printf(sc->acpi_dev,
2991 	"suspend request timed out, forcing sleep now\n");
2992     /*
2993      * XXX Suspending from callout causes freezes in DEVICE_SUSPEND().
2994      * Suspend from acpi_task thread instead.
2995      */
2996     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
2997 	acpi_sleep_force_task, sc)))
2998 	device_printf(sc->acpi_dev, "AcpiOsExecute() for sleeping failed\n");
2999 }
3000 #endif
3001 
3002 /*
3003  * Request that the system enter the given suspend state.  All /dev/apm
3004  * devices and devd(8) will be notified.  Userland then has a chance to
3005  * save state and acknowledge the request.  The system sleeps once all
3006  * acks are in.
3007  */
3008 int
3009 acpi_ReqSleepState(struct acpi_softc *sc, int state)
3010 {
3011 #if defined(__amd64__) || defined(__i386__)
3012     struct apm_clone_data *clone;
3013     ACPI_STATUS status;
3014 
3015     if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
3016 	return (EINVAL);
3017     if (!acpi_sleep_states[state])
3018 	return (EOPNOTSUPP);
3019 
3020     /*
3021      * If a reboot/shutdown/suspend request is already in progress or
3022      * suspend is blocked due to an upcoming shutdown, just return.
3023      */
3024     if (rebooting || sc->acpi_next_sstate != 0 || suspend_blocked) {
3025 	return (0);
3026     }
3027 
3028     /* Wait until sleep is enabled. */
3029     while (sc->acpi_sleep_disabled) {
3030 	AcpiOsSleep(1000);
3031     }
3032 
3033     ACPI_LOCK(acpi);
3034 
3035     sc->acpi_next_sstate = state;
3036 
3037     /* S5 (soft-off) should be entered directly with no waiting. */
3038     if (state == ACPI_STATE_S5) {
3039     	ACPI_UNLOCK(acpi);
3040 	status = acpi_EnterSleepState(sc, state);
3041 	return (ACPI_SUCCESS(status) ? 0 : ENXIO);
3042     }
3043 
3044     /* Record the pending state and notify all apm devices. */
3045     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
3046 	clone->notify_status = APM_EV_NONE;
3047 	if ((clone->flags & ACPI_EVF_DEVD) == 0) {
3048 	    selwakeuppri(&clone->sel_read, PZERO);
3049 	    KNOTE_LOCKED(&clone->sel_read.si_note, 0);
3050 	}
3051     }
3052 
3053     /* If devd(8) is not running, immediately enter the sleep state. */
3054     if (!devctl_process_running()) {
3055 	ACPI_UNLOCK(acpi);
3056 	status = acpi_EnterSleepState(sc, state);
3057 	return (ACPI_SUCCESS(status) ? 0 : ENXIO);
3058     }
3059 
3060     /*
3061      * Set a timeout to fire if userland doesn't ack the suspend request
3062      * in time.  This way we still eventually go to sleep if we were
3063      * overheating or running low on battery, even if userland is hung.
3064      * We cancel this timeout once all userland acks are in or the
3065      * suspend request is aborted.
3066      */
3067     callout_reset(&sc->susp_force_to, 10 * hz, acpi_sleep_force, sc);
3068     ACPI_UNLOCK(acpi);
3069 
3070     /* Now notify devd(8) also. */
3071     acpi_UserNotify("Suspend", ACPI_ROOT_OBJECT, state);
3072 
3073     return (0);
3074 #else
3075     /* This platform does not support acpi suspend/resume. */
3076     return (EOPNOTSUPP);
3077 #endif
3078 }
3079 
3080 /*
3081  * Acknowledge (or reject) a pending sleep state.  The caller has
3082  * prepared for suspend and is now ready for it to proceed.  If the
3083  * error argument is non-zero, it indicates suspend should be cancelled
3084  * and gives an errno value describing why.  Once all votes are in,
3085  * we suspend the system.
3086  */
3087 int
3088 acpi_AckSleepState(struct apm_clone_data *clone, int error)
3089 {
3090 #if defined(__amd64__) || defined(__i386__)
3091     struct acpi_softc *sc;
3092     int ret, sleeping;
3093 
3094     /* If no pending sleep state, return an error. */
3095     ACPI_LOCK(acpi);
3096     sc = clone->acpi_sc;
3097     if (sc->acpi_next_sstate == 0) {
3098     	ACPI_UNLOCK(acpi);
3099 	return (ENXIO);
3100     }
3101 
3102     /* Caller wants to abort suspend process. */
3103     if (error) {
3104 	sc->acpi_next_sstate = 0;
3105 	callout_stop(&sc->susp_force_to);
3106 	device_printf(sc->acpi_dev,
3107 	    "listener on %s cancelled the pending suspend\n",
3108 	    devtoname(clone->cdev));
3109     	ACPI_UNLOCK(acpi);
3110 	return (0);
3111     }
3112 
3113     /*
3114      * Mark this device as acking the suspend request.  Then, walk through
3115      * all devices, seeing if they agree yet.  We only count devices that
3116      * are writable since read-only devices couldn't ack the request.
3117      */
3118     sleeping = TRUE;
3119     clone->notify_status = APM_EV_ACKED;
3120     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
3121 	if ((clone->flags & ACPI_EVF_WRITE) != 0 &&
3122 	    clone->notify_status != APM_EV_ACKED) {
3123 	    sleeping = FALSE;
3124 	    break;
3125 	}
3126     }
3127 
3128     /* If all devices have voted "yes", we will suspend now. */
3129     if (sleeping)
3130 	callout_stop(&sc->susp_force_to);
3131     ACPI_UNLOCK(acpi);
3132     ret = 0;
3133     if (sleeping) {
3134 	if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
3135 		ret = ENODEV;
3136     }
3137     return (ret);
3138 #else
3139     /* This platform does not support acpi suspend/resume. */
3140     return (EOPNOTSUPP);
3141 #endif
3142 }
3143 
3144 static void
3145 acpi_sleep_enable(void *arg)
3146 {
3147     struct acpi_softc	*sc = (struct acpi_softc *)arg;
3148 
3149     ACPI_LOCK_ASSERT(acpi);
3150 
3151     /* Reschedule if the system is not fully up and running. */
3152     if (!AcpiGbl_SystemAwakeAndRunning) {
3153 	callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3154 	return;
3155     }
3156 
3157     sc->acpi_sleep_disabled = FALSE;
3158 }
3159 
3160 static ACPI_STATUS
3161 acpi_sleep_disable(struct acpi_softc *sc)
3162 {
3163     ACPI_STATUS		status;
3164 
3165     /* Fail if the system is not fully up and running. */
3166     if (!AcpiGbl_SystemAwakeAndRunning)
3167 	return (AE_ERROR);
3168 
3169     ACPI_LOCK(acpi);
3170     status = sc->acpi_sleep_disabled ? AE_ERROR : AE_OK;
3171     sc->acpi_sleep_disabled = TRUE;
3172     ACPI_UNLOCK(acpi);
3173 
3174     return (status);
3175 }
3176 
3177 enum acpi_sleep_state {
3178     ACPI_SS_NONE,
3179     ACPI_SS_GPE_SET,
3180     ACPI_SS_DEV_SUSPEND,
3181     ACPI_SS_SLP_PREP,
3182     ACPI_SS_SLEPT,
3183 };
3184 
3185 /*
3186  * Enter the desired system sleep state.
3187  *
3188  * Currently we support S1-S5 but S4 is only S4BIOS
3189  */
3190 static ACPI_STATUS
3191 acpi_EnterSleepState(struct acpi_softc *sc, int state)
3192 {
3193     register_t intr;
3194     ACPI_STATUS status;
3195     ACPI_EVENT_STATUS power_button_status;
3196     enum acpi_sleep_state slp_state;
3197     int sleep_result;
3198 
3199     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3200 
3201     if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
3202 	return_ACPI_STATUS (AE_BAD_PARAMETER);
3203     if (!acpi_sleep_states[state]) {
3204 	device_printf(sc->acpi_dev, "Sleep state S%d not supported by BIOS\n",
3205 	    state);
3206 	return (AE_SUPPORT);
3207     }
3208 
3209     /* Re-entry once we're suspending is not allowed. */
3210     status = acpi_sleep_disable(sc);
3211     if (ACPI_FAILURE(status)) {
3212 	device_printf(sc->acpi_dev,
3213 	    "suspend request ignored (not ready yet)\n");
3214 	return (status);
3215     }
3216 
3217     if (state == ACPI_STATE_S5) {
3218 	/*
3219 	 * Shut down cleanly and power off.  This will call us back through the
3220 	 * shutdown handlers.
3221 	 */
3222 	shutdown_nice(RB_POWEROFF);
3223 	return_ACPI_STATUS (AE_OK);
3224     }
3225 
3226     EVENTHANDLER_INVOKE(power_suspend_early);
3227     stop_all_proc();
3228     suspend_all_fs();
3229     EVENTHANDLER_INVOKE(power_suspend);
3230 
3231 #ifdef EARLY_AP_STARTUP
3232     MPASS(mp_ncpus == 1 || smp_started);
3233     thread_lock(curthread);
3234     sched_bind(curthread, 0);
3235     thread_unlock(curthread);
3236 #else
3237     if (smp_started) {
3238 	thread_lock(curthread);
3239 	sched_bind(curthread, 0);
3240 	thread_unlock(curthread);
3241     }
3242 #endif
3243 
3244     /*
3245      * Be sure to hold Giant across DEVICE_SUSPEND/RESUME
3246      */
3247     bus_topo_lock();
3248 
3249     slp_state = ACPI_SS_NONE;
3250 
3251     sc->acpi_sstate = state;
3252 
3253     /* Enable any GPEs as appropriate and requested by the user. */
3254     acpi_wake_prep_walk(state);
3255     slp_state = ACPI_SS_GPE_SET;
3256 
3257     /*
3258      * Inform all devices that we are going to sleep.  If at least one
3259      * device fails, DEVICE_SUSPEND() automatically resumes the tree.
3260      *
3261      * XXX Note that a better two-pass approach with a 'veto' pass
3262      * followed by a "real thing" pass would be better, but the current
3263      * bus interface does not provide for this.
3264      */
3265     if (DEVICE_SUSPEND(root_bus) != 0) {
3266 	device_printf(sc->acpi_dev, "device_suspend failed\n");
3267 	goto backout;
3268     }
3269     slp_state = ACPI_SS_DEV_SUSPEND;
3270 
3271     status = AcpiEnterSleepStatePrep(state);
3272     if (ACPI_FAILURE(status)) {
3273 	device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
3274 		      AcpiFormatException(status));
3275 	goto backout;
3276     }
3277     slp_state = ACPI_SS_SLP_PREP;
3278 
3279     if (sc->acpi_sleep_delay > 0)
3280 	DELAY(sc->acpi_sleep_delay * 1000000);
3281 
3282     suspendclock();
3283     intr = intr_disable();
3284     if (state != ACPI_STATE_S1) {
3285 	sleep_result = acpi_sleep_machdep(sc, state);
3286 	acpi_wakeup_machdep(sc, state, sleep_result, 0);
3287 
3288 	/*
3289 	 * XXX According to ACPI specification SCI_EN bit should be restored
3290 	 * by ACPI platform (BIOS, firmware) to its pre-sleep state.
3291 	 * Unfortunately some BIOSes fail to do that and that leads to
3292 	 * unexpected and serious consequences during wake up like a system
3293 	 * getting stuck in SMI handlers.
3294 	 * This hack is picked up from Linux, which claims that it follows
3295 	 * Windows behavior.
3296 	 */
3297 	if (sleep_result == 1 && state != ACPI_STATE_S4)
3298 	    AcpiWriteBitRegister(ACPI_BITREG_SCI_ENABLE, ACPI_ENABLE_EVENT);
3299 
3300 	if (sleep_result == 1 && state == ACPI_STATE_S3) {
3301 	    /*
3302 	     * Prevent mis-interpretation of the wakeup by power button
3303 	     * as a request for power off.
3304 	     * Ideally we should post an appropriate wakeup event,
3305 	     * perhaps using acpi_event_power_button_wake or alike.
3306 	     *
3307 	     * Clearing of power button status after wakeup is mandated
3308 	     * by ACPI specification in section "Fixed Power Button".
3309 	     *
3310 	     * XXX As of ACPICA 20121114 AcpiGetEventStatus provides
3311 	     * status as 0/1 corressponding to inactive/active despite
3312 	     * its type being ACPI_EVENT_STATUS.  In other words,
3313 	     * we should not test for ACPI_EVENT_FLAG_SET for time being.
3314 	     */
3315 	    if (ACPI_SUCCESS(AcpiGetEventStatus(ACPI_EVENT_POWER_BUTTON,
3316 		&power_button_status)) && power_button_status != 0) {
3317 		AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
3318 		device_printf(sc->acpi_dev,
3319 		    "cleared fixed power button status\n");
3320 	    }
3321 	}
3322 
3323 	intr_restore(intr);
3324 
3325 	/* call acpi_wakeup_machdep() again with interrupt enabled */
3326 	acpi_wakeup_machdep(sc, state, sleep_result, 1);
3327 
3328 	AcpiLeaveSleepStatePrep(state);
3329 
3330 	if (sleep_result == -1)
3331 		goto backout;
3332 
3333 	/* Re-enable ACPI hardware on wakeup from sleep state 4. */
3334 	if (state == ACPI_STATE_S4)
3335 	    AcpiEnable();
3336     } else {
3337 	status = AcpiEnterSleepState(state);
3338 	intr_restore(intr);
3339 	AcpiLeaveSleepStatePrep(state);
3340 	if (ACPI_FAILURE(status)) {
3341 	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
3342 			  AcpiFormatException(status));
3343 	    goto backout;
3344 	}
3345     }
3346     slp_state = ACPI_SS_SLEPT;
3347 
3348     /*
3349      * Back out state according to how far along we got in the suspend
3350      * process.  This handles both the error and success cases.
3351      */
3352 backout:
3353     if (slp_state >= ACPI_SS_SLP_PREP)
3354 	resumeclock();
3355     if (slp_state >= ACPI_SS_GPE_SET) {
3356 	acpi_wake_prep_walk(state);
3357 	sc->acpi_sstate = ACPI_STATE_S0;
3358     }
3359     if (slp_state >= ACPI_SS_DEV_SUSPEND)
3360 	DEVICE_RESUME(root_bus);
3361     if (slp_state >= ACPI_SS_SLP_PREP)
3362 	AcpiLeaveSleepState(state);
3363     if (slp_state >= ACPI_SS_SLEPT) {
3364 #if defined(__i386__) || defined(__amd64__)
3365 	/* NB: we are still using ACPI timecounter at this point. */
3366 	resume_TSC();
3367 #endif
3368 	acpi_resync_clock(sc);
3369 	acpi_enable_fixed_events(sc);
3370     }
3371     sc->acpi_next_sstate = 0;
3372 
3373     bus_topo_unlock();
3374 
3375 #ifdef EARLY_AP_STARTUP
3376     thread_lock(curthread);
3377     sched_unbind(curthread);
3378     thread_unlock(curthread);
3379 #else
3380     if (smp_started) {
3381 	thread_lock(curthread);
3382 	sched_unbind(curthread);
3383 	thread_unlock(curthread);
3384     }
3385 #endif
3386 
3387     resume_all_fs();
3388     resume_all_proc();
3389 
3390     EVENTHANDLER_INVOKE(power_resume);
3391 
3392     /* Allow another sleep request after a while. */
3393     callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3394 
3395     /* Run /etc/rc.resume after we are back. */
3396     if (devctl_process_running())
3397 	acpi_UserNotify("Resume", ACPI_ROOT_OBJECT, state);
3398 
3399     return_ACPI_STATUS (status);
3400 }
3401 
3402 static void
3403 acpi_resync_clock(struct acpi_softc *sc)
3404 {
3405 
3406     /*
3407      * Warm up timecounter again and reset system clock.
3408      */
3409     (void)timecounter->tc_get_timecount(timecounter);
3410     inittodr(time_second + sc->acpi_sleep_delay);
3411 }
3412 
3413 /* Enable or disable the device's wake GPE. */
3414 int
3415 acpi_wake_set_enable(device_t dev, int enable)
3416 {
3417     struct acpi_prw_data prw;
3418     ACPI_STATUS status;
3419     int flags;
3420 
3421     /* Make sure the device supports waking the system and get the GPE. */
3422     if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
3423 	return (ENXIO);
3424 
3425     flags = acpi_get_flags(dev);
3426     if (enable) {
3427 	status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3428 	    ACPI_GPE_ENABLE);
3429 	if (ACPI_FAILURE(status)) {
3430 	    device_printf(dev, "enable wake failed\n");
3431 	    return (ENXIO);
3432 	}
3433 	acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
3434     } else {
3435 	status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3436 	    ACPI_GPE_DISABLE);
3437 	if (ACPI_FAILURE(status)) {
3438 	    device_printf(dev, "disable wake failed\n");
3439 	    return (ENXIO);
3440 	}
3441 	acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
3442     }
3443 
3444     return (0);
3445 }
3446 
3447 static int
3448 acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate)
3449 {
3450     struct acpi_prw_data prw;
3451     device_t dev;
3452 
3453     /* Check that this is a wake-capable device and get its GPE. */
3454     if (acpi_parse_prw(handle, &prw) != 0)
3455 	return (ENXIO);
3456     dev = acpi_get_device(handle);
3457 
3458     /*
3459      * The destination sleep state must be less than (i.e., higher power)
3460      * or equal to the value specified by _PRW.  If this GPE cannot be
3461      * enabled for the next sleep state, then disable it.  If it can and
3462      * the user requested it be enabled, turn on any required power resources
3463      * and set _PSW.
3464      */
3465     if (sstate > prw.lowest_wake) {
3466 	AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_DISABLE);
3467 	if (bootverbose)
3468 	    device_printf(dev, "wake_prep disabled wake for %s (S%d)\n",
3469 		acpi_name(handle), sstate);
3470     } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
3471 	acpi_pwr_wake_enable(handle, 1);
3472 	acpi_SetInteger(handle, "_PSW", 1);
3473 	if (bootverbose)
3474 	    device_printf(dev, "wake_prep enabled for %s (S%d)\n",
3475 		acpi_name(handle), sstate);
3476     }
3477 
3478     return (0);
3479 }
3480 
3481 static int
3482 acpi_wake_run_prep(ACPI_HANDLE handle, int sstate)
3483 {
3484     struct acpi_prw_data prw;
3485     device_t dev;
3486 
3487     /*
3488      * Check that this is a wake-capable device and get its GPE.  Return
3489      * now if the user didn't enable this device for wake.
3490      */
3491     if (acpi_parse_prw(handle, &prw) != 0)
3492 	return (ENXIO);
3493     dev = acpi_get_device(handle);
3494     if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
3495 	return (0);
3496 
3497     /*
3498      * If this GPE couldn't be enabled for the previous sleep state, it was
3499      * disabled before going to sleep so re-enable it.  If it was enabled,
3500      * clear _PSW and turn off any power resources it used.
3501      */
3502     if (sstate > prw.lowest_wake) {
3503 	AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_ENABLE);
3504 	if (bootverbose)
3505 	    device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
3506     } else {
3507 	acpi_SetInteger(handle, "_PSW", 0);
3508 	acpi_pwr_wake_enable(handle, 0);
3509 	if (bootverbose)
3510 	    device_printf(dev, "run_prep cleaned up for %s\n",
3511 		acpi_name(handle));
3512     }
3513 
3514     return (0);
3515 }
3516 
3517 static ACPI_STATUS
3518 acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
3519 {
3520     int sstate;
3521 
3522     /* If suspending, run the sleep prep function, otherwise wake. */
3523     sstate = *(int *)context;
3524     if (AcpiGbl_SystemAwakeAndRunning)
3525 	acpi_wake_sleep_prep(handle, sstate);
3526     else
3527 	acpi_wake_run_prep(handle, sstate);
3528     return (AE_OK);
3529 }
3530 
3531 /* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
3532 static int
3533 acpi_wake_prep_walk(int sstate)
3534 {
3535     ACPI_HANDLE sb_handle;
3536 
3537     if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
3538 	AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
3539 	    acpi_wake_prep, NULL, &sstate, NULL);
3540     return (0);
3541 }
3542 
3543 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
3544 static int
3545 acpi_wake_sysctl_walk(device_t dev)
3546 {
3547     int error, i, numdevs;
3548     device_t *devlist;
3549     device_t child;
3550     ACPI_STATUS status;
3551 
3552     error = device_get_children(dev, &devlist, &numdevs);
3553     if (error != 0 || numdevs == 0) {
3554 	if (numdevs == 0)
3555 	    free(devlist, M_TEMP);
3556 	return (error);
3557     }
3558     for (i = 0; i < numdevs; i++) {
3559 	child = devlist[i];
3560 	acpi_wake_sysctl_walk(child);
3561 	if (!device_is_attached(child))
3562 	    continue;
3563 	status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
3564 	if (ACPI_SUCCESS(status)) {
3565 	    SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
3566 		SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
3567 		"wake", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, child, 0,
3568 		acpi_wake_set_sysctl, "I", "Device set to wake the system");
3569 	}
3570     }
3571     free(devlist, M_TEMP);
3572 
3573     return (0);
3574 }
3575 
3576 /* Enable or disable wake from userland. */
3577 static int
3578 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
3579 {
3580     int enable, error;
3581     device_t dev;
3582 
3583     dev = (device_t)arg1;
3584     enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
3585 
3586     error = sysctl_handle_int(oidp, &enable, 0, req);
3587     if (error != 0 || req->newptr == NULL)
3588 	return (error);
3589     if (enable != 0 && enable != 1)
3590 	return (EINVAL);
3591 
3592     return (acpi_wake_set_enable(dev, enable));
3593 }
3594 
3595 /* Parse a device's _PRW into a structure. */
3596 int
3597 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
3598 {
3599     ACPI_STATUS			status;
3600     ACPI_BUFFER			prw_buffer;
3601     ACPI_OBJECT			*res, *res2;
3602     int				error, i, power_count;
3603 
3604     if (h == NULL || prw == NULL)
3605 	return (EINVAL);
3606 
3607     /*
3608      * The _PRW object (7.2.9) is only required for devices that have the
3609      * ability to wake the system from a sleeping state.
3610      */
3611     error = EINVAL;
3612     prw_buffer.Pointer = NULL;
3613     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
3614     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
3615     if (ACPI_FAILURE(status))
3616 	return (ENOENT);
3617     res = (ACPI_OBJECT *)prw_buffer.Pointer;
3618     if (res == NULL)
3619 	return (ENOENT);
3620     if (!ACPI_PKG_VALID(res, 2))
3621 	goto out;
3622 
3623     /*
3624      * Element 1 of the _PRW object:
3625      * The lowest power system sleeping state that can be entered while still
3626      * providing wake functionality.  The sleeping state being entered must
3627      * be less than (i.e., higher power) or equal to this value.
3628      */
3629     if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
3630 	goto out;
3631 
3632     /*
3633      * Element 0 of the _PRW object:
3634      */
3635     switch (res->Package.Elements[0].Type) {
3636     case ACPI_TYPE_INTEGER:
3637 	/*
3638 	 * If the data type of this package element is numeric, then this
3639 	 * _PRW package element is the bit index in the GPEx_EN, in the
3640 	 * GPE blocks described in the FADT, of the enable bit that is
3641 	 * enabled for the wake event.
3642 	 */
3643 	prw->gpe_handle = NULL;
3644 	prw->gpe_bit = res->Package.Elements[0].Integer.Value;
3645 	error = 0;
3646 	break;
3647     case ACPI_TYPE_PACKAGE:
3648 	/*
3649 	 * If the data type of this package element is a package, then this
3650 	 * _PRW package element is itself a package containing two
3651 	 * elements.  The first is an object reference to the GPE Block
3652 	 * device that contains the GPE that will be triggered by the wake
3653 	 * event.  The second element is numeric and it contains the bit
3654 	 * index in the GPEx_EN, in the GPE Block referenced by the
3655 	 * first element in the package, of the enable bit that is enabled for
3656 	 * the wake event.
3657 	 *
3658 	 * For example, if this field is a package then it is of the form:
3659 	 * Package() {\_SB.PCI0.ISA.GPE, 2}
3660 	 */
3661 	res2 = &res->Package.Elements[0];
3662 	if (!ACPI_PKG_VALID(res2, 2))
3663 	    goto out;
3664 	prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
3665 	if (prw->gpe_handle == NULL)
3666 	    goto out;
3667 	if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
3668 	    goto out;
3669 	error = 0;
3670 	break;
3671     default:
3672 	goto out;
3673     }
3674 
3675     /* Elements 2 to N of the _PRW object are power resources. */
3676     power_count = res->Package.Count - 2;
3677     if (power_count > ACPI_PRW_MAX_POWERRES) {
3678 	printf("ACPI device %s has too many power resources\n", acpi_name(h));
3679 	power_count = 0;
3680     }
3681     prw->power_res_count = power_count;
3682     for (i = 0; i < power_count; i++)
3683 	prw->power_res[i] = res->Package.Elements[i];
3684 
3685 out:
3686     if (prw_buffer.Pointer != NULL)
3687 	AcpiOsFree(prw_buffer.Pointer);
3688     return (error);
3689 }
3690 
3691 /*
3692  * ACPI Event Handlers
3693  */
3694 
3695 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
3696 
3697 static void
3698 acpi_system_eventhandler_sleep(void *arg, int state)
3699 {
3700     struct acpi_softc *sc = (struct acpi_softc *)arg;
3701     int ret;
3702 
3703     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3704 
3705     /* Check if button action is disabled or unknown. */
3706     if (state == ACPI_STATE_UNKNOWN)
3707 	return;
3708 
3709     /* Request that the system prepare to enter the given suspend state. */
3710     ret = acpi_ReqSleepState(sc, state);
3711     if (ret != 0)
3712 	device_printf(sc->acpi_dev,
3713 	    "request to enter state S%d failed (err %d)\n", state, ret);
3714 
3715     return_VOID;
3716 }
3717 
3718 static void
3719 acpi_system_eventhandler_wakeup(void *arg, int state)
3720 {
3721 
3722     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3723 
3724     /* Currently, nothing to do for wakeup. */
3725 
3726     return_VOID;
3727 }
3728 
3729 /*
3730  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
3731  */
3732 static void
3733 acpi_invoke_sleep_eventhandler(void *context)
3734 {
3735 
3736     EVENTHANDLER_INVOKE(acpi_sleep_event, *(int *)context);
3737 }
3738 
3739 static void
3740 acpi_invoke_wake_eventhandler(void *context)
3741 {
3742 
3743     EVENTHANDLER_INVOKE(acpi_wakeup_event, *(int *)context);
3744 }
3745 
3746 UINT32
3747 acpi_event_power_button_sleep(void *context)
3748 {
3749     struct acpi_softc	*sc = (struct acpi_softc *)context;
3750 
3751     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3752 
3753     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3754 	acpi_invoke_sleep_eventhandler, &sc->acpi_power_button_sx)))
3755 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3756     return_VALUE (ACPI_INTERRUPT_HANDLED);
3757 }
3758 
3759 UINT32
3760 acpi_event_power_button_wake(void *context)
3761 {
3762     struct acpi_softc	*sc = (struct acpi_softc *)context;
3763 
3764     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3765 
3766     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3767 	acpi_invoke_wake_eventhandler, &sc->acpi_power_button_sx)))
3768 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3769     return_VALUE (ACPI_INTERRUPT_HANDLED);
3770 }
3771 
3772 UINT32
3773 acpi_event_sleep_button_sleep(void *context)
3774 {
3775     struct acpi_softc	*sc = (struct acpi_softc *)context;
3776 
3777     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3778 
3779     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3780 	acpi_invoke_sleep_eventhandler, &sc->acpi_sleep_button_sx)))
3781 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3782     return_VALUE (ACPI_INTERRUPT_HANDLED);
3783 }
3784 
3785 UINT32
3786 acpi_event_sleep_button_wake(void *context)
3787 {
3788     struct acpi_softc	*sc = (struct acpi_softc *)context;
3789 
3790     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3791 
3792     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3793 	acpi_invoke_wake_eventhandler, &sc->acpi_sleep_button_sx)))
3794 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3795     return_VALUE (ACPI_INTERRUPT_HANDLED);
3796 }
3797 
3798 /*
3799  * XXX This static buffer is suboptimal.  There is no locking so only
3800  * use this for single-threaded callers.
3801  */
3802 char *
3803 acpi_name(ACPI_HANDLE handle)
3804 {
3805     ACPI_BUFFER buf;
3806     static char data[256];
3807 
3808     buf.Length = sizeof(data);
3809     buf.Pointer = data;
3810 
3811     if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
3812 	return (data);
3813     return ("(unknown)");
3814 }
3815 
3816 /*
3817  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
3818  * parts of the namespace.
3819  */
3820 int
3821 acpi_avoid(ACPI_HANDLE handle)
3822 {
3823     char	*cp, *env, *np;
3824     int		len;
3825 
3826     np = acpi_name(handle);
3827     if (*np == '\\')
3828 	np++;
3829     if ((env = kern_getenv("debug.acpi.avoid")) == NULL)
3830 	return (0);
3831 
3832     /* Scan the avoid list checking for a match */
3833     cp = env;
3834     for (;;) {
3835 	while (*cp != 0 && isspace(*cp))
3836 	    cp++;
3837 	if (*cp == 0)
3838 	    break;
3839 	len = 0;
3840 	while (cp[len] != 0 && !isspace(cp[len]))
3841 	    len++;
3842 	if (!strncmp(cp, np, len)) {
3843 	    freeenv(env);
3844 	    return(1);
3845 	}
3846 	cp += len;
3847     }
3848     freeenv(env);
3849 
3850     return (0);
3851 }
3852 
3853 /*
3854  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
3855  */
3856 int
3857 acpi_disabled(char *subsys)
3858 {
3859     char	*cp, *env;
3860     int		len;
3861 
3862     if ((env = kern_getenv("debug.acpi.disabled")) == NULL)
3863 	return (0);
3864     if (strcmp(env, "all") == 0) {
3865 	freeenv(env);
3866 	return (1);
3867     }
3868 
3869     /* Scan the disable list, checking for a match. */
3870     cp = env;
3871     for (;;) {
3872 	while (*cp != '\0' && isspace(*cp))
3873 	    cp++;
3874 	if (*cp == '\0')
3875 	    break;
3876 	len = 0;
3877 	while (cp[len] != '\0' && !isspace(cp[len]))
3878 	    len++;
3879 	if (strncmp(cp, subsys, len) == 0) {
3880 	    freeenv(env);
3881 	    return (1);
3882 	}
3883 	cp += len;
3884     }
3885     freeenv(env);
3886 
3887     return (0);
3888 }
3889 
3890 static void
3891 acpi_lookup(void *arg, const char *name, device_t *dev)
3892 {
3893     ACPI_HANDLE handle;
3894 
3895     if (*dev != NULL)
3896 	return;
3897 
3898     /*
3899      * Allow any handle name that is specified as an absolute path and
3900      * starts with '\'.  We could restrict this to \_SB and friends,
3901      * but see acpi_probe_children() for notes on why we scan the entire
3902      * namespace for devices.
3903      *
3904      * XXX: The pathname argument to AcpiGetHandle() should be fixed to
3905      * be const.
3906      */
3907     if (name[0] != '\\')
3908 	return;
3909     if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, __DECONST(char *, name),
3910 	&handle)))
3911 	return;
3912     *dev = acpi_get_device(handle);
3913 }
3914 
3915 /*
3916  * Control interface.
3917  *
3918  * We multiplex ioctls for all participating ACPI devices here.  Individual
3919  * drivers wanting to be accessible via /dev/acpi should use the
3920  * register/deregister interface to make their handlers visible.
3921  */
3922 struct acpi_ioctl_hook
3923 {
3924     TAILQ_ENTRY(acpi_ioctl_hook) link;
3925     u_long			 cmd;
3926     acpi_ioctl_fn		 fn;
3927     void			 *arg;
3928 };
3929 
3930 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
3931 static int				acpi_ioctl_hooks_initted;
3932 
3933 int
3934 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
3935 {
3936     struct acpi_ioctl_hook	*hp;
3937 
3938     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
3939 	return (ENOMEM);
3940     hp->cmd = cmd;
3941     hp->fn = fn;
3942     hp->arg = arg;
3943 
3944     ACPI_LOCK(acpi);
3945     if (acpi_ioctl_hooks_initted == 0) {
3946 	TAILQ_INIT(&acpi_ioctl_hooks);
3947 	acpi_ioctl_hooks_initted = 1;
3948     }
3949     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
3950     ACPI_UNLOCK(acpi);
3951 
3952     return (0);
3953 }
3954 
3955 void
3956 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
3957 {
3958     struct acpi_ioctl_hook	*hp;
3959 
3960     ACPI_LOCK(acpi);
3961     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
3962 	if (hp->cmd == cmd && hp->fn == fn)
3963 	    break;
3964 
3965     if (hp != NULL) {
3966 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
3967 	free(hp, M_ACPIDEV);
3968     }
3969     ACPI_UNLOCK(acpi);
3970 }
3971 
3972 static int
3973 acpiopen(struct cdev *dev, int flag, int fmt, struct thread *td)
3974 {
3975     return (0);
3976 }
3977 
3978 static int
3979 acpiclose(struct cdev *dev, int flag, int fmt, struct thread *td)
3980 {
3981     return (0);
3982 }
3983 
3984 static int
3985 acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
3986 {
3987     struct acpi_softc		*sc;
3988     struct acpi_ioctl_hook	*hp;
3989     int				error, state;
3990 
3991     error = 0;
3992     hp = NULL;
3993     sc = dev->si_drv1;
3994 
3995     /*
3996      * Scan the list of registered ioctls, looking for handlers.
3997      */
3998     ACPI_LOCK(acpi);
3999     if (acpi_ioctl_hooks_initted)
4000 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
4001 	    if (hp->cmd == cmd)
4002 		break;
4003 	}
4004     ACPI_UNLOCK(acpi);
4005     if (hp)
4006 	return (hp->fn(cmd, addr, hp->arg));
4007 
4008     /*
4009      * Core ioctls are not permitted for non-writable user.
4010      * Currently, other ioctls just fetch information.
4011      * Not changing system behavior.
4012      */
4013     if ((flag & FWRITE) == 0)
4014 	return (EPERM);
4015 
4016     /* Core system ioctls. */
4017     switch (cmd) {
4018     case ACPIIO_REQSLPSTATE:
4019 	state = *(int *)addr;
4020 	if (state != ACPI_STATE_S5)
4021 	    return (acpi_ReqSleepState(sc, state));
4022 	device_printf(sc->acpi_dev, "power off via acpi ioctl not supported\n");
4023 	error = EOPNOTSUPP;
4024 	break;
4025     case ACPIIO_ACKSLPSTATE:
4026 	error = *(int *)addr;
4027 	error = acpi_AckSleepState(sc->acpi_clone, error);
4028 	break;
4029     case ACPIIO_SETSLPSTATE:	/* DEPRECATED */
4030 	state = *(int *)addr;
4031 	if (state < ACPI_STATE_S0 || state > ACPI_S_STATES_MAX)
4032 	    return (EINVAL);
4033 	if (!acpi_sleep_states[state])
4034 	    return (EOPNOTSUPP);
4035 	if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
4036 	    error = ENXIO;
4037 	break;
4038     default:
4039 	error = ENXIO;
4040 	break;
4041     }
4042 
4043     return (error);
4044 }
4045 
4046 static int
4047 acpi_sname2sstate(const char *sname)
4048 {
4049     int sstate;
4050 
4051     if (toupper(sname[0]) == 'S') {
4052 	sstate = sname[1] - '0';
4053 	if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5 &&
4054 	    sname[2] == '\0')
4055 	    return (sstate);
4056     } else if (strcasecmp(sname, "NONE") == 0)
4057 	return (ACPI_STATE_UNKNOWN);
4058     return (-1);
4059 }
4060 
4061 static const char *
4062 acpi_sstate2sname(int sstate)
4063 {
4064     static const char *snames[] = { "S0", "S1", "S2", "S3", "S4", "S5" };
4065 
4066     if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5)
4067 	return (snames[sstate]);
4068     else if (sstate == ACPI_STATE_UNKNOWN)
4069 	return ("NONE");
4070     return (NULL);
4071 }
4072 
4073 static int
4074 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
4075 {
4076     int error;
4077     struct sbuf sb;
4078     UINT8 state;
4079 
4080     sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
4081     for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
4082 	if (acpi_sleep_states[state])
4083 	    sbuf_printf(&sb, "%s ", acpi_sstate2sname(state));
4084     sbuf_trim(&sb);
4085     sbuf_finish(&sb);
4086     error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
4087     sbuf_delete(&sb);
4088     return (error);
4089 }
4090 
4091 static int
4092 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
4093 {
4094     char sleep_state[10];
4095     int error, new_state, old_state;
4096 
4097     old_state = *(int *)oidp->oid_arg1;
4098     strlcpy(sleep_state, acpi_sstate2sname(old_state), sizeof(sleep_state));
4099     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
4100     if (error == 0 && req->newptr != NULL) {
4101 	new_state = acpi_sname2sstate(sleep_state);
4102 	if (new_state < ACPI_STATE_S1)
4103 	    return (EINVAL);
4104 	if (new_state < ACPI_S_STATE_COUNT && !acpi_sleep_states[new_state])
4105 	    return (EOPNOTSUPP);
4106 	if (new_state != old_state)
4107 	    *(int *)oidp->oid_arg1 = new_state;
4108     }
4109     return (error);
4110 }
4111 
4112 /* Inform devctl(4) when we receive a Notify. */
4113 void
4114 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
4115 {
4116     char		notify_buf[16];
4117     ACPI_BUFFER		handle_buf;
4118     ACPI_STATUS		status;
4119 
4120     if (subsystem == NULL)
4121 	return;
4122 
4123     handle_buf.Pointer = NULL;
4124     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
4125     status = AcpiNsHandleToPathname(h, &handle_buf, FALSE);
4126     if (ACPI_FAILURE(status))
4127 	return;
4128     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
4129     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
4130     AcpiOsFree(handle_buf.Pointer);
4131 }
4132 
4133 #ifdef ACPI_DEBUG
4134 /*
4135  * Support for parsing debug options from the kernel environment.
4136  *
4137  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
4138  * by specifying the names of the bits in the debug.acpi.layer and
4139  * debug.acpi.level environment variables.  Bits may be unset by
4140  * prefixing the bit name with !.
4141  */
4142 struct debugtag
4143 {
4144     char	*name;
4145     UINT32	value;
4146 };
4147 
4148 static struct debugtag	dbg_layer[] = {
4149     {"ACPI_UTILITIES",		ACPI_UTILITIES},
4150     {"ACPI_HARDWARE",		ACPI_HARDWARE},
4151     {"ACPI_EVENTS",		ACPI_EVENTS},
4152     {"ACPI_TABLES",		ACPI_TABLES},
4153     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
4154     {"ACPI_PARSER",		ACPI_PARSER},
4155     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
4156     {"ACPI_EXECUTER",		ACPI_EXECUTER},
4157     {"ACPI_RESOURCES",		ACPI_RESOURCES},
4158     {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
4159     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
4160     {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
4161     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
4162 
4163     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
4164     {"ACPI_BATTERY",		ACPI_BATTERY},
4165     {"ACPI_BUS",		ACPI_BUS},
4166     {"ACPI_BUTTON",		ACPI_BUTTON},
4167     {"ACPI_EC", 		ACPI_EC},
4168     {"ACPI_FAN",		ACPI_FAN},
4169     {"ACPI_POWERRES",		ACPI_POWERRES},
4170     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
4171     {"ACPI_THERMAL",		ACPI_THERMAL},
4172     {"ACPI_TIMER",		ACPI_TIMER},
4173     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
4174     {NULL, 0}
4175 };
4176 
4177 static struct debugtag dbg_level[] = {
4178     {"ACPI_LV_INIT",		ACPI_LV_INIT},
4179     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
4180     {"ACPI_LV_INFO",		ACPI_LV_INFO},
4181     {"ACPI_LV_REPAIR",		ACPI_LV_REPAIR},
4182     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
4183 
4184     /* Trace verbosity level 1 [Standard Trace Level] */
4185     {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
4186     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
4187     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
4188     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
4189     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
4190     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
4191     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
4192     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
4193     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
4194     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
4195     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
4196     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
4197     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
4198     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
4199     {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
4200 
4201     /* Trace verbosity level 2 [Function tracing and memory allocation] */
4202     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
4203     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
4204     {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
4205     {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
4206     {"ACPI_LV_ALL",		ACPI_LV_ALL},
4207 
4208     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
4209     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
4210     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
4211     {"ACPI_LV_IO",		ACPI_LV_IO},
4212     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
4213     {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
4214 
4215     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
4216     {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
4217     {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
4218     {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
4219     {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
4220     {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
4221     {NULL, 0}
4222 };
4223 
4224 static void
4225 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
4226 {
4227     char	*ep;
4228     int		i, l;
4229     int		set;
4230 
4231     while (*cp) {
4232 	if (isspace(*cp)) {
4233 	    cp++;
4234 	    continue;
4235 	}
4236 	ep = cp;
4237 	while (*ep && !isspace(*ep))
4238 	    ep++;
4239 	if (*cp == '!') {
4240 	    set = 0;
4241 	    cp++;
4242 	    if (cp == ep)
4243 		continue;
4244 	} else {
4245 	    set = 1;
4246 	}
4247 	l = ep - cp;
4248 	for (i = 0; tag[i].name != NULL; i++) {
4249 	    if (!strncmp(cp, tag[i].name, l)) {
4250 		if (set)
4251 		    *flag |= tag[i].value;
4252 		else
4253 		    *flag &= ~tag[i].value;
4254 	    }
4255 	}
4256 	cp = ep;
4257     }
4258 }
4259 
4260 static void
4261 acpi_set_debugging(void *junk)
4262 {
4263     char	*layer, *level;
4264 
4265     if (cold) {
4266 	AcpiDbgLayer = 0;
4267 	AcpiDbgLevel = 0;
4268     }
4269 
4270     layer = kern_getenv("debug.acpi.layer");
4271     level = kern_getenv("debug.acpi.level");
4272     if (layer == NULL && level == NULL)
4273 	return;
4274 
4275     printf("ACPI set debug");
4276     if (layer != NULL) {
4277 	if (strcmp("NONE", layer) != 0)
4278 	    printf(" layer '%s'", layer);
4279 	acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
4280 	freeenv(layer);
4281     }
4282     if (level != NULL) {
4283 	if (strcmp("NONE", level) != 0)
4284 	    printf(" level '%s'", level);
4285 	acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
4286 	freeenv(level);
4287     }
4288     printf("\n");
4289 }
4290 
4291 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
4292 	NULL);
4293 
4294 static int
4295 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
4296 {
4297     int		 error, *dbg;
4298     struct	 debugtag *tag;
4299     struct	 sbuf sb;
4300     char	 temp[128];
4301 
4302     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
4303 	return (ENOMEM);
4304     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
4305 	tag = &dbg_layer[0];
4306 	dbg = &AcpiDbgLayer;
4307     } else {
4308 	tag = &dbg_level[0];
4309 	dbg = &AcpiDbgLevel;
4310     }
4311 
4312     /* Get old values if this is a get request. */
4313     ACPI_SERIAL_BEGIN(acpi);
4314     if (*dbg == 0) {
4315 	sbuf_cpy(&sb, "NONE");
4316     } else if (req->newptr == NULL) {
4317 	for (; tag->name != NULL; tag++) {
4318 	    if ((*dbg & tag->value) == tag->value)
4319 		sbuf_printf(&sb, "%s ", tag->name);
4320 	}
4321     }
4322     sbuf_trim(&sb);
4323     sbuf_finish(&sb);
4324     strlcpy(temp, sbuf_data(&sb), sizeof(temp));
4325     sbuf_delete(&sb);
4326 
4327     error = sysctl_handle_string(oidp, temp, sizeof(temp), req);
4328 
4329     /* Check for error or no change */
4330     if (error == 0 && req->newptr != NULL) {
4331 	*dbg = 0;
4332 	kern_setenv((char *)oidp->oid_arg1, temp);
4333 	acpi_set_debugging(NULL);
4334     }
4335     ACPI_SERIAL_END(acpi);
4336 
4337     return (error);
4338 }
4339 
4340 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer,
4341     CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, "debug.acpi.layer", 0,
4342     acpi_debug_sysctl, "A",
4343     "");
4344 SYSCTL_PROC(_debug_acpi, OID_AUTO, level,
4345     CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, "debug.acpi.level", 0,
4346     acpi_debug_sysctl, "A",
4347     "");
4348 #endif /* ACPI_DEBUG */
4349 
4350 static int
4351 acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)
4352 {
4353 	int	error;
4354 	int	old;
4355 
4356 	old = acpi_debug_objects;
4357 	error = sysctl_handle_int(oidp, &acpi_debug_objects, 0, req);
4358 	if (error != 0 || req->newptr == NULL)
4359 		return (error);
4360 	if (old == acpi_debug_objects || (old && acpi_debug_objects))
4361 		return (0);
4362 
4363 	ACPI_SERIAL_BEGIN(acpi);
4364 	AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
4365 	ACPI_SERIAL_END(acpi);
4366 
4367 	return (0);
4368 }
4369 
4370 static int
4371 acpi_parse_interfaces(char *str, struct acpi_interface *iface)
4372 {
4373 	char *p;
4374 	size_t len;
4375 	int i, j;
4376 
4377 	p = str;
4378 	while (isspace(*p) || *p == ',')
4379 		p++;
4380 	len = strlen(p);
4381 	if (len == 0)
4382 		return (0);
4383 	p = strdup(p, M_TEMP);
4384 	for (i = 0; i < len; i++)
4385 		if (p[i] == ',')
4386 			p[i] = '\0';
4387 	i = j = 0;
4388 	while (i < len)
4389 		if (isspace(p[i]) || p[i] == '\0')
4390 			i++;
4391 		else {
4392 			i += strlen(p + i) + 1;
4393 			j++;
4394 		}
4395 	if (j == 0) {
4396 		free(p, M_TEMP);
4397 		return (0);
4398 	}
4399 	iface->data = malloc(sizeof(*iface->data) * j, M_TEMP, M_WAITOK);
4400 	iface->num = j;
4401 	i = j = 0;
4402 	while (i < len)
4403 		if (isspace(p[i]) || p[i] == '\0')
4404 			i++;
4405 		else {
4406 			iface->data[j] = p + i;
4407 			i += strlen(p + i) + 1;
4408 			j++;
4409 		}
4410 
4411 	return (j);
4412 }
4413 
4414 static void
4415 acpi_free_interfaces(struct acpi_interface *iface)
4416 {
4417 
4418 	free(iface->data[0], M_TEMP);
4419 	free(iface->data, M_TEMP);
4420 }
4421 
4422 static void
4423 acpi_reset_interfaces(device_t dev)
4424 {
4425 	struct acpi_interface list;
4426 	ACPI_STATUS status;
4427 	int i;
4428 
4429 	if (acpi_parse_interfaces(acpi_install_interface, &list) > 0) {
4430 		for (i = 0; i < list.num; i++) {
4431 			status = AcpiInstallInterface(list.data[i]);
4432 			if (ACPI_FAILURE(status))
4433 				device_printf(dev,
4434 				    "failed to install _OSI(\"%s\"): %s\n",
4435 				    list.data[i], AcpiFormatException(status));
4436 			else if (bootverbose)
4437 				device_printf(dev, "installed _OSI(\"%s\")\n",
4438 				    list.data[i]);
4439 		}
4440 		acpi_free_interfaces(&list);
4441 	}
4442 	if (acpi_parse_interfaces(acpi_remove_interface, &list) > 0) {
4443 		for (i = 0; i < list.num; i++) {
4444 			status = AcpiRemoveInterface(list.data[i]);
4445 			if (ACPI_FAILURE(status))
4446 				device_printf(dev,
4447 				    "failed to remove _OSI(\"%s\"): %s\n",
4448 				    list.data[i], AcpiFormatException(status));
4449 			else if (bootverbose)
4450 				device_printf(dev, "removed _OSI(\"%s\")\n",
4451 				    list.data[i]);
4452 		}
4453 		acpi_free_interfaces(&list);
4454 	}
4455 }
4456 
4457 static int
4458 acpi_pm_func(u_long cmd, void *arg, ...)
4459 {
4460 	int	state, acpi_state;
4461 	int	error;
4462 	struct	acpi_softc *sc;
4463 	va_list	ap;
4464 
4465 	error = 0;
4466 	switch (cmd) {
4467 	case POWER_CMD_SUSPEND:
4468 		sc = (struct acpi_softc *)arg;
4469 		if (sc == NULL) {
4470 			error = EINVAL;
4471 			goto out;
4472 		}
4473 
4474 		va_start(ap, arg);
4475 		state = va_arg(ap, int);
4476 		va_end(ap);
4477 
4478 		switch (state) {
4479 		case POWER_SLEEP_STATE_STANDBY:
4480 			acpi_state = sc->acpi_standby_sx;
4481 			break;
4482 		case POWER_SLEEP_STATE_SUSPEND:
4483 			acpi_state = sc->acpi_suspend_sx;
4484 			break;
4485 		case POWER_SLEEP_STATE_HIBERNATE:
4486 			acpi_state = ACPI_STATE_S4;
4487 			break;
4488 		default:
4489 			error = EINVAL;
4490 			goto out;
4491 		}
4492 
4493 		if (ACPI_FAILURE(acpi_EnterSleepState(sc, acpi_state)))
4494 			error = ENXIO;
4495 		break;
4496 	default:
4497 		error = EINVAL;
4498 		goto out;
4499 	}
4500 
4501 out:
4502 	return (error);
4503 }
4504 
4505 static void
4506 acpi_pm_register(void *arg)
4507 {
4508     if (!cold || resource_disabled("acpi", 0))
4509 	return;
4510 
4511     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
4512 }
4513 
4514 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, NULL);
4515