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