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