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