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