xref: /freebsd/sys/dev/acpica/acpi.c (revision 50c9ba2c76d9f1b41c0f007beaebd3d8ce112a59)
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     /* Wait until sleep is enabled. */
2519     while (sc->acpi_sleep_disabled) {
2520 	AcpiOsSleep(1000);
2521     }
2522 
2523     ACPI_LOCK(acpi);
2524 
2525     /* If a suspend request is already in progress, just return. */
2526     if (sc->acpi_next_sstate != 0) {
2527     	ACPI_UNLOCK(acpi);
2528 	return (0);
2529     }
2530     sc->acpi_next_sstate = state;
2531 
2532     /* S5 (soft-off) should be entered directly with no waiting. */
2533     if (state == ACPI_STATE_S5) {
2534     	ACPI_UNLOCK(acpi);
2535 	status = acpi_EnterSleepState(sc, state);
2536 	return (ACPI_SUCCESS(status) ? 0 : ENXIO);
2537     }
2538 
2539     /* Record the pending state and notify all apm devices. */
2540     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
2541 	clone->notify_status = APM_EV_NONE;
2542 	if ((clone->flags & ACPI_EVF_DEVD) == 0) {
2543 	    selwakeuppri(&clone->sel_read, PZERO);
2544 	    KNOTE_LOCKED(&clone->sel_read.si_note, 0);
2545 	}
2546     }
2547 
2548     /* If devd(8) is not running, immediately enter the sleep state. */
2549     if (!devctl_process_running()) {
2550 	ACPI_UNLOCK(acpi);
2551 	status = acpi_EnterSleepState(sc, state);
2552 	return (ACPI_SUCCESS(status) ? 0 : ENXIO);
2553     }
2554 
2555     /*
2556      * Set a timeout to fire if userland doesn't ack the suspend request
2557      * in time.  This way we still eventually go to sleep if we were
2558      * overheating or running low on battery, even if userland is hung.
2559      * We cancel this timeout once all userland acks are in or the
2560      * suspend request is aborted.
2561      */
2562     callout_reset(&sc->susp_force_to, 10 * hz, acpi_sleep_force, sc);
2563     ACPI_UNLOCK(acpi);
2564 
2565     /* Now notify devd(8) also. */
2566     acpi_UserNotify("Suspend", ACPI_ROOT_OBJECT, state);
2567 
2568     return (0);
2569 #else
2570     /* This platform does not support acpi suspend/resume. */
2571     return (EOPNOTSUPP);
2572 #endif
2573 }
2574 
2575 /*
2576  * Acknowledge (or reject) a pending sleep state.  The caller has
2577  * prepared for suspend and is now ready for it to proceed.  If the
2578  * error argument is non-zero, it indicates suspend should be cancelled
2579  * and gives an errno value describing why.  Once all votes are in,
2580  * we suspend the system.
2581  */
2582 int
2583 acpi_AckSleepState(struct apm_clone_data *clone, int error)
2584 {
2585 #if defined(__amd64__) || defined(__i386__)
2586     struct acpi_softc *sc;
2587     int ret, sleeping;
2588 
2589     /* If no pending sleep state, return an error. */
2590     ACPI_LOCK(acpi);
2591     sc = clone->acpi_sc;
2592     if (sc->acpi_next_sstate == 0) {
2593     	ACPI_UNLOCK(acpi);
2594 	return (ENXIO);
2595     }
2596 
2597     /* Caller wants to abort suspend process. */
2598     if (error) {
2599 	sc->acpi_next_sstate = 0;
2600 	callout_stop(&sc->susp_force_to);
2601 	device_printf(sc->acpi_dev,
2602 	    "listener on %s cancelled the pending suspend\n",
2603 	    devtoname(clone->cdev));
2604     	ACPI_UNLOCK(acpi);
2605 	return (0);
2606     }
2607 
2608     /*
2609      * Mark this device as acking the suspend request.  Then, walk through
2610      * all devices, seeing if they agree yet.  We only count devices that
2611      * are writable since read-only devices couldn't ack the request.
2612      */
2613     sleeping = TRUE;
2614     clone->notify_status = APM_EV_ACKED;
2615     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
2616 	if ((clone->flags & ACPI_EVF_WRITE) != 0 &&
2617 	    clone->notify_status != APM_EV_ACKED) {
2618 	    sleeping = FALSE;
2619 	    break;
2620 	}
2621     }
2622 
2623     /* If all devices have voted "yes", we will suspend now. */
2624     if (sleeping)
2625 	callout_stop(&sc->susp_force_to);
2626     ACPI_UNLOCK(acpi);
2627     ret = 0;
2628     if (sleeping) {
2629 	if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
2630 		ret = ENODEV;
2631     }
2632     return (ret);
2633 #else
2634     /* This platform does not support acpi suspend/resume. */
2635     return (EOPNOTSUPP);
2636 #endif
2637 }
2638 
2639 static void
2640 acpi_sleep_enable(void *arg)
2641 {
2642     struct acpi_softc	*sc = (struct acpi_softc *)arg;
2643 
2644     /* Reschedule if the system is not fully up and running. */
2645     if (!AcpiGbl_SystemAwakeAndRunning) {
2646 	timeout(acpi_sleep_enable, sc, hz * ACPI_MINIMUM_AWAKETIME);
2647 	return;
2648     }
2649 
2650     ACPI_LOCK(acpi);
2651     sc->acpi_sleep_disabled = FALSE;
2652     ACPI_UNLOCK(acpi);
2653 }
2654 
2655 static ACPI_STATUS
2656 acpi_sleep_disable(struct acpi_softc *sc)
2657 {
2658     ACPI_STATUS		status;
2659 
2660     /* Fail if the system is not fully up and running. */
2661     if (!AcpiGbl_SystemAwakeAndRunning)
2662 	return (AE_ERROR);
2663 
2664     ACPI_LOCK(acpi);
2665     status = sc->acpi_sleep_disabled ? AE_ERROR : AE_OK;
2666     sc->acpi_sleep_disabled = TRUE;
2667     ACPI_UNLOCK(acpi);
2668 
2669     return (status);
2670 }
2671 
2672 enum acpi_sleep_state {
2673     ACPI_SS_NONE,
2674     ACPI_SS_GPE_SET,
2675     ACPI_SS_DEV_SUSPEND,
2676     ACPI_SS_SLP_PREP,
2677     ACPI_SS_SLEPT,
2678 };
2679 
2680 /*
2681  * Enter the desired system sleep state.
2682  *
2683  * Currently we support S1-S5 but S4 is only S4BIOS
2684  */
2685 static ACPI_STATUS
2686 acpi_EnterSleepState(struct acpi_softc *sc, int state)
2687 {
2688     register_t intr;
2689     ACPI_STATUS status;
2690     enum acpi_sleep_state slp_state;
2691 
2692     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2693 
2694     if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
2695 	return_ACPI_STATUS (AE_BAD_PARAMETER);
2696     if (!acpi_sleep_states[state]) {
2697 	device_printf(sc->acpi_dev, "Sleep state S%d not supported by BIOS\n",
2698 	    state);
2699 	return (AE_SUPPORT);
2700     }
2701 
2702     /* Re-entry once we're suspending is not allowed. */
2703     status = acpi_sleep_disable(sc);
2704     if (ACPI_FAILURE(status)) {
2705 	device_printf(sc->acpi_dev,
2706 	    "suspend request ignored (not ready yet)\n");
2707 	return (status);
2708     }
2709 
2710     if (state == ACPI_STATE_S5) {
2711 	/*
2712 	 * Shut down cleanly and power off.  This will call us back through the
2713 	 * shutdown handlers.
2714 	 */
2715 	shutdown_nice(RB_POWEROFF);
2716 	return_ACPI_STATUS (AE_OK);
2717     }
2718 
2719     EVENTHANDLER_INVOKE(power_suspend);
2720 
2721     if (smp_started) {
2722 	thread_lock(curthread);
2723 	sched_bind(curthread, 0);
2724 	thread_unlock(curthread);
2725     }
2726 
2727     /*
2728      * Be sure to hold Giant across DEVICE_SUSPEND/RESUME since non-MPSAFE
2729      * drivers need this.
2730      */
2731     mtx_lock(&Giant);
2732 
2733     slp_state = ACPI_SS_NONE;
2734 
2735     sc->acpi_sstate = state;
2736 
2737     /* Enable any GPEs as appropriate and requested by the user. */
2738     acpi_wake_prep_walk(state);
2739     slp_state = ACPI_SS_GPE_SET;
2740 
2741     /*
2742      * Inform all devices that we are going to sleep.  If at least one
2743      * device fails, DEVICE_SUSPEND() automatically resumes the tree.
2744      *
2745      * XXX Note that a better two-pass approach with a 'veto' pass
2746      * followed by a "real thing" pass would be better, but the current
2747      * bus interface does not provide for this.
2748      */
2749     if (DEVICE_SUSPEND(root_bus) != 0) {
2750 	device_printf(sc->acpi_dev, "device_suspend failed\n");
2751 	goto backout;
2752     }
2753     slp_state = ACPI_SS_DEV_SUSPEND;
2754 
2755     /* If testing device suspend only, back out of everything here. */
2756     if (acpi_susp_bounce)
2757 	goto backout;
2758 
2759     status = AcpiEnterSleepStatePrep(state);
2760     if (ACPI_FAILURE(status)) {
2761 	device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
2762 		      AcpiFormatException(status));
2763 	goto backout;
2764     }
2765     slp_state = ACPI_SS_SLP_PREP;
2766 
2767     if (sc->acpi_sleep_delay > 0)
2768 	DELAY(sc->acpi_sleep_delay * 1000000);
2769 
2770     if (state != ACPI_STATE_S1) {
2771 	if (acpi_sleep_machdep(sc, state))
2772 		goto backout;
2773 
2774 	/* Re-enable ACPI hardware on wakeup from sleep state 4. */
2775 	if (state == ACPI_STATE_S4)
2776 	    AcpiEnable();
2777     } else {
2778 	intr = intr_disable();
2779 	status = AcpiEnterSleepState(state, acpi_sleep_flags);
2780 	intr_restore(intr);
2781 	if (ACPI_FAILURE(status)) {
2782 	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
2783 			  AcpiFormatException(status));
2784 	    goto backout;
2785 	}
2786     }
2787     slp_state = ACPI_SS_SLEPT;
2788 
2789     /*
2790      * Back out state according to how far along we got in the suspend
2791      * process.  This handles both the error and success cases.
2792      */
2793 backout:
2794     if (slp_state >= ACPI_SS_GPE_SET) {
2795 	acpi_wake_prep_walk(state);
2796 	sc->acpi_sstate = ACPI_STATE_S0;
2797     }
2798     if (slp_state >= ACPI_SS_SLP_PREP) {
2799 	AcpiLeaveSleepStatePrep(state, acpi_sleep_flags);
2800 	AcpiLeaveSleepState(state);
2801     }
2802     if (slp_state >= ACPI_SS_DEV_SUSPEND)
2803 	DEVICE_RESUME(root_bus);
2804     if (slp_state >= ACPI_SS_SLEPT) {
2805 	acpi_resync_clock(sc);
2806 	acpi_enable_fixed_events(sc);
2807     }
2808     sc->acpi_next_sstate = 0;
2809 
2810     mtx_unlock(&Giant);
2811 
2812     if (smp_started) {
2813 	thread_lock(curthread);
2814 	sched_unbind(curthread);
2815 	thread_unlock(curthread);
2816     }
2817 
2818     EVENTHANDLER_INVOKE(power_resume);
2819 
2820     /* Allow another sleep request after a while. */
2821     timeout(acpi_sleep_enable, sc, hz * ACPI_MINIMUM_AWAKETIME);
2822 
2823     /* Run /etc/rc.resume after we are back. */
2824     if (devctl_process_running())
2825 	acpi_UserNotify("Resume", ACPI_ROOT_OBJECT, state);
2826 
2827     return_ACPI_STATUS (status);
2828 }
2829 
2830 static void
2831 acpi_resync_clock(struct acpi_softc *sc)
2832 {
2833 #ifdef __amd64__
2834     if (!acpi_reset_clock)
2835 	return;
2836 
2837     /*
2838      * Warm up timecounter again and reset system clock.
2839      */
2840     (void)timecounter->tc_get_timecount(timecounter);
2841     (void)timecounter->tc_get_timecount(timecounter);
2842     inittodr(time_second + sc->acpi_sleep_delay);
2843 #endif
2844 }
2845 
2846 /* Enable or disable the device's wake GPE. */
2847 int
2848 acpi_wake_set_enable(device_t dev, int enable)
2849 {
2850     struct acpi_prw_data prw;
2851     ACPI_STATUS status;
2852     int flags;
2853 
2854     /* Make sure the device supports waking the system and get the GPE. */
2855     if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
2856 	return (ENXIO);
2857 
2858     flags = acpi_get_flags(dev);
2859     if (enable) {
2860 	status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
2861 	    ACPI_GPE_ENABLE);
2862 	if (ACPI_FAILURE(status)) {
2863 	    device_printf(dev, "enable wake failed\n");
2864 	    return (ENXIO);
2865 	}
2866 	acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
2867     } else {
2868 	status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
2869 	    ACPI_GPE_DISABLE);
2870 	if (ACPI_FAILURE(status)) {
2871 	    device_printf(dev, "disable wake failed\n");
2872 	    return (ENXIO);
2873 	}
2874 	acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
2875     }
2876 
2877     return (0);
2878 }
2879 
2880 static int
2881 acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate)
2882 {
2883     struct acpi_prw_data prw;
2884     device_t dev;
2885 
2886     /* Check that this is a wake-capable device and get its GPE. */
2887     if (acpi_parse_prw(handle, &prw) != 0)
2888 	return (ENXIO);
2889     dev = acpi_get_device(handle);
2890 
2891     /*
2892      * The destination sleep state must be less than (i.e., higher power)
2893      * or equal to the value specified by _PRW.  If this GPE cannot be
2894      * enabled for the next sleep state, then disable it.  If it can and
2895      * the user requested it be enabled, turn on any required power resources
2896      * and set _PSW.
2897      */
2898     if (sstate > prw.lowest_wake) {
2899 	AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_DISABLE);
2900 	if (bootverbose)
2901 	    device_printf(dev, "wake_prep disabled wake for %s (S%d)\n",
2902 		acpi_name(handle), sstate);
2903     } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
2904 	acpi_pwr_wake_enable(handle, 1);
2905 	acpi_SetInteger(handle, "_PSW", 1);
2906 	if (bootverbose)
2907 	    device_printf(dev, "wake_prep enabled for %s (S%d)\n",
2908 		acpi_name(handle), sstate);
2909     }
2910 
2911     return (0);
2912 }
2913 
2914 static int
2915 acpi_wake_run_prep(ACPI_HANDLE handle, int sstate)
2916 {
2917     struct acpi_prw_data prw;
2918     device_t dev;
2919 
2920     /*
2921      * Check that this is a wake-capable device and get its GPE.  Return
2922      * now if the user didn't enable this device for wake.
2923      */
2924     if (acpi_parse_prw(handle, &prw) != 0)
2925 	return (ENXIO);
2926     dev = acpi_get_device(handle);
2927     if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
2928 	return (0);
2929 
2930     /*
2931      * If this GPE couldn't be enabled for the previous sleep state, it was
2932      * disabled before going to sleep so re-enable it.  If it was enabled,
2933      * clear _PSW and turn off any power resources it used.
2934      */
2935     if (sstate > prw.lowest_wake) {
2936 	AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_ENABLE);
2937 	if (bootverbose)
2938 	    device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
2939     } else {
2940 	acpi_SetInteger(handle, "_PSW", 0);
2941 	acpi_pwr_wake_enable(handle, 0);
2942 	if (bootverbose)
2943 	    device_printf(dev, "run_prep cleaned up for %s\n",
2944 		acpi_name(handle));
2945     }
2946 
2947     return (0);
2948 }
2949 
2950 static ACPI_STATUS
2951 acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2952 {
2953     int sstate;
2954 
2955     /* If suspending, run the sleep prep function, otherwise wake. */
2956     sstate = *(int *)context;
2957     if (AcpiGbl_SystemAwakeAndRunning)
2958 	acpi_wake_sleep_prep(handle, sstate);
2959     else
2960 	acpi_wake_run_prep(handle, sstate);
2961     return (AE_OK);
2962 }
2963 
2964 /* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
2965 static int
2966 acpi_wake_prep_walk(int sstate)
2967 {
2968     ACPI_HANDLE sb_handle;
2969 
2970     if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2971 	AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
2972 	    acpi_wake_prep, NULL, &sstate, NULL);
2973     return (0);
2974 }
2975 
2976 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
2977 static int
2978 acpi_wake_sysctl_walk(device_t dev)
2979 {
2980     int error, i, numdevs;
2981     device_t *devlist;
2982     device_t child;
2983     ACPI_STATUS status;
2984 
2985     error = device_get_children(dev, &devlist, &numdevs);
2986     if (error != 0 || numdevs == 0) {
2987 	if (numdevs == 0)
2988 	    free(devlist, M_TEMP);
2989 	return (error);
2990     }
2991     for (i = 0; i < numdevs; i++) {
2992 	child = devlist[i];
2993 	acpi_wake_sysctl_walk(child);
2994 	if (!device_is_attached(child))
2995 	    continue;
2996 	status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
2997 	if (ACPI_SUCCESS(status)) {
2998 	    SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
2999 		SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
3000 		"wake", CTLTYPE_INT | CTLFLAG_RW, child, 0,
3001 		acpi_wake_set_sysctl, "I", "Device set to wake the system");
3002 	}
3003     }
3004     free(devlist, M_TEMP);
3005 
3006     return (0);
3007 }
3008 
3009 /* Enable or disable wake from userland. */
3010 static int
3011 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
3012 {
3013     int enable, error;
3014     device_t dev;
3015 
3016     dev = (device_t)arg1;
3017     enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
3018 
3019     error = sysctl_handle_int(oidp, &enable, 0, req);
3020     if (error != 0 || req->newptr == NULL)
3021 	return (error);
3022     if (enable != 0 && enable != 1)
3023 	return (EINVAL);
3024 
3025     return (acpi_wake_set_enable(dev, enable));
3026 }
3027 
3028 /* Parse a device's _PRW into a structure. */
3029 int
3030 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
3031 {
3032     ACPI_STATUS			status;
3033     ACPI_BUFFER			prw_buffer;
3034     ACPI_OBJECT			*res, *res2;
3035     int				error, i, power_count;
3036 
3037     if (h == NULL || prw == NULL)
3038 	return (EINVAL);
3039 
3040     /*
3041      * The _PRW object (7.2.9) is only required for devices that have the
3042      * ability to wake the system from a sleeping state.
3043      */
3044     error = EINVAL;
3045     prw_buffer.Pointer = NULL;
3046     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
3047     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
3048     if (ACPI_FAILURE(status))
3049 	return (ENOENT);
3050     res = (ACPI_OBJECT *)prw_buffer.Pointer;
3051     if (res == NULL)
3052 	return (ENOENT);
3053     if (!ACPI_PKG_VALID(res, 2))
3054 	goto out;
3055 
3056     /*
3057      * Element 1 of the _PRW object:
3058      * The lowest power system sleeping state that can be entered while still
3059      * providing wake functionality.  The sleeping state being entered must
3060      * be less than (i.e., higher power) or equal to this value.
3061      */
3062     if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
3063 	goto out;
3064 
3065     /*
3066      * Element 0 of the _PRW object:
3067      */
3068     switch (res->Package.Elements[0].Type) {
3069     case ACPI_TYPE_INTEGER:
3070 	/*
3071 	 * If the data type of this package element is numeric, then this
3072 	 * _PRW package element is the bit index in the GPEx_EN, in the
3073 	 * GPE blocks described in the FADT, of the enable bit that is
3074 	 * enabled for the wake event.
3075 	 */
3076 	prw->gpe_handle = NULL;
3077 	prw->gpe_bit = res->Package.Elements[0].Integer.Value;
3078 	error = 0;
3079 	break;
3080     case ACPI_TYPE_PACKAGE:
3081 	/*
3082 	 * If the data type of this package element is a package, then this
3083 	 * _PRW package element is itself a package containing two
3084 	 * elements.  The first is an object reference to the GPE Block
3085 	 * device that contains the GPE that will be triggered by the wake
3086 	 * event.  The second element is numeric and it contains the bit
3087 	 * index in the GPEx_EN, in the GPE Block referenced by the
3088 	 * first element in the package, of the enable bit that is enabled for
3089 	 * the wake event.
3090 	 *
3091 	 * For example, if this field is a package then it is of the form:
3092 	 * Package() {\_SB.PCI0.ISA.GPE, 2}
3093 	 */
3094 	res2 = &res->Package.Elements[0];
3095 	if (!ACPI_PKG_VALID(res2, 2))
3096 	    goto out;
3097 	prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
3098 	if (prw->gpe_handle == NULL)
3099 	    goto out;
3100 	if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
3101 	    goto out;
3102 	error = 0;
3103 	break;
3104     default:
3105 	goto out;
3106     }
3107 
3108     /* Elements 2 to N of the _PRW object are power resources. */
3109     power_count = res->Package.Count - 2;
3110     if (power_count > ACPI_PRW_MAX_POWERRES) {
3111 	printf("ACPI device %s has too many power resources\n", acpi_name(h));
3112 	power_count = 0;
3113     }
3114     prw->power_res_count = power_count;
3115     for (i = 0; i < power_count; i++)
3116 	prw->power_res[i] = res->Package.Elements[i];
3117 
3118 out:
3119     if (prw_buffer.Pointer != NULL)
3120 	AcpiOsFree(prw_buffer.Pointer);
3121     return (error);
3122 }
3123 
3124 /*
3125  * ACPI Event Handlers
3126  */
3127 
3128 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
3129 
3130 static void
3131 acpi_system_eventhandler_sleep(void *arg, int state)
3132 {
3133     struct acpi_softc *sc = (struct acpi_softc *)arg;
3134     int ret;
3135 
3136     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3137 
3138     /* Check if button action is disabled or unknown. */
3139     if (state == ACPI_STATE_UNKNOWN)
3140 	return;
3141 
3142     /* Request that the system prepare to enter the given suspend state. */
3143     ret = acpi_ReqSleepState(sc, state);
3144     if (ret != 0)
3145 	device_printf(sc->acpi_dev,
3146 	    "request to enter state S%d failed (err %d)\n", state, ret);
3147 
3148     return_VOID;
3149 }
3150 
3151 static void
3152 acpi_system_eventhandler_wakeup(void *arg, int state)
3153 {
3154 
3155     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3156 
3157     /* Currently, nothing to do for wakeup. */
3158 
3159     return_VOID;
3160 }
3161 
3162 /*
3163  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
3164  */
3165 static void
3166 acpi_invoke_sleep_eventhandler(void *context)
3167 {
3168 
3169     EVENTHANDLER_INVOKE(acpi_sleep_event, *(int *)context);
3170 }
3171 
3172 static void
3173 acpi_invoke_wake_eventhandler(void *context)
3174 {
3175 
3176     EVENTHANDLER_INVOKE(acpi_wakeup_event, *(int *)context);
3177 }
3178 
3179 UINT32
3180 acpi_event_power_button_sleep(void *context)
3181 {
3182     struct acpi_softc	*sc = (struct acpi_softc *)context;
3183 
3184     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3185 
3186     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3187 	acpi_invoke_sleep_eventhandler, &sc->acpi_power_button_sx)))
3188 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3189     return_VALUE (ACPI_INTERRUPT_HANDLED);
3190 }
3191 
3192 UINT32
3193 acpi_event_power_button_wake(void *context)
3194 {
3195     struct acpi_softc	*sc = (struct acpi_softc *)context;
3196 
3197     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3198 
3199     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3200 	acpi_invoke_wake_eventhandler, &sc->acpi_power_button_sx)))
3201 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3202     return_VALUE (ACPI_INTERRUPT_HANDLED);
3203 }
3204 
3205 UINT32
3206 acpi_event_sleep_button_sleep(void *context)
3207 {
3208     struct acpi_softc	*sc = (struct acpi_softc *)context;
3209 
3210     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3211 
3212     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3213 	acpi_invoke_sleep_eventhandler, &sc->acpi_sleep_button_sx)))
3214 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3215     return_VALUE (ACPI_INTERRUPT_HANDLED);
3216 }
3217 
3218 UINT32
3219 acpi_event_sleep_button_wake(void *context)
3220 {
3221     struct acpi_softc	*sc = (struct acpi_softc *)context;
3222 
3223     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3224 
3225     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3226 	acpi_invoke_wake_eventhandler, &sc->acpi_sleep_button_sx)))
3227 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3228     return_VALUE (ACPI_INTERRUPT_HANDLED);
3229 }
3230 
3231 /*
3232  * XXX This static buffer is suboptimal.  There is no locking so only
3233  * use this for single-threaded callers.
3234  */
3235 char *
3236 acpi_name(ACPI_HANDLE handle)
3237 {
3238     ACPI_BUFFER buf;
3239     static char data[256];
3240 
3241     buf.Length = sizeof(data);
3242     buf.Pointer = data;
3243 
3244     if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
3245 	return (data);
3246     return ("(unknown)");
3247 }
3248 
3249 /*
3250  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
3251  * parts of the namespace.
3252  */
3253 int
3254 acpi_avoid(ACPI_HANDLE handle)
3255 {
3256     char	*cp, *env, *np;
3257     int		len;
3258 
3259     np = acpi_name(handle);
3260     if (*np == '\\')
3261 	np++;
3262     if ((env = getenv("debug.acpi.avoid")) == NULL)
3263 	return (0);
3264 
3265     /* Scan the avoid list checking for a match */
3266     cp = env;
3267     for (;;) {
3268 	while (*cp != 0 && isspace(*cp))
3269 	    cp++;
3270 	if (*cp == 0)
3271 	    break;
3272 	len = 0;
3273 	while (cp[len] != 0 && !isspace(cp[len]))
3274 	    len++;
3275 	if (!strncmp(cp, np, len)) {
3276 	    freeenv(env);
3277 	    return(1);
3278 	}
3279 	cp += len;
3280     }
3281     freeenv(env);
3282 
3283     return (0);
3284 }
3285 
3286 /*
3287  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
3288  */
3289 int
3290 acpi_disabled(char *subsys)
3291 {
3292     char	*cp, *env;
3293     int		len;
3294 
3295     if ((env = getenv("debug.acpi.disabled")) == NULL)
3296 	return (0);
3297     if (strcmp(env, "all") == 0) {
3298 	freeenv(env);
3299 	return (1);
3300     }
3301 
3302     /* Scan the disable list, checking for a match. */
3303     cp = env;
3304     for (;;) {
3305 	while (*cp != '\0' && isspace(*cp))
3306 	    cp++;
3307 	if (*cp == '\0')
3308 	    break;
3309 	len = 0;
3310 	while (cp[len] != '\0' && !isspace(cp[len]))
3311 	    len++;
3312 	if (strncmp(cp, subsys, len) == 0) {
3313 	    freeenv(env);
3314 	    return (1);
3315 	}
3316 	cp += len;
3317     }
3318     freeenv(env);
3319 
3320     return (0);
3321 }
3322 
3323 /*
3324  * Control interface.
3325  *
3326  * We multiplex ioctls for all participating ACPI devices here.  Individual
3327  * drivers wanting to be accessible via /dev/acpi should use the
3328  * register/deregister interface to make their handlers visible.
3329  */
3330 struct acpi_ioctl_hook
3331 {
3332     TAILQ_ENTRY(acpi_ioctl_hook) link;
3333     u_long			 cmd;
3334     acpi_ioctl_fn		 fn;
3335     void			 *arg;
3336 };
3337 
3338 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
3339 static int				acpi_ioctl_hooks_initted;
3340 
3341 int
3342 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
3343 {
3344     struct acpi_ioctl_hook	*hp;
3345 
3346     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
3347 	return (ENOMEM);
3348     hp->cmd = cmd;
3349     hp->fn = fn;
3350     hp->arg = arg;
3351 
3352     ACPI_LOCK(acpi);
3353     if (acpi_ioctl_hooks_initted == 0) {
3354 	TAILQ_INIT(&acpi_ioctl_hooks);
3355 	acpi_ioctl_hooks_initted = 1;
3356     }
3357     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
3358     ACPI_UNLOCK(acpi);
3359 
3360     return (0);
3361 }
3362 
3363 void
3364 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
3365 {
3366     struct acpi_ioctl_hook	*hp;
3367 
3368     ACPI_LOCK(acpi);
3369     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
3370 	if (hp->cmd == cmd && hp->fn == fn)
3371 	    break;
3372 
3373     if (hp != NULL) {
3374 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
3375 	free(hp, M_ACPIDEV);
3376     }
3377     ACPI_UNLOCK(acpi);
3378 }
3379 
3380 static int
3381 acpiopen(struct cdev *dev, int flag, int fmt, struct thread *td)
3382 {
3383     return (0);
3384 }
3385 
3386 static int
3387 acpiclose(struct cdev *dev, int flag, int fmt, struct thread *td)
3388 {
3389     return (0);
3390 }
3391 
3392 static int
3393 acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
3394 {
3395     struct acpi_softc		*sc;
3396     struct acpi_ioctl_hook	*hp;
3397     int				error, state;
3398 
3399     error = 0;
3400     hp = NULL;
3401     sc = dev->si_drv1;
3402 
3403     /*
3404      * Scan the list of registered ioctls, looking for handlers.
3405      */
3406     ACPI_LOCK(acpi);
3407     if (acpi_ioctl_hooks_initted)
3408 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
3409 	    if (hp->cmd == cmd)
3410 		break;
3411 	}
3412     ACPI_UNLOCK(acpi);
3413     if (hp)
3414 	return (hp->fn(cmd, addr, hp->arg));
3415 
3416     /*
3417      * Core ioctls are not permitted for non-writable user.
3418      * Currently, other ioctls just fetch information.
3419      * Not changing system behavior.
3420      */
3421     if ((flag & FWRITE) == 0)
3422 	return (EPERM);
3423 
3424     /* Core system ioctls. */
3425     switch (cmd) {
3426     case ACPIIO_REQSLPSTATE:
3427 	state = *(int *)addr;
3428 	if (state != ACPI_STATE_S5)
3429 	    return (acpi_ReqSleepState(sc, state));
3430 	device_printf(sc->acpi_dev, "power off via acpi ioctl not supported\n");
3431 	error = EOPNOTSUPP;
3432 	break;
3433     case ACPIIO_ACKSLPSTATE:
3434 	error = *(int *)addr;
3435 	error = acpi_AckSleepState(sc->acpi_clone, error);
3436 	break;
3437     case ACPIIO_SETSLPSTATE:	/* DEPRECATED */
3438 	state = *(int *)addr;
3439 	if (state < ACPI_STATE_S0 || state > ACPI_S_STATES_MAX)
3440 	    return (EINVAL);
3441 	if (!acpi_sleep_states[state])
3442 	    return (EOPNOTSUPP);
3443 	if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
3444 	    error = ENXIO;
3445 	break;
3446     default:
3447 	error = ENXIO;
3448 	break;
3449     }
3450 
3451     return (error);
3452 }
3453 
3454 static int
3455 acpi_sname2sstate(const char *sname)
3456 {
3457     int sstate;
3458 
3459     if (toupper(sname[0]) == 'S') {
3460 	sstate = sname[1] - '0';
3461 	if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5 &&
3462 	    sname[2] == '\0')
3463 	    return (sstate);
3464     } else if (strcasecmp(sname, "NONE") == 0)
3465 	return (ACPI_STATE_UNKNOWN);
3466     return (-1);
3467 }
3468 
3469 static const char *
3470 acpi_sstate2sname(int sstate)
3471 {
3472     static const char *snames[] = { "S0", "S1", "S2", "S3", "S4", "S5" };
3473 
3474     if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5)
3475 	return (snames[sstate]);
3476     else if (sstate == ACPI_STATE_UNKNOWN)
3477 	return ("NONE");
3478     return (NULL);
3479 }
3480 
3481 static int
3482 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
3483 {
3484     int error;
3485     struct sbuf sb;
3486     UINT8 state;
3487 
3488     sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
3489     for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
3490 	if (acpi_sleep_states[state])
3491 	    sbuf_printf(&sb, "%s ", acpi_sstate2sname(state));
3492     sbuf_trim(&sb);
3493     sbuf_finish(&sb);
3494     error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
3495     sbuf_delete(&sb);
3496     return (error);
3497 }
3498 
3499 static int
3500 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
3501 {
3502     char sleep_state[10];
3503     int error, new_state, old_state;
3504 
3505     old_state = *(int *)oidp->oid_arg1;
3506     strlcpy(sleep_state, acpi_sstate2sname(old_state), sizeof(sleep_state));
3507     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
3508     if (error == 0 && req->newptr != NULL) {
3509 	new_state = acpi_sname2sstate(sleep_state);
3510 	if (new_state < ACPI_STATE_S1)
3511 	    return (EINVAL);
3512 	if (new_state < ACPI_S_STATE_COUNT && !acpi_sleep_states[new_state])
3513 	    return (EOPNOTSUPP);
3514 	if (new_state != old_state)
3515 	    *(int *)oidp->oid_arg1 = new_state;
3516     }
3517     return (error);
3518 }
3519 
3520 /* Inform devctl(4) when we receive a Notify. */
3521 void
3522 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
3523 {
3524     char		notify_buf[16];
3525     ACPI_BUFFER		handle_buf;
3526     ACPI_STATUS		status;
3527 
3528     if (subsystem == NULL)
3529 	return;
3530 
3531     handle_buf.Pointer = NULL;
3532     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
3533     status = AcpiNsHandleToPathname(h, &handle_buf);
3534     if (ACPI_FAILURE(status))
3535 	return;
3536     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
3537     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
3538     AcpiOsFree(handle_buf.Pointer);
3539 }
3540 
3541 #ifdef ACPI_DEBUG
3542 /*
3543  * Support for parsing debug options from the kernel environment.
3544  *
3545  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
3546  * by specifying the names of the bits in the debug.acpi.layer and
3547  * debug.acpi.level environment variables.  Bits may be unset by
3548  * prefixing the bit name with !.
3549  */
3550 struct debugtag
3551 {
3552     char	*name;
3553     UINT32	value;
3554 };
3555 
3556 static struct debugtag	dbg_layer[] = {
3557     {"ACPI_UTILITIES",		ACPI_UTILITIES},
3558     {"ACPI_HARDWARE",		ACPI_HARDWARE},
3559     {"ACPI_EVENTS",		ACPI_EVENTS},
3560     {"ACPI_TABLES",		ACPI_TABLES},
3561     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
3562     {"ACPI_PARSER",		ACPI_PARSER},
3563     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
3564     {"ACPI_EXECUTER",		ACPI_EXECUTER},
3565     {"ACPI_RESOURCES",		ACPI_RESOURCES},
3566     {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
3567     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
3568     {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
3569     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
3570 
3571     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
3572     {"ACPI_BATTERY",		ACPI_BATTERY},
3573     {"ACPI_BUS",		ACPI_BUS},
3574     {"ACPI_BUTTON",		ACPI_BUTTON},
3575     {"ACPI_EC", 		ACPI_EC},
3576     {"ACPI_FAN",		ACPI_FAN},
3577     {"ACPI_POWERRES",		ACPI_POWERRES},
3578     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
3579     {"ACPI_THERMAL",		ACPI_THERMAL},
3580     {"ACPI_TIMER",		ACPI_TIMER},
3581     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
3582     {NULL, 0}
3583 };
3584 
3585 static struct debugtag dbg_level[] = {
3586     {"ACPI_LV_INIT",		ACPI_LV_INIT},
3587     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
3588     {"ACPI_LV_INFO",		ACPI_LV_INFO},
3589     {"ACPI_LV_REPAIR",		ACPI_LV_REPAIR},
3590     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
3591 
3592     /* Trace verbosity level 1 [Standard Trace Level] */
3593     {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
3594     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
3595     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
3596     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
3597     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
3598     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
3599     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
3600     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
3601     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
3602     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
3603     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
3604     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
3605     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
3606     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
3607     {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
3608 
3609     /* Trace verbosity level 2 [Function tracing and memory allocation] */
3610     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
3611     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
3612     {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
3613     {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
3614     {"ACPI_LV_ALL",		ACPI_LV_ALL},
3615 
3616     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
3617     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
3618     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
3619     {"ACPI_LV_IO",		ACPI_LV_IO},
3620     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
3621     {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
3622 
3623     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
3624     {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
3625     {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
3626     {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
3627     {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
3628     {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
3629     {NULL, 0}
3630 };
3631 
3632 static void
3633 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
3634 {
3635     char	*ep;
3636     int		i, l;
3637     int		set;
3638 
3639     while (*cp) {
3640 	if (isspace(*cp)) {
3641 	    cp++;
3642 	    continue;
3643 	}
3644 	ep = cp;
3645 	while (*ep && !isspace(*ep))
3646 	    ep++;
3647 	if (*cp == '!') {
3648 	    set = 0;
3649 	    cp++;
3650 	    if (cp == ep)
3651 		continue;
3652 	} else {
3653 	    set = 1;
3654 	}
3655 	l = ep - cp;
3656 	for (i = 0; tag[i].name != NULL; i++) {
3657 	    if (!strncmp(cp, tag[i].name, l)) {
3658 		if (set)
3659 		    *flag |= tag[i].value;
3660 		else
3661 		    *flag &= ~tag[i].value;
3662 	    }
3663 	}
3664 	cp = ep;
3665     }
3666 }
3667 
3668 static void
3669 acpi_set_debugging(void *junk)
3670 {
3671     char	*layer, *level;
3672 
3673     if (cold) {
3674 	AcpiDbgLayer = 0;
3675 	AcpiDbgLevel = 0;
3676     }
3677 
3678     layer = getenv("debug.acpi.layer");
3679     level = getenv("debug.acpi.level");
3680     if (layer == NULL && level == NULL)
3681 	return;
3682 
3683     printf("ACPI set debug");
3684     if (layer != NULL) {
3685 	if (strcmp("NONE", layer) != 0)
3686 	    printf(" layer '%s'", layer);
3687 	acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
3688 	freeenv(layer);
3689     }
3690     if (level != NULL) {
3691 	if (strcmp("NONE", level) != 0)
3692 	    printf(" level '%s'", level);
3693 	acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
3694 	freeenv(level);
3695     }
3696     printf("\n");
3697 }
3698 
3699 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
3700 	NULL);
3701 
3702 static int
3703 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
3704 {
3705     int		 error, *dbg;
3706     struct	 debugtag *tag;
3707     struct	 sbuf sb;
3708 
3709     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
3710 	return (ENOMEM);
3711     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
3712 	tag = &dbg_layer[0];
3713 	dbg = &AcpiDbgLayer;
3714     } else {
3715 	tag = &dbg_level[0];
3716 	dbg = &AcpiDbgLevel;
3717     }
3718 
3719     /* Get old values if this is a get request. */
3720     ACPI_SERIAL_BEGIN(acpi);
3721     if (*dbg == 0) {
3722 	sbuf_cpy(&sb, "NONE");
3723     } else if (req->newptr == NULL) {
3724 	for (; tag->name != NULL; tag++) {
3725 	    if ((*dbg & tag->value) == tag->value)
3726 		sbuf_printf(&sb, "%s ", tag->name);
3727 	}
3728     }
3729     sbuf_trim(&sb);
3730     sbuf_finish(&sb);
3731 
3732     /* Copy out the old values to the user. */
3733     error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
3734     sbuf_delete(&sb);
3735 
3736     /* If the user is setting a string, parse it. */
3737     if (error == 0 && req->newptr != NULL) {
3738 	*dbg = 0;
3739 	setenv((char *)oidp->oid_arg1, (char *)req->newptr);
3740 	acpi_set_debugging(NULL);
3741     }
3742     ACPI_SERIAL_END(acpi);
3743 
3744     return (error);
3745 }
3746 
3747 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
3748 	    "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
3749 SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
3750 	    "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
3751 #endif /* ACPI_DEBUG */
3752 
3753 static int
3754 acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)
3755 {
3756 	int	error;
3757 	int	old;
3758 
3759 	old = acpi_debug_objects;
3760 	error = sysctl_handle_int(oidp, &acpi_debug_objects, 0, req);
3761 	if (error != 0 || req->newptr == NULL)
3762 		return (error);
3763 	if (old == acpi_debug_objects || (old && acpi_debug_objects))
3764 		return (0);
3765 
3766 	ACPI_SERIAL_BEGIN(acpi);
3767 	AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
3768 	ACPI_SERIAL_END(acpi);
3769 
3770 	return (0);
3771 }
3772 
3773 static int
3774 acpi_parse_interfaces(char *str, struct acpi_interface *iface)
3775 {
3776 	char *p;
3777 	size_t len;
3778 	int i, j;
3779 
3780 	p = str;
3781 	while (isspace(*p) || *p == ',')
3782 		p++;
3783 	len = strlen(p);
3784 	if (len == 0)
3785 		return (0);
3786 	p = strdup(p, M_TEMP);
3787 	for (i = 0; i < len; i++)
3788 		if (p[i] == ',')
3789 			p[i] = '\0';
3790 	i = j = 0;
3791 	while (i < len)
3792 		if (isspace(p[i]) || p[i] == '\0')
3793 			i++;
3794 		else {
3795 			i += strlen(p + i) + 1;
3796 			j++;
3797 		}
3798 	if (j == 0) {
3799 		free(p, M_TEMP);
3800 		return (0);
3801 	}
3802 	iface->data = malloc(sizeof(*iface->data) * j, M_TEMP, M_WAITOK);
3803 	iface->num = j;
3804 	i = j = 0;
3805 	while (i < len)
3806 		if (isspace(p[i]) || p[i] == '\0')
3807 			i++;
3808 		else {
3809 			iface->data[j] = p + i;
3810 			i += strlen(p + i) + 1;
3811 			j++;
3812 		}
3813 
3814 	return (j);
3815 }
3816 
3817 static void
3818 acpi_free_interfaces(struct acpi_interface *iface)
3819 {
3820 
3821 	free(iface->data[0], M_TEMP);
3822 	free(iface->data, M_TEMP);
3823 }
3824 
3825 static void
3826 acpi_reset_interfaces(device_t dev)
3827 {
3828 	struct acpi_interface list;
3829 	ACPI_STATUS status;
3830 	int i;
3831 
3832 	if (acpi_parse_interfaces(acpi_install_interface, &list) > 0) {
3833 		for (i = 0; i < list.num; i++) {
3834 			status = AcpiInstallInterface(list.data[i]);
3835 			if (ACPI_FAILURE(status))
3836 				device_printf(dev,
3837 				    "failed to install _OSI(\"%s\"): %s\n",
3838 				    list.data[i], AcpiFormatException(status));
3839 			else if (bootverbose)
3840 				device_printf(dev, "installed _OSI(\"%s\")\n",
3841 				    list.data[i]);
3842 		}
3843 		acpi_free_interfaces(&list);
3844 	}
3845 	if (acpi_parse_interfaces(acpi_remove_interface, &list) > 0) {
3846 		for (i = 0; i < list.num; i++) {
3847 			status = AcpiRemoveInterface(list.data[i]);
3848 			if (ACPI_FAILURE(status))
3849 				device_printf(dev,
3850 				    "failed to remove _OSI(\"%s\"): %s\n",
3851 				    list.data[i], AcpiFormatException(status));
3852 			else if (bootverbose)
3853 				device_printf(dev, "removed _OSI(\"%s\")\n",
3854 				    list.data[i]);
3855 		}
3856 		acpi_free_interfaces(&list);
3857 	}
3858 }
3859 
3860 static int
3861 acpi_pm_func(u_long cmd, void *arg, ...)
3862 {
3863 	int	state, acpi_state;
3864 	int	error;
3865 	struct	acpi_softc *sc;
3866 	va_list	ap;
3867 
3868 	error = 0;
3869 	switch (cmd) {
3870 	case POWER_CMD_SUSPEND:
3871 		sc = (struct acpi_softc *)arg;
3872 		if (sc == NULL) {
3873 			error = EINVAL;
3874 			goto out;
3875 		}
3876 
3877 		va_start(ap, arg);
3878 		state = va_arg(ap, int);
3879 		va_end(ap);
3880 
3881 		switch (state) {
3882 		case POWER_SLEEP_STATE_STANDBY:
3883 			acpi_state = sc->acpi_standby_sx;
3884 			break;
3885 		case POWER_SLEEP_STATE_SUSPEND:
3886 			acpi_state = sc->acpi_suspend_sx;
3887 			break;
3888 		case POWER_SLEEP_STATE_HIBERNATE:
3889 			acpi_state = ACPI_STATE_S4;
3890 			break;
3891 		default:
3892 			error = EINVAL;
3893 			goto out;
3894 		}
3895 
3896 		if (ACPI_FAILURE(acpi_EnterSleepState(sc, acpi_state)))
3897 			error = ENXIO;
3898 		break;
3899 	default:
3900 		error = EINVAL;
3901 		goto out;
3902 	}
3903 
3904 out:
3905 	return (error);
3906 }
3907 
3908 static void
3909 acpi_pm_register(void *arg)
3910 {
3911     if (!cold || resource_disabled("acpi", 0))
3912 	return;
3913 
3914     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
3915 }
3916 
3917 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
3918