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