xref: /freebsd/sys/dev/acpica/acpi.c (revision e0c4386e)
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 + 150);
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     device_t *children;
1380     int child_count, i;
1381 
1382     if (device_get_children(dev, &children, &child_count) != 0)
1383 	return;
1384     for (i = 0; i < child_count; i++) {
1385 	ad = device_get_ivars(children[i]);
1386 	rl = &ad->ad_rl;
1387 
1388 	/* Don't reserve system resources. */
1389 	if (ACPI_ID_PROBE(dev, children[i], sysres_ids, NULL) <= 0)
1390 	    continue;
1391 
1392 	STAILQ_FOREACH(rle, rl, link) {
1393 	    /*
1394 	     * Don't reserve IRQ resources.  There are many sticky things
1395 	     * to get right otherwise (e.g. IRQs for psm, atkbd, and HPET
1396 	     * when using legacy routing).
1397 	     */
1398 	    if (rle->type == SYS_RES_IRQ)
1399 		continue;
1400 
1401 	    /*
1402 	     * Don't reserve the resource if it is already allocated.
1403 	     * The acpi_ec(4) driver can allocate its resources early
1404 	     * if ECDT is present.
1405 	     */
1406 	    if (rle->res != NULL)
1407 		continue;
1408 
1409 	    /*
1410 	     * Try to reserve the resource from our parent.  If this
1411 	     * fails because the resource is a system resource, just
1412 	     * let it be.  The resource range is already reserved so
1413 	     * that other devices will not use it.  If the driver
1414 	     * needs to allocate the resource, then
1415 	     * acpi_alloc_resource() will sub-alloc from the system
1416 	     * resource.
1417 	     */
1418 	    resource_list_reserve(rl, dev, children[i], rle->type, &rle->rid,
1419 		rle->start, rle->end, rle->count, 0);
1420 	}
1421     }
1422     free(children, M_TEMP);
1423 }
1424 
1425 static int
1426 acpi_set_resource(device_t dev, device_t child, int type, int rid,
1427     rman_res_t start, rman_res_t count)
1428 {
1429     struct acpi_device *ad = device_get_ivars(child);
1430     struct resource_list *rl = &ad->ad_rl;
1431     ACPI_DEVICE_INFO *devinfo;
1432     rman_res_t end;
1433     int allow;
1434 
1435     /* Ignore IRQ resources for PCI link devices. */
1436     if (type == SYS_RES_IRQ &&
1437 	ACPI_ID_PROBE(dev, child, pcilink_ids, NULL) <= 0)
1438 	return (0);
1439 
1440     /*
1441      * Ignore most resources for PCI root bridges.  Some BIOSes
1442      * incorrectly enumerate the memory ranges they decode as plain
1443      * memory resources instead of as ResourceProducer ranges.  Other
1444      * BIOSes incorrectly list system resource entries for I/O ranges
1445      * under the PCI bridge.  Do allow the one known-correct case on
1446      * x86 of a PCI bridge claiming the I/O ports used for PCI config
1447      * access.
1448      */
1449     if (type == SYS_RES_MEMORY || type == SYS_RES_IOPORT) {
1450 	if (ACPI_SUCCESS(AcpiGetObjectInfo(ad->ad_handle, &devinfo))) {
1451 	    if ((devinfo->Flags & ACPI_PCI_ROOT_BRIDGE) != 0) {
1452 #if defined(__i386__) || defined(__amd64__)
1453 		allow = (type == SYS_RES_IOPORT && start == CONF1_ADDR_PORT);
1454 #else
1455 		allow = 0;
1456 #endif
1457 		if (!allow) {
1458 		    AcpiOsFree(devinfo);
1459 		    return (0);
1460 		}
1461 	    }
1462 	    AcpiOsFree(devinfo);
1463 	}
1464     }
1465 
1466 #ifdef INTRNG
1467     /* map with default for now */
1468     if (type == SYS_RES_IRQ)
1469 	start = (rman_res_t)acpi_map_intr(child, (u_int)start,
1470 			acpi_get_handle(child));
1471 #endif
1472 
1473     /* If the resource is already allocated, fail. */
1474     if (resource_list_busy(rl, type, rid))
1475 	return (EBUSY);
1476 
1477     /* If the resource is already reserved, release it. */
1478     if (resource_list_reserved(rl, type, rid))
1479 	resource_list_unreserve(rl, dev, child, type, rid);
1480 
1481     /* Add the resource. */
1482     end = (start + count - 1);
1483     resource_list_add(rl, type, rid, start, end, count);
1484     return (0);
1485 }
1486 
1487 static struct resource *
1488 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
1489     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1490 {
1491 #ifndef INTRNG
1492     ACPI_RESOURCE ares;
1493 #endif
1494     struct acpi_device *ad;
1495     struct resource_list_entry *rle;
1496     struct resource_list *rl;
1497     struct resource *res;
1498     int isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
1499 
1500     /*
1501      * First attempt at allocating the resource.  For direct children,
1502      * use resource_list_alloc() to handle reserved resources.  For
1503      * other devices, pass the request up to our parent.
1504      */
1505     if (bus == device_get_parent(child)) {
1506 	ad = device_get_ivars(child);
1507 	rl = &ad->ad_rl;
1508 
1509 	/*
1510 	 * Simulate the behavior of the ISA bus for direct children
1511 	 * devices.  That is, if a non-default range is specified for
1512 	 * a resource that doesn't exist, use bus_set_resource() to
1513 	 * add the resource before allocating it.  Note that these
1514 	 * resources will not be reserved.
1515 	 */
1516 	if (!isdefault && resource_list_find(rl, type, *rid) == NULL)
1517 		resource_list_add(rl, type, *rid, start, end, count);
1518 	res = resource_list_alloc(rl, bus, child, type, rid, start, end, count,
1519 	    flags);
1520 #ifndef INTRNG
1521 	if (res != NULL && type == SYS_RES_IRQ) {
1522 	    /*
1523 	     * Since bus_config_intr() takes immediate effect, we cannot
1524 	     * configure the interrupt associated with a device when we
1525 	     * parse the resources but have to defer it until a driver
1526 	     * actually allocates the interrupt via bus_alloc_resource().
1527 	     *
1528 	     * XXX: Should we handle the lookup failing?
1529 	     */
1530 	    if (ACPI_SUCCESS(acpi_lookup_irq_resource(child, *rid, res, &ares)))
1531 		acpi_config_intr(child, &ares);
1532 	}
1533 #endif
1534 
1535 	/*
1536 	 * If this is an allocation of the "default" range for a given
1537 	 * RID, fetch the exact bounds for this resource from the
1538 	 * resource list entry to try to allocate the range from the
1539 	 * system resource regions.
1540 	 */
1541 	if (res == NULL && isdefault) {
1542 	    rle = resource_list_find(rl, type, *rid);
1543 	    if (rle != NULL) {
1544 		start = rle->start;
1545 		end = rle->end;
1546 		count = rle->count;
1547 	    }
1548 	}
1549     } else
1550 	res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child, type, rid,
1551 	    start, end, count, flags);
1552 
1553     /*
1554      * If the first attempt failed and this is an allocation of a
1555      * specific range, try to satisfy the request via a suballocation
1556      * from our system resource regions.
1557      */
1558     if (res == NULL && start + count - 1 == end)
1559 	res = acpi_alloc_sysres(child, type, rid, start, end, count, flags);
1560     return (res);
1561 }
1562 
1563 /*
1564  * Attempt to allocate a specific resource range from the system
1565  * resource ranges.  Note that we only handle memory and I/O port
1566  * system resources.
1567  */
1568 struct resource *
1569 acpi_alloc_sysres(device_t child, int type, int *rid, rman_res_t start,
1570     rman_res_t end, rman_res_t count, u_int flags)
1571 {
1572     struct rman *rm;
1573     struct resource *res;
1574 
1575     switch (type) {
1576     case SYS_RES_IOPORT:
1577 	rm = &acpi_rman_io;
1578 	break;
1579     case SYS_RES_MEMORY:
1580 	rm = &acpi_rman_mem;
1581 	break;
1582     default:
1583 	return (NULL);
1584     }
1585 
1586     KASSERT(start + count - 1 == end, ("wildcard resource range"));
1587     res = rman_reserve_resource(rm, start, end, count, flags & ~RF_ACTIVE,
1588 	child);
1589     if (res == NULL)
1590 	return (NULL);
1591 
1592     rman_set_rid(res, *rid);
1593 
1594     /* If requested, activate the resource using the parent's method. */
1595     if (flags & RF_ACTIVE)
1596 	if (bus_activate_resource(child, type, *rid, res) != 0) {
1597 	    rman_release_resource(res);
1598 	    return (NULL);
1599 	}
1600 
1601     return (res);
1602 }
1603 
1604 static int
1605 acpi_is_resource_managed(int type, struct resource *r)
1606 {
1607 
1608     /* We only handle memory and IO resources through rman. */
1609     switch (type) {
1610     case SYS_RES_IOPORT:
1611 	return (rman_is_region_manager(r, &acpi_rman_io));
1612     case SYS_RES_MEMORY:
1613 	return (rman_is_region_manager(r, &acpi_rman_mem));
1614     }
1615     return (0);
1616 }
1617 
1618 static int
1619 acpi_adjust_resource(device_t bus, device_t child, int type, struct resource *r,
1620     rman_res_t start, rman_res_t end)
1621 {
1622 
1623     if (acpi_is_resource_managed(type, r))
1624 	return (rman_adjust_resource(r, start, end));
1625     return (bus_generic_adjust_resource(bus, child, type, r, start, end));
1626 }
1627 
1628 static int
1629 acpi_release_resource(device_t bus, device_t child, int type, int rid,
1630     struct resource *r)
1631 {
1632     int ret;
1633 
1634     /*
1635      * If this resource belongs to one of our internal managers,
1636      * deactivate it and release it to the local pool.
1637      */
1638     if (acpi_is_resource_managed(type, r)) {
1639 	if (rman_get_flags(r) & RF_ACTIVE) {
1640 	    ret = bus_deactivate_resource(child, type, rid, r);
1641 	    if (ret != 0)
1642 		return (ret);
1643 	}
1644 	return (rman_release_resource(r));
1645     }
1646 
1647     return (bus_generic_rl_release_resource(bus, child, type, rid, r));
1648 }
1649 
1650 static void
1651 acpi_delete_resource(device_t bus, device_t child, int type, int rid)
1652 {
1653     struct resource_list *rl;
1654 
1655     rl = acpi_get_rlist(bus, child);
1656     if (resource_list_busy(rl, type, rid)) {
1657 	device_printf(bus, "delete_resource: Resource still owned by child"
1658 	    " (type=%d, rid=%d)\n", type, rid);
1659 	return;
1660     }
1661     resource_list_unreserve(rl, bus, child, type, rid);
1662     resource_list_delete(rl, type, rid);
1663 }
1664 
1665 /* Allocate an IO port or memory resource, given its GAS. */
1666 int
1667 acpi_bus_alloc_gas(device_t dev, int *type, int *rid, ACPI_GENERIC_ADDRESS *gas,
1668     struct resource **res, u_int flags)
1669 {
1670     int error, res_type;
1671 
1672     error = ENOMEM;
1673     if (type == NULL || rid == NULL || gas == NULL || res == NULL)
1674 	return (EINVAL);
1675 
1676     /* We only support memory and IO spaces. */
1677     switch (gas->SpaceId) {
1678     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
1679 	res_type = SYS_RES_MEMORY;
1680 	break;
1681     case ACPI_ADR_SPACE_SYSTEM_IO:
1682 	res_type = SYS_RES_IOPORT;
1683 	break;
1684     default:
1685 	return (EOPNOTSUPP);
1686     }
1687 
1688     /*
1689      * If the register width is less than 8, assume the BIOS author means
1690      * it is a bit field and just allocate a byte.
1691      */
1692     if (gas->BitWidth && gas->BitWidth < 8)
1693 	gas->BitWidth = 8;
1694 
1695     /* Validate the address after we're sure we support the space. */
1696     if (gas->Address == 0 || gas->BitWidth == 0)
1697 	return (EINVAL);
1698 
1699     bus_set_resource(dev, res_type, *rid, gas->Address,
1700 	gas->BitWidth / 8);
1701     *res = bus_alloc_resource_any(dev, res_type, rid, RF_ACTIVE | flags);
1702     if (*res != NULL) {
1703 	*type = res_type;
1704 	error = 0;
1705     } else
1706 	bus_delete_resource(dev, res_type, *rid);
1707 
1708     return (error);
1709 }
1710 
1711 /* Probe _HID and _CID for compatible ISA PNP ids. */
1712 static uint32_t
1713 acpi_isa_get_logicalid(device_t dev)
1714 {
1715     ACPI_DEVICE_INFO	*devinfo;
1716     ACPI_HANDLE		h;
1717     uint32_t		pnpid;
1718 
1719     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1720 
1721     /* Fetch and validate the HID. */
1722     if ((h = acpi_get_handle(dev)) == NULL ||
1723 	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1724 	return_VALUE (0);
1725 
1726     pnpid = (devinfo->Valid & ACPI_VALID_HID) != 0 &&
1727 	devinfo->HardwareId.Length >= ACPI_EISAID_STRING_SIZE ?
1728 	PNP_EISAID(devinfo->HardwareId.String) : 0;
1729     AcpiOsFree(devinfo);
1730 
1731     return_VALUE (pnpid);
1732 }
1733 
1734 static int
1735 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
1736 {
1737     ACPI_DEVICE_INFO	*devinfo;
1738     ACPI_PNP_DEVICE_ID	*ids;
1739     ACPI_HANDLE		h;
1740     uint32_t		*pnpid;
1741     int			i, valid;
1742 
1743     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1744 
1745     pnpid = cids;
1746 
1747     /* Fetch and validate the CID */
1748     if ((h = acpi_get_handle(dev)) == NULL ||
1749 	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1750 	return_VALUE (0);
1751 
1752     if ((devinfo->Valid & ACPI_VALID_CID) == 0) {
1753 	AcpiOsFree(devinfo);
1754 	return_VALUE (0);
1755     }
1756 
1757     if (devinfo->CompatibleIdList.Count < count)
1758 	count = devinfo->CompatibleIdList.Count;
1759     ids = devinfo->CompatibleIdList.Ids;
1760     for (i = 0, valid = 0; i < count; i++)
1761 	if (ids[i].Length >= ACPI_EISAID_STRING_SIZE &&
1762 	    strncmp(ids[i].String, "PNP", 3) == 0) {
1763 	    *pnpid++ = PNP_EISAID(ids[i].String);
1764 	    valid++;
1765 	}
1766     AcpiOsFree(devinfo);
1767 
1768     return_VALUE (valid);
1769 }
1770 
1771 static int
1772 acpi_device_id_probe(device_t bus, device_t dev, char **ids, char **match)
1773 {
1774     ACPI_HANDLE h;
1775     ACPI_OBJECT_TYPE t;
1776     int rv;
1777     int i;
1778 
1779     h = acpi_get_handle(dev);
1780     if (ids == NULL || h == NULL)
1781 	return (ENXIO);
1782     t = acpi_get_type(dev);
1783     if (t != ACPI_TYPE_DEVICE && t != ACPI_TYPE_PROCESSOR)
1784 	return (ENXIO);
1785 
1786     /* Try to match one of the array of IDs with a HID or CID. */
1787     for (i = 0; ids[i] != NULL; i++) {
1788 	rv = acpi_MatchHid(h, ids[i]);
1789 	if (rv == ACPI_MATCHHID_NOMATCH)
1790 	    continue;
1791 
1792 	if (match != NULL) {
1793 	    *match = ids[i];
1794 	}
1795 	return ((rv == ACPI_MATCHHID_HID)?
1796 		    BUS_PROBE_DEFAULT : BUS_PROBE_LOW_PRIORITY);
1797     }
1798     return (ENXIO);
1799 }
1800 
1801 static ACPI_STATUS
1802 acpi_device_eval_obj(device_t bus, device_t dev, ACPI_STRING pathname,
1803     ACPI_OBJECT_LIST *parameters, ACPI_BUFFER *ret)
1804 {
1805     ACPI_HANDLE h;
1806 
1807     if (dev == NULL)
1808 	h = ACPI_ROOT_OBJECT;
1809     else if ((h = acpi_get_handle(dev)) == NULL)
1810 	return (AE_BAD_PARAMETER);
1811     return (AcpiEvaluateObject(h, pathname, parameters, ret));
1812 }
1813 
1814 static ACPI_STATUS
1815 acpi_device_get_prop(device_t bus, device_t dev, ACPI_STRING propname,
1816     const ACPI_OBJECT **value)
1817 {
1818 	const ACPI_OBJECT *pkg, *name, *val;
1819 	struct acpi_device *ad;
1820 	ACPI_STATUS status;
1821 	int i;
1822 
1823 	ad = device_get_ivars(dev);
1824 
1825 	if (ad == NULL || propname == NULL)
1826 		return (AE_BAD_PARAMETER);
1827 	if (ad->dsd_pkg == NULL) {
1828 		if (ad->dsd.Pointer == NULL) {
1829 			status = acpi_find_dsd(ad);
1830 			if (ACPI_FAILURE(status))
1831 				return (status);
1832 		} else {
1833 			return (AE_NOT_FOUND);
1834 		}
1835 	}
1836 
1837 	for (i = 0; i < ad->dsd_pkg->Package.Count; i ++) {
1838 		pkg = &ad->dsd_pkg->Package.Elements[i];
1839 		if (pkg->Type != ACPI_TYPE_PACKAGE || pkg->Package.Count != 2)
1840 			continue;
1841 
1842 		name = &pkg->Package.Elements[0];
1843 		val = &pkg->Package.Elements[1];
1844 		if (name->Type != ACPI_TYPE_STRING)
1845 			continue;
1846 		if (strncmp(propname, name->String.Pointer, name->String.Length) == 0) {
1847 			if (value != NULL)
1848 				*value = val;
1849 
1850 			return (AE_OK);
1851 		}
1852 	}
1853 
1854 	return (AE_NOT_FOUND);
1855 }
1856 
1857 static ACPI_STATUS
1858 acpi_find_dsd(struct acpi_device *ad)
1859 {
1860 	const ACPI_OBJECT *dsd, *guid, *pkg;
1861 	ACPI_STATUS status;
1862 
1863 	ad->dsd.Length = ACPI_ALLOCATE_BUFFER;
1864 	ad->dsd.Pointer = NULL;
1865 	ad->dsd_pkg = NULL;
1866 
1867 	status = AcpiEvaluateObject(ad->ad_handle, "_DSD", NULL, &ad->dsd);
1868 	if (ACPI_FAILURE(status))
1869 		return (status);
1870 
1871 	dsd = ad->dsd.Pointer;
1872 	guid = &dsd->Package.Elements[0];
1873 	pkg = &dsd->Package.Elements[1];
1874 
1875 	if (guid->Type != ACPI_TYPE_BUFFER || pkg->Type != ACPI_TYPE_PACKAGE ||
1876 		guid->Buffer.Length != sizeof(acpi_dsd_uuid))
1877 		return (AE_NOT_FOUND);
1878 	if (memcmp(guid->Buffer.Pointer, &acpi_dsd_uuid,
1879 		sizeof(acpi_dsd_uuid)) == 0) {
1880 
1881 		ad->dsd_pkg = pkg;
1882 		return (AE_OK);
1883 	}
1884 
1885 	return (AE_NOT_FOUND);
1886 }
1887 
1888 static ssize_t
1889 acpi_bus_get_prop_handle(const ACPI_OBJECT *hobj, void *propvalue, size_t size)
1890 {
1891 	ACPI_OBJECT *pobj;
1892 	ACPI_HANDLE h;
1893 
1894 	if (hobj->Type != ACPI_TYPE_PACKAGE)
1895 		goto err;
1896 	if (hobj->Package.Count != 1)
1897 		goto err;
1898 
1899 	pobj = &hobj->Package.Elements[0];
1900 	if (pobj == NULL)
1901 		goto err;
1902 	if (pobj->Type != ACPI_TYPE_LOCAL_REFERENCE)
1903 		goto err;
1904 
1905 	h = acpi_GetReference(NULL, pobj);
1906 	if (h == NULL)
1907 		goto err;
1908 
1909 	if (propvalue != NULL && size >= sizeof(ACPI_HANDLE))
1910 		*(ACPI_HANDLE *)propvalue = h;
1911 	return (sizeof(ACPI_HANDLE));
1912 
1913 err:
1914 	return (-1);
1915 }
1916 
1917 static ssize_t
1918 acpi_bus_get_prop(device_t bus, device_t child, const char *propname,
1919     void *propvalue, size_t size, device_property_type_t type)
1920 {
1921 	ACPI_STATUS status;
1922 	const ACPI_OBJECT *obj;
1923 
1924 	status = acpi_device_get_prop(bus, child, __DECONST(char *, propname),
1925 		&obj);
1926 	if (ACPI_FAILURE(status))
1927 		return (-1);
1928 
1929 	switch (type) {
1930 	case DEVICE_PROP_ANY:
1931 	case DEVICE_PROP_BUFFER:
1932 	case DEVICE_PROP_UINT32:
1933 	case DEVICE_PROP_UINT64:
1934 		break;
1935 	case DEVICE_PROP_HANDLE:
1936 		return (acpi_bus_get_prop_handle(obj, propvalue, size));
1937 	default:
1938 		return (-1);
1939 	}
1940 
1941 	switch (obj->Type) {
1942 	case ACPI_TYPE_INTEGER:
1943 		if (type == DEVICE_PROP_UINT32) {
1944 			if (propvalue != NULL && size >= sizeof(uint32_t))
1945 				*((uint32_t *)propvalue) = obj->Integer.Value;
1946 			return (sizeof(uint32_t));
1947 		}
1948 		if (propvalue != NULL && size >= sizeof(uint64_t))
1949 			*((uint64_t *) propvalue) = obj->Integer.Value;
1950 		return (sizeof(uint64_t));
1951 
1952 	case ACPI_TYPE_STRING:
1953 		if (type != DEVICE_PROP_ANY &&
1954 		    type != DEVICE_PROP_BUFFER)
1955 			return (-1);
1956 
1957 		if (propvalue != NULL && size > 0)
1958 			memcpy(propvalue, obj->String.Pointer,
1959 			    MIN(size, obj->String.Length));
1960 		return (obj->String.Length);
1961 
1962 	case ACPI_TYPE_BUFFER:
1963 		if (propvalue != NULL && size > 0)
1964 			memcpy(propvalue, obj->Buffer.Pointer,
1965 			    MIN(size, obj->Buffer.Length));
1966 		return (obj->Buffer.Length);
1967 
1968 	case ACPI_TYPE_PACKAGE:
1969 		if (propvalue != NULL && size >= sizeof(ACPI_OBJECT *)) {
1970 			*((ACPI_OBJECT **) propvalue) =
1971 			    __DECONST(ACPI_OBJECT *, obj);
1972 		}
1973 		return (sizeof(ACPI_OBJECT *));
1974 
1975 	case ACPI_TYPE_LOCAL_REFERENCE:
1976 		if (propvalue != NULL && size >= sizeof(ACPI_HANDLE)) {
1977 			ACPI_HANDLE h;
1978 
1979 			h = acpi_GetReference(NULL,
1980 			    __DECONST(ACPI_OBJECT *, obj));
1981 			memcpy(propvalue, h, sizeof(ACPI_HANDLE));
1982 		}
1983 		return (sizeof(ACPI_HANDLE));
1984 	default:
1985 		return (0);
1986 	}
1987 }
1988 
1989 int
1990 acpi_device_pwr_for_sleep(device_t bus, device_t dev, int *dstate)
1991 {
1992     struct acpi_softc *sc;
1993     ACPI_HANDLE handle;
1994     ACPI_STATUS status;
1995     char sxd[8];
1996 
1997     handle = acpi_get_handle(dev);
1998 
1999     /*
2000      * XXX If we find these devices, don't try to power them down.
2001      * The serial and IRDA ports on my T23 hang the system when
2002      * set to D3 and it appears that such legacy devices may
2003      * need special handling in their drivers.
2004      */
2005     if (dstate == NULL || handle == NULL ||
2006 	acpi_MatchHid(handle, "PNP0500") ||
2007 	acpi_MatchHid(handle, "PNP0501") ||
2008 	acpi_MatchHid(handle, "PNP0502") ||
2009 	acpi_MatchHid(handle, "PNP0510") ||
2010 	acpi_MatchHid(handle, "PNP0511"))
2011 	return (ENXIO);
2012 
2013     /*
2014      * Override next state with the value from _SxD, if present.
2015      * Note illegal _S0D is evaluated because some systems expect this.
2016      */
2017     sc = device_get_softc(bus);
2018     snprintf(sxd, sizeof(sxd), "_S%dD", sc->acpi_sstate);
2019     status = acpi_GetInteger(handle, sxd, dstate);
2020     if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
2021 	    device_printf(dev, "failed to get %s on %s: %s\n", sxd,
2022 		acpi_name(handle), AcpiFormatException(status));
2023 	    return (ENXIO);
2024     }
2025 
2026     return (0);
2027 }
2028 
2029 /* Callback arg for our implementation of walking the namespace. */
2030 struct acpi_device_scan_ctx {
2031     acpi_scan_cb_t	user_fn;
2032     void		*arg;
2033     ACPI_HANDLE		parent;
2034 };
2035 
2036 static ACPI_STATUS
2037 acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level, void *arg, void **retval)
2038 {
2039     struct acpi_device_scan_ctx *ctx;
2040     device_t dev, old_dev;
2041     ACPI_STATUS status;
2042     ACPI_OBJECT_TYPE type;
2043 
2044     /*
2045      * Skip this device if we think we'll have trouble with it or it is
2046      * the parent where the scan began.
2047      */
2048     ctx = (struct acpi_device_scan_ctx *)arg;
2049     if (acpi_avoid(h) || h == ctx->parent)
2050 	return (AE_OK);
2051 
2052     /* If this is not a valid device type (e.g., a method), skip it. */
2053     if (ACPI_FAILURE(AcpiGetType(h, &type)))
2054 	return (AE_OK);
2055     if (type != ACPI_TYPE_DEVICE && type != ACPI_TYPE_PROCESSOR &&
2056 	type != ACPI_TYPE_THERMAL && type != ACPI_TYPE_POWER)
2057 	return (AE_OK);
2058 
2059     /*
2060      * Call the user function with the current device.  If it is unchanged
2061      * afterwards, return.  Otherwise, we update the handle to the new dev.
2062      */
2063     old_dev = acpi_get_device(h);
2064     dev = old_dev;
2065     status = ctx->user_fn(h, &dev, level, ctx->arg);
2066     if (ACPI_FAILURE(status) || old_dev == dev)
2067 	return (status);
2068 
2069     /* Remove the old child and its connection to the handle. */
2070     if (old_dev != NULL)
2071 	device_delete_child(device_get_parent(old_dev), old_dev);
2072 
2073     /* Recreate the handle association if the user created a device. */
2074     if (dev != NULL)
2075 	AcpiAttachData(h, acpi_fake_objhandler, dev);
2076 
2077     return (AE_OK);
2078 }
2079 
2080 static ACPI_STATUS
2081 acpi_device_scan_children(device_t bus, device_t dev, int max_depth,
2082     acpi_scan_cb_t user_fn, void *arg)
2083 {
2084     ACPI_HANDLE h;
2085     struct acpi_device_scan_ctx ctx;
2086 
2087     if (acpi_disabled("children"))
2088 	return (AE_OK);
2089 
2090     if (dev == NULL)
2091 	h = ACPI_ROOT_OBJECT;
2092     else if ((h = acpi_get_handle(dev)) == NULL)
2093 	return (AE_BAD_PARAMETER);
2094     ctx.user_fn = user_fn;
2095     ctx.arg = arg;
2096     ctx.parent = h;
2097     return (AcpiWalkNamespace(ACPI_TYPE_ANY, h, max_depth,
2098 	acpi_device_scan_cb, NULL, &ctx, NULL));
2099 }
2100 
2101 /*
2102  * Even though ACPI devices are not PCI, we use the PCI approach for setting
2103  * device power states since it's close enough to ACPI.
2104  */
2105 int
2106 acpi_set_powerstate(device_t child, int state)
2107 {
2108     ACPI_HANDLE h;
2109     ACPI_STATUS status;
2110 
2111     h = acpi_get_handle(child);
2112     if (state < ACPI_STATE_D0 || state > ACPI_D_STATES_MAX)
2113 	return (EINVAL);
2114     if (h == NULL)
2115 	return (0);
2116 
2117     /* Ignore errors if the power methods aren't present. */
2118     status = acpi_pwr_switch_consumer(h, state);
2119     if (ACPI_SUCCESS(status)) {
2120 	if (bootverbose)
2121 	    device_printf(child, "set ACPI power state D%d on %s\n",
2122 		state, acpi_name(h));
2123     } else if (status != AE_NOT_FOUND)
2124 	device_printf(child,
2125 	    "failed to set ACPI power state D%d on %s: %s\n", state,
2126 	    acpi_name(h), AcpiFormatException(status));
2127 
2128     return (0);
2129 }
2130 
2131 static int
2132 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
2133 {
2134     int			result, cid_count, i;
2135     uint32_t		lid, cids[8];
2136 
2137     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2138 
2139     /*
2140      * ISA-style drivers attached to ACPI may persist and
2141      * probe manually if we return ENOENT.  We never want
2142      * that to happen, so don't ever return it.
2143      */
2144     result = ENXIO;
2145 
2146     /* Scan the supplied IDs for a match */
2147     lid = acpi_isa_get_logicalid(child);
2148     cid_count = acpi_isa_get_compatid(child, cids, 8);
2149     while (ids && ids->ip_id) {
2150 	if (lid == ids->ip_id) {
2151 	    result = 0;
2152 	    goto out;
2153 	}
2154 	for (i = 0; i < cid_count; i++) {
2155 	    if (cids[i] == ids->ip_id) {
2156 		result = 0;
2157 		goto out;
2158 	    }
2159 	}
2160 	ids++;
2161     }
2162 
2163  out:
2164     if (result == 0 && ids->ip_desc)
2165 	device_set_desc(child, ids->ip_desc);
2166 
2167     return_VALUE (result);
2168 }
2169 
2170 /*
2171  * Look for a MCFG table.  If it is present, use the settings for
2172  * domain (segment) 0 to setup PCI config space access via the memory
2173  * map.
2174  *
2175  * On non-x86 architectures (arm64 for now), this will be done from the
2176  * PCI host bridge driver.
2177  */
2178 static void
2179 acpi_enable_pcie(void)
2180 {
2181 #if defined(__i386__) || defined(__amd64__)
2182 	ACPI_TABLE_HEADER *hdr;
2183 	ACPI_MCFG_ALLOCATION *alloc, *end;
2184 	ACPI_STATUS status;
2185 
2186 	status = AcpiGetTable(ACPI_SIG_MCFG, 1, &hdr);
2187 	if (ACPI_FAILURE(status))
2188 		return;
2189 
2190 	end = (ACPI_MCFG_ALLOCATION *)((char *)hdr + hdr->Length);
2191 	alloc = (ACPI_MCFG_ALLOCATION *)((ACPI_TABLE_MCFG *)hdr + 1);
2192 	while (alloc < end) {
2193 		pcie_cfgregopen(alloc->Address, alloc->PciSegment,
2194 		    alloc->StartBusNumber, alloc->EndBusNumber);
2195 		alloc++;
2196 	}
2197 #endif
2198 }
2199 
2200 static void
2201 acpi_platform_osc(device_t dev)
2202 {
2203 	ACPI_HANDLE sb_handle;
2204 	ACPI_STATUS status;
2205 	uint32_t cap_set[2];
2206 
2207 	/* 0811B06E-4A27-44F9-8D60-3CBBC22E7B48 */
2208 	static uint8_t acpi_platform_uuid[ACPI_UUID_LENGTH] = {
2209 		0x6e, 0xb0, 0x11, 0x08, 0x27, 0x4a, 0xf9, 0x44,
2210 		0x8d, 0x60, 0x3c, 0xbb, 0xc2, 0x2e, 0x7b, 0x48
2211 	};
2212 
2213 	if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2214 		return;
2215 
2216 	cap_set[1] = 0x10;	/* APEI Support */
2217 	status = acpi_EvaluateOSC(sb_handle, acpi_platform_uuid, 1,
2218 	    nitems(cap_set), cap_set, cap_set, false);
2219 	if (ACPI_FAILURE(status)) {
2220 		if (status == AE_NOT_FOUND)
2221 			return;
2222 		device_printf(dev, "_OSC failed: %s\n",
2223 		    AcpiFormatException(status));
2224 		return;
2225 	}
2226 }
2227 
2228 /*
2229  * Scan all of the ACPI namespace and attach child devices.
2230  *
2231  * We should only expect to find devices in the \_PR, \_TZ, \_SI, and
2232  * \_SB scopes, and \_PR and \_TZ became obsolete in the ACPI 2.0 spec.
2233  * However, in violation of the spec, some systems place their PCI link
2234  * devices in \, so we have to walk the whole namespace.  We check the
2235  * type of namespace nodes, so this should be ok.
2236  */
2237 static void
2238 acpi_probe_children(device_t bus)
2239 {
2240 
2241     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2242 
2243     /*
2244      * Scan the namespace and insert placeholders for all the devices that
2245      * we find.  We also probe/attach any early devices.
2246      *
2247      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
2248      * we want to create nodes for all devices, not just those that are
2249      * currently present. (This assumes that we don't want to create/remove
2250      * devices as they appear, which might be smarter.)
2251      */
2252     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
2253     AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, 100, acpi_probe_child,
2254 	NULL, bus, NULL);
2255 
2256     /* Pre-allocate resources for our rman from any sysresource devices. */
2257     acpi_sysres_alloc(bus);
2258 
2259     /* Reserve resources already allocated to children. */
2260     acpi_reserve_resources(bus);
2261 
2262     /* Create any static children by calling device identify methods. */
2263     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
2264     bus_generic_probe(bus);
2265 
2266     /* Probe/attach all children, created statically and from the namespace. */
2267     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "acpi bus_generic_attach\n"));
2268     bus_generic_attach(bus);
2269 
2270     /* Attach wake sysctls. */
2271     acpi_wake_sysctl_walk(bus);
2272 
2273     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
2274     return_VOID;
2275 }
2276 
2277 /*
2278  * Determine the probe order for a given device.
2279  */
2280 static void
2281 acpi_probe_order(ACPI_HANDLE handle, int *order)
2282 {
2283 	ACPI_OBJECT_TYPE type;
2284 
2285 	/*
2286 	 * 0. CPUs
2287 	 * 1. I/O port and memory system resource holders
2288 	 * 2. Clocks and timers (to handle early accesses)
2289 	 * 3. Embedded controllers (to handle early accesses)
2290 	 * 4. PCI Link Devices
2291 	 */
2292 	AcpiGetType(handle, &type);
2293 	if (type == ACPI_TYPE_PROCESSOR)
2294 		*order = 0;
2295 	else if (acpi_MatchHid(handle, "PNP0C01") ||
2296 	    acpi_MatchHid(handle, "PNP0C02"))
2297 		*order = 1;
2298 	else if (acpi_MatchHid(handle, "PNP0100") ||
2299 	    acpi_MatchHid(handle, "PNP0103") ||
2300 	    acpi_MatchHid(handle, "PNP0B00"))
2301 		*order = 2;
2302 	else if (acpi_MatchHid(handle, "PNP0C09"))
2303 		*order = 3;
2304 	else if (acpi_MatchHid(handle, "PNP0C0F"))
2305 		*order = 4;
2306 }
2307 
2308 /*
2309  * Evaluate a child device and determine whether we might attach a device to
2310  * it.
2311  */
2312 static ACPI_STATUS
2313 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2314 {
2315     ACPI_DEVICE_INFO *devinfo;
2316     struct acpi_device	*ad;
2317     struct acpi_prw_data prw;
2318     ACPI_OBJECT_TYPE type;
2319     ACPI_HANDLE h;
2320     device_t bus, child;
2321     char *handle_str;
2322     int order;
2323 
2324     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2325 
2326     if (acpi_disabled("children"))
2327 	return_ACPI_STATUS (AE_OK);
2328 
2329     /* Skip this device if we think we'll have trouble with it. */
2330     if (acpi_avoid(handle))
2331 	return_ACPI_STATUS (AE_OK);
2332 
2333     bus = (device_t)context;
2334     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
2335 	handle_str = acpi_name(handle);
2336 	switch (type) {
2337 	case ACPI_TYPE_DEVICE:
2338 	    /*
2339 	     * Since we scan from \, be sure to skip system scope objects.
2340 	     * \_SB_ and \_TZ_ are defined in ACPICA as devices to work around
2341 	     * BIOS bugs.  For example, \_SB_ is to allow \_SB_._INI to be run
2342 	     * during the initialization and \_TZ_ is to support Notify() on it.
2343 	     */
2344 	    if (strcmp(handle_str, "\\_SB_") == 0 ||
2345 		strcmp(handle_str, "\\_TZ_") == 0)
2346 		break;
2347 	    if (acpi_parse_prw(handle, &prw) == 0)
2348 		AcpiSetupGpeForWake(handle, prw.gpe_handle, prw.gpe_bit);
2349 
2350 	    /*
2351 	     * Ignore devices that do not have a _HID or _CID.  They should
2352 	     * be discovered by other buses (e.g. the PCI bus driver).
2353 	     */
2354 	    if (!acpi_has_hid(handle))
2355 		break;
2356 	    /* FALLTHROUGH */
2357 	case ACPI_TYPE_PROCESSOR:
2358 	case ACPI_TYPE_THERMAL:
2359 	case ACPI_TYPE_POWER:
2360 	    /*
2361 	     * Create a placeholder device for this node.  Sort the
2362 	     * placeholder so that the probe/attach passes will run
2363 	     * breadth-first.  Orders less than ACPI_DEV_BASE_ORDER
2364 	     * are reserved for special objects (i.e., system
2365 	     * resources).
2366 	     */
2367 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
2368 	    order = level * 10 + ACPI_DEV_BASE_ORDER;
2369 	    acpi_probe_order(handle, &order);
2370 	    child = BUS_ADD_CHILD(bus, order, NULL, -1);
2371 	    if (child == NULL)
2372 		break;
2373 
2374 	    /* Associate the handle with the device_t and vice versa. */
2375 	    acpi_set_handle(child, handle);
2376 	    AcpiAttachData(handle, acpi_fake_objhandler, child);
2377 
2378 	    /*
2379 	     * Check that the device is present.  If it's not present,
2380 	     * leave it disabled (so that we have a device_t attached to
2381 	     * the handle, but we don't probe it).
2382 	     *
2383 	     * XXX PCI link devices sometimes report "present" but not
2384 	     * "functional" (i.e. if disabled).  Go ahead and probe them
2385 	     * anyway since we may enable them later.
2386 	     */
2387 	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
2388 		/* Never disable PCI link devices. */
2389 		if (acpi_MatchHid(handle, "PNP0C0F"))
2390 		    break;
2391 
2392 		/*
2393 		 * RTC Device should be enabled for CMOS register space
2394 		 * unless FADT indicate it is not present.
2395 		 * (checked in RTC probe routine.)
2396 		 */
2397 		if (acpi_MatchHid(handle, "PNP0B00"))
2398 		    break;
2399 
2400 		/*
2401 		 * Docking stations should remain enabled since the system
2402 		 * may be undocked at boot.
2403 		 */
2404 		if (ACPI_SUCCESS(AcpiGetHandle(handle, "_DCK", &h)))
2405 		    break;
2406 
2407 		device_disable(child);
2408 		break;
2409 	    }
2410 
2411 	    /*
2412 	     * Get the device's resource settings and attach them.
2413 	     * Note that if the device has _PRS but no _CRS, we need
2414 	     * to decide when it's appropriate to try to configure the
2415 	     * device.  Ignore the return value here; it's OK for the
2416 	     * device not to have any resources.
2417 	     */
2418 	    acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
2419 
2420 	    ad = device_get_ivars(child);
2421 	    ad->ad_cls_class = 0xffffff;
2422 	    if (ACPI_SUCCESS(AcpiGetObjectInfo(handle, &devinfo))) {
2423 		if ((devinfo->Valid & ACPI_VALID_CLS) != 0 &&
2424 		    devinfo->ClassCode.Length >= ACPI_PCICLS_STRING_SIZE) {
2425 		    ad->ad_cls_class = strtoul(devinfo->ClassCode.String,
2426 			NULL, 16);
2427 		}
2428 		AcpiOsFree(devinfo);
2429 	    }
2430 	    break;
2431 	}
2432     }
2433 
2434     return_ACPI_STATUS (AE_OK);
2435 }
2436 
2437 /*
2438  * AcpiAttachData() requires an object handler but never uses it.  This is a
2439  * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
2440  */
2441 void
2442 acpi_fake_objhandler(ACPI_HANDLE h, void *data)
2443 {
2444 }
2445 
2446 static void
2447 acpi_shutdown_final(void *arg, int howto)
2448 {
2449     struct acpi_softc *sc = (struct acpi_softc *)arg;
2450     register_t intr;
2451     ACPI_STATUS status;
2452 
2453     /*
2454      * XXX Shutdown code should only run on the BSP (cpuid 0).
2455      * Some chipsets do not power off the system correctly if called from
2456      * an AP.
2457      */
2458     if ((howto & RB_POWEROFF) != 0) {
2459 	status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
2460 	if (ACPI_FAILURE(status)) {
2461 	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
2462 		AcpiFormatException(status));
2463 	    return;
2464 	}
2465 	device_printf(sc->acpi_dev, "Powering system off\n");
2466 	intr = intr_disable();
2467 	status = AcpiEnterSleepState(ACPI_STATE_S5);
2468 	if (ACPI_FAILURE(status)) {
2469 	    intr_restore(intr);
2470 	    device_printf(sc->acpi_dev, "power-off failed - %s\n",
2471 		AcpiFormatException(status));
2472 	} else {
2473 	    DELAY(1000000);
2474 	    intr_restore(intr);
2475 	    device_printf(sc->acpi_dev, "power-off failed - timeout\n");
2476 	}
2477     } else if ((howto & RB_HALT) == 0 && sc->acpi_handle_reboot) {
2478 	/* Reboot using the reset register. */
2479 	status = AcpiReset();
2480 	if (ACPI_SUCCESS(status)) {
2481 	    DELAY(1000000);
2482 	    device_printf(sc->acpi_dev, "reset failed - timeout\n");
2483 	} else if (status != AE_NOT_EXIST)
2484 	    device_printf(sc->acpi_dev, "reset failed - %s\n",
2485 		AcpiFormatException(status));
2486     } else if (sc->acpi_do_disable && !KERNEL_PANICKED()) {
2487 	/*
2488 	 * Only disable ACPI if the user requested.  On some systems, writing
2489 	 * the disable value to SMI_CMD hangs the system.
2490 	 */
2491 	device_printf(sc->acpi_dev, "Shutting down\n");
2492 	AcpiTerminate();
2493     }
2494 }
2495 
2496 static void
2497 acpi_enable_fixed_events(struct acpi_softc *sc)
2498 {
2499     static int	first_time = 1;
2500 
2501     /* Enable and clear fixed events and install handlers. */
2502     if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
2503 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
2504 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
2505 				     acpi_event_power_button_sleep, sc);
2506 	if (first_time)
2507 	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
2508     }
2509     if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
2510 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
2511 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
2512 				     acpi_event_sleep_button_sleep, sc);
2513 	if (first_time)
2514 	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
2515     }
2516 
2517     first_time = 0;
2518 }
2519 
2520 /*
2521  * Returns true if the device is actually present and should
2522  * be attached to.  This requires the present, enabled, UI-visible
2523  * and diagnostics-passed bits to be set.
2524  */
2525 BOOLEAN
2526 acpi_DeviceIsPresent(device_t dev)
2527 {
2528 	ACPI_HANDLE h;
2529 	UINT32 s;
2530 	ACPI_STATUS status;
2531 
2532 	h = acpi_get_handle(dev);
2533 	if (h == NULL)
2534 		return (FALSE);
2535 
2536 #ifdef ACPI_EARLY_EPYC_WAR
2537 	/*
2538 	 * Certain Treadripper boards always returns 0 for FreeBSD because it
2539 	 * only returns non-zero for the OS string "Windows 2015". Otherwise it
2540 	 * will return zero. Force them to always be treated as present.
2541 	 * Beata versions were worse: they always returned 0.
2542 	 */
2543 	if (acpi_MatchHid(h, "AMDI0020") || acpi_MatchHid(h, "AMDI0010"))
2544 		return (TRUE);
2545 #endif
2546 
2547 	status = acpi_GetInteger(h, "_STA", &s);
2548 
2549 	/*
2550 	 * If no _STA method or if it failed, then assume that
2551 	 * the device is present.
2552 	 */
2553 	if (ACPI_FAILURE(status))
2554 		return (TRUE);
2555 
2556 	return (ACPI_DEVICE_PRESENT(s) ? TRUE : FALSE);
2557 }
2558 
2559 /*
2560  * Returns true if the battery is actually present and inserted.
2561  */
2562 BOOLEAN
2563 acpi_BatteryIsPresent(device_t dev)
2564 {
2565 	ACPI_HANDLE h;
2566 	UINT32 s;
2567 	ACPI_STATUS status;
2568 
2569 	h = acpi_get_handle(dev);
2570 	if (h == NULL)
2571 		return (FALSE);
2572 	status = acpi_GetInteger(h, "_STA", &s);
2573 
2574 	/*
2575 	 * If no _STA method or if it failed, then assume that
2576 	 * the device is present.
2577 	 */
2578 	if (ACPI_FAILURE(status))
2579 		return (TRUE);
2580 
2581 	return (ACPI_BATTERY_PRESENT(s) ? TRUE : FALSE);
2582 }
2583 
2584 /*
2585  * Returns true if a device has at least one valid device ID.
2586  */
2587 BOOLEAN
2588 acpi_has_hid(ACPI_HANDLE h)
2589 {
2590     ACPI_DEVICE_INFO	*devinfo;
2591     BOOLEAN		ret;
2592 
2593     if (h == NULL ||
2594 	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2595 	return (FALSE);
2596 
2597     ret = FALSE;
2598     if ((devinfo->Valid & ACPI_VALID_HID) != 0)
2599 	ret = TRUE;
2600     else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2601 	if (devinfo->CompatibleIdList.Count > 0)
2602 	    ret = TRUE;
2603 
2604     AcpiOsFree(devinfo);
2605     return (ret);
2606 }
2607 
2608 /*
2609  * Match a HID string against a handle
2610  * returns ACPI_MATCHHID_HID if _HID match
2611  *         ACPI_MATCHHID_CID if _CID match and not _HID match.
2612  *         ACPI_MATCHHID_NOMATCH=0 if no match.
2613  */
2614 int
2615 acpi_MatchHid(ACPI_HANDLE h, const char *hid)
2616 {
2617     ACPI_DEVICE_INFO	*devinfo;
2618     BOOLEAN		ret;
2619     int			i;
2620 
2621     if (hid == NULL || h == NULL ||
2622 	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2623 	return (ACPI_MATCHHID_NOMATCH);
2624 
2625     ret = ACPI_MATCHHID_NOMATCH;
2626     if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
2627 	strcmp(hid, devinfo->HardwareId.String) == 0)
2628 	    ret = ACPI_MATCHHID_HID;
2629     else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2630 	for (i = 0; i < devinfo->CompatibleIdList.Count; i++) {
2631 	    if (strcmp(hid, devinfo->CompatibleIdList.Ids[i].String) == 0) {
2632 		ret = ACPI_MATCHHID_CID;
2633 		break;
2634 	    }
2635 	}
2636 
2637     AcpiOsFree(devinfo);
2638     return (ret);
2639 }
2640 
2641 /*
2642  * Return the handle of a named object within our scope, ie. that of (parent)
2643  * or one if its parents.
2644  */
2645 ACPI_STATUS
2646 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
2647 {
2648     ACPI_HANDLE		r;
2649     ACPI_STATUS		status;
2650 
2651     /* Walk back up the tree to the root */
2652     for (;;) {
2653 	status = AcpiGetHandle(parent, path, &r);
2654 	if (ACPI_SUCCESS(status)) {
2655 	    *result = r;
2656 	    return (AE_OK);
2657 	}
2658 	/* XXX Return error here? */
2659 	if (status != AE_NOT_FOUND)
2660 	    return (AE_OK);
2661 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
2662 	    return (AE_NOT_FOUND);
2663 	parent = r;
2664     }
2665 }
2666 
2667 ACPI_STATUS
2668 acpi_GetProperty(device_t dev, ACPI_STRING propname,
2669     const ACPI_OBJECT **value)
2670 {
2671 	device_t bus = device_get_parent(dev);
2672 
2673 	return (ACPI_GET_PROPERTY(bus, dev, propname, value));
2674 }
2675 
2676 /*
2677  * Allocate a buffer with a preset data size.
2678  */
2679 ACPI_BUFFER *
2680 acpi_AllocBuffer(int size)
2681 {
2682     ACPI_BUFFER	*buf;
2683 
2684     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
2685 	return (NULL);
2686     buf->Length = size;
2687     buf->Pointer = (void *)(buf + 1);
2688     return (buf);
2689 }
2690 
2691 ACPI_STATUS
2692 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
2693 {
2694     ACPI_OBJECT arg1;
2695     ACPI_OBJECT_LIST args;
2696 
2697     arg1.Type = ACPI_TYPE_INTEGER;
2698     arg1.Integer.Value = number;
2699     args.Count = 1;
2700     args.Pointer = &arg1;
2701 
2702     return (AcpiEvaluateObject(handle, path, &args, NULL));
2703 }
2704 
2705 /*
2706  * Evaluate a path that should return an integer.
2707  */
2708 ACPI_STATUS
2709 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
2710 {
2711     ACPI_STATUS	status;
2712     ACPI_BUFFER	buf;
2713     ACPI_OBJECT	param;
2714 
2715     if (handle == NULL)
2716 	handle = ACPI_ROOT_OBJECT;
2717 
2718     /*
2719      * Assume that what we've been pointed at is an Integer object, or
2720      * a method that will return an Integer.
2721      */
2722     buf.Pointer = &param;
2723     buf.Length = sizeof(param);
2724     status = AcpiEvaluateObject(handle, path, NULL, &buf);
2725     if (ACPI_SUCCESS(status)) {
2726 	if (param.Type == ACPI_TYPE_INTEGER)
2727 	    *number = param.Integer.Value;
2728 	else
2729 	    status = AE_TYPE;
2730     }
2731 
2732     /*
2733      * In some applications, a method that's expected to return an Integer
2734      * may instead return a Buffer (probably to simplify some internal
2735      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
2736      * convert it into an Integer as best we can.
2737      *
2738      * This is a hack.
2739      */
2740     if (status == AE_BUFFER_OVERFLOW) {
2741 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
2742 	    status = AE_NO_MEMORY;
2743 	} else {
2744 	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
2745 	    if (ACPI_SUCCESS(status))
2746 		status = acpi_ConvertBufferToInteger(&buf, number);
2747 	    AcpiOsFree(buf.Pointer);
2748 	}
2749     }
2750     return (status);
2751 }
2752 
2753 ACPI_STATUS
2754 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
2755 {
2756     ACPI_OBJECT	*p;
2757     UINT8	*val;
2758     int		i;
2759 
2760     p = (ACPI_OBJECT *)bufp->Pointer;
2761     if (p->Type == ACPI_TYPE_INTEGER) {
2762 	*number = p->Integer.Value;
2763 	return (AE_OK);
2764     }
2765     if (p->Type != ACPI_TYPE_BUFFER)
2766 	return (AE_TYPE);
2767     if (p->Buffer.Length > sizeof(int))
2768 	return (AE_BAD_DATA);
2769 
2770     *number = 0;
2771     val = p->Buffer.Pointer;
2772     for (i = 0; i < p->Buffer.Length; i++)
2773 	*number += val[i] << (i * 8);
2774     return (AE_OK);
2775 }
2776 
2777 /*
2778  * Iterate over the elements of an a package object, calling the supplied
2779  * function for each element.
2780  *
2781  * XXX possible enhancement might be to abort traversal on error.
2782  */
2783 ACPI_STATUS
2784 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
2785 	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
2786 {
2787     ACPI_OBJECT	*comp;
2788     int		i;
2789 
2790     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
2791 	return (AE_BAD_PARAMETER);
2792 
2793     /* Iterate over components */
2794     i = 0;
2795     comp = pkg->Package.Elements;
2796     for (; i < pkg->Package.Count; i++, comp++)
2797 	func(comp, arg);
2798 
2799     return (AE_OK);
2800 }
2801 
2802 /*
2803  * Find the (index)th resource object in a set.
2804  */
2805 ACPI_STATUS
2806 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
2807 {
2808     ACPI_RESOURCE	*rp;
2809     int			i;
2810 
2811     rp = (ACPI_RESOURCE *)buf->Pointer;
2812     i = index;
2813     while (i-- > 0) {
2814 	/* Range check */
2815 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2816 	    return (AE_BAD_PARAMETER);
2817 
2818 	/* Check for terminator */
2819 	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2820 	    return (AE_NOT_FOUND);
2821 	rp = ACPI_NEXT_RESOURCE(rp);
2822     }
2823     if (resp != NULL)
2824 	*resp = rp;
2825 
2826     return (AE_OK);
2827 }
2828 
2829 /*
2830  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
2831  *
2832  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
2833  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
2834  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
2835  * resources.
2836  */
2837 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
2838 
2839 ACPI_STATUS
2840 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
2841 {
2842     ACPI_RESOURCE	*rp;
2843     void		*newp;
2844 
2845     /* Initialise the buffer if necessary. */
2846     if (buf->Pointer == NULL) {
2847 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
2848 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
2849 	    return (AE_NO_MEMORY);
2850 	rp = (ACPI_RESOURCE *)buf->Pointer;
2851 	rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2852 	rp->Length = ACPI_RS_SIZE_MIN;
2853     }
2854     if (res == NULL)
2855 	return (AE_OK);
2856 
2857     /*
2858      * Scan the current buffer looking for the terminator.
2859      * This will either find the terminator or hit the end
2860      * of the buffer and return an error.
2861      */
2862     rp = (ACPI_RESOURCE *)buf->Pointer;
2863     for (;;) {
2864 	/* Range check, don't go outside the buffer */
2865 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2866 	    return (AE_BAD_PARAMETER);
2867 	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2868 	    break;
2869 	rp = ACPI_NEXT_RESOURCE(rp);
2870     }
2871 
2872     /*
2873      * Check the size of the buffer and expand if required.
2874      *
2875      * Required size is:
2876      *	size of existing resources before terminator +
2877      *	size of new resource and header +
2878      * 	size of terminator.
2879      *
2880      * Note that this loop should really only run once, unless
2881      * for some reason we are stuffing a *really* huge resource.
2882      */
2883     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
2884 	    res->Length + ACPI_RS_SIZE_NO_DATA +
2885 	    ACPI_RS_SIZE_MIN) >= buf->Length) {
2886 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
2887 	    return (AE_NO_MEMORY);
2888 	bcopy(buf->Pointer, newp, buf->Length);
2889 	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
2890 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
2891 	AcpiOsFree(buf->Pointer);
2892 	buf->Pointer = newp;
2893 	buf->Length += buf->Length;
2894     }
2895 
2896     /* Insert the new resource. */
2897     bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
2898 
2899     /* And add the terminator. */
2900     rp = ACPI_NEXT_RESOURCE(rp);
2901     rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2902     rp->Length = ACPI_RS_SIZE_MIN;
2903 
2904     return (AE_OK);
2905 }
2906 
2907 UINT64
2908 acpi_DSMQuery(ACPI_HANDLE h, const uint8_t *uuid, int revision)
2909 {
2910     /*
2911      * ACPI spec 9.1.1 defines this.
2912      *
2913      * "Arg2: Function Index Represents a specific function whose meaning is
2914      * specific to the UUID and Revision ID. Function indices should start
2915      * with 1. Function number zero is a query function (see the special
2916      * return code defined below)."
2917      */
2918     ACPI_BUFFER buf;
2919     ACPI_OBJECT *obj;
2920     UINT64 ret = 0;
2921     int i;
2922 
2923     if (!ACPI_SUCCESS(acpi_EvaluateDSM(h, uuid, revision, 0, NULL, &buf))) {
2924 	ACPI_INFO(("Failed to enumerate DSM functions\n"));
2925 	return (0);
2926     }
2927 
2928     obj = (ACPI_OBJECT *)buf.Pointer;
2929     KASSERT(obj, ("Object not allowed to be NULL\n"));
2930 
2931     /*
2932      * From ACPI 6.2 spec 9.1.1:
2933      * If Function Index = 0, a Buffer containing a function index bitfield.
2934      * Otherwise, the return value and type depends on the UUID and revision
2935      * ID (see below).
2936      */
2937     switch (obj->Type) {
2938     case ACPI_TYPE_BUFFER:
2939 	for (i = 0; i < MIN(obj->Buffer.Length, sizeof(ret)); i++)
2940 	    ret |= (((uint64_t)obj->Buffer.Pointer[i]) << (i * 8));
2941 	break;
2942     case ACPI_TYPE_INTEGER:
2943 	ACPI_BIOS_WARNING((AE_INFO,
2944 	    "Possibly buggy BIOS with ACPI_TYPE_INTEGER for function enumeration\n"));
2945 	ret = obj->Integer.Value;
2946 	break;
2947     default:
2948 	ACPI_WARNING((AE_INFO, "Unexpected return type %u\n", obj->Type));
2949     };
2950 
2951     AcpiOsFree(obj);
2952     return ret;
2953 }
2954 
2955 /*
2956  * DSM may return multiple types depending on the function. It is therefore
2957  * unsafe to use the typed evaluation. It is highly recommended that the caller
2958  * check the type of the returned object.
2959  */
2960 ACPI_STATUS
2961 acpi_EvaluateDSM(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
2962     UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf)
2963 {
2964 	return (acpi_EvaluateDSMTyped(handle, uuid, revision, function,
2965 	    package, out_buf, ACPI_TYPE_ANY));
2966 }
2967 
2968 ACPI_STATUS
2969 acpi_EvaluateDSMTyped(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
2970     UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf,
2971     ACPI_OBJECT_TYPE type)
2972 {
2973     ACPI_OBJECT arg[4];
2974     ACPI_OBJECT_LIST arglist;
2975     ACPI_BUFFER buf;
2976     ACPI_STATUS status;
2977 
2978     if (out_buf == NULL)
2979 	return (AE_NO_MEMORY);
2980 
2981     arg[0].Type = ACPI_TYPE_BUFFER;
2982     arg[0].Buffer.Length = ACPI_UUID_LENGTH;
2983     arg[0].Buffer.Pointer = __DECONST(uint8_t *, uuid);
2984     arg[1].Type = ACPI_TYPE_INTEGER;
2985     arg[1].Integer.Value = revision;
2986     arg[2].Type = ACPI_TYPE_INTEGER;
2987     arg[2].Integer.Value = function;
2988     if (package) {
2989 	arg[3] = *package;
2990     } else {
2991 	arg[3].Type = ACPI_TYPE_PACKAGE;
2992 	arg[3].Package.Count = 0;
2993 	arg[3].Package.Elements = NULL;
2994     }
2995 
2996     arglist.Pointer = arg;
2997     arglist.Count = 4;
2998     buf.Pointer = NULL;
2999     buf.Length = ACPI_ALLOCATE_BUFFER;
3000     status = AcpiEvaluateObjectTyped(handle, "_DSM", &arglist, &buf, type);
3001     if (ACPI_FAILURE(status))
3002 	return (status);
3003 
3004     KASSERT(ACPI_SUCCESS(status), ("Unexpected status"));
3005 
3006     *out_buf = buf;
3007     return (status);
3008 }
3009 
3010 ACPI_STATUS
3011 acpi_EvaluateOSC(ACPI_HANDLE handle, uint8_t *uuid, int revision, int count,
3012     uint32_t *caps_in, uint32_t *caps_out, bool query)
3013 {
3014 	ACPI_OBJECT arg[4], *ret;
3015 	ACPI_OBJECT_LIST arglist;
3016 	ACPI_BUFFER buf;
3017 	ACPI_STATUS status;
3018 
3019 	arglist.Pointer = arg;
3020 	arglist.Count = 4;
3021 	arg[0].Type = ACPI_TYPE_BUFFER;
3022 	arg[0].Buffer.Length = ACPI_UUID_LENGTH;
3023 	arg[0].Buffer.Pointer = uuid;
3024 	arg[1].Type = ACPI_TYPE_INTEGER;
3025 	arg[1].Integer.Value = revision;
3026 	arg[2].Type = ACPI_TYPE_INTEGER;
3027 	arg[2].Integer.Value = count;
3028 	arg[3].Type = ACPI_TYPE_BUFFER;
3029 	arg[3].Buffer.Length = count * sizeof(*caps_in);
3030 	arg[3].Buffer.Pointer = (uint8_t *)caps_in;
3031 	caps_in[0] = query ? 1 : 0;
3032 	buf.Pointer = NULL;
3033 	buf.Length = ACPI_ALLOCATE_BUFFER;
3034 	status = AcpiEvaluateObjectTyped(handle, "_OSC", &arglist, &buf,
3035 	    ACPI_TYPE_BUFFER);
3036 	if (ACPI_FAILURE(status))
3037 		return (status);
3038 	if (caps_out != NULL) {
3039 		ret = buf.Pointer;
3040 		if (ret->Buffer.Length != count * sizeof(*caps_out)) {
3041 			AcpiOsFree(buf.Pointer);
3042 			return (AE_BUFFER_OVERFLOW);
3043 		}
3044 		bcopy(ret->Buffer.Pointer, caps_out, ret->Buffer.Length);
3045 	}
3046 	AcpiOsFree(buf.Pointer);
3047 	return (status);
3048 }
3049 
3050 /*
3051  * Set interrupt model.
3052  */
3053 ACPI_STATUS
3054 acpi_SetIntrModel(int model)
3055 {
3056 
3057     return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
3058 }
3059 
3060 /*
3061  * Walk subtables of a table and call a callback routine for each
3062  * subtable.  The caller should provide the first subtable and a
3063  * pointer to the end of the table.  This can be used to walk tables
3064  * such as MADT and SRAT that use subtable entries.
3065  */
3066 void
3067 acpi_walk_subtables(void *first, void *end, acpi_subtable_handler *handler,
3068     void *arg)
3069 {
3070     ACPI_SUBTABLE_HEADER *entry;
3071 
3072     for (entry = first; (void *)entry < end; ) {
3073 	/* Avoid an infinite loop if we hit a bogus entry. */
3074 	if (entry->Length < sizeof(ACPI_SUBTABLE_HEADER))
3075 	    return;
3076 
3077 	handler(entry, arg);
3078 	entry = ACPI_ADD_PTR(ACPI_SUBTABLE_HEADER, entry, entry->Length);
3079     }
3080 }
3081 
3082 /*
3083  * DEPRECATED.  This interface has serious deficiencies and will be
3084  * removed.
3085  *
3086  * Immediately enter the sleep state.  In the old model, acpiconf(8) ran
3087  * rc.suspend and rc.resume so we don't have to notify devd(8) to do this.
3088  */
3089 ACPI_STATUS
3090 acpi_SetSleepState(struct acpi_softc *sc, int state)
3091 {
3092     static int once;
3093 
3094     if (!once) {
3095 	device_printf(sc->acpi_dev,
3096 "warning: acpi_SetSleepState() deprecated, need to update your software\n");
3097 	once = 1;
3098     }
3099     return (acpi_EnterSleepState(sc, state));
3100 }
3101 
3102 #if defined(__amd64__) || defined(__i386__)
3103 static void
3104 acpi_sleep_force_task(void *context)
3105 {
3106     struct acpi_softc *sc = (struct acpi_softc *)context;
3107 
3108     if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
3109 	device_printf(sc->acpi_dev, "force sleep state S%d failed\n",
3110 	    sc->acpi_next_sstate);
3111 }
3112 
3113 static void
3114 acpi_sleep_force(void *arg)
3115 {
3116     struct acpi_softc *sc = (struct acpi_softc *)arg;
3117 
3118     device_printf(sc->acpi_dev,
3119 	"suspend request timed out, forcing sleep now\n");
3120     /*
3121      * XXX Suspending from callout causes freezes in DEVICE_SUSPEND().
3122      * Suspend from acpi_task thread instead.
3123      */
3124     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3125 	acpi_sleep_force_task, sc)))
3126 	device_printf(sc->acpi_dev, "AcpiOsExecute() for sleeping failed\n");
3127 }
3128 #endif
3129 
3130 /*
3131  * Request that the system enter the given suspend state.  All /dev/apm
3132  * devices and devd(8) will be notified.  Userland then has a chance to
3133  * save state and acknowledge the request.  The system sleeps once all
3134  * acks are in.
3135  */
3136 int
3137 acpi_ReqSleepState(struct acpi_softc *sc, int state)
3138 {
3139 #if defined(__amd64__) || defined(__i386__)
3140     struct apm_clone_data *clone;
3141     ACPI_STATUS status;
3142 
3143     if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
3144 	return (EINVAL);
3145     if (!acpi_sleep_states[state])
3146 	return (EOPNOTSUPP);
3147 
3148     /*
3149      * If a reboot/shutdown/suspend request is already in progress or
3150      * suspend is blocked due to an upcoming shutdown, just return.
3151      */
3152     if (rebooting || sc->acpi_next_sstate != 0 || suspend_blocked) {
3153 	return (0);
3154     }
3155 
3156     /* Wait until sleep is enabled. */
3157     while (sc->acpi_sleep_disabled) {
3158 	AcpiOsSleep(1000);
3159     }
3160 
3161     ACPI_LOCK(acpi);
3162 
3163     sc->acpi_next_sstate = state;
3164 
3165     /* S5 (soft-off) should be entered directly with no waiting. */
3166     if (state == ACPI_STATE_S5) {
3167     	ACPI_UNLOCK(acpi);
3168 	status = acpi_EnterSleepState(sc, state);
3169 	return (ACPI_SUCCESS(status) ? 0 : ENXIO);
3170     }
3171 
3172     /* Record the pending state and notify all apm devices. */
3173     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
3174 	clone->notify_status = APM_EV_NONE;
3175 	if ((clone->flags & ACPI_EVF_DEVD) == 0) {
3176 	    selwakeuppri(&clone->sel_read, PZERO);
3177 	    KNOTE_LOCKED(&clone->sel_read.si_note, 0);
3178 	}
3179     }
3180 
3181     /* If devd(8) is not running, immediately enter the sleep state. */
3182     if (!devctl_process_running()) {
3183 	ACPI_UNLOCK(acpi);
3184 	status = acpi_EnterSleepState(sc, state);
3185 	return (ACPI_SUCCESS(status) ? 0 : ENXIO);
3186     }
3187 
3188     /*
3189      * Set a timeout to fire if userland doesn't ack the suspend request
3190      * in time.  This way we still eventually go to sleep if we were
3191      * overheating or running low on battery, even if userland is hung.
3192      * We cancel this timeout once all userland acks are in or the
3193      * suspend request is aborted.
3194      */
3195     callout_reset(&sc->susp_force_to, 10 * hz, acpi_sleep_force, sc);
3196     ACPI_UNLOCK(acpi);
3197 
3198     /* Now notify devd(8) also. */
3199     acpi_UserNotify("Suspend", ACPI_ROOT_OBJECT, state);
3200 
3201     return (0);
3202 #else
3203     /* This platform does not support acpi suspend/resume. */
3204     return (EOPNOTSUPP);
3205 #endif
3206 }
3207 
3208 /*
3209  * Acknowledge (or reject) a pending sleep state.  The caller has
3210  * prepared for suspend and is now ready for it to proceed.  If the
3211  * error argument is non-zero, it indicates suspend should be cancelled
3212  * and gives an errno value describing why.  Once all votes are in,
3213  * we suspend the system.
3214  */
3215 int
3216 acpi_AckSleepState(struct apm_clone_data *clone, int error)
3217 {
3218 #if defined(__amd64__) || defined(__i386__)
3219     struct acpi_softc *sc;
3220     int ret, sleeping;
3221 
3222     /* If no pending sleep state, return an error. */
3223     ACPI_LOCK(acpi);
3224     sc = clone->acpi_sc;
3225     if (sc->acpi_next_sstate == 0) {
3226     	ACPI_UNLOCK(acpi);
3227 	return (ENXIO);
3228     }
3229 
3230     /* Caller wants to abort suspend process. */
3231     if (error) {
3232 	sc->acpi_next_sstate = 0;
3233 	callout_stop(&sc->susp_force_to);
3234 	device_printf(sc->acpi_dev,
3235 	    "listener on %s cancelled the pending suspend\n",
3236 	    devtoname(clone->cdev));
3237     	ACPI_UNLOCK(acpi);
3238 	return (0);
3239     }
3240 
3241     /*
3242      * Mark this device as acking the suspend request.  Then, walk through
3243      * all devices, seeing if they agree yet.  We only count devices that
3244      * are writable since read-only devices couldn't ack the request.
3245      */
3246     sleeping = TRUE;
3247     clone->notify_status = APM_EV_ACKED;
3248     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
3249 	if ((clone->flags & ACPI_EVF_WRITE) != 0 &&
3250 	    clone->notify_status != APM_EV_ACKED) {
3251 	    sleeping = FALSE;
3252 	    break;
3253 	}
3254     }
3255 
3256     /* If all devices have voted "yes", we will suspend now. */
3257     if (sleeping)
3258 	callout_stop(&sc->susp_force_to);
3259     ACPI_UNLOCK(acpi);
3260     ret = 0;
3261     if (sleeping) {
3262 	if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
3263 		ret = ENODEV;
3264     }
3265     return (ret);
3266 #else
3267     /* This platform does not support acpi suspend/resume. */
3268     return (EOPNOTSUPP);
3269 #endif
3270 }
3271 
3272 static void
3273 acpi_sleep_enable(void *arg)
3274 {
3275     struct acpi_softc	*sc = (struct acpi_softc *)arg;
3276 
3277     ACPI_LOCK_ASSERT(acpi);
3278 
3279     /* Reschedule if the system is not fully up and running. */
3280     if (!AcpiGbl_SystemAwakeAndRunning) {
3281 	callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3282 	return;
3283     }
3284 
3285     sc->acpi_sleep_disabled = FALSE;
3286 }
3287 
3288 static ACPI_STATUS
3289 acpi_sleep_disable(struct acpi_softc *sc)
3290 {
3291     ACPI_STATUS		status;
3292 
3293     /* Fail if the system is not fully up and running. */
3294     if (!AcpiGbl_SystemAwakeAndRunning)
3295 	return (AE_ERROR);
3296 
3297     ACPI_LOCK(acpi);
3298     status = sc->acpi_sleep_disabled ? AE_ERROR : AE_OK;
3299     sc->acpi_sleep_disabled = TRUE;
3300     ACPI_UNLOCK(acpi);
3301 
3302     return (status);
3303 }
3304 
3305 enum acpi_sleep_state {
3306     ACPI_SS_NONE,
3307     ACPI_SS_GPE_SET,
3308     ACPI_SS_DEV_SUSPEND,
3309     ACPI_SS_SLP_PREP,
3310     ACPI_SS_SLEPT,
3311 };
3312 
3313 /*
3314  * Enter the desired system sleep state.
3315  *
3316  * Currently we support S1-S5 but S4 is only S4BIOS
3317  */
3318 static ACPI_STATUS
3319 acpi_EnterSleepState(struct acpi_softc *sc, int state)
3320 {
3321     register_t intr;
3322     ACPI_STATUS status;
3323     ACPI_EVENT_STATUS power_button_status;
3324     enum acpi_sleep_state slp_state;
3325     int sleep_result;
3326 
3327     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3328 
3329     if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
3330 	return_ACPI_STATUS (AE_BAD_PARAMETER);
3331     if (!acpi_sleep_states[state]) {
3332 	device_printf(sc->acpi_dev, "Sleep state S%d not supported by BIOS\n",
3333 	    state);
3334 	return (AE_SUPPORT);
3335     }
3336 
3337     /* Re-entry once we're suspending is not allowed. */
3338     status = acpi_sleep_disable(sc);
3339     if (ACPI_FAILURE(status)) {
3340 	device_printf(sc->acpi_dev,
3341 	    "suspend request ignored (not ready yet)\n");
3342 	return (status);
3343     }
3344 
3345     if (state == ACPI_STATE_S5) {
3346 	/*
3347 	 * Shut down cleanly and power off.  This will call us back through the
3348 	 * shutdown handlers.
3349 	 */
3350 	shutdown_nice(RB_POWEROFF);
3351 	return_ACPI_STATUS (AE_OK);
3352     }
3353 
3354     EVENTHANDLER_INVOKE(power_suspend_early);
3355     stop_all_proc();
3356     suspend_all_fs();
3357     EVENTHANDLER_INVOKE(power_suspend);
3358 
3359 #ifdef EARLY_AP_STARTUP
3360     MPASS(mp_ncpus == 1 || smp_started);
3361     thread_lock(curthread);
3362     sched_bind(curthread, 0);
3363     thread_unlock(curthread);
3364 #else
3365     if (smp_started) {
3366 	thread_lock(curthread);
3367 	sched_bind(curthread, 0);
3368 	thread_unlock(curthread);
3369     }
3370 #endif
3371 
3372     /*
3373      * Be sure to hold Giant across DEVICE_SUSPEND/RESUME
3374      */
3375     bus_topo_lock();
3376 
3377     slp_state = ACPI_SS_NONE;
3378 
3379     sc->acpi_sstate = state;
3380 
3381     /* Enable any GPEs as appropriate and requested by the user. */
3382     acpi_wake_prep_walk(state);
3383     slp_state = ACPI_SS_GPE_SET;
3384 
3385     /*
3386      * Inform all devices that we are going to sleep.  If at least one
3387      * device fails, DEVICE_SUSPEND() automatically resumes the tree.
3388      *
3389      * XXX Note that a better two-pass approach with a 'veto' pass
3390      * followed by a "real thing" pass would be better, but the current
3391      * bus interface does not provide for this.
3392      */
3393     if (DEVICE_SUSPEND(root_bus) != 0) {
3394 	device_printf(sc->acpi_dev, "device_suspend failed\n");
3395 	goto backout;
3396     }
3397     slp_state = ACPI_SS_DEV_SUSPEND;
3398 
3399     status = AcpiEnterSleepStatePrep(state);
3400     if (ACPI_FAILURE(status)) {
3401 	device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
3402 		      AcpiFormatException(status));
3403 	goto backout;
3404     }
3405     slp_state = ACPI_SS_SLP_PREP;
3406 
3407     if (sc->acpi_sleep_delay > 0)
3408 	DELAY(sc->acpi_sleep_delay * 1000000);
3409 
3410     suspendclock();
3411     intr = intr_disable();
3412     if (state != ACPI_STATE_S1) {
3413 	sleep_result = acpi_sleep_machdep(sc, state);
3414 	acpi_wakeup_machdep(sc, state, sleep_result, 0);
3415 
3416 	/*
3417 	 * XXX According to ACPI specification SCI_EN bit should be restored
3418 	 * by ACPI platform (BIOS, firmware) to its pre-sleep state.
3419 	 * Unfortunately some BIOSes fail to do that and that leads to
3420 	 * unexpected and serious consequences during wake up like a system
3421 	 * getting stuck in SMI handlers.
3422 	 * This hack is picked up from Linux, which claims that it follows
3423 	 * Windows behavior.
3424 	 */
3425 	if (sleep_result == 1 && state != ACPI_STATE_S4)
3426 	    AcpiWriteBitRegister(ACPI_BITREG_SCI_ENABLE, ACPI_ENABLE_EVENT);
3427 
3428 	if (sleep_result == 1 && state == ACPI_STATE_S3) {
3429 	    /*
3430 	     * Prevent mis-interpretation of the wakeup by power button
3431 	     * as a request for power off.
3432 	     * Ideally we should post an appropriate wakeup event,
3433 	     * perhaps using acpi_event_power_button_wake or alike.
3434 	     *
3435 	     * Clearing of power button status after wakeup is mandated
3436 	     * by ACPI specification in section "Fixed Power Button".
3437 	     *
3438 	     * XXX As of ACPICA 20121114 AcpiGetEventStatus provides
3439 	     * status as 0/1 corressponding to inactive/active despite
3440 	     * its type being ACPI_EVENT_STATUS.  In other words,
3441 	     * we should not test for ACPI_EVENT_FLAG_SET for time being.
3442 	     */
3443 	    if (ACPI_SUCCESS(AcpiGetEventStatus(ACPI_EVENT_POWER_BUTTON,
3444 		&power_button_status)) && power_button_status != 0) {
3445 		AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
3446 		device_printf(sc->acpi_dev,
3447 		    "cleared fixed power button status\n");
3448 	    }
3449 	}
3450 
3451 	intr_restore(intr);
3452 
3453 	/* call acpi_wakeup_machdep() again with interrupt enabled */
3454 	acpi_wakeup_machdep(sc, state, sleep_result, 1);
3455 
3456 	AcpiLeaveSleepStatePrep(state);
3457 
3458 	if (sleep_result == -1)
3459 		goto backout;
3460 
3461 	/* Re-enable ACPI hardware on wakeup from sleep state 4. */
3462 	if (state == ACPI_STATE_S4)
3463 	    AcpiEnable();
3464     } else {
3465 	status = AcpiEnterSleepState(state);
3466 	intr_restore(intr);
3467 	AcpiLeaveSleepStatePrep(state);
3468 	if (ACPI_FAILURE(status)) {
3469 	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
3470 			  AcpiFormatException(status));
3471 	    goto backout;
3472 	}
3473     }
3474     slp_state = ACPI_SS_SLEPT;
3475 
3476     /*
3477      * Back out state according to how far along we got in the suspend
3478      * process.  This handles both the error and success cases.
3479      */
3480 backout:
3481     if (slp_state >= ACPI_SS_SLP_PREP)
3482 	resumeclock();
3483     if (slp_state >= ACPI_SS_GPE_SET) {
3484 	acpi_wake_prep_walk(state);
3485 	sc->acpi_sstate = ACPI_STATE_S0;
3486     }
3487     if (slp_state >= ACPI_SS_DEV_SUSPEND)
3488 	DEVICE_RESUME(root_bus);
3489     if (slp_state >= ACPI_SS_SLP_PREP)
3490 	AcpiLeaveSleepState(state);
3491     if (slp_state >= ACPI_SS_SLEPT) {
3492 #if defined(__i386__) || defined(__amd64__)
3493 	/* NB: we are still using ACPI timecounter at this point. */
3494 	resume_TSC();
3495 #endif
3496 	acpi_resync_clock(sc);
3497 	acpi_enable_fixed_events(sc);
3498     }
3499     sc->acpi_next_sstate = 0;
3500 
3501     bus_topo_unlock();
3502 
3503 #ifdef EARLY_AP_STARTUP
3504     thread_lock(curthread);
3505     sched_unbind(curthread);
3506     thread_unlock(curthread);
3507 #else
3508     if (smp_started) {
3509 	thread_lock(curthread);
3510 	sched_unbind(curthread);
3511 	thread_unlock(curthread);
3512     }
3513 #endif
3514 
3515     resume_all_fs();
3516     resume_all_proc();
3517 
3518     EVENTHANDLER_INVOKE(power_resume);
3519 
3520     /* Allow another sleep request after a while. */
3521     callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3522 
3523     /* Run /etc/rc.resume after we are back. */
3524     if (devctl_process_running())
3525 	acpi_UserNotify("Resume", ACPI_ROOT_OBJECT, state);
3526 
3527     return_ACPI_STATUS (status);
3528 }
3529 
3530 static void
3531 acpi_resync_clock(struct acpi_softc *sc)
3532 {
3533 
3534     /*
3535      * Warm up timecounter again and reset system clock.
3536      */
3537     (void)timecounter->tc_get_timecount(timecounter);
3538     inittodr(time_second + sc->acpi_sleep_delay);
3539 }
3540 
3541 /* Enable or disable the device's wake GPE. */
3542 int
3543 acpi_wake_set_enable(device_t dev, int enable)
3544 {
3545     struct acpi_prw_data prw;
3546     ACPI_STATUS status;
3547     int flags;
3548 
3549     /* Make sure the device supports waking the system and get the GPE. */
3550     if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
3551 	return (ENXIO);
3552 
3553     flags = acpi_get_flags(dev);
3554     if (enable) {
3555 	status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3556 	    ACPI_GPE_ENABLE);
3557 	if (ACPI_FAILURE(status)) {
3558 	    device_printf(dev, "enable wake failed\n");
3559 	    return (ENXIO);
3560 	}
3561 	acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
3562     } else {
3563 	status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3564 	    ACPI_GPE_DISABLE);
3565 	if (ACPI_FAILURE(status)) {
3566 	    device_printf(dev, "disable wake failed\n");
3567 	    return (ENXIO);
3568 	}
3569 	acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
3570     }
3571 
3572     return (0);
3573 }
3574 
3575 static int
3576 acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate)
3577 {
3578     struct acpi_prw_data prw;
3579     device_t dev;
3580 
3581     /* Check that this is a wake-capable device and get its GPE. */
3582     if (acpi_parse_prw(handle, &prw) != 0)
3583 	return (ENXIO);
3584     dev = acpi_get_device(handle);
3585 
3586     /*
3587      * The destination sleep state must be less than (i.e., higher power)
3588      * or equal to the value specified by _PRW.  If this GPE cannot be
3589      * enabled for the next sleep state, then disable it.  If it can and
3590      * the user requested it be enabled, turn on any required power resources
3591      * and set _PSW.
3592      */
3593     if (sstate > prw.lowest_wake) {
3594 	AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_DISABLE);
3595 	if (bootverbose)
3596 	    device_printf(dev, "wake_prep disabled wake for %s (S%d)\n",
3597 		acpi_name(handle), sstate);
3598     } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
3599 	acpi_pwr_wake_enable(handle, 1);
3600 	acpi_SetInteger(handle, "_PSW", 1);
3601 	if (bootverbose)
3602 	    device_printf(dev, "wake_prep enabled for %s (S%d)\n",
3603 		acpi_name(handle), sstate);
3604     }
3605 
3606     return (0);
3607 }
3608 
3609 static int
3610 acpi_wake_run_prep(ACPI_HANDLE handle, int sstate)
3611 {
3612     struct acpi_prw_data prw;
3613     device_t dev;
3614 
3615     /*
3616      * Check that this is a wake-capable device and get its GPE.  Return
3617      * now if the user didn't enable this device for wake.
3618      */
3619     if (acpi_parse_prw(handle, &prw) != 0)
3620 	return (ENXIO);
3621     dev = acpi_get_device(handle);
3622     if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
3623 	return (0);
3624 
3625     /*
3626      * If this GPE couldn't be enabled for the previous sleep state, it was
3627      * disabled before going to sleep so re-enable it.  If it was enabled,
3628      * clear _PSW and turn off any power resources it used.
3629      */
3630     if (sstate > prw.lowest_wake) {
3631 	AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_ENABLE);
3632 	if (bootverbose)
3633 	    device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
3634     } else {
3635 	acpi_SetInteger(handle, "_PSW", 0);
3636 	acpi_pwr_wake_enable(handle, 0);
3637 	if (bootverbose)
3638 	    device_printf(dev, "run_prep cleaned up for %s\n",
3639 		acpi_name(handle));
3640     }
3641 
3642     return (0);
3643 }
3644 
3645 static ACPI_STATUS
3646 acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
3647 {
3648     int sstate;
3649 
3650     /* If suspending, run the sleep prep function, otherwise wake. */
3651     sstate = *(int *)context;
3652     if (AcpiGbl_SystemAwakeAndRunning)
3653 	acpi_wake_sleep_prep(handle, sstate);
3654     else
3655 	acpi_wake_run_prep(handle, sstate);
3656     return (AE_OK);
3657 }
3658 
3659 /* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
3660 static int
3661 acpi_wake_prep_walk(int sstate)
3662 {
3663     ACPI_HANDLE sb_handle;
3664 
3665     if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
3666 	AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
3667 	    acpi_wake_prep, NULL, &sstate, NULL);
3668     return (0);
3669 }
3670 
3671 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
3672 static int
3673 acpi_wake_sysctl_walk(device_t dev)
3674 {
3675     int error, i, numdevs;
3676     device_t *devlist;
3677     device_t child;
3678     ACPI_STATUS status;
3679 
3680     error = device_get_children(dev, &devlist, &numdevs);
3681     if (error != 0 || numdevs == 0) {
3682 	if (numdevs == 0)
3683 	    free(devlist, M_TEMP);
3684 	return (error);
3685     }
3686     for (i = 0; i < numdevs; i++) {
3687 	child = devlist[i];
3688 	acpi_wake_sysctl_walk(child);
3689 	if (!device_is_attached(child))
3690 	    continue;
3691 	status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
3692 	if (ACPI_SUCCESS(status)) {
3693 	    SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
3694 		SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
3695 		"wake", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, child, 0,
3696 		acpi_wake_set_sysctl, "I", "Device set to wake the system");
3697 	}
3698     }
3699     free(devlist, M_TEMP);
3700 
3701     return (0);
3702 }
3703 
3704 /* Enable or disable wake from userland. */
3705 static int
3706 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
3707 {
3708     int enable, error;
3709     device_t dev;
3710 
3711     dev = (device_t)arg1;
3712     enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
3713 
3714     error = sysctl_handle_int(oidp, &enable, 0, req);
3715     if (error != 0 || req->newptr == NULL)
3716 	return (error);
3717     if (enable != 0 && enable != 1)
3718 	return (EINVAL);
3719 
3720     return (acpi_wake_set_enable(dev, enable));
3721 }
3722 
3723 /* Parse a device's _PRW into a structure. */
3724 int
3725 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
3726 {
3727     ACPI_STATUS			status;
3728     ACPI_BUFFER			prw_buffer;
3729     ACPI_OBJECT			*res, *res2;
3730     int				error, i, power_count;
3731 
3732     if (h == NULL || prw == NULL)
3733 	return (EINVAL);
3734 
3735     /*
3736      * The _PRW object (7.2.9) is only required for devices that have the
3737      * ability to wake the system from a sleeping state.
3738      */
3739     error = EINVAL;
3740     prw_buffer.Pointer = NULL;
3741     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
3742     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
3743     if (ACPI_FAILURE(status))
3744 	return (ENOENT);
3745     res = (ACPI_OBJECT *)prw_buffer.Pointer;
3746     if (res == NULL)
3747 	return (ENOENT);
3748     if (!ACPI_PKG_VALID(res, 2))
3749 	goto out;
3750 
3751     /*
3752      * Element 1 of the _PRW object:
3753      * The lowest power system sleeping state that can be entered while still
3754      * providing wake functionality.  The sleeping state being entered must
3755      * be less than (i.e., higher power) or equal to this value.
3756      */
3757     if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
3758 	goto out;
3759 
3760     /*
3761      * Element 0 of the _PRW object:
3762      */
3763     switch (res->Package.Elements[0].Type) {
3764     case ACPI_TYPE_INTEGER:
3765 	/*
3766 	 * If the data type of this package element is numeric, then this
3767 	 * _PRW package element is the bit index in the GPEx_EN, in the
3768 	 * GPE blocks described in the FADT, of the enable bit that is
3769 	 * enabled for the wake event.
3770 	 */
3771 	prw->gpe_handle = NULL;
3772 	prw->gpe_bit = res->Package.Elements[0].Integer.Value;
3773 	error = 0;
3774 	break;
3775     case ACPI_TYPE_PACKAGE:
3776 	/*
3777 	 * If the data type of this package element is a package, then this
3778 	 * _PRW package element is itself a package containing two
3779 	 * elements.  The first is an object reference to the GPE Block
3780 	 * device that contains the GPE that will be triggered by the wake
3781 	 * event.  The second element is numeric and it contains the bit
3782 	 * index in the GPEx_EN, in the GPE Block referenced by the
3783 	 * first element in the package, of the enable bit that is enabled for
3784 	 * the wake event.
3785 	 *
3786 	 * For example, if this field is a package then it is of the form:
3787 	 * Package() {\_SB.PCI0.ISA.GPE, 2}
3788 	 */
3789 	res2 = &res->Package.Elements[0];
3790 	if (!ACPI_PKG_VALID(res2, 2))
3791 	    goto out;
3792 	prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
3793 	if (prw->gpe_handle == NULL)
3794 	    goto out;
3795 	if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
3796 	    goto out;
3797 	error = 0;
3798 	break;
3799     default:
3800 	goto out;
3801     }
3802 
3803     /* Elements 2 to N of the _PRW object are power resources. */
3804     power_count = res->Package.Count - 2;
3805     if (power_count > ACPI_PRW_MAX_POWERRES) {
3806 	printf("ACPI device %s has too many power resources\n", acpi_name(h));
3807 	power_count = 0;
3808     }
3809     prw->power_res_count = power_count;
3810     for (i = 0; i < power_count; i++)
3811 	prw->power_res[i] = res->Package.Elements[i];
3812 
3813 out:
3814     if (prw_buffer.Pointer != NULL)
3815 	AcpiOsFree(prw_buffer.Pointer);
3816     return (error);
3817 }
3818 
3819 /*
3820  * ACPI Event Handlers
3821  */
3822 
3823 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
3824 
3825 static void
3826 acpi_system_eventhandler_sleep(void *arg, int state)
3827 {
3828     struct acpi_softc *sc = (struct acpi_softc *)arg;
3829     int ret;
3830 
3831     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3832 
3833     /* Check if button action is disabled or unknown. */
3834     if (state == ACPI_STATE_UNKNOWN)
3835 	return;
3836 
3837     /* Request that the system prepare to enter the given suspend state. */
3838     ret = acpi_ReqSleepState(sc, state);
3839     if (ret != 0)
3840 	device_printf(sc->acpi_dev,
3841 	    "request to enter state S%d failed (err %d)\n", state, ret);
3842 
3843     return_VOID;
3844 }
3845 
3846 static void
3847 acpi_system_eventhandler_wakeup(void *arg, int state)
3848 {
3849 
3850     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3851 
3852     /* Currently, nothing to do for wakeup. */
3853 
3854     return_VOID;
3855 }
3856 
3857 /*
3858  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
3859  */
3860 static void
3861 acpi_invoke_sleep_eventhandler(void *context)
3862 {
3863 
3864     EVENTHANDLER_INVOKE(acpi_sleep_event, *(int *)context);
3865 }
3866 
3867 static void
3868 acpi_invoke_wake_eventhandler(void *context)
3869 {
3870 
3871     EVENTHANDLER_INVOKE(acpi_wakeup_event, *(int *)context);
3872 }
3873 
3874 UINT32
3875 acpi_event_power_button_sleep(void *context)
3876 {
3877     struct acpi_softc	*sc = (struct acpi_softc *)context;
3878 
3879     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3880 
3881     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3882 	acpi_invoke_sleep_eventhandler, &sc->acpi_power_button_sx)))
3883 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3884     return_VALUE (ACPI_INTERRUPT_HANDLED);
3885 }
3886 
3887 UINT32
3888 acpi_event_power_button_wake(void *context)
3889 {
3890     struct acpi_softc	*sc = (struct acpi_softc *)context;
3891 
3892     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3893 
3894     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3895 	acpi_invoke_wake_eventhandler, &sc->acpi_power_button_sx)))
3896 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3897     return_VALUE (ACPI_INTERRUPT_HANDLED);
3898 }
3899 
3900 UINT32
3901 acpi_event_sleep_button_sleep(void *context)
3902 {
3903     struct acpi_softc	*sc = (struct acpi_softc *)context;
3904 
3905     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3906 
3907     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3908 	acpi_invoke_sleep_eventhandler, &sc->acpi_sleep_button_sx)))
3909 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3910     return_VALUE (ACPI_INTERRUPT_HANDLED);
3911 }
3912 
3913 UINT32
3914 acpi_event_sleep_button_wake(void *context)
3915 {
3916     struct acpi_softc	*sc = (struct acpi_softc *)context;
3917 
3918     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3919 
3920     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3921 	acpi_invoke_wake_eventhandler, &sc->acpi_sleep_button_sx)))
3922 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3923     return_VALUE (ACPI_INTERRUPT_HANDLED);
3924 }
3925 
3926 /*
3927  * XXX This static buffer is suboptimal.  There is no locking so only
3928  * use this for single-threaded callers.
3929  */
3930 char *
3931 acpi_name(ACPI_HANDLE handle)
3932 {
3933     ACPI_BUFFER buf;
3934     static char data[256];
3935 
3936     buf.Length = sizeof(data);
3937     buf.Pointer = data;
3938 
3939     if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
3940 	return (data);
3941     return ("(unknown)");
3942 }
3943 
3944 /*
3945  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
3946  * parts of the namespace.
3947  */
3948 int
3949 acpi_avoid(ACPI_HANDLE handle)
3950 {
3951     char	*cp, *env, *np;
3952     int		len;
3953 
3954     np = acpi_name(handle);
3955     if (*np == '\\')
3956 	np++;
3957     if ((env = kern_getenv("debug.acpi.avoid")) == NULL)
3958 	return (0);
3959 
3960     /* Scan the avoid list checking for a match */
3961     cp = env;
3962     for (;;) {
3963 	while (*cp != 0 && isspace(*cp))
3964 	    cp++;
3965 	if (*cp == 0)
3966 	    break;
3967 	len = 0;
3968 	while (cp[len] != 0 && !isspace(cp[len]))
3969 	    len++;
3970 	if (!strncmp(cp, np, len)) {
3971 	    freeenv(env);
3972 	    return(1);
3973 	}
3974 	cp += len;
3975     }
3976     freeenv(env);
3977 
3978     return (0);
3979 }
3980 
3981 /*
3982  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
3983  */
3984 int
3985 acpi_disabled(char *subsys)
3986 {
3987     char	*cp, *env;
3988     int		len;
3989 
3990     if ((env = kern_getenv("debug.acpi.disabled")) == NULL)
3991 	return (0);
3992     if (strcmp(env, "all") == 0) {
3993 	freeenv(env);
3994 	return (1);
3995     }
3996 
3997     /* Scan the disable list, checking for a match. */
3998     cp = env;
3999     for (;;) {
4000 	while (*cp != '\0' && isspace(*cp))
4001 	    cp++;
4002 	if (*cp == '\0')
4003 	    break;
4004 	len = 0;
4005 	while (cp[len] != '\0' && !isspace(cp[len]))
4006 	    len++;
4007 	if (strncmp(cp, subsys, len) == 0) {
4008 	    freeenv(env);
4009 	    return (1);
4010 	}
4011 	cp += len;
4012     }
4013     freeenv(env);
4014 
4015     return (0);
4016 }
4017 
4018 static void
4019 acpi_lookup(void *arg, const char *name, device_t *dev)
4020 {
4021     ACPI_HANDLE handle;
4022 
4023     if (*dev != NULL)
4024 	return;
4025 
4026     /*
4027      * Allow any handle name that is specified as an absolute path and
4028      * starts with '\'.  We could restrict this to \_SB and friends,
4029      * but see acpi_probe_children() for notes on why we scan the entire
4030      * namespace for devices.
4031      *
4032      * XXX: The pathname argument to AcpiGetHandle() should be fixed to
4033      * be const.
4034      */
4035     if (name[0] != '\\')
4036 	return;
4037     if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, __DECONST(char *, name),
4038 	&handle)))
4039 	return;
4040     *dev = acpi_get_device(handle);
4041 }
4042 
4043 /*
4044  * Control interface.
4045  *
4046  * We multiplex ioctls for all participating ACPI devices here.  Individual
4047  * drivers wanting to be accessible via /dev/acpi should use the
4048  * register/deregister interface to make their handlers visible.
4049  */
4050 struct acpi_ioctl_hook
4051 {
4052     TAILQ_ENTRY(acpi_ioctl_hook) link;
4053     u_long			 cmd;
4054     acpi_ioctl_fn		 fn;
4055     void			 *arg;
4056 };
4057 
4058 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
4059 static int				acpi_ioctl_hooks_initted;
4060 
4061 int
4062 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
4063 {
4064     struct acpi_ioctl_hook	*hp;
4065 
4066     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
4067 	return (ENOMEM);
4068     hp->cmd = cmd;
4069     hp->fn = fn;
4070     hp->arg = arg;
4071 
4072     ACPI_LOCK(acpi);
4073     if (acpi_ioctl_hooks_initted == 0) {
4074 	TAILQ_INIT(&acpi_ioctl_hooks);
4075 	acpi_ioctl_hooks_initted = 1;
4076     }
4077     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
4078     ACPI_UNLOCK(acpi);
4079 
4080     return (0);
4081 }
4082 
4083 void
4084 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
4085 {
4086     struct acpi_ioctl_hook	*hp;
4087 
4088     ACPI_LOCK(acpi);
4089     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
4090 	if (hp->cmd == cmd && hp->fn == fn)
4091 	    break;
4092 
4093     if (hp != NULL) {
4094 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
4095 	free(hp, M_ACPIDEV);
4096     }
4097     ACPI_UNLOCK(acpi);
4098 }
4099 
4100 static int
4101 acpiopen(struct cdev *dev, int flag, int fmt, struct thread *td)
4102 {
4103     return (0);
4104 }
4105 
4106 static int
4107 acpiclose(struct cdev *dev, int flag, int fmt, struct thread *td)
4108 {
4109     return (0);
4110 }
4111 
4112 static int
4113 acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
4114 {
4115     struct acpi_softc		*sc;
4116     struct acpi_ioctl_hook	*hp;
4117     int				error, state;
4118 
4119     error = 0;
4120     hp = NULL;
4121     sc = dev->si_drv1;
4122 
4123     /*
4124      * Scan the list of registered ioctls, looking for handlers.
4125      */
4126     ACPI_LOCK(acpi);
4127     if (acpi_ioctl_hooks_initted)
4128 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
4129 	    if (hp->cmd == cmd)
4130 		break;
4131 	}
4132     ACPI_UNLOCK(acpi);
4133     if (hp)
4134 	return (hp->fn(cmd, addr, hp->arg));
4135 
4136     /*
4137      * Core ioctls are not permitted for non-writable user.
4138      * Currently, other ioctls just fetch information.
4139      * Not changing system behavior.
4140      */
4141     if ((flag & FWRITE) == 0)
4142 	return (EPERM);
4143 
4144     /* Core system ioctls. */
4145     switch (cmd) {
4146     case ACPIIO_REQSLPSTATE:
4147 	state = *(int *)addr;
4148 	if (state != ACPI_STATE_S5)
4149 	    return (acpi_ReqSleepState(sc, state));
4150 	device_printf(sc->acpi_dev, "power off via acpi ioctl not supported\n");
4151 	error = EOPNOTSUPP;
4152 	break;
4153     case ACPIIO_ACKSLPSTATE:
4154 	error = *(int *)addr;
4155 	error = acpi_AckSleepState(sc->acpi_clone, error);
4156 	break;
4157     case ACPIIO_SETSLPSTATE:	/* DEPRECATED */
4158 	state = *(int *)addr;
4159 	if (state < ACPI_STATE_S0 || state > ACPI_S_STATES_MAX)
4160 	    return (EINVAL);
4161 	if (!acpi_sleep_states[state])
4162 	    return (EOPNOTSUPP);
4163 	if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
4164 	    error = ENXIO;
4165 	break;
4166     default:
4167 	error = ENXIO;
4168 	break;
4169     }
4170 
4171     return (error);
4172 }
4173 
4174 static int
4175 acpi_sname2sstate(const char *sname)
4176 {
4177     int sstate;
4178 
4179     if (toupper(sname[0]) == 'S') {
4180 	sstate = sname[1] - '0';
4181 	if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5 &&
4182 	    sname[2] == '\0')
4183 	    return (sstate);
4184     } else if (strcasecmp(sname, "NONE") == 0)
4185 	return (ACPI_STATE_UNKNOWN);
4186     return (-1);
4187 }
4188 
4189 static const char *
4190 acpi_sstate2sname(int sstate)
4191 {
4192     static const char *snames[] = { "S0", "S1", "S2", "S3", "S4", "S5" };
4193 
4194     if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5)
4195 	return (snames[sstate]);
4196     else if (sstate == ACPI_STATE_UNKNOWN)
4197 	return ("NONE");
4198     return (NULL);
4199 }
4200 
4201 static int
4202 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
4203 {
4204     int error;
4205     struct sbuf sb;
4206     UINT8 state;
4207 
4208     sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
4209     for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
4210 	if (acpi_sleep_states[state])
4211 	    sbuf_printf(&sb, "%s ", acpi_sstate2sname(state));
4212     sbuf_trim(&sb);
4213     sbuf_finish(&sb);
4214     error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
4215     sbuf_delete(&sb);
4216     return (error);
4217 }
4218 
4219 static int
4220 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
4221 {
4222     char sleep_state[10];
4223     int error, new_state, old_state;
4224 
4225     old_state = *(int *)oidp->oid_arg1;
4226     strlcpy(sleep_state, acpi_sstate2sname(old_state), sizeof(sleep_state));
4227     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
4228     if (error == 0 && req->newptr != NULL) {
4229 	new_state = acpi_sname2sstate(sleep_state);
4230 	if (new_state < ACPI_STATE_S1)
4231 	    return (EINVAL);
4232 	if (new_state < ACPI_S_STATE_COUNT && !acpi_sleep_states[new_state])
4233 	    return (EOPNOTSUPP);
4234 	if (new_state != old_state)
4235 	    *(int *)oidp->oid_arg1 = new_state;
4236     }
4237     return (error);
4238 }
4239 
4240 /* Inform devctl(4) when we receive a Notify. */
4241 void
4242 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
4243 {
4244     char		notify_buf[16];
4245     ACPI_BUFFER		handle_buf;
4246     ACPI_STATUS		status;
4247 
4248     if (subsystem == NULL)
4249 	return;
4250 
4251     handle_buf.Pointer = NULL;
4252     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
4253     status = AcpiNsHandleToPathname(h, &handle_buf, FALSE);
4254     if (ACPI_FAILURE(status))
4255 	return;
4256     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
4257     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
4258     AcpiOsFree(handle_buf.Pointer);
4259 }
4260 
4261 #ifdef ACPI_DEBUG
4262 /*
4263  * Support for parsing debug options from the kernel environment.
4264  *
4265  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
4266  * by specifying the names of the bits in the debug.acpi.layer and
4267  * debug.acpi.level environment variables.  Bits may be unset by
4268  * prefixing the bit name with !.
4269  */
4270 struct debugtag
4271 {
4272     char	*name;
4273     UINT32	value;
4274 };
4275 
4276 static struct debugtag	dbg_layer[] = {
4277     {"ACPI_UTILITIES",		ACPI_UTILITIES},
4278     {"ACPI_HARDWARE",		ACPI_HARDWARE},
4279     {"ACPI_EVENTS",		ACPI_EVENTS},
4280     {"ACPI_TABLES",		ACPI_TABLES},
4281     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
4282     {"ACPI_PARSER",		ACPI_PARSER},
4283     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
4284     {"ACPI_EXECUTER",		ACPI_EXECUTER},
4285     {"ACPI_RESOURCES",		ACPI_RESOURCES},
4286     {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
4287     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
4288     {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
4289     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
4290 
4291     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
4292     {"ACPI_BATTERY",		ACPI_BATTERY},
4293     {"ACPI_BUS",		ACPI_BUS},
4294     {"ACPI_BUTTON",		ACPI_BUTTON},
4295     {"ACPI_EC", 		ACPI_EC},
4296     {"ACPI_FAN",		ACPI_FAN},
4297     {"ACPI_POWERRES",		ACPI_POWERRES},
4298     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
4299     {"ACPI_THERMAL",		ACPI_THERMAL},
4300     {"ACPI_TIMER",		ACPI_TIMER},
4301     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
4302     {NULL, 0}
4303 };
4304 
4305 static struct debugtag dbg_level[] = {
4306     {"ACPI_LV_INIT",		ACPI_LV_INIT},
4307     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
4308     {"ACPI_LV_INFO",		ACPI_LV_INFO},
4309     {"ACPI_LV_REPAIR",		ACPI_LV_REPAIR},
4310     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
4311 
4312     /* Trace verbosity level 1 [Standard Trace Level] */
4313     {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
4314     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
4315     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
4316     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
4317     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
4318     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
4319     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
4320     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
4321     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
4322     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
4323     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
4324     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
4325     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
4326     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
4327     {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
4328 
4329     /* Trace verbosity level 2 [Function tracing and memory allocation] */
4330     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
4331     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
4332     {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
4333     {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
4334     {"ACPI_LV_ALL",		ACPI_LV_ALL},
4335 
4336     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
4337     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
4338     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
4339     {"ACPI_LV_IO",		ACPI_LV_IO},
4340     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
4341     {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
4342 
4343     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
4344     {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
4345     {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
4346     {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
4347     {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
4348     {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
4349     {NULL, 0}
4350 };
4351 
4352 static void
4353 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
4354 {
4355     char	*ep;
4356     int		i, l;
4357     int		set;
4358 
4359     while (*cp) {
4360 	if (isspace(*cp)) {
4361 	    cp++;
4362 	    continue;
4363 	}
4364 	ep = cp;
4365 	while (*ep && !isspace(*ep))
4366 	    ep++;
4367 	if (*cp == '!') {
4368 	    set = 0;
4369 	    cp++;
4370 	    if (cp == ep)
4371 		continue;
4372 	} else {
4373 	    set = 1;
4374 	}
4375 	l = ep - cp;
4376 	for (i = 0; tag[i].name != NULL; i++) {
4377 	    if (!strncmp(cp, tag[i].name, l)) {
4378 		if (set)
4379 		    *flag |= tag[i].value;
4380 		else
4381 		    *flag &= ~tag[i].value;
4382 	    }
4383 	}
4384 	cp = ep;
4385     }
4386 }
4387 
4388 static void
4389 acpi_set_debugging(void *junk)
4390 {
4391     char	*layer, *level;
4392 
4393     if (cold) {
4394 	AcpiDbgLayer = 0;
4395 	AcpiDbgLevel = 0;
4396     }
4397 
4398     layer = kern_getenv("debug.acpi.layer");
4399     level = kern_getenv("debug.acpi.level");
4400     if (layer == NULL && level == NULL)
4401 	return;
4402 
4403     printf("ACPI set debug");
4404     if (layer != NULL) {
4405 	if (strcmp("NONE", layer) != 0)
4406 	    printf(" layer '%s'", layer);
4407 	acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
4408 	freeenv(layer);
4409     }
4410     if (level != NULL) {
4411 	if (strcmp("NONE", level) != 0)
4412 	    printf(" level '%s'", level);
4413 	acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
4414 	freeenv(level);
4415     }
4416     printf("\n");
4417 }
4418 
4419 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
4420 	NULL);
4421 
4422 static int
4423 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
4424 {
4425     int		 error, *dbg;
4426     struct	 debugtag *tag;
4427     struct	 sbuf sb;
4428     char	 temp[128];
4429 
4430     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
4431 	return (ENOMEM);
4432     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
4433 	tag = &dbg_layer[0];
4434 	dbg = &AcpiDbgLayer;
4435     } else {
4436 	tag = &dbg_level[0];
4437 	dbg = &AcpiDbgLevel;
4438     }
4439 
4440     /* Get old values if this is a get request. */
4441     ACPI_SERIAL_BEGIN(acpi);
4442     if (*dbg == 0) {
4443 	sbuf_cpy(&sb, "NONE");
4444     } else if (req->newptr == NULL) {
4445 	for (; tag->name != NULL; tag++) {
4446 	    if ((*dbg & tag->value) == tag->value)
4447 		sbuf_printf(&sb, "%s ", tag->name);
4448 	}
4449     }
4450     sbuf_trim(&sb);
4451     sbuf_finish(&sb);
4452     strlcpy(temp, sbuf_data(&sb), sizeof(temp));
4453     sbuf_delete(&sb);
4454 
4455     error = sysctl_handle_string(oidp, temp, sizeof(temp), req);
4456 
4457     /* Check for error or no change */
4458     if (error == 0 && req->newptr != NULL) {
4459 	*dbg = 0;
4460 	kern_setenv((char *)oidp->oid_arg1, temp);
4461 	acpi_set_debugging(NULL);
4462     }
4463     ACPI_SERIAL_END(acpi);
4464 
4465     return (error);
4466 }
4467 
4468 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer,
4469     CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, "debug.acpi.layer", 0,
4470     acpi_debug_sysctl, "A",
4471     "");
4472 SYSCTL_PROC(_debug_acpi, OID_AUTO, level,
4473     CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, "debug.acpi.level", 0,
4474     acpi_debug_sysctl, "A",
4475     "");
4476 #endif /* ACPI_DEBUG */
4477 
4478 static int
4479 acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)
4480 {
4481 	int	error;
4482 	int	old;
4483 
4484 	old = acpi_debug_objects;
4485 	error = sysctl_handle_int(oidp, &acpi_debug_objects, 0, req);
4486 	if (error != 0 || req->newptr == NULL)
4487 		return (error);
4488 	if (old == acpi_debug_objects || (old && acpi_debug_objects))
4489 		return (0);
4490 
4491 	ACPI_SERIAL_BEGIN(acpi);
4492 	AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
4493 	ACPI_SERIAL_END(acpi);
4494 
4495 	return (0);
4496 }
4497 
4498 static int
4499 acpi_parse_interfaces(char *str, struct acpi_interface *iface)
4500 {
4501 	char *p;
4502 	size_t len;
4503 	int i, j;
4504 
4505 	p = str;
4506 	while (isspace(*p) || *p == ',')
4507 		p++;
4508 	len = strlen(p);
4509 	if (len == 0)
4510 		return (0);
4511 	p = strdup(p, M_TEMP);
4512 	for (i = 0; i < len; i++)
4513 		if (p[i] == ',')
4514 			p[i] = '\0';
4515 	i = j = 0;
4516 	while (i < len)
4517 		if (isspace(p[i]) || p[i] == '\0')
4518 			i++;
4519 		else {
4520 			i += strlen(p + i) + 1;
4521 			j++;
4522 		}
4523 	if (j == 0) {
4524 		free(p, M_TEMP);
4525 		return (0);
4526 	}
4527 	iface->data = malloc(sizeof(*iface->data) * j, M_TEMP, M_WAITOK);
4528 	iface->num = j;
4529 	i = j = 0;
4530 	while (i < len)
4531 		if (isspace(p[i]) || p[i] == '\0')
4532 			i++;
4533 		else {
4534 			iface->data[j] = p + i;
4535 			i += strlen(p + i) + 1;
4536 			j++;
4537 		}
4538 
4539 	return (j);
4540 }
4541 
4542 static void
4543 acpi_free_interfaces(struct acpi_interface *iface)
4544 {
4545 
4546 	free(iface->data[0], M_TEMP);
4547 	free(iface->data, M_TEMP);
4548 }
4549 
4550 static void
4551 acpi_reset_interfaces(device_t dev)
4552 {
4553 	struct acpi_interface list;
4554 	ACPI_STATUS status;
4555 	int i;
4556 
4557 	if (acpi_parse_interfaces(acpi_install_interface, &list) > 0) {
4558 		for (i = 0; i < list.num; i++) {
4559 			status = AcpiInstallInterface(list.data[i]);
4560 			if (ACPI_FAILURE(status))
4561 				device_printf(dev,
4562 				    "failed to install _OSI(\"%s\"): %s\n",
4563 				    list.data[i], AcpiFormatException(status));
4564 			else if (bootverbose)
4565 				device_printf(dev, "installed _OSI(\"%s\")\n",
4566 				    list.data[i]);
4567 		}
4568 		acpi_free_interfaces(&list);
4569 	}
4570 	if (acpi_parse_interfaces(acpi_remove_interface, &list) > 0) {
4571 		for (i = 0; i < list.num; i++) {
4572 			status = AcpiRemoveInterface(list.data[i]);
4573 			if (ACPI_FAILURE(status))
4574 				device_printf(dev,
4575 				    "failed to remove _OSI(\"%s\"): %s\n",
4576 				    list.data[i], AcpiFormatException(status));
4577 			else if (bootverbose)
4578 				device_printf(dev, "removed _OSI(\"%s\")\n",
4579 				    list.data[i]);
4580 		}
4581 		acpi_free_interfaces(&list);
4582 	}
4583 }
4584 
4585 static int
4586 acpi_pm_func(u_long cmd, void *arg, ...)
4587 {
4588 	int	state, acpi_state;
4589 	int	error;
4590 	struct	acpi_softc *sc;
4591 	va_list	ap;
4592 
4593 	error = 0;
4594 	switch (cmd) {
4595 	case POWER_CMD_SUSPEND:
4596 		sc = (struct acpi_softc *)arg;
4597 		if (sc == NULL) {
4598 			error = EINVAL;
4599 			goto out;
4600 		}
4601 
4602 		va_start(ap, arg);
4603 		state = va_arg(ap, int);
4604 		va_end(ap);
4605 
4606 		switch (state) {
4607 		case POWER_SLEEP_STATE_STANDBY:
4608 			acpi_state = sc->acpi_standby_sx;
4609 			break;
4610 		case POWER_SLEEP_STATE_SUSPEND:
4611 			acpi_state = sc->acpi_suspend_sx;
4612 			break;
4613 		case POWER_SLEEP_STATE_HIBERNATE:
4614 			acpi_state = ACPI_STATE_S4;
4615 			break;
4616 		default:
4617 			error = EINVAL;
4618 			goto out;
4619 		}
4620 
4621 		if (ACPI_FAILURE(acpi_EnterSleepState(sc, acpi_state)))
4622 			error = ENXIO;
4623 		break;
4624 	default:
4625 		error = EINVAL;
4626 		goto out;
4627 	}
4628 
4629 out:
4630 	return (error);
4631 }
4632 
4633 static void
4634 acpi_pm_register(void *arg)
4635 {
4636     if (!cold || resource_disabled("acpi", 0))
4637 	return;
4638 
4639     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
4640 }
4641 
4642 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, NULL);
4643