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