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