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