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