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