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