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