]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/acpica/acpi.c
This commit was generated by cvs2svn to compensate for changes in r105081,
[FreeBSD/FreeBSD.git] / sys / dev / acpica / 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$
30  */
31
32 #include "opt_acpi.h"
33 #include <sys/param.h>
34 #include <sys/kernel.h>
35 #include <sys/proc.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mutex.h>
39 #include <sys/bus.h>
40 #include <sys/conf.h>
41 #include <sys/ioccom.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
48 #include <machine/clock.h>
49 #include <machine/resource.h>
50
51 #include <isa/isavar.h>
52
53 #include "acpi.h"
54
55 #include <dev/acpica/acpica_support.h>
56
57 #include <dev/acpica/acpivar.h>
58 #include <dev/acpica/acpiio.h>
59
60 MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
61
62 /*
63  * Hooks for the ACPI CA debugging infrastructure
64  */
65 #define _COMPONENT      ACPI_BUS
66 ACPI_MODULE_NAME("ACPI")
67
68 /*
69  * Character device 
70  */
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 cdevsw acpi_cdevsw = {
78     acpiopen,
79     acpiclose,
80     noread,
81     nowrite,
82     acpiioctl,
83     nopoll,
84     nommap,
85     nostrategy,
86     "acpi",
87     CDEV_MAJOR,
88     nodump,
89     nopsize,
90     0
91 };
92
93 static const char* sleep_state_names[] = {
94     "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
95
96 /* this has to be static, as the softc is gone when we need it */
97 static int acpi_off_state = ACPI_STATE_S5;
98
99 struct mtx      acpi_mutex;
100
101 static int      acpi_modevent(struct module *mod, int event, void *junk);
102 static void     acpi_identify(driver_t *driver, device_t parent);
103 static int      acpi_probe(device_t dev);
104 static int      acpi_attach(device_t dev);
105 static device_t acpi_add_child(device_t bus, int order, const char *name, int unit);
106 static int      acpi_print_child(device_t bus, device_t child);
107 static int      acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result);
108 static int      acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value);
109 static int      acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start,
110                                   u_long count);
111 static int      acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp,
112                                   u_long *countp);
113 static struct resource *acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
114                                             u_long start, u_long end, u_long count, u_int flags);
115 static int      acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r);
116 static u_int32_t acpi_isa_get_logicalid(device_t dev);
117 static int      acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids);
118
119 static void     acpi_probe_children(device_t bus);
120 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status);
121
122 static void     acpi_shutdown_pre_sync(void *arg, int howto);
123 static void     acpi_shutdown_final(void *arg, int howto);
124
125 static void     acpi_enable_fixed_events(struct acpi_softc *sc);
126
127 static void     acpi_system_eventhandler_sleep(void *arg, int state);
128 static void     acpi_system_eventhandler_wakeup(void *arg, int state);
129 static int      acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
130
131 static int      acpi_pm_func(u_long cmd, void *arg, ...);
132
133 static device_method_t acpi_methods[] = {
134     /* Device interface */
135     DEVMETHOD(device_identify,          acpi_identify),
136     DEVMETHOD(device_probe,             acpi_probe),
137     DEVMETHOD(device_attach,            acpi_attach),
138     DEVMETHOD(device_shutdown,          bus_generic_shutdown),
139     DEVMETHOD(device_suspend,           bus_generic_suspend),
140     DEVMETHOD(device_resume,            bus_generic_resume),
141
142     /* Bus interface */
143     DEVMETHOD(bus_add_child,            acpi_add_child),
144     DEVMETHOD(bus_print_child,          acpi_print_child),
145     DEVMETHOD(bus_read_ivar,            acpi_read_ivar),
146     DEVMETHOD(bus_write_ivar,           acpi_write_ivar),
147     DEVMETHOD(bus_set_resource,         acpi_set_resource),
148     DEVMETHOD(bus_get_resource,         acpi_get_resource),
149     DEVMETHOD(bus_alloc_resource,       acpi_alloc_resource),
150     DEVMETHOD(bus_release_resource,     acpi_release_resource),
151     DEVMETHOD(bus_driver_added,         bus_generic_driver_added),
152     DEVMETHOD(bus_activate_resource,    bus_generic_activate_resource),
153     DEVMETHOD(bus_deactivate_resource,  bus_generic_deactivate_resource),
154     DEVMETHOD(bus_setup_intr,           bus_generic_setup_intr),
155     DEVMETHOD(bus_teardown_intr,        bus_generic_teardown_intr),
156
157     /* ISA emulation */
158     DEVMETHOD(isa_pnp_probe,            acpi_isa_pnp_probe),
159
160     {0, 0}
161 };
162
163 static driver_t acpi_driver = {
164     "acpi",
165     acpi_methods,
166     sizeof(struct acpi_softc),
167 };
168
169 static devclass_t acpi_devclass;
170 DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
171 MODULE_VERSION(acpi, 100);
172
173 SYSCTL_INT(_debug, OID_AUTO, acpi_debug_layer, CTLFLAG_RW, &AcpiDbgLayer, 0, "");
174 SYSCTL_INT(_debug, OID_AUTO, acpi_debug_level, CTLFLAG_RW, &AcpiDbgLevel, 0, "");
175 static int acpi_ca_version = ACPI_CA_VERSION;
176 SYSCTL_INT(_debug, OID_AUTO, acpi_ca_version, CTLFLAG_RD, &acpi_ca_version, 0, "");
177
178 /*
179  * ACPI can only be loaded as a module by the loader; activating it after
180  * system bootstrap time is not useful, and can be fatal to the system.
181  * It also cannot be unloaded, since the entire system bus heirarchy hangs off it.
182  */
183 static int
184 acpi_modevent(struct module *mod, int event, void *junk)
185 {
186     switch(event) {
187     case MOD_LOAD:
188         if (!cold)
189             return(EPERM);
190         break;
191     case MOD_UNLOAD:
192         if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
193             return(EBUSY);
194         break;
195     default:
196         break;
197     }
198     return(0);
199 }
200
201 /*
202  * Detect ACPI, perform early initialisation
203  */
204 static void
205 acpi_identify(driver_t *driver, device_t parent)
206 {
207     device_t                    child;
208     int                         error;
209 #ifdef ACPI_DEBUGGER
210     char                        *debugpoint;
211 #endif
212
213     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
214
215     if(!cold){
216             printf("Don't load this driver from userland!!\n");
217             return ;
218     }
219
220     /*
221      * Check that we haven't been disabled with a hint.
222      */
223     if (!resource_int_value("acpi", 0, "disabled", &error) &&
224         (error != 0))
225         return_VOID;
226
227     /*
228      * Make sure we're not being doubly invoked.
229      */
230     if (device_find_child(parent, "acpi", 0) != NULL)
231         return_VOID;
232
233     /* initialise the ACPI mutex */
234     mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
235
236     /*
237      * Start up the ACPI CA subsystem.
238      */
239 #ifdef ACPI_DEBUGGER
240     debugpoint = getenv("debug.acpi.debugger");
241     if (debugpoint) {
242         if (!strcmp(debugpoint, "init"))
243             acpi_EnterDebugger();
244         freeenv(debugpoint);
245     }
246 #endif
247     if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
248         printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
249         return_VOID;
250     }
251 #ifdef ACPI_DEBUGGER
252     debugpoint = getenv("debug.acpi.debugger");
253     if (debugpoint) {
254         if (!strcmp(debugpoint, "tables"))
255             acpi_EnterDebugger();
256         freeenv(debugpoint);
257     }
258 #endif
259
260     if (ACPI_FAILURE(error = AcpiLoadTables())) {
261         printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
262         return_VOID;
263     }
264     
265     /*
266      * Attach the actual ACPI device.
267      */
268     if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
269             device_printf(parent, "ACPI: could not attach\n");
270             return_VOID;
271     }
272 }
273
274 /*
275  * Fetch some descriptive data from ACPI to put in our attach message
276  */
277 static int
278 acpi_probe(device_t dev)
279 {
280     ACPI_TABLE_HEADER   th;
281     char                buf[20];
282     ACPI_STATUS         status;
283     int                 error;
284
285     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
286
287     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
288         power_pm_get_type() != POWER_PM_TYPE_ACPI) {
289         device_printf(dev, "Other PM system enabled.\n");
290         return_VALUE(ENXIO);
291     }
292
293     ACPI_LOCK;
294
295     if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
296         device_printf(dev, "couldn't get XSDT header: %s\n", AcpiFormatException(status));
297         error = ENXIO;
298     } else {
299         sprintf(buf, "%.6s %.8s", th.OemId, th.OemTableId);
300         device_set_desc_copy(dev, buf);
301         error = 0;
302     }
303     ACPI_UNLOCK;
304     return_VALUE(error);
305 }
306
307 static int
308 acpi_attach(device_t dev)
309 {
310     struct acpi_softc   *sc;
311     ACPI_STATUS         status;
312     int                 error;
313     UINT32              flags;
314     
315 #ifdef ACPI_DEBUGGER
316     char                *debugpoint;
317 #endif
318
319     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
320     ACPI_LOCK;
321     sc = device_get_softc(dev);
322     bzero(sc, sizeof(*sc));
323     sc->acpi_dev = dev;
324
325 #ifdef ACPI_DEBUGGER
326     debugpoint = getenv("debug.acpi.debugger");
327     if (debugpoint) {
328         if (!strcmp(debugpoint, "spaces"))
329             acpi_EnterDebugger();
330         freeenv(debugpoint);
331     }
332 #endif
333
334     /*
335      * Install the default address space handlers.
336      */
337     error = ENXIO;
338     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
339                                                 ACPI_ADR_SPACE_SYSTEM_MEMORY,
340                                                 ACPI_DEFAULT_HANDLER,
341                                                 NULL, NULL))) {
342         device_printf(dev, "could not initialise SystemMemory handler: %s\n", AcpiFormatException(status));
343         goto out;
344     }
345     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
346                                                 ACPI_ADR_SPACE_SYSTEM_IO,
347                                                 ACPI_DEFAULT_HANDLER,
348                                                 NULL, NULL))) {
349         device_printf(dev, "could not initialise SystemIO handler: %s\n", AcpiFormatException(status));
350         goto out;
351     }
352     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
353                                                 ACPI_ADR_SPACE_PCI_CONFIG,
354                                                 ACPI_DEFAULT_HANDLER,
355                                                 NULL, NULL))) {
356         device_printf(dev, "could not initialise PciConfig handler: %s\n", AcpiFormatException(status));
357         goto out;
358     }
359
360     /*
361      * Bring ACPI fully online.
362      *
363      * Note that some systems (specifically, those with namespace evaluation issues
364      * that require the avoidance of parts of the namespace) must avoid running _INI
365      * and _STA on everything, as well as dodging the final object init pass.
366      *
367      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
368      *
369      * XXX We should arrange for the object init pass after we have attached all our 
370      *     child devices, but on many systems it works here.
371      */
372 #ifdef ACPI_DEBUGGER
373     debugpoint = getenv("debug.acpi.debugger");
374     if (debugpoint) {
375         if (!strcmp(debugpoint, "enable"))
376             acpi_EnterDebugger();
377         freeenv(debugpoint);
378     }
379 #endif
380     flags = 0;
381     if (testenv("debug.acpi.avoid"))
382         flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
383     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
384         device_printf(dev, "could not enable ACPI: %s\n", AcpiFormatException(status));
385         goto out;
386     }
387
388     if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
389         device_printf(dev, "could not initialize ACPI objects: %s\n", AcpiFormatException(status));
390         goto out;
391     }
392
393     /*
394      * Setup our sysctl tree.
395      *
396      * XXX: This doesn't check to make sure that none of these fail.
397      */
398     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
399     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
400                                SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
401                                device_get_name(dev), CTLFLAG_RD, 0, "");
402     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
403         OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
404         &sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
405     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
406         OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
407         &sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
408     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
409         OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
410         &sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
411     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
412         OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
413         &sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
414     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
415         OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
416         &sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
417     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
418         OID_AUTO, "sleep_delay", CTLFLAG_RD | CTLFLAG_RW,
419         &sc->acpi_sleep_delay, 0, "sleep delay");
420     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
421         OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
422         &sc->acpi_s4bios, 0, "S4BIOS mode");
423     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
424         OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
425         &sc->acpi_verbose, 0, "verbose mode");
426     sc->acpi_sleep_delay = 0;
427     sc->acpi_s4bios = 1;
428     if (bootverbose)
429         sc->acpi_verbose = 1;
430     
431     /*
432      * Dispatch the default sleep state to devices.
433      * TBD: should be configured from userland policy manager.
434      */
435     sc->acpi_power_button_sx = ACPI_POWER_BUTTON_DEFAULT_SX;
436     sc->acpi_sleep_button_sx = ACPI_SLEEP_BUTTON_DEFAULT_SX;
437     sc->acpi_lid_switch_sx = ACPI_LID_SWITCH_DEFAULT_SX;
438     sc->acpi_standby_sx = ACPI_STATE_S1;
439     sc->acpi_suspend_sx = ACPI_STATE_S3;
440
441     acpi_enable_fixed_events(sc);
442
443     /*
444      * Scan the namespace and attach/initialise children.
445      */
446 #ifdef ACPI_DEBUGGER
447     debugpoint = getenv("debug.acpi.debugger");
448     if (debugpoint) {
449         if (!strcmp(debugpoint, "probe"))
450             acpi_EnterDebugger();
451         freeenv(debugpoint);
452     }
453 #endif
454
455     /*
456      * Register our shutdown handlers
457      */
458     EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc, SHUTDOWN_PRI_LAST);
459     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc, SHUTDOWN_PRI_LAST);
460
461     /*
462      * Register our acpi event handlers.
463      * XXX should be configurable eg. via userland policy manager.
464      */
465     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep, sc, ACPI_EVENT_PRI_LAST);
466     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup, sc, ACPI_EVENT_PRI_LAST);
467
468     /*
469      * Flag our initial states.
470      */
471     sc->acpi_enabled = 1;
472     sc->acpi_sstate = ACPI_STATE_S0;
473     sc->acpi_sleep_disabled = 0;
474
475     /*
476      * Create the control device
477      */
478     sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, 0, 5, 0660, "acpi");
479     sc->acpi_dev_t->si_drv1 = sc;
480
481 #ifdef ACPI_DEBUGGER
482     debugpoint = getenv("debug.acpi.debugger");
483     if (debugpoint) {
484         if (!strcmp(debugpoint, "running"))
485             acpi_EnterDebugger();
486         freeenv(debugpoint);
487     }
488 #endif
489
490 #if defined(ACPI_MAX_THREADS) && ACPI_MAX_THREADS > 0
491     if ((error = acpi_task_thread_init())) {
492         goto out;
493     }
494 #endif
495
496     if ((error = acpi_machdep_init(dev))) {
497         goto out;
498     }
499
500     /* Register ACPI again to pass the correct argument of pm_func. */
501     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
502
503     if (!acpi_disabled("bus"))
504         acpi_probe_children(dev);
505
506     error = 0;
507
508  out:
509     ACPI_UNLOCK;
510     return_VALUE(error);
511 }
512
513 /*
514  * Handle a new device being added
515  */
516 static device_t
517 acpi_add_child(device_t bus, int order, const char *name, int unit)
518 {
519     struct acpi_device  *ad;
520     device_t            child;
521
522     if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT)) == NULL)
523         return(NULL);
524     bzero(ad, sizeof(*ad));
525
526     resource_list_init(&ad->ad_rl);
527     
528     child = device_add_child_ordered(bus, order, name, unit);
529     if (child != NULL)
530         device_set_ivars(child, ad);
531     return(child);
532 }
533
534 static int
535 acpi_print_child(device_t bus, device_t child)
536 {
537     struct acpi_device          *adev = device_get_ivars(child);
538     struct resource_list        *rl = &adev->ad_rl;
539     int retval = 0;
540
541     retval += bus_print_child_header(bus, child);
542     retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
543     retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
544     retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
545     retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
546     retval += bus_print_child_footer(bus, child);
547
548     return(retval);
549 }
550
551
552 /*
553  * Handle per-device ivars
554  */
555 static int
556 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
557 {
558     struct acpi_device  *ad;
559
560     if ((ad = device_get_ivars(child)) == NULL) {
561         printf("device has no ivars\n");
562         return(ENOENT);
563     }
564
565     switch(index) {
566         /* ACPI ivars */
567     case ACPI_IVAR_HANDLE:
568         *(ACPI_HANDLE *)result = ad->ad_handle;
569         break;
570     case ACPI_IVAR_MAGIC:
571         *(int *)result = ad->ad_magic;
572         break;
573     case ACPI_IVAR_PRIVATE:
574         *(void **)result = ad->ad_private;
575         break;
576
577         /* ISA compatibility */
578     case ISA_IVAR_VENDORID:
579     case ISA_IVAR_SERIAL:
580     case ISA_IVAR_COMPATID:
581         *(int *)result = -1;
582         break;
583
584     case ISA_IVAR_LOGICALID:
585         *(int *)result = acpi_isa_get_logicalid(child);
586         break;
587
588     default:
589         return(ENOENT);
590     }
591     return(0);
592 }
593
594 static int
595 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
596 {
597     struct acpi_device  *ad;
598
599     if ((ad = device_get_ivars(child)) == NULL) {
600         printf("device has no ivars\n");
601         return(ENOENT);
602     }
603
604     switch(index) {
605         /* ACPI ivars */
606     case ACPI_IVAR_HANDLE:
607         ad->ad_handle = (ACPI_HANDLE)value;
608         break;
609     case ACPI_IVAR_MAGIC:
610         ad->ad_magic = (int )value;
611         break;
612     case ACPI_IVAR_PRIVATE:
613         ad->ad_private = (void *)value;
614         break;
615
616     default:
617         panic("bad ivar write request (%d)", index);
618         return(ENOENT);
619     }
620     return(0);
621 }
622
623 /*
624  * Handle child resource allocation/removal
625  */
626 static int
627 acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start, u_long count)
628 {
629     struct acpi_device          *ad = device_get_ivars(child);
630     struct resource_list        *rl = &ad->ad_rl;
631
632     resource_list_add(rl, type, rid, start, start + count -1, count);
633
634     return(0);
635 }
636
637 static int
638 acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp, u_long *countp)
639 {
640     struct acpi_device          *ad = device_get_ivars(child);
641     struct resource_list        *rl = &ad->ad_rl;
642     struct resource_list_entry  *rle;
643
644     rle = resource_list_find(rl, type, rid);
645     if (!rle)
646         return(ENOENT);
647         
648     if (startp)
649         *startp = rle->start;
650     if (countp)
651         *countp = rle->count;
652
653     return(0);
654 }
655
656 static struct resource *
657 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
658                     u_long start, u_long end, u_long count, u_int flags)
659 {
660     struct acpi_device *ad = device_get_ivars(child);
661     struct resource_list *rl = &ad->ad_rl;
662
663     return(resource_list_alloc(rl, bus, child, type, rid, start, end, count, flags));
664 }
665
666 static int
667 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
668 {
669     struct acpi_device *ad = device_get_ivars(child);
670     struct resource_list *rl = &ad->ad_rl;
671
672     return(resource_list_release(rl, bus, child, type, rid, r));
673 }
674
675 /*
676  * Handle ISA-like devices probing for a PnP ID to match.
677  */
678 #define PNP_EISAID(s)                           \
679         ((((s[0] - '@') & 0x1f) << 2)           \
680          | (((s[1] - '@') & 0x18) >> 3)         \
681          | (((s[1] - '@') & 0x07) << 13)        \
682          | (((s[2] - '@') & 0x1f) << 8)         \
683          | (PNP_HEXTONUM(s[4]) << 16)           \
684          | (PNP_HEXTONUM(s[3]) << 20)           \
685          | (PNP_HEXTONUM(s[6]) << 24)           \
686          | (PNP_HEXTONUM(s[5]) << 28))
687
688 static u_int32_t
689 acpi_isa_get_logicalid(device_t dev)
690 {
691     ACPI_HANDLE         h;
692     ACPI_DEVICE_INFO    devinfo;
693     ACPI_STATUS         error;
694     u_int32_t           pnpid;
695
696     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
697
698     pnpid = 0;
699     ACPI_LOCK;
700     
701     /* fetch and validate the HID */
702     if ((h = acpi_get_handle(dev)) == NULL)
703         goto out;
704     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
705         goto out;
706     if (!(devinfo.Valid & ACPI_VALID_HID))
707         goto out;
708
709     pnpid = PNP_EISAID(devinfo.HardwareId);
710 out:
711     ACPI_UNLOCK;
712     return_VALUE(pnpid);
713 }
714
715 static int
716 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
717 {
718     int                 result;
719     u_int32_t           pnpid;
720
721     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
722
723     /*
724      * ISA-style drivers attached to ACPI may persist and
725      * probe manually if we return ENOENT.  We never want
726      * that to happen, so don't ever return it.
727      */
728     result = ENXIO;
729
730     /* scan the supplied IDs for a match */
731     pnpid = acpi_isa_get_logicalid(child);
732     while (ids && ids->ip_id) {
733         if (pnpid == ids->ip_id) {
734             result = 0;
735             goto out;
736         }
737         ids++;
738     }
739  out:
740     return_VALUE(result);
741 }
742
743 /*
744  * Scan relevant portions of the ACPI namespace and attach child devices.
745  *
746  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and \_SB_ scopes, 
747  * and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
748  */
749 static void
750 acpi_probe_children(device_t bus)
751 {
752     ACPI_HANDLE         parent;
753     static char         *scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
754     int                 i;
755
756     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
757     ACPI_ASSERTLOCK;
758
759     /*
760      * Create any static children by calling device identify methods.
761      */
762     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
763     bus_generic_probe(bus);
764
765     /*
766      * Scan the namespace and insert placeholders for all the devices that
767      * we find.
768      *
769      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
770      * we want to create nodes for all devices, not just those that are currently
771      * present. (This assumes that we don't want to create/remove devices as they
772      * appear, which might be smarter.)
773      */
774     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
775     for (i = 0; scopes[i] != NULL; i++)
776         if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent)))
777             AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child, bus, NULL);
778
779     /*
780      * Scan all of the child devices we have created and let them probe/attach.
781      */
782     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
783     bus_generic_attach(bus);
784
785     /*
786      * Some of these children may have attached others as part of their attach
787      * process (eg. the root PCI bus driver), so rescan.
788      */
789     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
790     bus_generic_attach(bus);
791
792     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
793     return_VOID;
794 }
795
796 /*
797  * Evaluate a child device and determine whether we might attach a device to
798  * it.
799  */
800 static ACPI_STATUS
801 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
802 {
803     ACPI_OBJECT_TYPE    type;
804     device_t            child, bus = (device_t)context;
805
806     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
807
808     /*
809      * Skip this device if we think we'll have trouble with it.
810      */
811     if (acpi_avoid(handle))
812         return_ACPI_STATUS(AE_OK);
813
814     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
815         switch(type) {
816         case ACPI_TYPE_DEVICE:
817         case ACPI_TYPE_PROCESSOR:
818         case ACPI_TYPE_THERMAL:
819         case ACPI_TYPE_POWER:
820             if (acpi_disabled("children"))
821                 break;
822             /* 
823              * Create a placeholder device for this node.  Sort the placeholder
824              * so that the probe/attach passes will run breadth-first.
825              */
826             ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", acpi_name(handle)));
827             child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
828             if (child == NULL)
829                 break;
830             acpi_set_handle(child, handle);
831
832             /*
833              * Check that the device is present.  If it's not present,
834              * leave it disabled (so that we have a device_t attached to
835              * the handle, but we don't probe it).
836              */
837             if ((type == ACPI_TYPE_DEVICE) && (!acpi_DeviceIsPresent(child))) {
838                 device_disable(child);
839                 break;
840             }
841
842             /*
843              * Get the device's resource settings and attach them.
844              * Note that if the device has _PRS but no _CRS, we need
845              * to decide when it's appropriate to try to configure the
846              * device.  Ignore the return value here; it's OK for the
847              * device not to have any resources.
848              */
849             acpi_parse_resources(child, handle, &acpi_res_parse_set);
850
851             /* if we're debugging, probe/attach now rather than later */
852             ACPI_DEBUG_EXEC(device_probe_and_attach(child));
853             break;
854         }
855     }
856     return_ACPI_STATUS(AE_OK);
857 }
858
859 static void
860 acpi_shutdown_pre_sync(void *arg, int howto)
861 {
862
863     ACPI_ASSERTLOCK;
864     
865     /*
866      * Disable all ACPI events before soft off, otherwise the system
867      * will be turned on again on some laptops.
868      *
869      * XXX this should probably be restricted to masking some events just
870      *     before powering down, since we may still need ACPI during the
871      *     shutdown process.
872      */
873     acpi_Disable((struct acpi_softc *)arg);
874 }
875
876 static void
877 acpi_shutdown_final(void *arg, int howto)
878 {
879     ACPI_STATUS status;
880
881     ACPI_ASSERTLOCK;
882
883     if (howto & RB_POWEROFF) {
884         printf("Power system off using ACPI...\n");
885         if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(acpi_off_state))) {
886             printf("AcpiEnterSleepStatePrep failed - %s\n",
887                    AcpiFormatException(status));
888             return;
889         }
890         if (ACPI_FAILURE(status = AcpiEnterSleepState(acpi_off_state))) {
891             printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
892         } else {
893             DELAY(1000000);
894             printf("ACPI power-off failed - timeout\n");
895         }
896     } else {
897         printf("Terminate ACPI\n");
898         AcpiTerminate();
899     }
900 }
901
902 static void
903 acpi_enable_fixed_events(struct acpi_softc *sc)
904 {
905     static int  first_time = 1;
906 #define MSGFORMAT "%s button is handled as a fixed feature programming model.\n"
907
908     ACPI_ASSERTLOCK;
909
910     /* Enable and clear fixed events and install handlers. */
911     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->PwrButton == 0)) {
912         AcpiEnableEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED, 0);
913         AcpiClearEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
914         AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
915                                      acpi_eventhandler_power_button_for_sleep, sc);
916         if (first_time) {
917             device_printf(sc->acpi_dev, MSGFORMAT, "power");
918         }
919     }
920     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->SleepButton == 0)) {
921         AcpiEnableEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED, 0);
922         AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
923         AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
924                                      acpi_eventhandler_sleep_button_for_sleep, sc);
925         if (first_time) {
926             device_printf(sc->acpi_dev, MSGFORMAT, "sleep");
927         }
928     }
929
930     first_time = 0;
931 }
932
933 /*
934  * Returns true if the device is actually present and should
935  * be attached to.  This requires the present, enabled, UI-visible 
936  * and diagnostics-passed bits to be set.
937  */
938 BOOLEAN
939 acpi_DeviceIsPresent(device_t dev)
940 {
941     ACPI_HANDLE         h;
942     ACPI_DEVICE_INFO    devinfo;
943     ACPI_STATUS         error;
944
945     ACPI_ASSERTLOCK;
946     
947     if ((h = acpi_get_handle(dev)) == NULL)
948         return(FALSE);
949     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
950         return(FALSE);
951     /* if no _STA method, must be present */
952     if (!(devinfo.Valid & ACPI_VALID_STA))
953         return(TRUE);
954     /* return true for 'present' and 'functioning' */
955     if ((devinfo.CurrentStatus & 0x9) == 0x9)
956         return(TRUE);
957     return(FALSE);
958 }
959
960 /*
961  * Returns true if the battery is actually present and inserted.
962  */
963 BOOLEAN
964 acpi_BatteryIsPresent(device_t dev)
965 {
966     ACPI_HANDLE         h;
967     ACPI_DEVICE_INFO    devinfo;
968     ACPI_STATUS         error;
969
970     ACPI_ASSERTLOCK;
971     
972     if ((h = acpi_get_handle(dev)) == NULL)
973         return(FALSE);
974     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
975         return(FALSE);
976     /* if no _STA method, must be present */
977     if (!(devinfo.Valid & ACPI_VALID_STA))
978         return(TRUE);
979     /* return true for 'present' and 'functioning' */
980     if ((devinfo.CurrentStatus & 0x19) == 0x19)
981         return(TRUE);
982     return(FALSE);
983 }
984
985 /*
986  * Match a HID string against a device
987  */
988 BOOLEAN
989 acpi_MatchHid(device_t dev, char *hid) 
990 {
991     ACPI_HANDLE         h;
992     ACPI_DEVICE_INFO    devinfo;
993     ACPI_STATUS         error;
994     int                 cid;
995
996     ACPI_ASSERTLOCK;
997
998     if (hid == NULL)
999         return(FALSE);
1000     if ((h = acpi_get_handle(dev)) == NULL)
1001         return(FALSE);
1002     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
1003         return(FALSE);
1004     if ((devinfo.Valid & ACPI_VALID_HID) && !strcmp(hid, devinfo.HardwareId))
1005         return(TRUE);
1006     if (ACPI_FAILURE(error = acpi_EvaluateInteger(h, "_CID", &cid)))
1007         return(FALSE);
1008     if (cid == PNP_EISAID(hid))
1009         return(TRUE);
1010     return(FALSE);
1011 }
1012
1013 /*
1014  * Return the handle of a named object within our scope, ie. that of (parent)
1015  * or one if its parents.
1016  */
1017 ACPI_STATUS
1018 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1019 {
1020     ACPI_HANDLE         r;
1021     ACPI_STATUS         status;
1022
1023     ACPI_ASSERTLOCK;
1024
1025     /* walk back up the tree to the root */
1026     for (;;) {
1027         if (ACPI_SUCCESS(status = AcpiGetHandle(parent, path, &r))) {
1028             *result = r;
1029             return(AE_OK);
1030         }
1031         if (status != AE_NOT_FOUND)
1032             return(AE_OK);
1033         if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1034             return(AE_NOT_FOUND);
1035         parent = r;
1036     }
1037 }
1038
1039 /*
1040  * Allocate a buffer with a preset data size.
1041  */
1042 ACPI_BUFFER *
1043 acpi_AllocBuffer(int size)
1044 {
1045     ACPI_BUFFER *buf;
1046
1047     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1048         return(NULL);
1049     buf->Length = size;
1050     buf->Pointer = (void *)(buf + 1);
1051     return(buf);
1052 }
1053
1054 /*
1055  * Evaluate a path that should return an integer.
1056  */
1057 ACPI_STATUS
1058 acpi_EvaluateInteger(ACPI_HANDLE handle, char *path, int *number)
1059 {
1060     ACPI_STATUS error;
1061     ACPI_BUFFER buf;
1062     ACPI_OBJECT param;
1063
1064     ACPI_ASSERTLOCK;
1065
1066     if (handle == NULL)
1067         handle = ACPI_ROOT_OBJECT;
1068
1069     /*
1070      * Assume that what we've been pointed at is an Integer object, or
1071      * a method that will return an Integer.
1072      */
1073     buf.Pointer = &param;
1074     buf.Length = sizeof(param);
1075     if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
1076         if (param.Type == ACPI_TYPE_INTEGER) {
1077             *number = param.Integer.Value;
1078         } else {
1079             error = AE_TYPE;
1080         }
1081     }
1082
1083     /* 
1084      * In some applications, a method that's expected to return an Integer
1085      * may instead return a Buffer (probably to simplify some internal
1086      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1087      * convert it into an Integer as best we can.
1088      *
1089      * This is a hack.
1090      */
1091     if (error == AE_BUFFER_OVERFLOW) {
1092         if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1093             error = AE_NO_MEMORY;
1094         } else {
1095             if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
1096                 error = acpi_ConvertBufferToInteger(&buf, number);
1097             }
1098         }
1099         AcpiOsFree(buf.Pointer);
1100     }
1101     return(error);
1102 }
1103
1104 ACPI_STATUS
1105 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, int *number)
1106 {
1107     ACPI_OBJECT *p;
1108     int         i;
1109
1110     p = (ACPI_OBJECT *)bufp->Pointer;
1111     if (p->Type == ACPI_TYPE_INTEGER) {
1112         *number = p->Integer.Value;
1113         return(AE_OK);
1114     }
1115     if (p->Type != ACPI_TYPE_BUFFER)
1116         return(AE_TYPE);
1117     if (p->Buffer.Length > sizeof(int))
1118         return(AE_BAD_DATA);
1119     *number = 0;
1120     for (i = 0; i < p->Buffer.Length; i++)
1121         *number += (*(p->Buffer.Pointer + i) << (i * 8));
1122     return(AE_OK);
1123 }
1124
1125 /*
1126  * Iterate over the elements of an a package object, calling the supplied
1127  * function for each element.
1128  *
1129  * XXX possible enhancement might be to abort traversal on error.
1130  */
1131 ACPI_STATUS
1132 acpi_ForeachPackageObject(ACPI_OBJECT *pkg, void (* func)(ACPI_OBJECT *comp, void *arg), void *arg)
1133 {
1134     ACPI_OBJECT *comp;
1135     int         i;
1136     
1137     if ((pkg == NULL) || (pkg->Type != ACPI_TYPE_PACKAGE))
1138         return(AE_BAD_PARAMETER);
1139
1140     /* iterate over components */
1141     for (i = 0, comp = pkg->Package.Elements; i < pkg->Package.Count; i++, comp++)
1142         func(comp, arg);
1143
1144     return(AE_OK);
1145 }
1146
1147 /*
1148  * Find the (index)th resource object in a set.
1149  */
1150 ACPI_STATUS
1151 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1152 {
1153     ACPI_RESOURCE       *rp;
1154     int                 i;
1155
1156     rp = (ACPI_RESOURCE *)buf->Pointer;
1157     i = index;
1158     while (i-- > 0) {
1159         /* range check */       
1160         if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1161             return(AE_BAD_PARAMETER);
1162         /* check for terminator */
1163         if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1164             (rp->Length == 0))
1165             return(AE_NOT_FOUND);
1166         rp = ACPI_RESOURCE_NEXT(rp);
1167     }
1168     if (resp != NULL)
1169         *resp = rp;
1170     return(AE_OK);
1171 }
1172
1173 /*
1174  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1175  *
1176  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1177  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1178  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1179  * resources.
1180  */
1181 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE       512
1182
1183 ACPI_STATUS
1184 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1185 {
1186     ACPI_RESOURCE       *rp;
1187     void                *newp;
1188     
1189     /*
1190      * Initialise the buffer if necessary.
1191      */
1192     if (buf->Pointer == NULL) {
1193         buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1194         if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1195             return(AE_NO_MEMORY);
1196         rp = (ACPI_RESOURCE *)buf->Pointer;
1197         rp->Id = ACPI_RSTYPE_END_TAG;
1198         rp->Length = 0;
1199     }
1200     if (res == NULL)
1201         return(AE_OK);
1202     
1203     /*
1204      * Scan the current buffer looking for the terminator.
1205      * This will either find the terminator or hit the end
1206      * of the buffer and return an error.
1207      */
1208     rp = (ACPI_RESOURCE *)buf->Pointer;
1209     for (;;) {
1210         /* range check, don't go outside the buffer */
1211         if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1212             return(AE_BAD_PARAMETER);
1213         if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1214             (rp->Length == 0)) {
1215             break;
1216         }
1217         rp = ACPI_RESOURCE_NEXT(rp);
1218     }
1219
1220     /*
1221      * Check the size of the buffer and expand if required.
1222      *
1223      * Required size is:
1224      *  size of existing resources before terminator + 
1225      *  size of new resource and header +
1226      *  size of terminator.
1227      *
1228      * Note that this loop should really only run once, unless
1229      * for some reason we are stuffing a *really* huge resource.
1230      */
1231     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) + 
1232             res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1233             ACPI_RESOURCE_LENGTH) >= buf->Length) {
1234         if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1235             return(AE_NO_MEMORY);
1236         bcopy(buf->Pointer, newp, buf->Length);
1237         rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1238                                ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1239         AcpiOsFree(buf->Pointer);
1240         buf->Pointer = newp;
1241         buf->Length += buf->Length;
1242     }
1243     
1244     /*
1245      * Insert the new resource.
1246      */
1247     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1248     
1249     /*
1250      * And add the terminator.
1251      */
1252     rp = ACPI_RESOURCE_NEXT(rp);
1253     rp->Id = ACPI_RSTYPE_END_TAG;
1254     rp->Length = 0;
1255
1256     return(AE_OK);
1257 }
1258
1259 /*
1260  * Set interrupt model.
1261  */
1262 ACPI_STATUS
1263 acpi_SetIntrModel(int model)
1264 {
1265         ACPI_OBJECT_LIST ArgList;
1266         ACPI_OBJECT Arg;
1267
1268         Arg.Type = ACPI_TYPE_INTEGER;
1269         Arg.Integer.Value = model;
1270         ArgList.Count = 1;
1271         ArgList.Pointer = &Arg;
1272         return (AcpiEvaluateObject(ACPI_ROOT_OBJECT, "_PIC", &ArgList, NULL));
1273 }
1274
1275 #define ACPI_MINIMUM_AWAKETIME  5
1276
1277 static void
1278 acpi_sleep_enable(void *arg)
1279 {
1280     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1281 }
1282
1283 /*
1284  * Set the system sleep state
1285  *
1286  * Currently we only support S1 and S5
1287  */
1288 ACPI_STATUS
1289 acpi_SetSleepState(struct acpi_softc *sc, int state)
1290 {
1291     ACPI_STATUS status = AE_OK;
1292     UINT8       TypeA;
1293     UINT8       TypeB;
1294
1295     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1296     ACPI_ASSERTLOCK;
1297
1298     if (sc->acpi_sstate != ACPI_STATE_S0)
1299         return_ACPI_STATUS(AE_BAD_PARAMETER);   /* avoid reentry */
1300
1301     if (sc->acpi_sleep_disabled)
1302         return_ACPI_STATUS(AE_OK);
1303
1304     switch (state) {
1305     case ACPI_STATE_S0: /* XXX only for testing */
1306         if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
1307             device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1308         }
1309         break;
1310
1311     case ACPI_STATE_S1:
1312     case ACPI_STATE_S2:
1313     case ACPI_STATE_S3:
1314     case ACPI_STATE_S4:
1315         if (ACPI_FAILURE(status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB))) {
1316             device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n", AcpiFormatException(status));
1317             break;
1318         }
1319
1320         sc->acpi_sstate = state;
1321         sc->acpi_sleep_disabled = 1;
1322
1323         /*
1324          * Inform all devices that we are going to sleep.
1325          */
1326         if (DEVICE_SUSPEND(root_bus) != 0) {
1327             /*
1328              * Re-wake the system.
1329              *
1330              * XXX note that a better two-pass approach with a 'veto' pass
1331              *     followed by a "real thing" pass would be better, but the
1332              *     current bus interface does not provide for this.
1333              */
1334             DEVICE_RESUME(root_bus);
1335             return_ACPI_STATUS(AE_ERROR);
1336         }
1337
1338         if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(state))) {
1339             device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1340                           AcpiFormatException(status));
1341             break;
1342         }
1343
1344         if (sc->acpi_sleep_delay > 0) {
1345             DELAY(sc->acpi_sleep_delay * 1000000);
1346         }
1347
1348         if (state != ACPI_STATE_S1) {
1349             acpi_sleep_machdep(sc, state);
1350
1351             /* AcpiEnterSleepState() maybe incompleted, unlock here if locked. */
1352             if (AcpiGbl_AcpiMutexInfo[ACPI_MTX_HARDWARE].OwnerId != ACPI_MUTEX_NOT_ACQUIRED) {
1353                 AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1354             }
1355
1356             /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1357             if (state == ACPI_STATE_S4) {
1358                 AcpiEnable();
1359             }
1360         } else {
1361             if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
1362                 device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1363                 break;
1364             }
1365         }
1366         AcpiLeaveSleepState((UINT8)state);
1367         DEVICE_RESUME(root_bus);
1368         sc->acpi_sstate = ACPI_STATE_S0;
1369         acpi_enable_fixed_events(sc);
1370         break;
1371
1372     case ACPI_STATE_S5:
1373         /*
1374          * Shut down cleanly and power off.  This will call us back through the
1375          * shutdown handlers.
1376          */
1377         shutdown_nice(RB_POWEROFF);
1378         break;
1379
1380     default:
1381         status = AE_BAD_PARAMETER;
1382         break;
1383     }
1384
1385     if (sc->acpi_sleep_disabled)
1386         timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
1387
1388     return_ACPI_STATUS(status);
1389 }
1390
1391 /*
1392  * Enable/Disable ACPI
1393  */
1394 ACPI_STATUS
1395 acpi_Enable(struct acpi_softc *sc)
1396 {
1397     ACPI_STATUS status;
1398     u_int32_t   flags;
1399
1400     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1401     ACPI_ASSERTLOCK;
1402
1403     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
1404             ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
1405     if (!sc->acpi_enabled) {
1406         status = AcpiEnableSubsystem(flags);
1407     } else {
1408         status = AE_OK;
1409     }
1410     if (status == AE_OK)
1411         sc->acpi_enabled = 1;
1412     return_ACPI_STATUS(status);
1413 }
1414
1415 ACPI_STATUS
1416 acpi_Disable(struct acpi_softc *sc)
1417 {
1418     ACPI_STATUS status;
1419
1420     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1421     ACPI_ASSERTLOCK;
1422
1423     if (sc->acpi_enabled) {
1424         status = AcpiDisable();
1425     } else {
1426         status = AE_OK;
1427     }
1428     if (status == AE_OK)
1429         sc->acpi_enabled = 0;
1430     return_ACPI_STATUS(status);
1431 }
1432
1433 /*
1434  * ACPI Event Handlers
1435  */
1436
1437 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1438
1439 static void
1440 acpi_system_eventhandler_sleep(void *arg, int state)
1441 {
1442     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1443
1444     ACPI_LOCK;
1445     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
1446         acpi_SetSleepState((struct acpi_softc *)arg, state);
1447     ACPI_UNLOCK;
1448     return_VOID;
1449 }
1450
1451 static void
1452 acpi_system_eventhandler_wakeup(void *arg, int state)
1453 {
1454     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1455
1456     /* Well, what to do? :-) */
1457
1458     ACPI_LOCK;
1459     ACPI_UNLOCK;
1460
1461     return_VOID;
1462 }
1463
1464 /* 
1465  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1466  */
1467 UINT32
1468 acpi_eventhandler_power_button_for_sleep(void *context)
1469 {
1470     struct acpi_softc   *sc = (struct acpi_softc *)context;
1471
1472     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1473
1474     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1475
1476     return_VALUE(ACPI_INTERRUPT_HANDLED);
1477 }
1478
1479 UINT32
1480 acpi_eventhandler_power_button_for_wakeup(void *context)
1481 {
1482     struct acpi_softc   *sc = (struct acpi_softc *)context;
1483
1484     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1485
1486     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1487
1488     return_VALUE(ACPI_INTERRUPT_HANDLED);
1489 }
1490
1491 UINT32
1492 acpi_eventhandler_sleep_button_for_sleep(void *context)
1493 {
1494     struct acpi_softc   *sc = (struct acpi_softc *)context;
1495
1496     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1497
1498     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1499
1500     return_VALUE(ACPI_INTERRUPT_HANDLED);
1501 }
1502
1503 UINT32
1504 acpi_eventhandler_sleep_button_for_wakeup(void *context)
1505 {
1506     struct acpi_softc   *sc = (struct acpi_softc *)context;
1507
1508     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1509
1510     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1511
1512     return_VALUE(ACPI_INTERRUPT_HANDLED);
1513 }
1514
1515 /*
1516  * XXX This is kinda ugly, and should not be here.
1517  */
1518 struct acpi_staticbuf {
1519     ACPI_BUFFER buffer;
1520     char        data[512];
1521 };
1522
1523 char *
1524 acpi_name(ACPI_HANDLE handle)
1525 {
1526     static struct acpi_staticbuf        buf;
1527
1528     ACPI_ASSERTLOCK;
1529
1530     buf.buffer.Length = 512;
1531     buf.buffer.Pointer = &buf.data[0];
1532
1533     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
1534         return(buf.buffer.Pointer);
1535     return("(unknown path)");
1536 }
1537
1538 /*
1539  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1540  * parts of the namespace.
1541  */
1542 int
1543 acpi_avoid(ACPI_HANDLE handle)
1544 {
1545     char        *cp, *env, *np;
1546     int         len;
1547
1548     np = acpi_name(handle);
1549     if (*np == '\\')
1550         np++;
1551     if ((env = getenv("debug.acpi.avoid")) == NULL)
1552         return(0);
1553
1554     /* scan the avoid list checking for a match */
1555     cp = env;
1556     for (;;) {
1557         while ((*cp != 0) && isspace(*cp))
1558             cp++;
1559         if (*cp == 0)
1560             break;
1561         len = 0;
1562         while ((cp[len] != 0) && !isspace(cp[len]))
1563             len++;
1564         if (!strncmp(cp, np, len)) {
1565             freeenv(env);
1566             return(1);
1567         }
1568         cp += len;
1569     }
1570     freeenv(env);
1571     return(0);
1572 }
1573
1574 /*
1575  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1576  */
1577 int
1578 acpi_disabled(char *subsys)
1579 {
1580     char        *cp, *env;
1581     int         len;
1582
1583     if ((env = getenv("debug.acpi.disable")) == NULL)
1584         return(0);
1585     if (!strcmp(env, "all")) {
1586         freeenv(env);
1587         return(1);
1588     }
1589
1590     /* scan the disable list checking for a match */
1591     cp = env;
1592     for (;;) {
1593         while ((*cp != 0) && isspace(*cp))
1594             cp++;
1595         if (*cp == 0)
1596             break;
1597         len = 0;
1598         while ((cp[len] != 0) && !isspace(cp[len]))
1599             len++;
1600         if (!strncmp(cp, subsys, len)) {
1601             freeenv(env);
1602             return(1);
1603         }
1604         cp += len;
1605     }
1606     freeenv(env);
1607     return(0);
1608 }
1609
1610 /*
1611  * Device wake capability enable/disable.
1612  */
1613 void
1614 acpi_device_enable_wake_capability(ACPI_HANDLE h, int enable)
1615 {
1616     ACPI_OBJECT_LIST            ArgList;
1617     ACPI_OBJECT                 Arg;
1618
1619     /*
1620      * TBD: All Power Resources referenced by elements 2 through N
1621      *      of the _PRW object are put into the ON state.
1622      */
1623
1624     /*
1625      * enable/disable device wake function.
1626      */
1627
1628     ArgList.Count = 1;
1629     ArgList.Pointer = &Arg;
1630
1631     Arg.Type = ACPI_TYPE_INTEGER;
1632     Arg.Integer.Value = enable;
1633
1634     (void)AcpiEvaluateObject(h, "_PSW", &ArgList, NULL);
1635 }
1636
1637 void
1638 acpi_device_enable_wake_event(ACPI_HANDLE h)
1639 {
1640     struct acpi_softc           *sc;
1641     ACPI_STATUS                 status;
1642     ACPI_BUFFER                 prw_buffer;
1643     ACPI_OBJECT                 *res;
1644
1645     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1646
1647     if ((sc = devclass_get_softc(acpi_devclass, 0)) == NULL) {
1648         return;
1649     }
1650
1651     /*
1652      * _PRW object is only required for devices that have the ability
1653      * to wake the system from a system sleeping state.
1654      */
1655     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
1656     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
1657     if (ACPI_FAILURE(status)) {
1658         return;
1659     }
1660
1661     res = (ACPI_OBJECT *)prw_buffer.Pointer;
1662     if (res == NULL) {
1663         return;
1664     }
1665
1666     if ((res->Type != ACPI_TYPE_PACKAGE) || (res->Package.Count < 2)) {
1667         goto out;
1668     }
1669
1670     /*
1671      * The element 1 of the _PRW object:
1672      * The lowest power system sleeping state that can be entered
1673      * while still providing wake functionality.
1674      * The sleeping state being entered must be greater or equal to
1675      * the power state declared in element 1 of the _PRW object.
1676      */
1677     if (res->Package.Elements[1].Type != ACPI_TYPE_INTEGER) {
1678         goto out;
1679     }
1680
1681     if (sc->acpi_sstate > res->Package.Elements[1].Integer.Value) {
1682         goto out;
1683     }
1684
1685     /*
1686      * The element 0 of the _PRW object:
1687      */
1688     switch(res->Package.Elements[0].Type) {
1689     case ACPI_TYPE_INTEGER:
1690         /* 
1691          * If the data type of this package element is numeric, then this
1692          * _PRW package element is the bit index in the GPEx_EN, in the
1693          * GPE blocks described in the FADT, of the enable bit that is
1694          * enabled for the wake event.
1695          */
1696
1697         status = AcpiEnableEvent(res->Package.Elements[0].Integer.Value,
1698                                  ACPI_EVENT_GPE, ACPI_EVENT_WAKE_ENABLE);
1699         if (ACPI_FAILURE(status))
1700             printf("%s: EnableEvent Failed\n", __func__);
1701         break;
1702
1703     case ACPI_TYPE_PACKAGE:
1704         /* XXX TBD */
1705
1706         /*
1707          * If the data type of this package element is a package, then this
1708          * _PRW package element is itself a package containing two
1709          * elements. The first is an object reference to the GPE Block
1710          * device that contains the GPE that will be triggered by the wake
1711          * event. The second element is numeric and it contains the bit
1712          * index in the GPEx_EN, in the GPE Block referenced by the
1713          * first element in the package, of the enable bit that is enabled for
1714          * the wake event.
1715          * For example, if this field is a package then it is of the form:
1716          * Package() {\_SB.PCI0.ISA.GPE, 2}
1717          */
1718
1719         break;
1720
1721     default:
1722         break;
1723     }
1724
1725 out:
1726     if (prw_buffer.Pointer != NULL)
1727         AcpiOsFree(prw_buffer.Pointer);
1728     return;
1729 }
1730
1731 /*
1732  * Control interface.
1733  *
1734  * We multiplex ioctls for all participating ACPI devices here.  Individual 
1735  * drivers wanting to be accessible via /dev/acpi should use the register/deregister
1736  * interface to make their handlers visible.
1737  */
1738 struct acpi_ioctl_hook
1739 {
1740     TAILQ_ENTRY(acpi_ioctl_hook)        link;
1741     u_long                              cmd;
1742     int                                 (* fn)(u_long cmd, caddr_t addr, void *arg);
1743     void                                *arg;
1744 };
1745
1746 static TAILQ_HEAD(,acpi_ioctl_hook)     acpi_ioctl_hooks;
1747 static int                              acpi_ioctl_hooks_initted;
1748
1749 /*
1750  * Register an ioctl handler.
1751  */
1752 int
1753 acpi_register_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg), void *arg)
1754 {
1755     struct acpi_ioctl_hook      *hp;
1756
1757     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
1758         return(ENOMEM);
1759     hp->cmd = cmd;
1760     hp->fn = fn;
1761     hp->arg = arg;
1762     if (acpi_ioctl_hooks_initted == 0) {
1763         TAILQ_INIT(&acpi_ioctl_hooks);
1764         acpi_ioctl_hooks_initted = 1;
1765     }
1766     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
1767     return(0);
1768 }
1769
1770 /*
1771  * Deregister an ioctl handler.
1772  */
1773 void    
1774 acpi_deregister_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg))
1775 {
1776     struct acpi_ioctl_hook      *hp;
1777
1778     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
1779         if ((hp->cmd == cmd) && (hp->fn == fn))
1780             break;
1781
1782     if (hp != NULL) {
1783         TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
1784         free(hp, M_ACPIDEV);
1785     }
1786 }
1787
1788 static int
1789 acpiopen(dev_t dev, int flag, int fmt, d_thread_t *td)
1790 {
1791     return(0);
1792 }
1793
1794 static int
1795 acpiclose(dev_t dev, int flag, int fmt, d_thread_t *td)
1796 {
1797     return(0);
1798 }
1799
1800 static int
1801 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
1802 {
1803     struct acpi_softc           *sc;
1804     struct acpi_ioctl_hook      *hp;
1805     int                         error, xerror, state;
1806
1807     ACPI_LOCK;
1808
1809     error = state = 0;
1810     sc = dev->si_drv1;
1811
1812     /*
1813      * Scan the list of registered ioctls, looking for handlers.
1814      */
1815     if (acpi_ioctl_hooks_initted) {
1816         TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
1817             if (hp->cmd == cmd) {
1818                 xerror = hp->fn(cmd, addr, hp->arg);
1819                 if (xerror != 0)
1820                     error = xerror;
1821                 goto out;
1822             }
1823         }
1824     }
1825
1826     /*
1827      * Core system ioctls.
1828      */
1829     switch (cmd) {
1830     case ACPIIO_ENABLE:
1831         if (ACPI_FAILURE(acpi_Enable(sc)))
1832             error = ENXIO;
1833         break;
1834
1835     case ACPIIO_DISABLE:
1836         if (ACPI_FAILURE(acpi_Disable(sc)))
1837             error = ENXIO;
1838         break;
1839
1840     case ACPIIO_SETSLPSTATE:
1841         if (!sc->acpi_enabled) {
1842             error = ENXIO;
1843             break;
1844         }
1845         state = *(int *)addr;
1846         if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
1847             acpi_SetSleepState(sc, state);
1848         } else {
1849             error = EINVAL;
1850         }
1851         break;
1852
1853     default:
1854         if (error == 0)
1855             error = EINVAL;
1856         break;
1857     }
1858
1859 out:
1860     ACPI_UNLOCK;
1861     return(error);
1862 }
1863
1864 static int
1865 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
1866 {
1867     char sleep_state[10];
1868     int error;
1869     u_int new_state, old_state;
1870
1871     old_state = *(u_int *)oidp->oid_arg1;
1872     if (old_state > ACPI_S_STATES_MAX+1) {
1873         strcpy(sleep_state, "unknown");
1874     } else {
1875         bzero(sleep_state, sizeof(sleep_state));
1876         strncpy(sleep_state, sleep_state_names[old_state],
1877                 sizeof(sleep_state_names[old_state]));
1878     }
1879     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
1880     if (error == 0 && req->newptr != NULL) {
1881         for (new_state = ACPI_STATE_S0; new_state <= ACPI_S_STATES_MAX+1; new_state++) {
1882             if (strncmp(sleep_state, sleep_state_names[new_state],
1883                         sizeof(sleep_state)) == 0)
1884                 break;
1885         }
1886         if (new_state <= ACPI_S_STATES_MAX+1) {
1887             if (new_state != old_state) {
1888                 *(u_int *)oidp->oid_arg1 = new_state;
1889             }
1890         } else {
1891             error = EINVAL;
1892         }
1893     }
1894     return(error);
1895 }
1896
1897 #ifdef ACPI_DEBUG
1898 /*
1899  * Support for parsing debug options from the kernel environment.
1900  *
1901  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
1902  * by specifying the names of the bits in the debug.acpi.layer and
1903  * debug.acpi.level environment variables.  Bits may be unset by 
1904  * prefixing the bit name with !.
1905  */
1906 struct debugtag
1907 {
1908     char        *name;
1909     UINT32      value;
1910 };
1911
1912 static struct debugtag  dbg_layer[] = {
1913     {"ACPI_UTILITIES",          ACPI_UTILITIES},
1914     {"ACPI_HARDWARE",           ACPI_HARDWARE},
1915     {"ACPI_EVENTS",             ACPI_EVENTS},
1916     {"ACPI_TABLES",             ACPI_TABLES},
1917     {"ACPI_NAMESPACE",          ACPI_NAMESPACE},
1918     {"ACPI_PARSER",             ACPI_PARSER},
1919     {"ACPI_DISPATCHER",         ACPI_DISPATCHER},
1920     {"ACPI_EXECUTER",           ACPI_EXECUTER},
1921     {"ACPI_RESOURCES",          ACPI_RESOURCES},
1922     {"ACPI_CA_DEBUGGER",        ACPI_CA_DEBUGGER},
1923     {"ACPI_OS_SERVICES",        ACPI_OS_SERVICES},
1924     {"ACPI_CA_DISASSEMBLER",    ACPI_CA_DISASSEMBLER},
1925
1926     {"ACPI_BUS",                ACPI_BUS},
1927     {"ACPI_SYSTEM",             ACPI_SYSTEM},
1928     {"ACPI_POWER",              ACPI_POWER},
1929     {"ACPI_EC",                 ACPI_EC},
1930     {"ACPI_AC_ADAPTER",         ACPI_AC_ADAPTER},
1931     {"ACPI_BATTERY",            ACPI_BATTERY},
1932     {"ACPI_BUTTON",             ACPI_BUTTON},
1933     {"ACPI_PROCESSOR",          ACPI_PROCESSOR},
1934     {"ACPI_THERMAL",            ACPI_THERMAL},
1935     {"ACPI_FAN",                ACPI_FAN},
1936
1937     {"ACPI_ALL_DRIVERS",        ACPI_ALL_DRIVERS},
1938     {"ACPI_ALL_COMPONENTS",     ACPI_ALL_COMPONENTS},
1939     {NULL, 0}
1940 };
1941
1942 static struct debugtag dbg_level[] = {
1943     {"ACPI_LV_OK",              ACPI_LV_OK},
1944     {"ACPI_LV_INFO",            ACPI_LV_INFO},
1945     {"ACPI_LV_WARN",            ACPI_LV_WARN},
1946     {"ACPI_LV_ERROR",           ACPI_LV_ERROR},
1947     {"ACPI_LV_FATAL",           ACPI_LV_FATAL},
1948     {"ACPI_LV_DEBUG_OBJECT",    ACPI_LV_DEBUG_OBJECT},
1949     {"ACPI_LV_ALL_EXCEPTIONS",  ACPI_LV_ALL_EXCEPTIONS},
1950
1951     /* Trace verbosity level 1 [Standard Trace Level] */
1952     {"ACPI_LV_PARSE",           ACPI_LV_PARSE},
1953     {"ACPI_LV_LOAD",            ACPI_LV_LOAD},
1954     {"ACPI_LV_DISPATCH",        ACPI_LV_DISPATCH},
1955     {"ACPI_LV_EXEC",            ACPI_LV_EXEC},
1956     {"ACPI_LV_NAMES",           ACPI_LV_NAMES},
1957     {"ACPI_LV_OPREGION",        ACPI_LV_OPREGION},
1958     {"ACPI_LV_BFIELD",          ACPI_LV_BFIELD},
1959     {"ACPI_LV_TABLES",          ACPI_LV_TABLES},
1960     {"ACPI_LV_VALUES",          ACPI_LV_VALUES},
1961     {"ACPI_LV_OBJECTS",         ACPI_LV_OBJECTS},
1962     {"ACPI_LV_RESOURCES",       ACPI_LV_RESOURCES},
1963     {"ACPI_LV_USER_REQUESTS",   ACPI_LV_USER_REQUESTS},
1964     {"ACPI_LV_PACKAGE",         ACPI_LV_PACKAGE},
1965     {"ACPI_LV_INIT",            ACPI_LV_INIT},
1966     {"ACPI_LV_VERBOSITY1",      ACPI_LV_VERBOSITY1},
1967
1968     /* Trace verbosity level 2 [Function tracing and memory allocation] */
1969     {"ACPI_LV_ALLOCATIONS",     ACPI_LV_ALLOCATIONS},
1970     {"ACPI_LV_FUNCTIONS",       ACPI_LV_FUNCTIONS},
1971     {"ACPI_LV_OPTIMIZATIONS",   ACPI_LV_OPTIMIZATIONS},
1972     {"ACPI_LV_VERBOSITY2",      ACPI_LV_VERBOSITY2},
1973     {"ACPI_LV_ALL",             ACPI_LV_ALL},
1974
1975     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
1976     {"ACPI_LV_MUTEX",           ACPI_LV_MUTEX},
1977     {"ACPI_LV_THREADS",         ACPI_LV_THREADS},
1978     {"ACPI_LV_IO",              ACPI_LV_IO},
1979     {"ACPI_LV_INTERRUPTS",      ACPI_LV_INTERRUPTS},
1980     {"ACPI_LV_VERBOSITY3",      ACPI_LV_VERBOSITY3},
1981
1982     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
1983     {"ACPI_LV_AML_DISASSEMBLE", ACPI_LV_AML_DISASSEMBLE},
1984     {"ACPI_LV_VERBOSE_INFO",    ACPI_LV_VERBOSE_INFO},
1985     {"ACPI_LV_FULL_TABLES",     ACPI_LV_FULL_TABLES},
1986     {"ACPI_LV_EVENTS",          ACPI_LV_EVENTS},
1987     {"ACPI_LV_VERBOSE",         ACPI_LV_VERBOSE},
1988     {NULL, 0}
1989 };    
1990
1991 static void
1992 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
1993 {
1994     char        *ep;
1995     int         i, l;
1996     int         set;
1997
1998     while (*cp) {
1999         if (isspace(*cp)) {
2000             cp++;
2001             continue;
2002         }
2003         ep = cp;
2004         while (*ep && !isspace(*ep))
2005             ep++;
2006         if (*cp == '!') {
2007             set = 0;
2008             cp++;
2009             if (cp == ep)
2010                 continue;
2011         } else {
2012             set = 1;
2013         }
2014         l = ep - cp;
2015         for (i = 0; tag[i].name != NULL; i++) {
2016             if (!strncmp(cp, tag[i].name, l)) {
2017                 if (set) {
2018                     *flag |= tag[i].value;
2019                 } else {
2020                     *flag &= ~tag[i].value;
2021                 }
2022                 printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
2023             }
2024         }
2025         cp = ep;
2026     }
2027 }
2028
2029 static void
2030 acpi_set_debugging(void *junk)
2031 {
2032     char        *cp;
2033
2034     AcpiDbgLayer = 0;
2035     AcpiDbgLevel = 0;
2036     if ((cp = getenv("debug.acpi.layer")) != NULL) {
2037         acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
2038         freeenv(cp);
2039     }
2040     if ((cp = getenv("debug.acpi.level")) != NULL) {
2041         acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
2042         freeenv(cp);
2043     }
2044
2045     printf("ACPI debug layer 0x%x  debug level 0x%x\n", AcpiDbgLayer, AcpiDbgLevel);
2046 }
2047 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging, NULL);
2048 #endif
2049
2050 static int
2051 acpi_pm_func(u_long cmd, void *arg, ...)
2052 {
2053         int     state, acpi_state;
2054         int     error;
2055         struct  acpi_softc *sc;
2056         va_list ap;
2057
2058         error = 0;
2059         switch (cmd) {
2060         case POWER_CMD_SUSPEND:
2061                 sc = (struct acpi_softc *)arg;
2062                 if (sc == NULL) {
2063                         error = EINVAL;
2064                         goto out;
2065                 }
2066
2067                 va_start(ap, arg);
2068                 state = va_arg(ap, int);
2069                 va_end(ap);     
2070
2071                 switch (state) {
2072                 case POWER_SLEEP_STATE_STANDBY:
2073                         acpi_state = sc->acpi_standby_sx;
2074                         break;
2075                 case POWER_SLEEP_STATE_SUSPEND:
2076                         acpi_state = sc->acpi_suspend_sx;
2077                         break;
2078                 case POWER_SLEEP_STATE_HIBERNATE:
2079                         acpi_state = ACPI_STATE_S4;
2080                         break;
2081                 default:
2082                         error = EINVAL;
2083                         goto out;
2084                 }
2085
2086                 acpi_SetSleepState(sc, acpi_state);
2087                 break;
2088
2089         default:
2090                 error = EINVAL;
2091                 goto out;
2092         }
2093
2094 out:
2095         return (error);
2096 }
2097
2098 static void
2099 acpi_pm_register(void *arg)
2100 {
2101         int     error;
2102
2103     if (!resource_int_value("acpi", 0, "disabled", &error) &&
2104        (error != 0))
2105                 return;
2106
2107         power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2108 }
2109
2110 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
2111