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