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