Merge from vendor branch TNFTP:
[dragonfly.git] / sys / dev / acpica5 / acpi.c
1 /*-
2  * Copyright (c) 2000 Takanori Watanabe <takawata@jp.freebsd.org>
3  * Copyright (c) 2000 Mitsuru IWASAKI <iwasaki@jp.freebsd.org>
4  * Copyright (c) 2000, 2001 Michael Smith
5  * Copyright (c) 2000 BSDi
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      $FreeBSD: src/sys/dev/acpica/acpi.c,v 1.157 2004/06/05 09:56:04 njl Exp $
30  *      $DragonFly: src/sys/dev/acpica5/acpi.c,v 1.31 2007/04/30 07:18:47 dillon Exp $
31  */
32
33 #include "opt_acpi.h"
34 #include <sys/param.h>
35 #include <sys/kernel.h>
36 #include <sys/proc.h>
37 #include <sys/fcntl.h>
38 #include <sys/malloc.h>
39 #include <sys/bus.h>
40 #include <sys/conf.h>
41 #include <sys/device.h>
42 #include <sys/ioccom.h>
43 #include <sys/reboot.h>
44 #include <sys/sysctl.h>
45 #include <sys/ctype.h>
46 #include <sys/linker.h>
47 #include <sys/power.h>
48 #include <sys/sbuf.h>
49 #include <sys/rman.h>
50
51 #include <sys/thread2.h>
52 #include <sys/lock.h>
53
54 #include <machine/clock.h>
55 #include <machine/globaldata.h>
56 #include <bus/isa/isavar.h>
57
58 #include "acpi.h"
59 #include <dev/acpica5/acpivar.h>
60 #include <dev/acpica5/acpiio.h>
61 #include <acnamesp.h>
62
63 MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
64
65 /* Hooks for the ACPI CA debugging infrastructure */
66 #define _COMPONENT      ACPI_BUS
67 ACPI_MODULE_NAME("ACPI")
68
69 static d_open_t         acpiopen;
70 static d_close_t        acpiclose;
71 static d_ioctl_t        acpiioctl;
72
73 #define CDEV_MAJOR 152
74 static struct dev_ops acpi_ops = {
75         { "acpi", CDEV_MAJOR, 0 },
76         .d_open = acpiopen,
77         .d_close = acpiclose,
78         .d_ioctl = acpiioctl
79 };
80
81 #if __FreeBSD_version >= 500000
82 struct mtx      acpi_mutex;
83 #endif
84
85 struct acpi_quirks {
86     char        *OemId;
87     uint32_t    OemRevision;
88     char        *value;
89 };
90
91 #define ACPI_OEM_REV_ANY        0
92
93 static struct acpi_quirks acpi_quirks_table[] = {
94 #ifdef notyet
95     /* Bad PCI routing table.  Used on some SuperMicro boards. */
96     { "PTLTD ", 0x06040000, "pci_link" },
97 #endif
98 #ifdef ACPI_QUIRK_VMWARE
99     /*
100      * VMware's ACPI-fast24 timer runs roughly 65 times too fast, and not
101      * predictably/monotonic either. This is observed at least under SMP
102      * conditions.
103      *
104      * NOTE: this combination of OemId and OemRevision is NOT unique; it is
105      * known or suspected that at least some SuperMicro boards (see above) and
106      * the Compaq Presario 1952 use this combination. That's why this quirks
107      * entry is guarded by an #ifdef, and associated config option.
108      */
109     { "PTLTD ", 0x06040000, "timer" },
110 #endif /* ACPI_QUIRK_VMWARE */
111     { NULL, 0, NULL }
112 };
113
114 static int      acpi_modevent(struct module *mod, int event, void *junk);
115 static int      acpi_identify(driver_t *driver, device_t parent);
116 static int      acpi_probe(device_t dev);
117 static int      acpi_attach(device_t dev);
118 static int      acpi_shutdown(device_t dev);
119 static void     acpi_quirks_set(void);
120 static device_t acpi_add_child(device_t bus, device_t parent, int order,
121                         const char *name, int unit);
122 static int      acpi_print_child(device_t bus, device_t child);
123 static int      acpi_read_ivar(device_t dev, device_t child, int index,
124                         uintptr_t *result);
125 static int      acpi_write_ivar(device_t dev, device_t child, int index,
126                         uintptr_t value);
127 static int      acpi_set_resource(device_t dev, device_t child, int type,
128                         int rid, u_long start, u_long count);
129 static int      acpi_get_resource(device_t dev, device_t child, int type,
130                         int rid, u_long *startp, u_long *countp);
131 static struct resource *acpi_alloc_resource(device_t bus, device_t child,
132                         int type, int *rid, u_long start, u_long end,
133                         u_long count, u_int flags);
134 static int      acpi_release_resource(device_t bus, device_t child, int type,
135                         int rid, struct resource *r);
136 static uint32_t acpi_isa_get_logicalid(device_t dev);
137 static int      acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
138 static int      acpi_isa_pnp_probe(device_t bus, device_t child,
139                         struct isa_pnp_id *ids);
140 static void     acpi_probe_children(device_t bus);
141 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
142                         void *context, void **status);
143 static void     acpi_shutdown_pre_sync(void *arg, int howto);
144 static void     acpi_shutdown_final(void *arg, int howto);
145 static void     acpi_shutdown_poweroff(void *arg);
146 static void     acpi_enable_fixed_events(struct acpi_softc *sc);
147 static int      acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw);
148 static ACPI_STATUS acpi_wake_limit(ACPI_HANDLE h, UINT32 level, void *context,
149                     void **status);
150 static int      acpi_wake_limit_walk(int sstate);
151 static int      acpi_wake_sysctl_walk(device_t dev);
152 #ifdef dfly_notyet
153 static int      acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS);
154 #endif
155 static void     acpi_system_eventhandler_sleep(void *arg, int state);
156 static void     acpi_system_eventhandler_wakeup(void *arg, int state);
157 static int      acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
158 static int      acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
159 static int      acpi_pm_func(u_long cmd, void *arg, ...);
160 static int      acpi_child_location_str_method(device_t acdev, device_t child,
161                                                char *buf, size_t buflen);
162 static int      acpi_child_pnpinfo_str_method(device_t acdev, device_t child,
163                                               char *buf, size_t buflen);
164
165 static device_method_t acpi_methods[] = {
166     /* Device interface */
167     DEVMETHOD(device_identify,          acpi_identify),
168     DEVMETHOD(device_probe,             acpi_probe),
169     DEVMETHOD(device_attach,            acpi_attach),
170     DEVMETHOD(device_shutdown,          acpi_shutdown),
171     DEVMETHOD(device_detach,            bus_generic_detach),
172     DEVMETHOD(device_suspend,           bus_generic_suspend),
173     DEVMETHOD(device_resume,            bus_generic_resume),
174
175     /* Bus interface */
176     DEVMETHOD(bus_add_child,            acpi_add_child),
177     DEVMETHOD(bus_print_child,          acpi_print_child),
178     DEVMETHOD(bus_read_ivar,            acpi_read_ivar),
179     DEVMETHOD(bus_write_ivar,           acpi_write_ivar),
180     DEVMETHOD(bus_set_resource,         acpi_set_resource),
181     DEVMETHOD(bus_get_resource,         acpi_get_resource),
182     DEVMETHOD(bus_alloc_resource,       acpi_alloc_resource),
183     DEVMETHOD(bus_release_resource,     acpi_release_resource),
184     DEVMETHOD(bus_child_pnpinfo_str,    acpi_child_pnpinfo_str_method),
185     DEVMETHOD(bus_child_location_str,   acpi_child_location_str_method),
186     DEVMETHOD(bus_driver_added,         bus_generic_driver_added),
187     DEVMETHOD(bus_activate_resource,    bus_generic_activate_resource),
188     DEVMETHOD(bus_deactivate_resource,  bus_generic_deactivate_resource),
189     DEVMETHOD(bus_setup_intr,           bus_generic_setup_intr),
190     DEVMETHOD(bus_teardown_intr,        bus_generic_teardown_intr),
191
192     /* ISA emulation */
193     DEVMETHOD(isa_pnp_probe,            acpi_isa_pnp_probe),
194
195     {0, 0}
196 };
197
198 static driver_t acpi_driver = {
199     "acpi",
200     acpi_methods,
201     sizeof(struct acpi_softc),
202 };
203
204 static devclass_t acpi_devclass;
205 DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
206 MODULE_VERSION(acpi, 1);
207
208 static const char* sleep_state_names[] = {
209     "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
210
211 SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RW, NULL, "ACPI debugging");
212 static char acpi_ca_version[12];
213 SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
214               acpi_ca_version, 0, "Version of Intel ACPI-CA");
215
216 /*
217  * Allow override of whether methods execute in parallel or not.
218  * Enable this for serial behavior, which fixes "AE_ALREADY_EXISTS"
219  * errors for AML that really can't handle parallel method execution.
220  * It is off by default since this breaks recursive methods and
221  * some IBMs use such code.
222  */
223 static int acpi_serialize_methods;
224 TUNABLE_INT("hw.acpi.serialize_methods", &acpi_serialize_methods);
225
226 /*
227  * ACPI can only be loaded as a module by the loader; activating it after
228  * system bootstrap time is not useful, and can be fatal to the system.
229  * It also cannot be unloaded, since the entire system bus heirarchy hangs
230  * off it.
231  */
232 static int
233 acpi_modevent(struct module *mod, int event, void *junk)
234 {
235     switch(event) {
236     case MOD_LOAD:
237         if (!cold) {
238             kprintf("The ACPI driver cannot be loaded after boot.\n");
239             return (EPERM);
240         }
241         break;
242     case MOD_UNLOAD:
243         if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
244             return (EBUSY);
245         break;
246     default:
247         break;
248     }
249     return (0);
250 }
251
252 /*
253  * Perform early initialization.
254  */
255 ACPI_STATUS
256 acpi_Startup(void)
257 {
258 #ifdef ACPI_DEBUGGER
259     char *debugpoint;
260 #endif
261     static int error, started = 0;
262
263     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
264
265     if (started)
266         return_VALUE (error);
267     started = 1;
268
269     /* Start up the ACPI CA subsystem. */
270 #ifdef ACPI_DEBUGGER
271     debugpoint = kgetenv("debug.acpi.debugger");
272     if (debugpoint) {
273         if (!strcmp(debugpoint, "init"))
274             acpi_EnterDebugger();
275         freeenv(debugpoint);
276     }
277 #endif
278     error = AcpiInitializeTables(NULL, 16, TRUE);
279     if (ACPI_FAILURE(error)) {
280         kprintf("ACPI: table initialization failed:\n");
281         return_VALUE (error);
282     }
283
284     /* Set up any quirks we have for this XSDT. */
285     acpi_quirks_set();
286     if (acpi_disabled("acpi"))
287         return_VALUE (AE_ERROR);
288
289     return_VALUE (AE_OK);
290 }
291
292 /*
293  * Detect ACPI, perform early initialisation
294  */
295 static int
296 acpi_identify(driver_t *driver, device_t parent)
297 {
298     device_t    child;
299
300     /*
301      * No sense rescanning an ACPI 'bus'.
302      */
303     if (device_get_state(parent) == DS_ATTACHED)
304         return(0);
305
306     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
307
308     if (!cold)
309         return (ENXIO);
310
311     /* Check that we haven't been disabled with a hint. */
312     if (resource_disabled("acpi", 0))
313         return (ENXIO);
314
315     /* Make sure we're not being doubly invoked. */
316     if (device_find_child(parent, "acpi", 0) != NULL)
317         return (ENXIO);
318
319     /* Initialize ACPI-CA. */
320     if (ACPI_FAILURE(acpi_Startup()))
321         return (ENXIO);
322
323     ksnprintf(acpi_ca_version, sizeof(acpi_ca_version), "%#x", ACPI_CA_VERSION);
324
325     /* Attach the actual ACPI device. */
326     if ((child = BUS_ADD_CHILD(parent, parent, 0, "acpi", 0)) == NULL) {
327         device_printf(parent, "ACPI: could not attach\n");
328         return (ENXIO);
329     }
330     return (0);
331 }
332
333 /*
334  * Get a mapping of the root table header, as ACPICA code no longer
335  * keeps local copy of RSDT/XSDT
336  *
337  * return value: if non-NULL, mapped physical address of root table header.
338  * caller is supposed to unmap the region by AcpiOsUnmapMemory()
339  */
340 static ACPI_TABLE_HEADER *
341 acpi_map_rsdt_header(void)
342 {
343     ACPI_PHYSICAL_ADDRESS rsdp_addr, addr;
344     ACPI_TABLE_RSDP *rsdp;
345
346     if ((rsdp_addr = AcpiOsGetRootPointer()) == NULL)
347         return(NULL);
348     if ((rsdp = AcpiOsMapMemory(rsdp_addr, sizeof(*rsdp))) == NULL)
349         return(NULL);
350     if (rsdp->Revision > 1 && rsdp->XsdtPhysicalAddress)
351         addr = (ACPI_PHYSICAL_ADDRESS)rsdp->XsdtPhysicalAddress;
352     else
353         addr = (ACPI_PHYSICAL_ADDRESS)rsdp->RsdtPhysicalAddress;
354     AcpiOsUnmapMemory(rsdp, sizeof(*rsdp));
355
356     return AcpiOsMapMemory(addr, sizeof(ACPI_TABLE_HEADER));
357 }
358
359 /*
360  * Fetch some descriptive data from ACPI to put in our attach message
361  */
362 static int
363 acpi_probe(device_t dev)
364 {
365     ACPI_TABLE_HEADER   *th;
366     char                buf[20];
367     int                 error;
368     struct sbuf         sb;
369     ACPI_LOCK_DECL;
370
371     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
372
373     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
374         power_pm_get_type() != POWER_PM_TYPE_ACPI) {
375
376         device_printf(dev, "Other PM system enabled.\n");
377         return_VALUE(ENXIO);
378     }
379
380     ACPI_LOCK;
381
382     th = acpi_map_rsdt_header();
383     if (th == NULL) {
384         device_printf(dev, "couldn't get RSDT header\n");
385         error = ENXIO;
386         goto unlock;
387     }
388
389     sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
390     sbuf_bcat(&sb, th->OemId, 6);
391     sbuf_trim(&sb);
392     sbuf_putc(&sb, ' ');
393     sbuf_bcat(&sb, th->OemTableId, 8);
394     sbuf_trim(&sb);
395     sbuf_finish(&sb);
396     device_set_desc_copy(dev, sbuf_data(&sb));
397     sbuf_delete(&sb);
398     AcpiOsUnmapMemory(th, sizeof(*th));
399     error = 0;
400 unlock:
401     ACPI_UNLOCK;
402     return_VALUE(error);
403 }
404
405 static int
406 acpi_attach(device_t dev)
407 {
408     struct acpi_softc   *sc;
409     ACPI_STATUS         status;
410     int                 error, state;
411     UINT32              flags;
412     UINT8               TypeA, TypeB;
413     char                *env;
414     ACPI_TABLE_FACS     *facsp;
415 #ifdef ACPI_DEBUGGER
416     char                *debugpoint;
417 #endif
418     ACPI_LOCK_DECL;
419
420     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
421 #if __FreeBSD_version >= 500000
422     /* Initialise the ACPI mutex */
423     mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
424 #endif
425
426     ACPI_LOCK;
427     sc = device_get_softc(dev);
428     bzero(sc, sizeof(*sc));
429     sc->acpi_dev = dev;
430     callout_init(&sc->acpi_sleep_timer);
431
432     if ((error = acpi_task_thread_init())) {
433         device_printf(dev, "Could not start task thread.\n");
434         goto out;
435     }
436
437     /*
438      * Set the globals from our tunables.  This is needed because ACPI-CA
439      * uses UINT8 for some values and we have no tunable_byte.
440      */
441     AcpiGbl_AllMethodsSerialized = (UINT8)acpi_serialize_methods;
442     AcpiGbl_EnableInterpreterSlack = TRUE;
443
444     error = ENXIO;
445 #ifdef ACPI_DEBUGGER
446     debugpoint = kgetenv("debug.acpi.debugger");
447     if (debugpoint) {
448         if (!strcmp(debugpoint, "tables"))
449             acpi_EnterDebugger();
450         freeenv(debugpoint);
451     }
452 #endif
453
454     if (ACPI_FAILURE(status = AcpiInitializeSubsystem())) {
455         kprintf("ACPI: initialisation failed: %s\n",
456                AcpiFormatException(status));
457         goto out;
458     }
459     if (ACPI_FAILURE(status = AcpiLoadTables())) {
460         kprintf("ACPI: table load failed: %s\n", AcpiFormatException(status));
461         goto out;
462     }
463
464 #ifdef ACPI_DEBUGGER
465     debugpoint = kgetenv("debug.acpi.debugger");
466     if (debugpoint) {
467         if (!strcmp(debugpoint, "spaces"))
468             acpi_EnterDebugger();
469         freeenv(debugpoint);
470     }
471 #endif
472     /* Install the default address space handlers. */
473     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
474                 ACPI_ADR_SPACE_SYSTEM_MEMORY, ACPI_DEFAULT_HANDLER, NULL, NULL);
475     if (ACPI_FAILURE(status)) {
476         device_printf(dev, "Could not initialise SystemMemory handler: %s\n",
477                       AcpiFormatException(status));
478         goto out;
479     }
480     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
481                 ACPI_ADR_SPACE_SYSTEM_IO, ACPI_DEFAULT_HANDLER, NULL, NULL);
482     if (ACPI_FAILURE(status)) {
483         device_printf(dev, "Could not initialise SystemIO handler: %s\n",
484                       AcpiFormatException(status));
485         goto out;
486     }
487     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
488                 ACPI_ADR_SPACE_PCI_CONFIG, ACPI_DEFAULT_HANDLER, NULL, NULL);
489     if (ACPI_FAILURE(status)) {
490         device_printf(dev, "could not initialise PciConfig handler: %s\n",
491                       AcpiFormatException(status));
492         goto out;
493     }
494
495     /*
496      * Bring ACPI fully online.
497      *
498      * Note that some systems (specifically, those with namespace evaluation
499      * issues that require the avoidance of parts of the namespace) must
500      * avoid running _INI and _STA on everything, as well as dodging the final
501      * object init pass.
502      *
503      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
504      * For avoiding portions of the namespace without totally disabling _INI
505      * and _STA, use "debug.acpi.avoid.paths".
506      *
507      * XXX We should arrange for the object init pass after we have attached
508      *     all our child devices, but on many systems it works here.
509      */
510 #ifdef ACPI_DEBUGGER
511     debugpoint = kgetenv("debug.acpi.debugger");
512     if (debugpoint) {
513         if (!strcmp(debugpoint, "enable"))
514             acpi_EnterDebugger();
515         freeenv(debugpoint);
516     }
517 #endif
518     flags = 0;
519     if (testenv("debug.acpi.avoid"))
520         flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
521     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
522         device_printf(dev, "Could not enable ACPI: %s\n",
523                       AcpiFormatException(status));
524         goto out;
525     }
526
527     /*
528      * Call the ECDT probe function to provide EC functionality before
529      * the namespace has been evaluated.
530      */
531     acpi_ec_ecdt_probe(dev);
532
533     if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
534         device_printf(dev, "Could not initialize ACPI objects: %s\n",
535                       AcpiFormatException(status));
536         goto out;
537     }
538
539     /*
540      * Setup our sysctl tree.
541      *
542      * XXX: This doesn't check to make sure that none of these fail.
543      */
544     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
545     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
546                                SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
547                                device_get_name(dev), CTLFLAG_RD, 0, "");
548     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
549         OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
550         0, 0, acpi_supported_sleep_state_sysctl, "A", "");
551     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
552         OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
553         &sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
554     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
555         OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
556         &sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
557     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
558         OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
559         &sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
560     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
561         OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
562         &sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
563     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
564         OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
565         &sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
566     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
567         OID_AUTO, "sleep_delay", CTLFLAG_RD | CTLFLAG_RW,
568         &sc->acpi_sleep_delay, 0, "sleep delay");
569     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
570         OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
571         &sc->acpi_s4bios, 0, "S4BIOS mode");
572     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
573         OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
574         &sc->acpi_verbose, 0, "verbose mode");
575     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
576         OID_AUTO, "disable_on_poweroff", CTLFLAG_RD | CTLFLAG_RW,
577         &sc->acpi_disable_on_poweroff, 0, "ACPI subsystem disable on poweroff");
578
579     /*
580      * Default to 1 second before sleeping to give some machines time to
581      * stabilize.
582      */
583     sc->acpi_sleep_delay = 1;
584     sc->acpi_disable_on_poweroff = 0;
585     if (bootverbose)
586         sc->acpi_verbose = 1;
587     if ((env = kgetenv("hw.acpi.verbose")) && strcmp(env, "0")) {
588         sc->acpi_verbose = 1;
589         freeenv(env);
590     }
591
592     /* Only enable S4BIOS by default if the FACS says it is available. */
593     status = AcpiGetTableByIndex(ACPI_TABLE_INDEX_FACS,
594                                 (ACPI_TABLE_HEADER **)&facsp);
595     if (ACPI_SUCCESS(status)) {
596         if ((facsp->Flags & ACPI_FACS_S4_BIOS_PRESENT) != 0)
597             sc->acpi_s4bios = 1;
598     }
599
600     /*
601      * Dispatch the default sleep state to devices.  The lid switch is set
602      * to NONE by default to avoid surprising users.
603      */
604     sc->acpi_power_button_sx = ACPI_STATE_S5;
605     sc->acpi_lid_switch_sx = ACPI_S_STATES_MAX + 1;
606     sc->acpi_standby_sx = ACPI_STATE_S1;
607     sc->acpi_suspend_sx = ACPI_STATE_S3;
608
609     /* Pick the first valid sleep state for the sleep button default. */
610     sc->acpi_sleep_button_sx = ACPI_S_STATES_MAX + 1;
611     for (state = ACPI_STATE_S1; state < ACPI_STATE_S5; state++)
612         if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
613             sc->acpi_sleep_button_sx = state;
614             break;
615         }
616
617     acpi_enable_fixed_events(sc);
618
619     /*
620      * Scan the namespace and attach/initialise children.
621      */
622 #ifdef ACPI_DEBUGGER
623     debugpoint = kgetenv("debug.acpi.debugger");
624     if (debugpoint) {
625         if (!strcmp(debugpoint, "probe"))
626             acpi_EnterDebugger();
627         freeenv(debugpoint);
628     }
629 #endif
630
631     /* Register our shutdown handlers */
632     EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc,
633         SHUTDOWN_PRI_LAST);
634     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
635         SHUTDOWN_PRI_LAST);
636
637     /*
638      * Register our acpi event handlers.
639      * XXX should be configurable eg. via userland policy manager.
640      */
641     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
642         sc, ACPI_EVENT_PRI_LAST);
643     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
644         sc, ACPI_EVENT_PRI_LAST);
645
646     /* Flag our initial states. */
647     sc->acpi_enabled = 1;
648     sc->acpi_sstate = ACPI_STATE_S0;
649     sc->acpi_sleep_disabled = 0;
650
651     /* Create the control device */
652     dev_ops_add(&acpi_ops, 0, 0);
653     sc->acpi_dev_t = make_dev(&acpi_ops, 0, UID_ROOT, GID_WHEEL, 0644,
654                               "acpi");
655     sc->acpi_dev_t->si_drv1 = sc;
656
657 #ifdef ACPI_DEBUGGER
658     debugpoint = kgetenv("debug.acpi.debugger");
659     if (debugpoint) {
660         if (strcmp(debugpoint, "running") == 0)
661             acpi_EnterDebugger();
662         freeenv(debugpoint);
663     }
664 #endif
665
666     if ((error = acpi_machdep_init(dev)))
667         goto out;
668
669     /* Register ACPI again to pass the correct argument of pm_func. */
670     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
671
672     if (!acpi_disabled("bus"))
673         acpi_probe_children(dev);
674
675     error = 0;
676
677  out:
678     ACPI_UNLOCK;
679     return_VALUE (error);
680 }
681
682 static int
683 acpi_shutdown(device_t dev)
684 {
685     /* Allow children to shutdown first. */
686     bus_generic_shutdown(dev);
687
688     /* Disable all wake GPEs not appropriate for reboot/poweroff. */
689     acpi_wake_limit_walk(ACPI_STATE_S5);
690     return (0);
691 }
692
693 static void
694 acpi_quirks_set(void)
695 {
696     ACPI_TABLE_HEADER *rsdt;
697     struct acpi_quirks *quirk;
698     char *env, *tmp;
699     int len;
700
701     /*
702      * If the user loaded a custom table or disabled "quirks", leave
703      * the settings alone.
704      */
705     len = 0;
706     if ((env = kgetenv("acpi_dsdt_load")) != NULL) {
707         /* XXX No strcasecmp but this is good enough. */
708         if (*env == 'Y' || *env == 'y')
709             goto out;
710         kfreeenv(env);
711     }
712     if ((env = kgetenv("debug.acpi.disabled")) != NULL) {
713         if (strstr("quirks", env) != NULL)
714             goto out;
715         len = strlen(env);
716     }
717
718     /*
719      * Search through our quirk table and concatenate the disabled
720      * values with whatever we find.
721      */
722     if ((rsdt = acpi_map_rsdt_header()) == NULL)
723         goto out;
724     for (quirk = acpi_quirks_table; quirk->OemId; quirk++) {
725         if (!strncmp(rsdt->OemId, quirk->OemId, strlen(quirk->OemId)) &&
726             (rsdt->OemRevision == quirk->OemRevision ||
727             quirk->OemRevision == ACPI_OEM_REV_ANY)) {
728                 len += strlen(quirk->value) + 2;
729                 if ((tmp = kmalloc(len, M_TEMP, M_NOWAIT)) == NULL)
730                     goto out;
731                 ksprintf(tmp, "%s %s", env ? env : "", quirk->value);
732                 ksetenv("debug.acpi.disabled", tmp);
733                 kfree(tmp, M_TEMP);
734                 break;
735         }
736     }
737     AcpiOsUnmapMemory(rsdt, sizeof(*rsdt));
738
739 out:
740     if (env)
741         kfreeenv(env);
742 }
743
744 /*
745  * Handle a new device being added
746  */
747 static device_t
748 acpi_add_child(device_t bus, device_t parent, int order,
749                 const char *name, int unit)
750 {
751     struct acpi_device  *ad;
752     device_t            child;
753
754     ad = kmalloc(sizeof(*ad), M_ACPIDEV, M_INTWAIT | M_ZERO);
755
756     resource_list_init(&ad->ad_rl);
757
758     child = device_add_child_ordered(parent, order, name, unit);
759     if (child != NULL)
760         device_set_ivars(child, ad);
761     return (child);
762 }
763
764 static int
765 acpi_print_child(device_t bus, device_t child)
766 {
767     struct acpi_device   *adev = device_get_ivars(child);
768     struct resource_list *rl = &adev->ad_rl;
769     int retval = 0;
770
771     retval += bus_print_child_header(bus, child);
772     retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
773     retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
774     retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
775     retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
776     retval += bus_print_child_footer(bus, child);
777
778     return (retval);
779 }
780
781 /* Location hint for devctl(8) */
782 static int
783 acpi_child_location_str_method(device_t cbdev, device_t child, char *buf,
784     size_t buflen)
785 {
786     struct acpi_device *dinfo = device_get_ivars(child);
787
788     if (dinfo->ad_handle)
789         ksnprintf(buf, buflen, "path=%s", acpi_name(dinfo->ad_handle));
790     else
791         ksnprintf(buf, buflen, "magic=unknown");
792     return (0);
793 }
794
795 /* PnP information for devctl(8) */
796 static int
797 acpi_child_pnpinfo_str_method(device_t cbdev, device_t child, char *buf,
798     size_t buflen)
799 {
800     ACPI_BUFFER adbuf = {ACPI_ALLOCATE_BUFFER, NULL};
801     ACPI_DEVICE_INFO *adinfo;
802     struct acpi_device *dinfo = device_get_ivars(child);
803     char *end;
804     int error;
805
806     error = AcpiGetObjectInfo(dinfo->ad_handle, &adbuf);
807     adinfo = (ACPI_DEVICE_INFO *) adbuf.Pointer;
808
809     if (error)
810         ksnprintf(buf, buflen, "Unknown");
811     else
812         ksnprintf(buf, buflen, "_HID=%s _UID=%lu",
813                 (adinfo->Valid & ACPI_VALID_HID) ?
814                 adinfo->HardwareId.Value : "UNKNOWN",
815                 (adinfo->Valid & ACPI_VALID_UID) ?
816                 strtoul(adinfo->UniqueId.Value, &end, 10) : 0);
817
818     if (adinfo)
819         AcpiOsFree(adinfo);
820
821     return (0);
822 }
823
824 /*
825  * Handle per-device ivars
826  */
827 static int
828 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
829 {
830     struct acpi_device  *ad;
831
832     if ((ad = device_get_ivars(child)) == NULL) {
833         kprintf("device has no ivars\n");
834         return (ENOENT);
835     }
836
837     /* ACPI and ISA compatibility ivars */
838     switch(index) {
839     case ACPI_IVAR_HANDLE:
840         *(ACPI_HANDLE *)result = ad->ad_handle;
841         break;
842     case ACPI_IVAR_MAGIC:
843         *(int *)result = ad->ad_magic;
844         break;
845     case ACPI_IVAR_PRIVATE:
846         *(void **)result = ad->ad_private;
847         break;
848     case ISA_IVAR_VENDORID:
849     case ISA_IVAR_SERIAL:
850     case ISA_IVAR_COMPATID:
851         *(int *)result = -1;
852         break;
853     case ISA_IVAR_LOGICALID:
854         *(int *)result = acpi_isa_get_logicalid(child);
855         break;
856     default:
857         return (ENOENT);
858     }
859
860     return (0);
861 }
862
863 static int
864 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
865 {
866     struct acpi_device  *ad;
867
868     if ((ad = device_get_ivars(child)) == NULL) {
869         kprintf("device has no ivars\n");
870         return (ENOENT);
871     }
872
873     switch(index) {
874     case ACPI_IVAR_HANDLE:
875         ad->ad_handle = (ACPI_HANDLE)value;
876         break;
877     case ACPI_IVAR_MAGIC:
878         ad->ad_magic = (int)value;
879         break;
880     case ACPI_IVAR_PRIVATE:
881         ad->ad_private = (void *)value;
882         break;
883     default:
884         panic("bad ivar write request (%d)", index);
885         return (ENOENT);
886     }
887
888     return (0);
889 }
890
891 /*
892  * Handle child resource allocation/removal
893  */
894 static int
895 acpi_set_resource(device_t dev, device_t child, int type, int rid,
896                   u_long start, u_long count)
897 {
898     struct acpi_device          *ad = device_get_ivars(child);
899     struct resource_list        *rl = &ad->ad_rl;
900
901     resource_list_add(rl, type, rid, start, start + count -1, count);
902
903     return(0);
904 }
905
906 static int
907 acpi_get_resource(device_t dev, device_t child, int type, int rid,
908                   u_long *startp, u_long *countp)
909 {
910     struct acpi_device          *ad = device_get_ivars(child);
911     struct resource_list        *rl = &ad->ad_rl;
912     struct resource_list_entry  *rle;
913
914     rle = resource_list_find(rl, type, rid);
915     if (!rle)
916         return(ENOENT);
917         
918     if (startp)
919         *startp = rle->start;
920     if (countp)
921         *countp = rle->count;
922
923     return (0);
924 }
925
926 static struct resource *
927 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
928                     u_long start, u_long end, u_long count, u_int flags)
929 {
930     struct acpi_device *ad = device_get_ivars(child);
931     struct resource_list *rl = &ad->ad_rl;
932
933     return (resource_list_alloc(rl, bus, child, type, rid, start, end, count,
934             flags));
935 }
936
937 static int
938 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
939 {
940     struct acpi_device *ad = device_get_ivars(child);
941     struct resource_list *rl = &ad->ad_rl;
942
943     return (resource_list_release(rl, bus, child, type, rid, r));
944 }
945
946 /* Allocate an IO port or memory resource, given its GAS. */
947 struct resource *
948 acpi_bus_alloc_gas(device_t dev, int *rid, ACPI_GENERIC_ADDRESS *gas)
949 {
950     int type;
951
952     if (gas == NULL || !ACPI_VALID_ADDRESS(gas->Address) || gas->BitWidth < 8)
953         return (NULL);
954
955     switch (gas->SpaceId) {
956     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
957         type = SYS_RES_MEMORY;
958         break;
959     case ACPI_ADR_SPACE_SYSTEM_IO:
960         type = SYS_RES_IOPORT;
961         break;
962     default:
963         return (NULL);
964     }
965
966     bus_set_resource(dev, type, *rid, gas->Address, gas->BitWidth / 8);
967     return (bus_alloc_resource_any(dev, type, rid, RF_ACTIVE));
968 }
969
970 /*
971  * Handle ISA-like devices probing for a PnP ID to match.
972  */
973 #define PNP_EISAID(s)                           \
974         ((((s[0] - '@') & 0x1f) << 2)           \
975          | (((s[1] - '@') & 0x18) >> 3)         \
976          | (((s[1] - '@') & 0x07) << 13)        \
977          | (((s[2] - '@') & 0x1f) << 8)         \
978          | (PNP_HEXTONUM(s[4]) << 16)           \
979          | (PNP_HEXTONUM(s[3]) << 20)           \
980          | (PNP_HEXTONUM(s[6]) << 24)           \
981          | (PNP_HEXTONUM(s[5]) << 28))
982
983 static uint32_t
984 acpi_isa_get_logicalid(device_t dev)
985 {
986     ACPI_DEVICE_INFO    *devinfo;
987     ACPI_BUFFER         buf;
988     ACPI_HANDLE         h;
989     ACPI_STATUS         error;
990     u_int32_t           pnpid;
991     ACPI_LOCK_DECL;
992
993     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
994
995     pnpid = 0;
996     buf.Pointer = NULL;
997     buf.Length = ACPI_ALLOCATE_BUFFER;
998
999     ACPI_LOCK;
1000     
1001     /* Fetch and validate the HID. */
1002     if ((h = acpi_get_handle(dev)) == NULL)
1003         goto out;
1004     error = AcpiGetObjectInfo(h, &buf);
1005     if (ACPI_FAILURE(error))
1006         goto out;
1007     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1008
1009     if ((devinfo->Valid & ACPI_VALID_HID) != 0)
1010         pnpid = PNP_EISAID(devinfo->HardwareId.Value);
1011
1012 out:
1013     if (buf.Pointer != NULL)
1014         AcpiOsFree(buf.Pointer);
1015     ACPI_UNLOCK;
1016     return_VALUE (pnpid);
1017 }
1018
1019 static int
1020 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
1021 {
1022     ACPI_DEVICE_INFO    *devinfo;
1023     ACPI_BUFFER         buf;
1024     ACPI_HANDLE         h;
1025     ACPI_STATUS         error;
1026     uint32_t            *pnpid;
1027     int                 valid, i;
1028     ACPI_LOCK_DECL;
1029
1030     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1031
1032     pnpid = cids;
1033     valid = 0;
1034     buf.Pointer = NULL;
1035     buf.Length = ACPI_ALLOCATE_BUFFER;
1036
1037     ACPI_LOCK;
1038     
1039     /* Fetch and validate the CID */
1040     if ((h = acpi_get_handle(dev)) == NULL)
1041         goto out;
1042     error = AcpiGetObjectInfo(h, &buf);
1043     if (ACPI_FAILURE(error))
1044         goto out;
1045     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1046     if ((devinfo->Valid & ACPI_VALID_CID) == 0)
1047         goto out;
1048
1049     if (devinfo->CompatibilityId.Count < count)
1050         count = devinfo->CompatibilityId.Count;
1051     for (i = 0; i < count; i++) {
1052         if (strncmp(devinfo->CompatibilityId.Id[i].Value, "PNP", 3) != 0)
1053             continue;
1054         *pnpid++ = PNP_EISAID(devinfo->CompatibilityId.Id[i].Value);
1055         valid++;
1056     }
1057
1058 out:
1059     if (buf.Pointer != NULL)
1060         AcpiOsFree(buf.Pointer);
1061     ACPI_UNLOCK;
1062     return_VALUE (valid);
1063 }
1064
1065 static int
1066 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
1067 {
1068     int                 result, cid_count, i;
1069     uint32_t            lid, cids[8];
1070
1071     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1072
1073     /*
1074      * ISA-style drivers attached to ACPI may persist and
1075      * probe manually if we return ENOENT.  We never want
1076      * that to happen, so don't ever return it.
1077      */
1078     result = ENXIO;
1079
1080     /* Scan the supplied IDs for a match */
1081     lid = acpi_isa_get_logicalid(child);
1082     cid_count = acpi_isa_get_compatid(child, cids, 8);
1083     while (ids && ids->ip_id) {
1084         if (lid == ids->ip_id) {
1085             result = 0;
1086             goto out;
1087         }
1088         for (i = 0; i < cid_count; i++) {
1089             if (cids[i] == ids->ip_id) {
1090                 result = 0;
1091                 goto out;
1092             }
1093         }
1094         ids++;
1095     }
1096
1097  out:
1098     return_VALUE (result);
1099 }
1100
1101 /*
1102  * Scan relevant portions of the ACPI namespace and attach child devices.
1103  *
1104  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and
1105  * \_SB_ scopes, and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
1106  */
1107 static void
1108 acpi_probe_children(device_t bus)
1109 {
1110     ACPI_HANDLE parent;
1111     ACPI_STATUS status;
1112     static char *scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
1113     int         i;
1114
1115     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1116     ACPI_ASSERTLOCK;
1117
1118     /* Create any static children by calling device identify methods. */
1119     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
1120     bus_generic_probe(bus);
1121
1122     /*
1123      * Scan the namespace and insert placeholders for all the devices that
1124      * we find.
1125      *
1126      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
1127      * we want to create nodes for all devices, not just those that are
1128      * currently present. (This assumes that we don't want to create/remove
1129      * devices as they appear, which might be smarter.)
1130      */
1131     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
1132     for (i = 0; scopes[i] != NULL; i++) {
1133         status = AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent);
1134         if (ACPI_SUCCESS(status)) {
1135             AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child,
1136                               bus, NULL);
1137         }
1138     }
1139
1140     /*
1141      * Scan all of the child devices we have created and let them probe/attach.
1142      */
1143     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
1144     bus_generic_attach(bus);
1145
1146     /*
1147      * Some of these children may have attached others as part of their attach
1148      * process (eg. the root PCI bus driver), so rescan.
1149      */
1150     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
1151     bus_generic_attach(bus);
1152
1153     /* Attach wake sysctls. */
1154     acpi_wake_sysctl_walk(bus);
1155
1156     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
1157     return_VOID;
1158 }
1159
1160 /*
1161  * Evaluate a child device and determine whether we might attach a device to
1162  * it.
1163  */
1164 static ACPI_STATUS
1165 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
1166 {
1167     ACPI_OBJECT_TYPE    type;
1168     device_t            child, bus = (device_t)context;
1169
1170     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1171
1172     /* Skip this device if we think we'll have trouble with it. */
1173     if (acpi_avoid(handle)) {
1174         ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "not scanning '%s'\n",
1175                          acpi_name(handle)));
1176         return_ACPI_STATUS (AE_OK);
1177     }
1178
1179     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
1180         switch(type) {
1181         case ACPI_TYPE_DEVICE:
1182         case ACPI_TYPE_PROCESSOR:
1183         case ACPI_TYPE_THERMAL:
1184         case ACPI_TYPE_POWER:
1185             if (acpi_disabled("children"))
1186                 break;
1187
1188             /* 
1189              * Create a placeholder device for this node.  Sort the placeholder
1190              * so that the probe/attach passes will run breadth-first.
1191              */
1192             ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n",
1193                              acpi_name(handle)));
1194             child = BUS_ADD_CHILD(bus, bus, level * 10, NULL, -1);
1195             if (child == NULL)
1196                 break;
1197             acpi_set_handle(child, handle);
1198
1199             /* Check if the device can generate wake events. */
1200             if (ACPI_SUCCESS(AcpiEvaluateObject(handle, "_PRW", NULL, NULL)))
1201                 device_set_flags(child, ACPI_FLAG_WAKE_CAPABLE);
1202
1203             /*
1204              * Check that the device is present.  If it's not present,
1205              * leave it disabled (so that we have a device_t attached to
1206              * the handle, but we don't probe it).
1207              */
1208             if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1209                 device_disable(child);
1210                 break;
1211             }
1212
1213             /*
1214              * Get the device's resource settings and attach them.
1215              * Note that if the device has _PRS but no _CRS, we need
1216              * to decide when it's appropriate to try to configure the
1217              * device.  Ignore the return value here; it's OK for the
1218              * device not to have any resources.
1219              */
1220             acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
1221
1222             /* If we're debugging, probe/attach now rather than later */
1223             ACPI_DEBUG_EXEC(device_probe_and_attach(child));
1224             break;
1225         }
1226     }
1227
1228     return_ACPI_STATUS (AE_OK);
1229 }
1230
1231 static void
1232 acpi_shutdown_pre_sync(void *arg, int howto)
1233 {
1234     struct acpi_softc *sc = arg;
1235
1236     ACPI_ASSERTLOCK;
1237
1238     /*
1239      * Disable all ACPI events before soft off, otherwise the system
1240      * will be turned on again on some laptops.
1241      *
1242      * XXX this should probably be restricted to masking some events just
1243      *     before powering down, since we may still need ACPI during the
1244      *     shutdown process.
1245      */
1246     if (sc->acpi_disable_on_poweroff)
1247         acpi_Disable(sc);
1248 }
1249
1250 static void
1251 acpi_shutdown_final(void *arg, int howto)
1252 {
1253     ACPI_STATUS status;
1254     ACPI_ASSERTLOCK;
1255
1256     /*
1257      * If powering off, run the actual shutdown code on each processor.
1258      * It will only perform the shutdown on the BSP.  Some chipsets do
1259      * not power off the system correctly if called from an AP.
1260      */
1261     if ((howto & RB_POWEROFF) != 0) {
1262         status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
1263         if (ACPI_FAILURE(status)) {
1264             kprintf("AcpiEnterSleepStatePrep failed - %s\n",
1265                    AcpiFormatException(status));
1266             return;
1267         }
1268         kprintf("Powering system off using ACPI\n");
1269         acpi_shutdown_poweroff(NULL);
1270     } else {
1271         kprintf("Shutting down ACPI\n");
1272         AcpiTerminate();
1273     }
1274 }
1275
1276 /*
1277  * Since this function may be called with locks held or in an unknown
1278  * context, it cannot allocate memory, acquire locks, sleep, etc.
1279  */
1280 static void
1281 acpi_shutdown_poweroff(void *arg)
1282 {
1283     ACPI_STATUS status;
1284
1285     ACPI_ASSERTLOCK;
1286
1287     /* Only attempt to power off if this is the BSP (cpuid 0). */
1288     if (mdcpu->mi.gd_cpuid != 0)
1289         return;
1290
1291     ACPI_DISABLE_IRQS();
1292     status = AcpiEnterSleepState(ACPI_STATE_S5);
1293     if (ACPI_FAILURE(status)) {
1294         kprintf("ACPI power-off failed - %s\n", AcpiFormatException(status));
1295     } else {
1296         DELAY(1000000);
1297         kprintf("ACPI power-off failed - timeout\n");
1298     }
1299 }
1300
1301 static void
1302 acpi_enable_fixed_events(struct acpi_softc *sc)
1303 {
1304     static int  first_time = 1;
1305
1306     ACPI_ASSERTLOCK;
1307
1308     /* Enable and clear fixed events and install handlers. */
1309     if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
1310         AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
1311         AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
1312                                      acpi_event_power_button_sleep, sc);
1313         if (first_time)
1314             device_printf(sc->acpi_dev, "Power Button (fixed)\n");
1315     }
1316     if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
1317         AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
1318         AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
1319                                      acpi_event_sleep_button_sleep, sc);
1320         if (first_time)
1321             device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
1322     }
1323
1324     first_time = 0;
1325 }
1326
1327 /*
1328  * Returns true if the device is actually present and should
1329  * be attached to.  This requires the present, enabled, UI-visible 
1330  * and diagnostics-passed bits to be set.
1331  */
1332 BOOLEAN
1333 acpi_DeviceIsPresent(device_t dev)
1334 {
1335     ACPI_DEVICE_INFO    *devinfo;
1336     ACPI_HANDLE         h;
1337     ACPI_BUFFER         buf;
1338     ACPI_STATUS         error;
1339     int                 ret;
1340
1341     ACPI_ASSERTLOCK;
1342     
1343     ret = FALSE;
1344     if ((h = acpi_get_handle(dev)) == NULL)
1345         return (FALSE);
1346     buf.Pointer = NULL;
1347     buf.Length = ACPI_ALLOCATE_BUFFER;
1348     error = AcpiGetObjectInfo(h, &buf);
1349     if (ACPI_FAILURE(error))
1350         return (FALSE);
1351     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1352
1353     /* If no _STA method, must be present */
1354     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1355         ret = TRUE;
1356
1357     /* Return true for 'present' and 'functioning' */
1358     if ((devinfo->CurrentStatus & 0x9) == 0x9)
1359         ret = TRUE;
1360
1361     AcpiOsFree(buf.Pointer);
1362     return (ret);
1363 }
1364
1365 /*
1366  * Returns true if the battery is actually present and inserted.
1367  */
1368 BOOLEAN
1369 acpi_BatteryIsPresent(device_t dev)
1370 {
1371     ACPI_DEVICE_INFO    *devinfo;
1372     ACPI_HANDLE         h;
1373     ACPI_BUFFER         buf;
1374     ACPI_STATUS         error;
1375     int                 ret;
1376
1377     ACPI_ASSERTLOCK;
1378     
1379     ret = FALSE;
1380     if ((h = acpi_get_handle(dev)) == NULL)
1381         return (FALSE);
1382     buf.Pointer = NULL;
1383     buf.Length = ACPI_ALLOCATE_BUFFER;
1384     error = AcpiGetObjectInfo(h, &buf);
1385     if (ACPI_FAILURE(error))
1386         return (FALSE);
1387     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1388
1389     /* If no _STA method, must be present */
1390     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1391         ret = TRUE;
1392
1393     /* Return true for 'present' and 'functioning' */
1394     if ((devinfo->CurrentStatus & 0x19) == 0x19)
1395         ret = TRUE;
1396
1397     AcpiOsFree(buf.Pointer);
1398     return (ret);
1399 }
1400
1401 /*
1402  * Match a HID string against a device
1403  */
1404 BOOLEAN
1405 acpi_MatchHid(device_t dev, char *hid) 
1406 {
1407     ACPI_DEVICE_INFO    *devinfo;
1408     ACPI_HANDLE         h;
1409     ACPI_BUFFER         buf;
1410     ACPI_STATUS         error;
1411     int                 ret, i;
1412
1413     ACPI_ASSERTLOCK;
1414
1415     ret = FALSE;
1416     if (hid == NULL)
1417         return (FALSE);
1418     if ((h = acpi_get_handle(dev)) == NULL)
1419         return (FALSE);
1420     buf.Pointer = NULL;
1421     buf.Length = ACPI_ALLOCATE_BUFFER;
1422     error = AcpiGetObjectInfo(h, &buf);
1423     if (ACPI_FAILURE(error))
1424         return (FALSE);
1425     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1426
1427     if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
1428         strcmp(hid, devinfo->HardwareId.Value) == 0)
1429             ret = TRUE;
1430     else if ((devinfo->Valid & ACPI_VALID_CID) != 0) {
1431         for (i = 0; i < devinfo->CompatibilityId.Count; i++) {
1432             if (strcmp(hid, devinfo->CompatibilityId.Id[i].Value) == 0) {
1433                 ret = TRUE;
1434                 break;
1435             }
1436         }
1437     }
1438
1439     AcpiOsFree(buf.Pointer);
1440     return (ret);
1441 }
1442
1443 /*
1444  * Return the handle of a named object within our scope, ie. that of (parent)
1445  * or one if its parents.
1446  */
1447 ACPI_STATUS
1448 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1449 {
1450     ACPI_HANDLE         r;
1451     ACPI_STATUS         status;
1452
1453     ACPI_ASSERTLOCK;
1454
1455     /* Walk back up the tree to the root */
1456     for (;;) {
1457         status = AcpiGetHandle(parent, path, &r);
1458         if (ACPI_SUCCESS(status)) {
1459             *result = r;
1460             return (AE_OK);
1461         }
1462         if (status != AE_NOT_FOUND)
1463             return (AE_OK);
1464         if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1465             return (AE_NOT_FOUND);
1466         parent = r;
1467     }
1468 }
1469
1470 /* Find the difference between two PM tick counts. */
1471 uint32_t
1472 acpi_TimerDelta(uint32_t end, uint32_t start)
1473 {
1474     uint32_t delta;
1475
1476     if (end >= start)
1477         delta = end - start;
1478     else if ((AcpiGbl_FADT.Flags & ACPI_FADT_32BIT_TIMER) == 0)
1479         delta = ((0x00FFFFFF - start) + end + 1) & 0x00FFFFFF;
1480     else
1481         delta = ((0xFFFFFFFF - start) + end + 1);
1482     return (delta);
1483 }
1484
1485 /*
1486  * Allocate a buffer with a preset data size.
1487  */
1488 ACPI_BUFFER *
1489 acpi_AllocBuffer(int size)
1490 {
1491     ACPI_BUFFER *buf;
1492
1493     buf = kmalloc(size + sizeof(*buf), M_ACPIDEV, M_INTWAIT);
1494     buf->Length = size;
1495     buf->Pointer = (void *)(buf + 1);
1496     return (buf);
1497 }
1498
1499 ACPI_STATUS
1500 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
1501 {
1502     ACPI_OBJECT arg1;
1503     ACPI_OBJECT_LIST args;
1504
1505     ACPI_ASSERTLOCK;
1506
1507     arg1.Type = ACPI_TYPE_INTEGER;
1508     arg1.Integer.Value = number;
1509     args.Count = 1;
1510     args.Pointer = &arg1;
1511
1512     return (AcpiEvaluateObject(handle, path, &args, NULL));
1513 }
1514
1515 /*
1516  * Evaluate a path that should return an integer.
1517  */
1518 ACPI_STATUS
1519 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
1520 {
1521     ACPI_STATUS status;
1522     ACPI_BUFFER buf;
1523     ACPI_OBJECT param;
1524
1525     ACPI_ASSERTLOCK;
1526
1527     if (handle == NULL)
1528         handle = ACPI_ROOT_OBJECT;
1529
1530     /*
1531      * Assume that what we've been pointed at is an Integer object, or
1532      * a method that will return an Integer.
1533      */
1534     buf.Pointer = &param;
1535     buf.Length = sizeof(param);
1536     status = AcpiEvaluateObject(handle, path, NULL, &buf);
1537     if (ACPI_SUCCESS(status)) {
1538         if (param.Type == ACPI_TYPE_INTEGER)
1539             *number = param.Integer.Value;
1540         else
1541             status = AE_TYPE;
1542     }
1543
1544     /* 
1545      * In some applications, a method that's expected to return an Integer
1546      * may instead return a Buffer (probably to simplify some internal
1547      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1548      * convert it into an Integer as best we can.
1549      *
1550      * This is a hack.
1551      */
1552     if (status == AE_BUFFER_OVERFLOW) {
1553         if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1554             status = AE_NO_MEMORY;
1555         } else {
1556             status = AcpiEvaluateObject(handle, path, NULL, &buf);
1557             if (ACPI_SUCCESS(status))
1558                 status = acpi_ConvertBufferToInteger(&buf, number);
1559             AcpiOsFree(buf.Pointer);
1560         }
1561     }
1562     return (status);
1563 }
1564
1565 ACPI_STATUS
1566 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
1567 {
1568     ACPI_OBJECT *p;
1569     UINT8       *val;
1570     int         i;
1571
1572     p = (ACPI_OBJECT *)bufp->Pointer;
1573     if (p->Type == ACPI_TYPE_INTEGER) {
1574         *number = p->Integer.Value;
1575         return (AE_OK);
1576     }
1577     if (p->Type != ACPI_TYPE_BUFFER)
1578         return (AE_TYPE);
1579     if (p->Buffer.Length > sizeof(int))
1580         return (AE_BAD_DATA);
1581
1582     *number = 0;
1583     val = p->Buffer.Pointer;
1584     for (i = 0; i < p->Buffer.Length; i++)
1585         *number += val[i] << (i * 8);
1586     return (AE_OK);
1587 }
1588
1589 /*
1590  * Iterate over the elements of an a package object, calling the supplied
1591  * function for each element.
1592  *
1593  * XXX possible enhancement might be to abort traversal on error.
1594  */
1595 ACPI_STATUS
1596 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
1597         void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
1598 {
1599     ACPI_OBJECT *comp;
1600     int         i;
1601     
1602     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
1603         return (AE_BAD_PARAMETER);
1604
1605     /* Iterate over components */
1606     i = 0;
1607     comp = pkg->Package.Elements;
1608     for (; i < pkg->Package.Count; i++, comp++)
1609         func(comp, arg);
1610
1611     return (AE_OK);
1612 }
1613
1614 /*
1615  * Find the (index)th resource object in a set.
1616  */
1617 ACPI_STATUS
1618 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1619 {
1620     ACPI_RESOURCE       *rp;
1621     int                 i;
1622
1623     rp = (ACPI_RESOURCE *)buf->Pointer;
1624     i = index;
1625     while (i-- > 0) {
1626         /* Range check */       
1627         if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1628             return (AE_BAD_PARAMETER);
1629
1630         /* Check for terminator */
1631         if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
1632             return (AE_NOT_FOUND);
1633         rp = ACPI_NEXT_RESOURCE(rp);
1634     }
1635     if (resp != NULL)
1636         *resp = rp;
1637
1638     return (AE_OK);
1639 }
1640
1641 /*
1642  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1643  *
1644  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1645  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1646  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1647  * resources.
1648  */
1649 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE       512
1650
1651 ACPI_STATUS
1652 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1653 {
1654     ACPI_RESOURCE       *rp;
1655     void                *newp;
1656     
1657     /* Initialise the buffer if necessary. */
1658     if (buf->Pointer == NULL) {
1659         buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1660         if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1661             return (AE_NO_MEMORY);
1662         rp = (ACPI_RESOURCE *)buf->Pointer;
1663         rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
1664         rp->Length = 0;
1665     }
1666     if (res == NULL)
1667         return (AE_OK);
1668     
1669     /*
1670      * Scan the current buffer looking for the terminator.
1671      * This will either find the terminator or hit the end
1672      * of the buffer and return an error.
1673      */
1674     rp = (ACPI_RESOURCE *)buf->Pointer;
1675     for (;;) {
1676         /* Range check, don't go outside the buffer */
1677         if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1678             return (AE_BAD_PARAMETER);
1679         if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
1680             break;
1681         rp = ACPI_NEXT_RESOURCE(rp);
1682     }
1683
1684     /*
1685      * Check the size of the buffer and expand if required.
1686      *
1687      * Required size is:
1688      *  size of existing resources before terminator + 
1689      *  size of new resource and header +
1690      *  size of terminator.
1691      *
1692      * Note that this loop should really only run once, unless
1693      * for some reason we are stuffing a *really* huge resource.
1694      */
1695     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) + 
1696             res->Length + ACPI_RS_SIZE_NO_DATA +
1697             ACPI_RS_SIZE_MIN) >= buf->Length) {
1698         if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1699             return (AE_NO_MEMORY);
1700         bcopy(buf->Pointer, newp, buf->Length);
1701         rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1702                                ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1703         AcpiOsFree(buf->Pointer);
1704         buf->Pointer = newp;
1705         buf->Length += buf->Length;
1706     }
1707     
1708     /* Insert the new resource. */
1709     bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
1710     
1711     /* And add the terminator. */
1712     rp = ACPI_NEXT_RESOURCE(rp);
1713     rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
1714     rp->Length = 0;
1715
1716     return (AE_OK);
1717 }
1718
1719 /*
1720  * Set interrupt model.
1721  */
1722 ACPI_STATUS
1723 acpi_SetIntrModel(int model)
1724 {
1725     return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
1726 }
1727
1728 #define ACPI_MINIMUM_AWAKETIME  5
1729
1730 static void
1731 acpi_sleep_enable(void *arg)
1732 {
1733     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1734 }
1735
1736 /*
1737  * Set the system sleep state
1738  *
1739  * Currently we support S1-S5 but S4 is only S4BIOS
1740  */
1741 ACPI_STATUS
1742 acpi_SetSleepState(struct acpi_softc *sc, int state)
1743 {
1744     ACPI_STATUS status = AE_OK;
1745     UINT8       TypeA;
1746     UINT8       TypeB;
1747
1748     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1749     ACPI_ASSERTLOCK;
1750
1751     /* Avoid reentry if already attempting to suspend. */
1752     if (sc->acpi_sstate != ACPI_STATE_S0)
1753         return_ACPI_STATUS (AE_BAD_PARAMETER);
1754
1755     /* We recently woke up so don't suspend again for a while. */
1756     if (sc->acpi_sleep_disabled)
1757         return_ACPI_STATUS (AE_OK);
1758
1759     switch (state) {
1760     case ACPI_STATE_S1:
1761     case ACPI_STATE_S2:
1762     case ACPI_STATE_S3:
1763     case ACPI_STATE_S4:
1764         status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB);
1765         if (status == AE_NOT_FOUND) {
1766             device_printf(sc->acpi_dev,
1767                           "Sleep state S%d not supported by BIOS\n", state);
1768             break;
1769         } else if (ACPI_FAILURE(status)) {
1770             device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n",
1771                           AcpiFormatException(status));
1772             break;
1773         }
1774
1775         sc->acpi_sstate = state;
1776         sc->acpi_sleep_disabled = 1;
1777
1778         /* Disable all wake GPEs not appropriate for this state. */
1779         acpi_wake_limit_walk(state);
1780
1781         /* Inform all devices that we are going to sleep. */
1782         if (DEVICE_SUSPEND(root_bus) != 0) {
1783             /*
1784              * Re-wake the system.
1785              *
1786              * XXX note that a better two-pass approach with a 'veto' pass
1787              *     followed by a "real thing" pass would be better, but the
1788              *     current bus interface does not provide for this.
1789              */
1790             DEVICE_RESUME(root_bus);
1791             return_ACPI_STATUS (AE_ERROR);
1792         }
1793
1794         status = AcpiEnterSleepStatePrep(state);
1795         if (ACPI_FAILURE(status)) {
1796             device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1797                           AcpiFormatException(status));
1798             break;
1799         }
1800
1801         if (sc->acpi_sleep_delay > 0)
1802             DELAY(sc->acpi_sleep_delay * 1000000);
1803
1804         if (state != ACPI_STATE_S1) {
1805             acpi_sleep_machdep(sc, state);
1806 #if 0
1807             /* AcpiEnterSleepState() may be incomplete, unlock if locked. */
1808             AcpiOsReleaseLock(AcpiGbl_HardwareLock, 1);
1809 #endif
1810             /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1811             if (state == ACPI_STATE_S4)
1812                 AcpiEnable();
1813         } else {
1814             status = AcpiEnterSleepState((UINT8)state);
1815             if (ACPI_FAILURE(status)) {
1816                 device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
1817                               AcpiFormatException(status));
1818                 break;
1819             }
1820         }
1821         AcpiLeaveSleepState((UINT8)state);
1822         DEVICE_RESUME(root_bus);
1823         sc->acpi_sstate = ACPI_STATE_S0;
1824         acpi_enable_fixed_events(sc);
1825         break;
1826     case ACPI_STATE_S5:
1827         /*
1828          * Shut down cleanly and power off.  This will call us back through the
1829          * shutdown handlers.
1830          */
1831         shutdown_nice(RB_POWEROFF);
1832         break;
1833     case ACPI_STATE_S0:
1834     default:
1835         status = AE_BAD_PARAMETER;
1836         break;
1837     }
1838
1839     /* Disable a second sleep request for a short period */
1840     if (sc->acpi_sleep_disabled)
1841         callout_reset(&sc->acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME,
1842                       acpi_sleep_enable, sc);
1843
1844     return_ACPI_STATUS (status);
1845 }
1846
1847 /* Initialize a device's wake GPE. */
1848 int
1849 acpi_wake_init(device_t dev, int type)
1850 {
1851     struct acpi_prw_data prw;
1852
1853     /* Check that the device can wake the system. */
1854     if ((device_get_flags(dev) & ACPI_FLAG_WAKE_CAPABLE) == 0)
1855         return (ENXIO);
1856
1857     /* Evaluate _PRW to find the GPE. */
1858     if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
1859         return (ENXIO);
1860
1861     /* Set the requested type for the GPE (runtime, wake, or both). */
1862     if (ACPI_FAILURE(AcpiSetGpeType(prw.gpe_handle, prw.gpe_bit, type))) {
1863         device_printf(dev, "set GPE type failed\n");
1864         return (ENXIO);
1865     }
1866
1867     return (0);
1868 }
1869
1870 /* Enable or disable the device's wake GPE. */
1871 int
1872 acpi_wake_set_enable(device_t dev, int enable)
1873 {
1874     struct acpi_prw_data prw;
1875     ACPI_HANDLE handle;
1876     ACPI_STATUS status;
1877     int flags;
1878
1879     /* Make sure the device supports waking the system. */
1880     flags = device_get_flags(dev);
1881     handle = acpi_get_handle(dev);
1882     if ((flags & ACPI_FLAG_WAKE_CAPABLE) == 0 || handle == NULL)
1883         return (ENXIO);
1884
1885     /* Evaluate _PRW to find the GPE. */
1886     if (acpi_parse_prw(handle, &prw) != 0)
1887         return (ENXIO);
1888
1889     if (enable) {
1890         status = AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1891         if (ACPI_FAILURE(status)) {
1892             device_printf(dev, "enable wake failed\n");
1893             return (ENXIO);
1894         }
1895         device_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
1896     } else {
1897         status = AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1898         if (ACPI_FAILURE(status)) {
1899             device_printf(dev, "disable wake failed\n");
1900             return (ENXIO);
1901         }
1902         device_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
1903     }
1904
1905     return (0);
1906 }
1907
1908 /* Configure a device's GPE appropriately for the new sleep state. */
1909 int
1910 acpi_wake_sleep_prep(device_t dev, int sstate)
1911 {
1912     struct acpi_prw_data prw;
1913     ACPI_HANDLE handle;
1914     int flags;
1915
1916     /* Check that this is an ACPI device and get its GPE. */
1917     flags = device_get_flags(dev);
1918     handle = acpi_get_handle(dev);
1919     if ((flags & ACPI_FLAG_WAKE_CAPABLE) == 0 || handle == NULL)
1920         return (ENXIO);
1921
1922     /* Evaluate _PRW to find the GPE. */
1923     if (acpi_parse_prw(handle, &prw) != 0)
1924         return (ENXIO);
1925
1926     /*
1927      * TBD: All Power Resources referenced by elements 2 through N
1928      *      of the _PRW object are put into the ON state.
1929      */
1930
1931     /*
1932      * If the user requested that this device wake the system and the next
1933      * sleep state is valid for this GPE, enable it and the device's wake
1934      * capability.  The sleep state must be less than (i.e., higher power)
1935      * or equal to the value specified by _PRW.  Return early, leaving
1936      * the appropriate power resources enabled.
1937      */
1938     if ((flags & ACPI_FLAG_WAKE_ENABLED) != 0 &&
1939         sstate <= prw.lowest_wake) {
1940         if (bootverbose)
1941             device_printf(dev, "wake_prep enabled gpe %#x for state %d\n",
1942                 prw.gpe_bit, sstate);
1943         AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1944         acpi_SetInteger(handle, "_PSW", 1);
1945         return (0);
1946     }
1947
1948     /*
1949      * If the device wake was disabled or this sleep state is too low for
1950      * this device, disable its wake capability and GPE.
1951      */
1952     AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1953     acpi_SetInteger(handle, "_PSW", 0);
1954     if (bootverbose)
1955         device_printf(dev, "wake_prep disabled gpe %#x for state %d\n",
1956             prw.gpe_bit, sstate);
1957
1958     /*
1959      * TBD: All Power Resources referenced by elements 2 through N
1960      *      of the _PRW object are put into the OFF state.
1961      */
1962
1963     return (0);
1964 }
1965
1966 /* Re-enable GPEs after wake. */
1967 int
1968 acpi_wake_run_prep(device_t dev)
1969 {
1970     struct acpi_prw_data prw;
1971     ACPI_HANDLE handle;
1972     int flags;
1973
1974     /* Check that this is an ACPI device and get its GPE. */
1975     flags = device_get_flags(dev);
1976     handle = acpi_get_handle(dev);
1977     if ((flags & ACPI_FLAG_WAKE_CAPABLE) == 0 || handle == NULL)
1978         return (ENXIO);
1979
1980     /* Evaluate _PRW to find the GPE. */
1981     if (acpi_parse_prw(handle, &prw) != 0)
1982         return (ENXIO);
1983
1984     /*
1985      * TBD: Be sure all Power Resources referenced by elements 2 through N
1986      *      of the _PRW object are in the ON state.
1987      */
1988
1989     /* Disable wake capability and if the user requested, enable the GPE. */
1990     acpi_SetInteger(handle, "_PSW", 0);
1991     if ((flags & ACPI_FLAG_WAKE_ENABLED) != 0)
1992         AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1993     return (0);
1994 }
1995
1996 static ACPI_STATUS
1997 acpi_wake_limit(ACPI_HANDLE h, UINT32 level, void *context, void **status)
1998 {
1999     struct acpi_prw_data prw;
2000     int *sstate;
2001
2002     /* It's ok not to have _PRW if the device can't wake the system. */
2003     if (acpi_parse_prw(h, &prw) != 0)
2004         return (AE_OK);
2005
2006     sstate = (int *)context;
2007     if (*sstate > prw.lowest_wake)
2008         AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2009
2010     return (AE_OK);
2011 }
2012
2013 /* Walk all system devices, disabling them if necessary for sstate. */
2014 static int
2015 acpi_wake_limit_walk(int sstate)
2016 {
2017     ACPI_HANDLE sb_handle;
2018
2019     if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2020         AcpiWalkNamespace(ACPI_TYPE_ANY, sb_handle, 100,
2021             acpi_wake_limit, &sstate, NULL);
2022     return (0);
2023 }
2024
2025 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
2026 static int
2027 acpi_wake_sysctl_walk(device_t dev)
2028 {
2029     int error, i, numdevs;
2030     device_t *devlist;
2031     device_t child;
2032
2033     error = device_get_children(dev, &devlist, &numdevs);
2034     if (error != 0 || numdevs == 0)
2035         return (error);
2036     for (i = 0; i < numdevs; i++) {
2037         child = devlist[i];
2038         if (!device_is_attached(child))
2039             continue;
2040         if (device_get_flags(child) & ACPI_FLAG_WAKE_CAPABLE) {
2041 #ifdef dfly_notyet
2042             SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
2043                 SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
2044                 "wake", CTLTYPE_INT | CTLFLAG_RW, child, 0,
2045                 acpi_wake_set_sysctl, "I", "Device set to wake the system");
2046 #endif /* dfly_notyet */
2047         }
2048         acpi_wake_sysctl_walk(child);
2049     }
2050     kfree(devlist, M_TEMP);
2051
2052     return (0);
2053 }
2054
2055 #ifdef dfly_notyet
2056 /* Enable or disable wake from userland. */
2057 static int
2058 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
2059 {
2060     int enable, error;
2061     device_t dev;
2062
2063     dev = (device_t)arg1;
2064     enable = (device_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
2065
2066     error = sysctl_handle_int(oidp, &enable, 0, req);
2067     if (error != 0 || req->newptr == NULL)
2068         return (error);
2069     if (enable != 0 && enable != 1)
2070         return (EINVAL);
2071
2072     return (acpi_wake_set_enable(dev, enable));
2073 }
2074 #endif /* dfly_notyet */
2075
2076 /* Parse a device's _PRW into a structure. */
2077 static int
2078 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
2079 {
2080     ACPI_STATUS                 status;
2081     ACPI_BUFFER                 prw_buffer;
2082     ACPI_OBJECT                 *res, *res2;
2083     int error;
2084
2085     if (h == NULL || prw == NULL)
2086         return (EINVAL);
2087
2088     /*
2089      * The _PRW object (7.2.9) is only required for devices that have the
2090      * ability to wake the system from a sleeping state.
2091      */
2092     error = EINVAL;
2093     prw_buffer.Pointer = NULL;
2094     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
2095     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
2096     if (ACPI_FAILURE(status))
2097         return (ENOENT);
2098     res = (ACPI_OBJECT *)prw_buffer.Pointer;
2099     if (res == NULL)
2100         return (ENOENT);
2101     if (!ACPI_PKG_VALID(res, 2))
2102         goto out;
2103
2104     /*
2105      * Element 1 of the _PRW object:
2106      * The lowest power system sleeping state that can be entered while still
2107      * providing wake functionality.  The sleeping state being entered must
2108      * be less than (i.e., higher power) or equal to this value.
2109      */
2110     if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
2111         goto out;
2112
2113     /*
2114      * Element 0 of the _PRW object:
2115      */
2116     switch (res->Package.Elements[0].Type) {
2117     case ACPI_TYPE_INTEGER:
2118         /*
2119          * If the data type of this package element is numeric, then this
2120          * _PRW package element is the bit index in the GPEx_EN, in the
2121          * GPE blocks described in the FADT, of the enable bit that is
2122          * enabled for the wake event.
2123          */
2124         prw->gpe_handle = NULL;
2125         prw->gpe_bit = res->Package.Elements[0].Integer.Value;
2126         error = 0;
2127         break;
2128     case ACPI_TYPE_PACKAGE:
2129         /*
2130          * If the data type of this package element is a package, then this
2131          * _PRW package element is itself a package containing two
2132          * elements.  The first is an object reference to the GPE Block
2133          * device that contains the GPE that will be triggered by the wake
2134          * event.  The second element is numeric and it contains the bit
2135          * index in the GPEx_EN, in the GPE Block referenced by the
2136          * first element in the package, of the enable bit that is enabled for
2137          * the wake event.
2138          *
2139          * For example, if this field is a package then it is of the form:
2140          * Package() {\_SB.PCI0.ISA.GPE, 2}
2141          */
2142         res2 = &res->Package.Elements[0];
2143         if (!ACPI_PKG_VALID(res2, 2))
2144             goto out;
2145         prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
2146         if (prw->gpe_handle == NULL)
2147             goto out;
2148         if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
2149             goto out;
2150         error = 0;
2151         break;
2152     default:
2153         goto out;
2154     }
2155
2156     /* XXX No power resource handling yet. */
2157     prw->power_res = NULL;
2158
2159 out:
2160     if (prw_buffer.Pointer != NULL)
2161         AcpiOsFree(prw_buffer.Pointer);
2162     return (error);
2163 }
2164
2165 /*
2166  * Enable/Disable ACPI
2167  */
2168 ACPI_STATUS
2169 acpi_Enable(struct acpi_softc *sc)
2170 {
2171     ACPI_STATUS status;
2172     u_int32_t   flags;
2173
2174     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2175     ACPI_ASSERTLOCK;
2176
2177     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
2178             ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
2179     if (!sc->acpi_enabled)
2180         status = AcpiEnableSubsystem(flags);
2181     else
2182         status = AE_OK;
2183
2184     if (status == AE_OK)
2185         sc->acpi_enabled = 1;
2186
2187     return_ACPI_STATUS (status);
2188 }
2189
2190 ACPI_STATUS
2191 acpi_Disable(struct acpi_softc *sc)
2192 {
2193     ACPI_STATUS status;
2194
2195     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2196     ACPI_ASSERTLOCK;
2197
2198     if (sc->acpi_enabled)
2199         status = AcpiDisable();
2200     else
2201         status = AE_OK;
2202
2203     if (status == AE_OK)
2204         sc->acpi_enabled = 0;
2205
2206     return_ACPI_STATUS (status);
2207 }
2208
2209 /*
2210  * ACPI Event Handlers
2211  */
2212
2213 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
2214
2215 static void
2216 acpi_system_eventhandler_sleep(void *arg, int state)
2217 {
2218     ACPI_LOCK_DECL;
2219     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2220
2221     ACPI_LOCK;
2222     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
2223         acpi_SetSleepState((struct acpi_softc *)arg, state);
2224     ACPI_UNLOCK;
2225     return_VOID;
2226 }
2227
2228 static void
2229 acpi_system_eventhandler_wakeup(void *arg, int state)
2230 {
2231     ACPI_LOCK_DECL;
2232     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2233
2234     /* Well, what to do? :-) */
2235
2236     ACPI_LOCK;
2237     ACPI_UNLOCK;
2238
2239     return_VOID;
2240 }
2241
2242 /* 
2243  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
2244  */
2245 UINT32
2246 acpi_event_power_button_sleep(void *context)
2247 {
2248     struct acpi_softc   *sc = (struct acpi_softc *)context;
2249
2250     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2251
2252     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
2253
2254     return_VALUE (ACPI_INTERRUPT_HANDLED);
2255 }
2256
2257 UINT32
2258 acpi_event_power_button_wake(void *context)
2259 {
2260     struct acpi_softc   *sc = (struct acpi_softc *)context;
2261
2262     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2263
2264     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
2265
2266     return_VALUE (ACPI_INTERRUPT_HANDLED);
2267 }
2268
2269 UINT32
2270 acpi_event_sleep_button_sleep(void *context)
2271 {
2272     struct acpi_softc   *sc = (struct acpi_softc *)context;
2273
2274     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2275
2276     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
2277
2278     return_VALUE (ACPI_INTERRUPT_HANDLED);
2279 }
2280
2281 UINT32
2282 acpi_event_sleep_button_wake(void *context)
2283 {
2284     struct acpi_softc   *sc = (struct acpi_softc *)context;
2285
2286     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2287
2288     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
2289
2290     return_VALUE (ACPI_INTERRUPT_HANDLED);
2291 }
2292
2293 /*
2294  * XXX This is kinda ugly, and should not be here.
2295  */
2296 struct acpi_staticbuf {
2297     ACPI_BUFFER buffer;
2298     char        data[512];
2299 };
2300
2301 char *
2302 acpi_name(ACPI_HANDLE handle)
2303 {
2304     static struct acpi_staticbuf        buf;
2305
2306     ACPI_ASSERTLOCK;
2307
2308     buf.buffer.Length = 512;
2309     buf.buffer.Pointer = &buf.data[0];
2310
2311     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
2312         return (buf.buffer.Pointer);
2313
2314     return ("(unknown path)");
2315 }
2316
2317 /*
2318  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
2319  * parts of the namespace.
2320  */
2321 int
2322 acpi_avoid(ACPI_HANDLE handle)
2323 {
2324     char        *cp, *env, *np;
2325     int         len;
2326
2327     np = acpi_name(handle);
2328     if (*np == '\\')
2329         np++;
2330     if ((env = kgetenv("debug.acpi.avoid.paths")) == NULL &&
2331         (env = kgetenv("debug.acpi.avoid")) == NULL)
2332         return (0);
2333
2334     /* Scan the avoid list checking for a match */
2335     cp = env;
2336     for (;;) {
2337         while ((*cp != 0) && isspace(*cp))
2338             cp++;
2339         if (*cp == 0)
2340             break;
2341         len = 0;
2342         while ((cp[len] != 0) && !isspace(cp[len]))
2343             len++;
2344         if (!strncmp(cp, np, len)) {
2345             freeenv(env);
2346             return(1);
2347         }
2348         cp += len;
2349     }
2350     freeenv(env);
2351
2352     return (0);
2353 }
2354
2355 /*
2356  * Debugging/bug-avoidance.  Disable ACPI subsystem components.   Note that
2357  * some components may be disabled by default and can only be enabled
2358  * via acpi_enabled() (debug.acpi.enabled).
2359  */
2360 int
2361 acpi_disabled(char *subsys)
2362 {
2363     char        *cp, *env;
2364     int         len;
2365
2366     if ((env = kgetenv("debug.acpi.disabled")) == NULL)
2367         return (0);
2368     if (strcmp(env, "all") == 0) {
2369         freeenv(env);
2370         return (1);
2371     }
2372
2373     /* Scan the disable list, checking for a match. */
2374     cp = env;
2375     for (;;) {
2376         while (*cp != '\0' && isspace(*cp))
2377             cp++;
2378         if (*cp == '\0')
2379             break;
2380         len = 0;
2381         while (cp[len] != '\0' && !isspace(cp[len]))
2382             len++;
2383         if (strncmp(cp, subsys, len) == 0) {
2384             freeenv(env);
2385             return (1);
2386         }
2387         cp += len;
2388     }
2389     freeenv(env);
2390
2391     return (0);
2392 }
2393
2394 /*
2395  * Debugging/bug-avoidance.  Enable ACPI subsystem components.  Most 
2396  * components are enabled by default.  The ones that are not have to be 
2397  * enabled via debug.acpi.enabled.
2398  */
2399 int
2400 acpi_enabled(char *subsys)
2401 {
2402     char        *cp, *env;
2403     int         len;
2404
2405     if ((env = kgetenv("debug.acpi.enabled")) == NULL)
2406         return (0);
2407     if (strcmp(env, "all") == 0) {
2408         freeenv(env);
2409         return (1);
2410     }
2411
2412     /* Scan the enable list, checking for a match. */
2413     cp = env;
2414     for (;;) {
2415         while (*cp != '\0' && isspace(*cp))
2416             cp++;
2417         if (*cp == '\0')
2418             break;
2419         len = 0;
2420         while (cp[len] != '\0' && !isspace(cp[len]))
2421             len++;
2422         if (strncmp(cp, subsys, len) == 0) {
2423             freeenv(env);
2424             return (1);
2425         }
2426         cp += len;
2427     }
2428     freeenv(env);
2429
2430     return (0);
2431 }
2432
2433 /*
2434  * Control interface.
2435  *
2436  * We multiplex ioctls for all participating ACPI devices here.  Individual 
2437  * drivers wanting to be accessible via /dev/acpi should use the
2438  * register/deregister interface to make their handlers visible.
2439  */
2440 struct acpi_ioctl_hook
2441 {
2442     TAILQ_ENTRY(acpi_ioctl_hook) link;
2443     u_long                       cmd;
2444     acpi_ioctl_fn                fn;
2445     void                         *arg;
2446 };
2447
2448 static TAILQ_HEAD(,acpi_ioctl_hook)     acpi_ioctl_hooks;
2449 static int                              acpi_ioctl_hooks_initted;
2450
2451 /*
2452  * Register an ioctl handler.
2453  */
2454 int
2455 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
2456 {
2457     struct acpi_ioctl_hook      *hp;
2458
2459     hp = kmalloc(sizeof(*hp), M_ACPIDEV, M_INTWAIT);
2460     hp->cmd = cmd;
2461     hp->fn = fn;
2462     hp->arg = arg;
2463     if (acpi_ioctl_hooks_initted == 0) {
2464         TAILQ_INIT(&acpi_ioctl_hooks);
2465         acpi_ioctl_hooks_initted = 1;
2466     }
2467     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
2468     return (0);
2469 }
2470
2471 /*
2472  * Deregister an ioctl handler.
2473  */
2474 void    
2475 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
2476 {
2477     struct acpi_ioctl_hook      *hp;
2478
2479     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
2480         if ((hp->cmd == cmd) && (hp->fn == fn))
2481             break;
2482
2483     if (hp != NULL) {
2484         TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
2485         kfree(hp, M_ACPIDEV);
2486     }
2487 }
2488
2489 static int
2490 acpiopen(struct dev_open_args *ap)
2491 {
2492     return (0);
2493 }
2494
2495 static int
2496 acpiclose(struct dev_close_args *ap)
2497 {
2498     return (0);
2499 }
2500
2501 static int
2502 acpiioctl(struct dev_ioctl_args *ap)
2503 {
2504     struct acpi_softc           *sc;
2505     struct acpi_ioctl_hook      *hp;
2506     int                         error, xerror, state;
2507     ACPI_LOCK_DECL;
2508
2509     ACPI_LOCK;
2510
2511     error = state = 0;
2512     sc = ap->a_head.a_dev->si_drv1;
2513
2514     /*
2515      * Scan the list of registered ioctls, looking for handlers.
2516      */
2517     if (acpi_ioctl_hooks_initted) {
2518         TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
2519             if (hp->cmd == ap->a_cmd) {
2520                 xerror = hp->fn(ap->a_cmd, ap->a_data, hp->arg);
2521                 if (xerror != 0)
2522                     error = xerror;
2523                 goto out;
2524             }
2525         }
2526     }
2527
2528     /*
2529      * Core ioctls are not permitted for non-writable user.
2530      * Currently, other ioctls just fetch information.
2531      * Not changing system behavior.
2532      */
2533     if((ap->a_fflag & FWRITE) == 0) {
2534         error = EPERM;
2535         goto out;
2536     }
2537
2538     /* Core system ioctls. */
2539     switch (ap->a_cmd) {
2540     case ACPIIO_ENABLE:
2541         if (ACPI_FAILURE(acpi_Enable(sc)))
2542             error = ENXIO;
2543         break;
2544     case ACPIIO_DISABLE:
2545         if (ACPI_FAILURE(acpi_Disable(sc)))
2546             error = ENXIO;
2547         break;
2548     case ACPIIO_SETSLPSTATE:
2549         if (!sc->acpi_enabled) {
2550             error = ENXIO;
2551             break;
2552         }
2553         state = *(int *)ap->a_data;
2554         if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
2555             if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
2556                 error = EINVAL;
2557         } else {
2558             error = EINVAL;
2559         }
2560         break;
2561     default:
2562         if (error == 0)
2563             error = EINVAL;
2564         break;
2565     }
2566
2567 out:
2568     ACPI_UNLOCK;
2569     return (error);
2570 }
2571
2572 static int
2573 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2574 {
2575     char sleep_state[4];
2576     char buf[16];
2577     int error;
2578     UINT8 state, TypeA, TypeB;
2579
2580     buf[0] = '\0';
2581     for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX + 1; state++) {
2582         if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
2583             ksprintf(sleep_state, "S%d ", state);
2584             strcat(buf, sleep_state);
2585         }
2586     }
2587     error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2588     return (error);
2589 }
2590
2591 static int
2592 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2593 {
2594     char sleep_state[10];
2595     int error;
2596     u_int new_state, old_state;
2597
2598     old_state = *(u_int *)oidp->oid_arg1;
2599     if (old_state > ACPI_S_STATES_MAX + 1) {
2600         strcpy(sleep_state, "unknown");
2601     } else {
2602         bzero(sleep_state, sizeof(sleep_state));
2603         strncpy(sleep_state, sleep_state_names[old_state],
2604                 sizeof(sleep_state_names[old_state]));
2605     }
2606     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
2607     if (error == 0 && req->newptr != NULL) {
2608         new_state = ACPI_STATE_S0;
2609         for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++) {
2610             if (strncmp(sleep_state, sleep_state_names[new_state],
2611                         sizeof(sleep_state)) == 0)
2612                 break;
2613         }
2614         if (new_state <= ACPI_S_STATES_MAX + 1) {
2615             if (new_state != old_state)
2616                 *(u_int *)oidp->oid_arg1 = new_state;
2617         } else {
2618             error = EINVAL;
2619         }
2620     }
2621
2622     return (error);
2623 }
2624
2625 /* Inform devctl(4) when we receive a Notify. */
2626 void
2627 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
2628 {
2629     char                notify_buf[16];
2630     ACPI_BUFFER         handle_buf;
2631     ACPI_STATUS         status;
2632
2633     if (subsystem == NULL)
2634         return;
2635
2636     handle_buf.Pointer = NULL;
2637     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
2638     status = AcpiNsHandleToPathname(h, &handle_buf);
2639     if (ACPI_FAILURE(status))
2640         return;
2641     ksnprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
2642 #if 0
2643     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
2644 #endif
2645     AcpiOsFree(handle_buf.Pointer);
2646 }
2647
2648 #ifdef ACPI_DEBUG
2649 /*
2650  * Support for parsing debug options from the kernel environment.
2651  *
2652  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
2653  * by specifying the names of the bits in the debug.acpi.layer and
2654  * debug.acpi.level environment variables.  Bits may be unset by 
2655  * prefixing the bit name with !.
2656  */
2657 struct debugtag
2658 {
2659     char        *name;
2660     UINT32      value;
2661 };
2662
2663 static struct debugtag  dbg_layer[] = {
2664     {"ACPI_UTILITIES",          ACPI_UTILITIES},
2665     {"ACPI_HARDWARE",           ACPI_HARDWARE},
2666     {"ACPI_EVENTS",             ACPI_EVENTS},
2667     {"ACPI_TABLES",             ACPI_TABLES},
2668     {"ACPI_NAMESPACE",          ACPI_NAMESPACE},
2669     {"ACPI_PARSER",             ACPI_PARSER},
2670     {"ACPI_DISPATCHER",         ACPI_DISPATCHER},
2671     {"ACPI_EXECUTER",           ACPI_EXECUTER},
2672     {"ACPI_RESOURCES",          ACPI_RESOURCES},
2673     {"ACPI_CA_DEBUGGER",        ACPI_CA_DEBUGGER},
2674     {"ACPI_OS_SERVICES",        ACPI_OS_SERVICES},
2675     {"ACPI_CA_DISASSEMBLER",    ACPI_CA_DISASSEMBLER},
2676     {"ACPI_ALL_COMPONENTS",     ACPI_ALL_COMPONENTS},
2677
2678     {"ACPI_AC_ADAPTER",         ACPI_AC_ADAPTER},
2679     {"ACPI_BATTERY",            ACPI_BATTERY},
2680     {"ACPI_BUS",                ACPI_BUS},
2681     {"ACPI_BUTTON",             ACPI_BUTTON},
2682     {"ACPI_EC",                 ACPI_EC},
2683     {"ACPI_FAN",                ACPI_FAN},
2684     {"ACPI_POWERRES",           ACPI_POWERRES},
2685     {"ACPI_PROCESSOR",          ACPI_PROCESSOR},
2686     {"ACPI_THERMAL",            ACPI_THERMAL},
2687     {"ACPI_TIMER",              ACPI_TIMER},
2688     {"ACPI_ALL_DRIVERS",        ACPI_ALL_DRIVERS},
2689     {NULL, 0}
2690 };
2691
2692 static struct debugtag dbg_level[] = {
2693     {"ACPI_LV_ERROR",           ACPI_LV_ERROR},
2694     {"ACPI_LV_WARN",            ACPI_LV_WARN},
2695     {"ACPI_LV_INIT",            ACPI_LV_INIT},
2696     {"ACPI_LV_DEBUG_OBJECT",    ACPI_LV_DEBUG_OBJECT},
2697     {"ACPI_LV_INFO",            ACPI_LV_INFO},
2698     {"ACPI_LV_ALL_EXCEPTIONS",  ACPI_LV_ALL_EXCEPTIONS},
2699
2700     /* Trace verbosity level 1 [Standard Trace Level] */
2701     {"ACPI_LV_INIT_NAMES",      ACPI_LV_INIT_NAMES},
2702     {"ACPI_LV_PARSE",           ACPI_LV_PARSE},
2703     {"ACPI_LV_LOAD",            ACPI_LV_LOAD},
2704     {"ACPI_LV_DISPATCH",        ACPI_LV_DISPATCH},
2705     {"ACPI_LV_EXEC",            ACPI_LV_EXEC},
2706     {"ACPI_LV_NAMES",           ACPI_LV_NAMES},
2707     {"ACPI_LV_OPREGION",        ACPI_LV_OPREGION},
2708     {"ACPI_LV_BFIELD",          ACPI_LV_BFIELD},
2709     {"ACPI_LV_TABLES",          ACPI_LV_TABLES},
2710     {"ACPI_LV_VALUES",          ACPI_LV_VALUES},
2711     {"ACPI_LV_OBJECTS",         ACPI_LV_OBJECTS},
2712     {"ACPI_LV_RESOURCES",       ACPI_LV_RESOURCES},
2713     {"ACPI_LV_USER_REQUESTS",   ACPI_LV_USER_REQUESTS},
2714     {"ACPI_LV_PACKAGE",         ACPI_LV_PACKAGE},
2715     {"ACPI_LV_VERBOSITY1",      ACPI_LV_VERBOSITY1},
2716
2717     /* Trace verbosity level 2 [Function tracing and memory allocation] */
2718     {"ACPI_LV_ALLOCATIONS",     ACPI_LV_ALLOCATIONS},
2719     {"ACPI_LV_FUNCTIONS",       ACPI_LV_FUNCTIONS},
2720     {"ACPI_LV_OPTIMIZATIONS",   ACPI_LV_OPTIMIZATIONS},
2721     {"ACPI_LV_VERBOSITY2",      ACPI_LV_VERBOSITY2},
2722     {"ACPI_LV_ALL",             ACPI_LV_ALL},
2723
2724     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2725     {"ACPI_LV_MUTEX",           ACPI_LV_MUTEX},
2726     {"ACPI_LV_THREADS",         ACPI_LV_THREADS},
2727     {"ACPI_LV_IO",              ACPI_LV_IO},
2728     {"ACPI_LV_INTERRUPTS",      ACPI_LV_INTERRUPTS},
2729     {"ACPI_LV_VERBOSITY3",      ACPI_LV_VERBOSITY3},
2730
2731     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2732     {"ACPI_LV_AML_DISASSEMBLE", ACPI_LV_AML_DISASSEMBLE},
2733     {"ACPI_LV_VERBOSE_INFO",    ACPI_LV_VERBOSE_INFO},
2734     {"ACPI_LV_FULL_TABLES",     ACPI_LV_FULL_TABLES},
2735     {"ACPI_LV_EVENTS",          ACPI_LV_EVENTS},
2736     {"ACPI_LV_VERBOSE",         ACPI_LV_VERBOSE},
2737     {NULL, 0}
2738 };    
2739
2740 static void
2741 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2742 {
2743     char        *ep;
2744     int         i, l;
2745     int         set;
2746
2747     while (*cp) {
2748         if (isspace(*cp)) {
2749             cp++;
2750             continue;
2751         }
2752         ep = cp;
2753         while (*ep && !isspace(*ep))
2754             ep++;
2755         if (*cp == '!') {
2756             set = 0;
2757             cp++;
2758             if (cp == ep)
2759                 continue;
2760         } else {
2761             set = 1;
2762         }
2763         l = ep - cp;
2764         for (i = 0; tag[i].name != NULL; i++) {
2765             if (!strncmp(cp, tag[i].name, l)) {
2766                 if (set)
2767                     *flag |= tag[i].value;
2768                 else
2769                     *flag &= ~tag[i].value;
2770             }
2771         }
2772         cp = ep;
2773     }
2774 }
2775
2776 /*
2777  * Warning: also called in early boot, before any allocators
2778  * are working.
2779  */
2780 static void
2781 acpi_set_debugging(void *junk)
2782 {
2783     char *layer, *level;
2784
2785     if (cold) {
2786         AcpiDbgLayer = 0;
2787         AcpiDbgLevel = 0;
2788     }
2789
2790     layer = kgetenv("debug.acpi.layer");
2791     level = kgetenv("debug.acpi.level");
2792     if (layer == NULL && level == NULL)
2793         return;
2794
2795     kprintf("ACPI set debug");
2796     if (layer != NULL) {
2797         if (strcmp("NONE", layer) != 0)
2798             kprintf(" layer '%s'", layer);
2799         acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
2800         freeenv(layer);
2801     }
2802     if (level != NULL) {
2803         if (strcmp("NONE", level) != 0)
2804             kprintf(" level '%s'", level);
2805         acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
2806         freeenv(level);
2807     }
2808     kprintf("\n");
2809 }
2810 SYSINIT(acpi_debugging, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
2811         acpi_set_debugging, NULL);
2812
2813 static int
2814 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
2815 {
2816     int          error, *dbg;
2817     struct       debugtag *tag;
2818     struct       sbuf sb;
2819
2820     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
2821         return (ENOMEM);
2822     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
2823         tag = &dbg_layer[0];
2824         dbg = &AcpiDbgLayer;
2825     } else {
2826         tag = &dbg_level[0];
2827         dbg = &AcpiDbgLevel;
2828     }
2829
2830     /* Get old values if this is a get request. */
2831     if (*dbg == 0) {
2832         sbuf_cpy(&sb, "NONE");
2833     } else if (req->newptr == NULL) {
2834         for (; tag->name != NULL; tag++) {
2835             if ((*dbg & tag->value) == tag->value)
2836                 sbuf_printf(&sb, "%s ", tag->name);
2837         }
2838     }
2839     sbuf_trim(&sb);
2840     sbuf_finish(&sb);
2841
2842     /* Copy out the old values to the user. */
2843     error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
2844     sbuf_delete(&sb);
2845
2846     /* If the user is setting a string, parse it. */
2847     if (error == 0 && req->newptr != NULL) {
2848         *dbg = 0;
2849         ksetenv(oidp->oid_arg1, req->newptr);
2850         acpi_set_debugging(NULL);
2851     }
2852
2853     return (error);
2854 }
2855 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
2856             "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
2857 SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
2858             "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
2859 #endif
2860
2861 static int
2862 acpi_pm_func(u_long cmd, void *arg, ...)
2863 {
2864         int     state, acpi_state;
2865         int     error;
2866         struct  acpi_softc *sc;
2867         va_list ap;
2868
2869         error = 0;
2870         switch (cmd) {
2871         case POWER_CMD_SUSPEND:
2872                 sc = (struct acpi_softc *)arg;
2873                 if (sc == NULL) {
2874                         error = EINVAL;
2875                         goto out;
2876                 }
2877
2878                 va_start(ap, arg);
2879                 state = va_arg(ap, int);
2880                 va_end(ap);     
2881
2882                 switch (state) {
2883                 case POWER_SLEEP_STATE_STANDBY:
2884                         acpi_state = sc->acpi_standby_sx;
2885                         break;
2886                 case POWER_SLEEP_STATE_SUSPEND:
2887                         acpi_state = sc->acpi_suspend_sx;
2888                         break;
2889                 case POWER_SLEEP_STATE_HIBERNATE:
2890                         acpi_state = ACPI_STATE_S4;
2891                         break;
2892                 default:
2893                         error = EINVAL;
2894                         goto out;
2895                 }
2896
2897                 acpi_SetSleepState(sc, acpi_state);
2898                 break;
2899         default:
2900                 error = EINVAL;
2901                 goto out;
2902         }
2903
2904 out:
2905         return (error);
2906 }
2907
2908 static void
2909 acpi_pm_register(void *arg)
2910 {
2911     if (!cold || resource_disabled("acpi", 0))
2912         return;
2913
2914     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2915 }
2916
2917 SYSINIT(power, SI_BOOT2_KLD, SI_ORDER_ANY, acpi_pm_register, 0);