]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/acpica/acpi.c
This commit was generated by cvs2svn to compensate for changes in r103449,
[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         panic("bad ivar read request (%d)", index);
590         return(ENOENT);
591     }
592     return(0);
593 }
594
595 static int
596 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
597 {
598     struct acpi_device  *ad;
599
600     if ((ad = device_get_ivars(child)) == NULL) {
601         printf("device has no ivars\n");
602         return(ENOENT);
603     }
604
605     switch(index) {
606         /* ACPI ivars */
607     case ACPI_IVAR_HANDLE:
608         ad->ad_handle = (ACPI_HANDLE)value;
609         break;
610     case ACPI_IVAR_MAGIC:
611         ad->ad_magic = (int )value;
612         break;
613     case ACPI_IVAR_PRIVATE:
614         ad->ad_private = (void *)value;
615         break;
616
617     default:
618         panic("bad ivar write request (%d)", index);
619         return(ENOENT);
620     }
621     return(0);
622 }
623
624 /*
625  * Handle child resource allocation/removal
626  */
627 static int
628 acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start, u_long count)
629 {
630     struct acpi_device          *ad = device_get_ivars(child);
631     struct resource_list        *rl = &ad->ad_rl;
632
633     resource_list_add(rl, type, rid, start, start + count -1, count);
634
635     return(0);
636 }
637
638 static int
639 acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp, u_long *countp)
640 {
641     struct acpi_device          *ad = device_get_ivars(child);
642     struct resource_list        *rl = &ad->ad_rl;
643     struct resource_list_entry  *rle;
644
645     rle = resource_list_find(rl, type, rid);
646     if (!rle)
647         return(ENOENT);
648         
649     if (startp)
650         *startp = rle->start;
651     if (countp)
652         *countp = rle->count;
653
654     return(0);
655 }
656
657 static struct resource *
658 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
659                     u_long start, u_long end, u_long count, u_int flags)
660 {
661     struct acpi_device *ad = device_get_ivars(child);
662     struct resource_list *rl = &ad->ad_rl;
663
664     return(resource_list_alloc(rl, bus, child, type, rid, start, end, count, flags));
665 }
666
667 static int
668 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
669 {
670     struct acpi_device *ad = device_get_ivars(child);
671     struct resource_list *rl = &ad->ad_rl;
672
673     return(resource_list_release(rl, bus, child, type, rid, r));
674 }
675
676 /*
677  * Handle ISA-like devices probing for a PnP ID to match.
678  */
679 #define PNP_EISAID(s)                           \
680         ((((s[0] - '@') & 0x1f) << 2)           \
681          | (((s[1] - '@') & 0x18) >> 3)         \
682          | (((s[1] - '@') & 0x07) << 13)        \
683          | (((s[2] - '@') & 0x1f) << 8)         \
684          | (PNP_HEXTONUM(s[4]) << 16)           \
685          | (PNP_HEXTONUM(s[3]) << 20)           \
686          | (PNP_HEXTONUM(s[6]) << 24)           \
687          | (PNP_HEXTONUM(s[5]) << 28))
688
689 static u_int32_t
690 acpi_isa_get_logicalid(device_t dev)
691 {
692     ACPI_HANDLE         h;
693     ACPI_DEVICE_INFO    devinfo;
694     ACPI_STATUS         error;
695     u_int32_t           pnpid;
696
697     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
698
699     pnpid = 0;
700     ACPI_LOCK;
701     
702     /* fetch and validate the HID */
703     if ((h = acpi_get_handle(dev)) == NULL)
704         goto out;
705     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
706         goto out;
707     if (!(devinfo.Valid & ACPI_VALID_HID))
708         goto out;
709
710     pnpid = PNP_EISAID(devinfo.HardwareId);
711 out:
712     ACPI_UNLOCK;
713     return_VALUE(pnpid);
714 }
715
716 static int
717 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
718 {
719     int                 result;
720     u_int32_t           pnpid;
721
722     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
723
724     /*
725      * ISA-style drivers attached to ACPI may persist and
726      * probe manually if we return ENOENT.  We never want
727      * that to happen, so don't ever return it.
728      */
729     result = ENXIO;
730
731     /* scan the supplied IDs for a match */
732     pnpid = acpi_isa_get_logicalid(child);
733     while (ids && ids->ip_id) {
734         if (pnpid == ids->ip_id) {
735             result = 0;
736             goto out;
737         }
738         ids++;
739     }
740  out:
741     return_VALUE(result);
742 }
743
744 /*
745  * Scan relevant portions of the ACPI namespace and attach child devices.
746  *
747  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and \_SB_ scopes, 
748  * and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
749  */
750 static void
751 acpi_probe_children(device_t bus)
752 {
753     ACPI_HANDLE         parent;
754     static char         *scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
755     int                 i;
756
757     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
758     ACPI_ASSERTLOCK;
759
760     /*
761      * Create any static children by calling device identify methods.
762      */
763     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
764     bus_generic_probe(bus);
765
766     /*
767      * Scan the namespace and insert placeholders for all the devices that
768      * we find.
769      *
770      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
771      * we want to create nodes for all devices, not just those that are currently
772      * present. (This assumes that we don't want to create/remove devices as they
773      * appear, which might be smarter.)
774      */
775     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
776     for (i = 0; scopes[i] != NULL; i++)
777         if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent)))
778             AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child, bus, NULL);
779
780     /*
781      * Scan all of the child devices we have created and let them probe/attach.
782      */
783     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
784     bus_generic_attach(bus);
785
786     /*
787      * Some of these children may have attached others as part of their attach
788      * process (eg. the root PCI bus driver), so rescan.
789      */
790     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
791     bus_generic_attach(bus);
792
793     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
794     return_VOID;
795 }
796
797 /*
798  * Evaluate a child device and determine whether we might attach a device to
799  * it.
800  */
801 static ACPI_STATUS
802 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
803 {
804     ACPI_OBJECT_TYPE    type;
805     device_t            child, bus = (device_t)context;
806
807     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
808
809     /*
810      * Skip this device if we think we'll have trouble with it.
811      */
812     if (acpi_avoid(handle))
813         return_ACPI_STATUS(AE_OK);
814
815     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
816         switch(type) {
817         case ACPI_TYPE_DEVICE:
818         case ACPI_TYPE_PROCESSOR:
819         case ACPI_TYPE_THERMAL:
820         case ACPI_TYPE_POWER:
821             if (acpi_disabled("children"))
822                 break;
823             /* 
824              * Create a placeholder device for this node.  Sort the placeholder
825              * so that the probe/attach passes will run breadth-first.
826              */
827             ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", acpi_name(handle)));
828             child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
829             if (child == NULL)
830                 break;
831             acpi_set_handle(child, handle);
832
833             /*
834              * Check that the device is present.  If it's not present,
835              * leave it disabled (so that we have a device_t attached to
836              * the handle, but we don't probe it).
837              */
838             if ((type == ACPI_TYPE_DEVICE) && (!acpi_DeviceIsPresent(child))) {
839                 device_disable(child);
840                 break;
841             }
842
843             /*
844              * Get the device's resource settings and attach them.
845              * Note that if the device has _PRS but no _CRS, we need
846              * to decide when it's appropriate to try to configure the
847              * device.  Ignore the return value here; it's OK for the
848              * device not to have any resources.
849              */
850             acpi_parse_resources(child, handle, &acpi_res_parse_set);
851
852             /* if we're debugging, probe/attach now rather than later */
853             ACPI_DEBUG_EXEC(device_probe_and_attach(child));
854             break;
855         }
856     }
857     return_ACPI_STATUS(AE_OK);
858 }
859
860 static void
861 acpi_shutdown_pre_sync(void *arg, int howto)
862 {
863
864     ACPI_ASSERTLOCK;
865     
866     /*
867      * Disable all ACPI events before soft off, otherwise the system
868      * will be turned on again on some laptops.
869      *
870      * XXX this should probably be restricted to masking some events just
871      *     before powering down, since we may still need ACPI during the
872      *     shutdown process.
873      */
874     acpi_Disable((struct acpi_softc *)arg);
875 }
876
877 static void
878 acpi_shutdown_final(void *arg, int howto)
879 {
880     ACPI_STATUS status;
881
882     ACPI_ASSERTLOCK;
883
884     if (howto & RB_POWEROFF) {
885         printf("Power system off using ACPI...\n");
886         if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(acpi_off_state))) {
887             printf("AcpiEnterSleepStatePrep failed - %s\n",
888                    AcpiFormatException(status));
889             return;
890         }
891         if (ACPI_FAILURE(status = AcpiEnterSleepState(acpi_off_state))) {
892             printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
893         } else {
894             DELAY(1000000);
895             printf("ACPI power-off failed - timeout\n");
896         }
897     } else {
898         printf("Terminate ACPI\n");
899         AcpiTerminate();
900     }
901 }
902
903 static void
904 acpi_enable_fixed_events(struct acpi_softc *sc)
905 {
906     static int  first_time = 1;
907 #define MSGFORMAT "%s button is handled as a fixed feature programming model.\n"
908
909     ACPI_ASSERTLOCK;
910
911     /* Enable and clear fixed events and install handlers. */
912     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->PwrButton == 0)) {
913         AcpiEnableEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED, 0);
914         AcpiClearEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
915         AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
916                                      acpi_eventhandler_power_button_for_sleep, sc);
917         if (first_time) {
918             device_printf(sc->acpi_dev, MSGFORMAT, "power");
919         }
920     }
921     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->SleepButton == 0)) {
922         AcpiEnableEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED, 0);
923         AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
924         AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
925                                      acpi_eventhandler_sleep_button_for_sleep, sc);
926         if (first_time) {
927             device_printf(sc->acpi_dev, MSGFORMAT, "sleep");
928         }
929     }
930
931     first_time = 0;
932 }
933
934 /*
935  * Returns true if the device is actually present and should
936  * be attached to.  This requires the present, enabled, UI-visible 
937  * and diagnostics-passed bits to be set.
938  */
939 BOOLEAN
940 acpi_DeviceIsPresent(device_t dev)
941 {
942     ACPI_HANDLE         h;
943     ACPI_DEVICE_INFO    devinfo;
944     ACPI_STATUS         error;
945
946     ACPI_ASSERTLOCK;
947     
948     if ((h = acpi_get_handle(dev)) == NULL)
949         return(FALSE);
950     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
951         return(FALSE);
952     /* if no _STA method, must be present */
953     if (!(devinfo.Valid & ACPI_VALID_STA))
954         return(TRUE);
955     /* return true for 'present' and 'functioning' */
956     if ((devinfo.CurrentStatus & 0x9) == 0x9)
957         return(TRUE);
958     return(FALSE);
959 }
960
961 /*
962  * Returns true if the battery is actually present and inserted.
963  */
964 BOOLEAN
965 acpi_BatteryIsPresent(device_t dev)
966 {
967     ACPI_HANDLE         h;
968     ACPI_DEVICE_INFO    devinfo;
969     ACPI_STATUS         error;
970
971     ACPI_ASSERTLOCK;
972     
973     if ((h = acpi_get_handle(dev)) == NULL)
974         return(FALSE);
975     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
976         return(FALSE);
977     /* if no _STA method, must be present */
978     if (!(devinfo.Valid & ACPI_VALID_STA))
979         return(TRUE);
980     /* return true for 'present' and 'functioning' */
981     if ((devinfo.CurrentStatus & 0x19) == 0x19)
982         return(TRUE);
983     return(FALSE);
984 }
985
986 /*
987  * Match a HID string against a device
988  */
989 BOOLEAN
990 acpi_MatchHid(device_t dev, char *hid) 
991 {
992     ACPI_HANDLE         h;
993     ACPI_DEVICE_INFO    devinfo;
994     ACPI_STATUS         error;
995     int                 cid;
996
997     ACPI_ASSERTLOCK;
998
999     if (hid == NULL)
1000         return(FALSE);
1001     if ((h = acpi_get_handle(dev)) == NULL)
1002         return(FALSE);
1003     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
1004         return(FALSE);
1005     if ((devinfo.Valid & ACPI_VALID_HID) && !strcmp(hid, devinfo.HardwareId))
1006         return(TRUE);
1007     if (ACPI_FAILURE(error = acpi_EvaluateInteger(h, "_CID", &cid)))
1008         return(FALSE);
1009     if (cid == PNP_EISAID(hid))
1010         return(TRUE);
1011     return(FALSE);
1012 }
1013
1014 /*
1015  * Return the handle of a named object within our scope, ie. that of (parent)
1016  * or one if its parents.
1017  */
1018 ACPI_STATUS
1019 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1020 {
1021     ACPI_HANDLE         r;
1022     ACPI_STATUS         status;
1023
1024     ACPI_ASSERTLOCK;
1025
1026     /* walk back up the tree to the root */
1027     for (;;) {
1028         if (ACPI_SUCCESS(status = AcpiGetHandle(parent, path, &r))) {
1029             *result = r;
1030             return(AE_OK);
1031         }
1032         if (status != AE_NOT_FOUND)
1033             return(AE_OK);
1034         if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1035             return(AE_NOT_FOUND);
1036         parent = r;
1037     }
1038 }
1039
1040 /*
1041  * Allocate a buffer with a preset data size.
1042  */
1043 ACPI_BUFFER *
1044 acpi_AllocBuffer(int size)
1045 {
1046     ACPI_BUFFER *buf;
1047
1048     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1049         return(NULL);
1050     buf->Length = size;
1051     buf->Pointer = (void *)(buf + 1);
1052     return(buf);
1053 }
1054
1055 /*
1056  * Evaluate a path that should return an integer.
1057  */
1058 ACPI_STATUS
1059 acpi_EvaluateInteger(ACPI_HANDLE handle, char *path, int *number)
1060 {
1061     ACPI_STATUS error;
1062     ACPI_BUFFER buf;
1063     ACPI_OBJECT param;
1064
1065     ACPI_ASSERTLOCK;
1066
1067     if (handle == NULL)
1068         handle = ACPI_ROOT_OBJECT;
1069
1070     /*
1071      * Assume that what we've been pointed at is an Integer object, or
1072      * a method that will return an Integer.
1073      */
1074     buf.Pointer = &param;
1075     buf.Length = sizeof(param);
1076     if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
1077         if (param.Type == ACPI_TYPE_INTEGER) {
1078             *number = param.Integer.Value;
1079         } else {
1080             error = AE_TYPE;
1081         }
1082     }
1083
1084     /* 
1085      * In some applications, a method that's expected to return an Integer
1086      * may instead return a Buffer (probably to simplify some internal
1087      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1088      * convert it into an Integer as best we can.
1089      *
1090      * This is a hack.
1091      */
1092     if (error == AE_BUFFER_OVERFLOW) {
1093         if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1094             error = AE_NO_MEMORY;
1095         } else {
1096             if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
1097                 error = acpi_ConvertBufferToInteger(&buf, number);
1098             }
1099         }
1100         AcpiOsFree(buf.Pointer);
1101     }
1102     return(error);
1103 }
1104
1105 ACPI_STATUS
1106 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, int *number)
1107 {
1108     ACPI_OBJECT *p;
1109     int         i;
1110
1111     p = (ACPI_OBJECT *)bufp->Pointer;
1112     if (p->Type == ACPI_TYPE_INTEGER) {
1113         *number = p->Integer.Value;
1114         return(AE_OK);
1115     }
1116     if (p->Type != ACPI_TYPE_BUFFER)
1117         return(AE_TYPE);
1118     if (p->Buffer.Length > sizeof(int))
1119         return(AE_BAD_DATA);
1120     *number = 0;
1121     for (i = 0; i < p->Buffer.Length; i++)
1122         *number += (*(p->Buffer.Pointer + i) << (i * 8));
1123     return(AE_OK);
1124 }
1125
1126 /*
1127  * Iterate over the elements of an a package object, calling the supplied
1128  * function for each element.
1129  *
1130  * XXX possible enhancement might be to abort traversal on error.
1131  */
1132 ACPI_STATUS
1133 acpi_ForeachPackageObject(ACPI_OBJECT *pkg, void (* func)(ACPI_OBJECT *comp, void *arg), void *arg)
1134 {
1135     ACPI_OBJECT *comp;
1136     int         i;
1137     
1138     if ((pkg == NULL) || (pkg->Type != ACPI_TYPE_PACKAGE))
1139         return(AE_BAD_PARAMETER);
1140
1141     /* iterate over components */
1142     for (i = 0, comp = pkg->Package.Elements; i < pkg->Package.Count; i++, comp++)
1143         func(comp, arg);
1144
1145     return(AE_OK);
1146 }
1147
1148 /*
1149  * Find the (index)th resource object in a set.
1150  */
1151 ACPI_STATUS
1152 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1153 {
1154     ACPI_RESOURCE       *rp;
1155     int                 i;
1156
1157     rp = (ACPI_RESOURCE *)buf->Pointer;
1158     i = index;
1159     while (i-- > 0) {
1160         /* range check */       
1161         if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1162             return(AE_BAD_PARAMETER);
1163         /* check for terminator */
1164         if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1165             (rp->Length == 0))
1166             return(AE_NOT_FOUND);
1167         rp = ACPI_RESOURCE_NEXT(rp);
1168     }
1169     if (resp != NULL)
1170         *resp = rp;
1171     return(AE_OK);
1172 }
1173
1174 /*
1175  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1176  *
1177  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1178  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1179  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1180  * resources.
1181  */
1182 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE       512
1183
1184 ACPI_STATUS
1185 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1186 {
1187     ACPI_RESOURCE       *rp;
1188     void                *newp;
1189     
1190     /*
1191      * Initialise the buffer if necessary.
1192      */
1193     if (buf->Pointer == NULL) {
1194         buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1195         if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1196             return(AE_NO_MEMORY);
1197         rp = (ACPI_RESOURCE *)buf->Pointer;
1198         rp->Id = ACPI_RSTYPE_END_TAG;
1199         rp->Length = 0;
1200     }
1201     if (res == NULL)
1202         return(AE_OK);
1203     
1204     /*
1205      * Scan the current buffer looking for the terminator.
1206      * This will either find the terminator or hit the end
1207      * of the buffer and return an error.
1208      */
1209     rp = (ACPI_RESOURCE *)buf->Pointer;
1210     for (;;) {
1211         /* range check, don't go outside the buffer */
1212         if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1213             return(AE_BAD_PARAMETER);
1214         if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1215             (rp->Length == 0)) {
1216             break;
1217         }
1218         rp = ACPI_RESOURCE_NEXT(rp);
1219     }
1220
1221     /*
1222      * Check the size of the buffer and expand if required.
1223      *
1224      * Required size is:
1225      *  size of existing resources before terminator + 
1226      *  size of new resource and header +
1227      *  size of terminator.
1228      *
1229      * Note that this loop should really only run once, unless
1230      * for some reason we are stuffing a *really* huge resource.
1231      */
1232     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) + 
1233             res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1234             ACPI_RESOURCE_LENGTH) >= buf->Length) {
1235         if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1236             return(AE_NO_MEMORY);
1237         bcopy(buf->Pointer, newp, buf->Length);
1238         rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1239                                ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1240         AcpiOsFree(buf->Pointer);
1241         buf->Pointer = newp;
1242         buf->Length += buf->Length;
1243     }
1244     
1245     /*
1246      * Insert the new resource.
1247      */
1248     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1249     
1250     /*
1251      * And add the terminator.
1252      */
1253     rp = ACPI_RESOURCE_NEXT(rp);
1254     rp->Id = ACPI_RSTYPE_END_TAG;
1255     rp->Length = 0;
1256
1257     return(AE_OK);
1258 }
1259
1260 /*
1261  * Set interrupt model.
1262  */
1263 ACPI_STATUS
1264 acpi_SetIntrModel(int model)
1265 {
1266         ACPI_OBJECT_LIST ArgList;
1267         ACPI_OBJECT Arg;
1268
1269         Arg.Type = ACPI_TYPE_INTEGER;
1270         Arg.Integer.Value = model;
1271         ArgList.Count = 1;
1272         ArgList.Pointer = &Arg;
1273         return (AcpiEvaluateObject(ACPI_ROOT_OBJECT, "_PIC", &ArgList, NULL));
1274 }
1275
1276 #define ACPI_MINIMUM_AWAKETIME  5
1277
1278 static void
1279 acpi_sleep_enable(void *arg)
1280 {
1281     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1282 }
1283
1284 /*
1285  * Set the system sleep state
1286  *
1287  * Currently we only support S1 and S5
1288  */
1289 ACPI_STATUS
1290 acpi_SetSleepState(struct acpi_softc *sc, int state)
1291 {
1292     ACPI_STATUS status = AE_OK;
1293     UINT8       TypeA;
1294     UINT8       TypeB;
1295
1296     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1297     ACPI_ASSERTLOCK;
1298
1299     if (sc->acpi_sstate != ACPI_STATE_S0)
1300         return_ACPI_STATUS(AE_BAD_PARAMETER);   /* avoid reentry */
1301
1302     if (sc->acpi_sleep_disabled)
1303         return_ACPI_STATUS(AE_OK);
1304
1305     switch (state) {
1306     case ACPI_STATE_S0: /* XXX only for testing */
1307         if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
1308             device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1309         }
1310         break;
1311
1312     case ACPI_STATE_S1:
1313     case ACPI_STATE_S2:
1314     case ACPI_STATE_S3:
1315     case ACPI_STATE_S4:
1316         if (ACPI_FAILURE(status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB))) {
1317             device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n", AcpiFormatException(status));
1318             break;
1319         }
1320
1321         sc->acpi_sstate = state;
1322         sc->acpi_sleep_disabled = 1;
1323
1324         /*
1325          * Inform all devices that we are going to sleep.
1326          */
1327         if (DEVICE_SUSPEND(root_bus) != 0) {
1328             /*
1329              * Re-wake the system.
1330              *
1331              * XXX note that a better two-pass approach with a 'veto' pass
1332              *     followed by a "real thing" pass would be better, but the
1333              *     current bus interface does not provide for this.
1334              */
1335             DEVICE_RESUME(root_bus);
1336             return_ACPI_STATUS(AE_ERROR);
1337         }
1338
1339         if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(state))) {
1340             device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1341                           AcpiFormatException(status));
1342             break;
1343         }
1344
1345         if (sc->acpi_sleep_delay > 0) {
1346             DELAY(sc->acpi_sleep_delay * 1000000);
1347         }
1348
1349         if (state != ACPI_STATE_S1) {
1350             acpi_sleep_machdep(sc, state);
1351
1352             /* AcpiEnterSleepState() maybe incompleted, unlock here if locked. */
1353             if (AcpiGbl_AcpiMutexInfo[ACPI_MTX_HARDWARE].OwnerId != ACPI_MUTEX_NOT_ACQUIRED) {
1354                 AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1355             }
1356
1357             /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1358             if (state == ACPI_STATE_S4) {
1359                 AcpiEnable();
1360             }
1361         } else {
1362             if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
1363                 device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1364                 break;
1365             }
1366         }
1367         AcpiLeaveSleepState((UINT8)state);
1368         DEVICE_RESUME(root_bus);
1369         sc->acpi_sstate = ACPI_STATE_S0;
1370         acpi_enable_fixed_events(sc);
1371         break;
1372
1373     case ACPI_STATE_S5:
1374         /*
1375          * Shut down cleanly and power off.  This will call us back through the
1376          * shutdown handlers.
1377          */
1378         shutdown_nice(RB_POWEROFF);
1379         break;
1380
1381     default:
1382         status = AE_BAD_PARAMETER;
1383         break;
1384     }
1385
1386     if (sc->acpi_sleep_disabled)
1387         timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
1388
1389     return_ACPI_STATUS(status);
1390 }
1391
1392 /*
1393  * Enable/Disable ACPI
1394  */
1395 ACPI_STATUS
1396 acpi_Enable(struct acpi_softc *sc)
1397 {
1398     ACPI_STATUS status;
1399     u_int32_t   flags;
1400
1401     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1402     ACPI_ASSERTLOCK;
1403
1404     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
1405             ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
1406     if (!sc->acpi_enabled) {
1407         status = AcpiEnableSubsystem(flags);
1408     } else {
1409         status = AE_OK;
1410     }
1411     if (status == AE_OK)
1412         sc->acpi_enabled = 1;
1413     return_ACPI_STATUS(status);
1414 }
1415
1416 ACPI_STATUS
1417 acpi_Disable(struct acpi_softc *sc)
1418 {
1419     ACPI_STATUS status;
1420
1421     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1422     ACPI_ASSERTLOCK;
1423
1424     if (sc->acpi_enabled) {
1425         status = AcpiDisable();
1426     } else {
1427         status = AE_OK;
1428     }
1429     if (status == AE_OK)
1430         sc->acpi_enabled = 0;
1431     return_ACPI_STATUS(status);
1432 }
1433
1434 /*
1435  * ACPI Event Handlers
1436  */
1437
1438 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1439
1440 static void
1441 acpi_system_eventhandler_sleep(void *arg, int state)
1442 {
1443     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1444
1445     ACPI_LOCK;
1446     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
1447         acpi_SetSleepState((struct acpi_softc *)arg, state);
1448     ACPI_UNLOCK;
1449     return_VOID;
1450 }
1451
1452 static void
1453 acpi_system_eventhandler_wakeup(void *arg, int state)
1454 {
1455     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1456
1457     /* Well, what to do? :-) */
1458
1459     ACPI_LOCK;
1460     ACPI_UNLOCK;
1461
1462     return_VOID;
1463 }
1464
1465 /* 
1466  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1467  */
1468 UINT32
1469 acpi_eventhandler_power_button_for_sleep(void *context)
1470 {
1471     struct acpi_softc   *sc = (struct acpi_softc *)context;
1472
1473     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1474
1475     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1476
1477     return_VALUE(ACPI_INTERRUPT_HANDLED);
1478 }
1479
1480 UINT32
1481 acpi_eventhandler_power_button_for_wakeup(void *context)
1482 {
1483     struct acpi_softc   *sc = (struct acpi_softc *)context;
1484
1485     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1486
1487     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1488
1489     return_VALUE(ACPI_INTERRUPT_HANDLED);
1490 }
1491
1492 UINT32
1493 acpi_eventhandler_sleep_button_for_sleep(void *context)
1494 {
1495     struct acpi_softc   *sc = (struct acpi_softc *)context;
1496
1497     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1498
1499     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1500
1501     return_VALUE(ACPI_INTERRUPT_HANDLED);
1502 }
1503
1504 UINT32
1505 acpi_eventhandler_sleep_button_for_wakeup(void *context)
1506 {
1507     struct acpi_softc   *sc = (struct acpi_softc *)context;
1508
1509     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1510
1511     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1512
1513     return_VALUE(ACPI_INTERRUPT_HANDLED);
1514 }
1515
1516 /*
1517  * XXX This is kinda ugly, and should not be here.
1518  */
1519 struct acpi_staticbuf {
1520     ACPI_BUFFER buffer;
1521     char        data[512];
1522 };
1523
1524 char *
1525 acpi_name(ACPI_HANDLE handle)
1526 {
1527     static struct acpi_staticbuf        buf;
1528
1529     ACPI_ASSERTLOCK;
1530
1531     buf.buffer.Length = 512;
1532     buf.buffer.Pointer = &buf.data[0];
1533
1534     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
1535         return(buf.buffer.Pointer);
1536     return("(unknown path)");
1537 }
1538
1539 /*
1540  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1541  * parts of the namespace.
1542  */
1543 int
1544 acpi_avoid(ACPI_HANDLE handle)
1545 {
1546     char        *cp, *env, *np;
1547     int         len;
1548
1549     np = acpi_name(handle);
1550     if (*np == '\\')
1551         np++;
1552     if ((env = getenv("debug.acpi.avoid")) == NULL)
1553         return(0);
1554
1555     /* scan the avoid list checking for a match */
1556     cp = env;
1557     for (;;) {
1558         while ((*cp != 0) && isspace(*cp))
1559             cp++;
1560         if (*cp == 0)
1561             break;
1562         len = 0;
1563         while ((cp[len] != 0) && !isspace(cp[len]))
1564             len++;
1565         if (!strncmp(cp, np, len)) {
1566             freeenv(env);
1567             return(1);
1568         }
1569         cp += len;
1570     }
1571     freeenv(env);
1572     return(0);
1573 }
1574
1575 /*
1576  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1577  */
1578 int
1579 acpi_disabled(char *subsys)
1580 {
1581     char        *cp, *env;
1582     int         len;
1583
1584     if ((env = getenv("debug.acpi.disable")) == NULL)
1585         return(0);
1586     if (!strcmp(env, "all")) {
1587         freeenv(env);
1588         return(1);
1589     }
1590
1591     /* scan the disable list checking for a match */
1592     cp = env;
1593     for (;;) {
1594         while ((*cp != 0) && isspace(*cp))
1595             cp++;
1596         if (*cp == 0)
1597             break;
1598         len = 0;
1599         while ((cp[len] != 0) && !isspace(cp[len]))
1600             len++;
1601         if (!strncmp(cp, subsys, len)) {
1602             freeenv(env);
1603             return(1);
1604         }
1605         cp += len;
1606     }
1607     freeenv(env);
1608     return(0);
1609 }
1610
1611 /*
1612  * Device wake capability enable/disable.
1613  */
1614 void
1615 acpi_device_enable_wake_capability(ACPI_HANDLE h, int enable)
1616 {
1617     ACPI_OBJECT_LIST            ArgList;
1618     ACPI_OBJECT                 Arg;
1619
1620     /*
1621      * TBD: All Power Resources referenced by elements 2 through N
1622      *      of the _PRW object are put into the ON state.
1623      */
1624
1625     /*
1626      * enable/disable device wake function.
1627      */
1628
1629     ArgList.Count = 1;
1630     ArgList.Pointer = &Arg;
1631
1632     Arg.Type = ACPI_TYPE_INTEGER;
1633     Arg.Integer.Value = enable;
1634
1635     (void)AcpiEvaluateObject(h, "_PSW", &ArgList, NULL);
1636 }
1637
1638 void
1639 acpi_device_enable_wake_event(ACPI_HANDLE h)
1640 {
1641     struct acpi_softc           *sc;
1642     ACPI_STATUS                 status;
1643     ACPI_BUFFER                 prw_buffer;
1644     ACPI_OBJECT                 *res;
1645
1646     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1647
1648     if ((sc = devclass_get_softc(acpi_devclass, 0)) == NULL) {
1649         return;
1650     }
1651
1652     /*
1653      * _PRW object is only required for devices that have the ability
1654      * to wake the system from a system sleeping state.
1655      */
1656     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
1657     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
1658     if (ACPI_FAILURE(status)) {
1659         return;
1660     }
1661
1662     res = (ACPI_OBJECT *)prw_buffer.Pointer;
1663     if (res == NULL) {
1664         return;
1665     }
1666
1667     if ((res->Type != ACPI_TYPE_PACKAGE) || (res->Package.Count < 2)) {
1668         goto out;
1669     }
1670
1671     /*
1672      * The element 1 of the _PRW object:
1673      * The lowest power system sleeping state that can be entered
1674      * while still providing wake functionality.
1675      * The sleeping state being entered must be greater or equal to
1676      * the power state declared in element 1 of the _PRW object.
1677      */
1678     if (res->Package.Elements[1].Type != ACPI_TYPE_INTEGER) {
1679         goto out;
1680     }
1681
1682     if (sc->acpi_sstate > res->Package.Elements[1].Integer.Value) {
1683         goto out;
1684     }
1685
1686     /*
1687      * The element 0 of the _PRW object:
1688      */
1689     switch(res->Package.Elements[0].Type) {
1690     case ACPI_TYPE_INTEGER:
1691         /* 
1692          * If the data type of this package element is numeric, then this
1693          * _PRW package element is the bit index in the GPEx_EN, in the
1694          * GPE blocks described in the FADT, of the enable bit that is
1695          * enabled for the wake event.
1696          */
1697
1698         status = AcpiEnableEvent(res->Package.Elements[0].Integer.Value,
1699                                  ACPI_EVENT_GPE, ACPI_EVENT_WAKE_ENABLE);
1700         if (ACPI_FAILURE(status))
1701             printf("%s: EnableEvent Failed\n", __func__);
1702         break;
1703
1704     case ACPI_TYPE_PACKAGE:
1705         /* XXX TBD */
1706
1707         /*
1708          * If the data type of this package element is a package, then this
1709          * _PRW package element is itself a package containing two
1710          * elements. The first is an object reference to the GPE Block
1711          * device that contains the GPE that will be triggered by the wake
1712          * event. The second element is numeric and it contains the bit
1713          * index in the GPEx_EN, in the GPE Block referenced by the
1714          * first element in the package, of the enable bit that is enabled for
1715          * the wake event.
1716          * For example, if this field is a package then it is of the form:
1717          * Package() {\_SB.PCI0.ISA.GPE, 2}
1718          */
1719
1720         break;
1721
1722     default:
1723         break;
1724     }
1725
1726 out:
1727     if (prw_buffer.Pointer != NULL)
1728         AcpiOsFree(prw_buffer.Pointer);
1729     return;
1730 }
1731
1732 /*
1733  * Control interface.
1734  *
1735  * We multiplex ioctls for all participating ACPI devices here.  Individual 
1736  * drivers wanting to be accessible via /dev/acpi should use the register/deregister
1737  * interface to make their handlers visible.
1738  */
1739 struct acpi_ioctl_hook
1740 {
1741     TAILQ_ENTRY(acpi_ioctl_hook)        link;
1742     u_long                              cmd;
1743     int                                 (* fn)(u_long cmd, caddr_t addr, void *arg);
1744     void                                *arg;
1745 };
1746
1747 static TAILQ_HEAD(,acpi_ioctl_hook)     acpi_ioctl_hooks;
1748 static int                              acpi_ioctl_hooks_initted;
1749
1750 /*
1751  * Register an ioctl handler.
1752  */
1753 int
1754 acpi_register_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg), void *arg)
1755 {
1756     struct acpi_ioctl_hook      *hp;
1757
1758     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
1759         return(ENOMEM);
1760     hp->cmd = cmd;
1761     hp->fn = fn;
1762     hp->arg = arg;
1763     if (acpi_ioctl_hooks_initted == 0) {
1764         TAILQ_INIT(&acpi_ioctl_hooks);
1765         acpi_ioctl_hooks_initted = 1;
1766     }
1767     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
1768     return(0);
1769 }
1770
1771 /*
1772  * Deregister an ioctl handler.
1773  */
1774 void    
1775 acpi_deregister_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg))
1776 {
1777     struct acpi_ioctl_hook      *hp;
1778
1779     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
1780         if ((hp->cmd == cmd) && (hp->fn == fn))
1781             break;
1782
1783     if (hp != NULL) {
1784         TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
1785         free(hp, M_ACPIDEV);
1786     }
1787 }
1788
1789 static int
1790 acpiopen(dev_t dev, int flag, int fmt, struct thread *td)
1791 {
1792     return(0);
1793 }
1794
1795 static int
1796 acpiclose(dev_t dev, int flag, int fmt, struct thread *td)
1797 {
1798     return(0);
1799 }
1800
1801 static int
1802 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1803 {
1804     struct acpi_softc           *sc;
1805     struct acpi_ioctl_hook      *hp;
1806     int                         error, xerror, state;
1807
1808     ACPI_LOCK;
1809
1810     error = state = 0;
1811     sc = dev->si_drv1;
1812
1813     /*
1814      * Scan the list of registered ioctls, looking for handlers.
1815      */
1816     if (acpi_ioctl_hooks_initted) {
1817         TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
1818             if (hp->cmd == cmd) {
1819                 xerror = hp->fn(cmd, addr, hp->arg);
1820                 if (xerror != 0)
1821                     error = xerror;
1822                 goto out;
1823             }
1824         }
1825     }
1826
1827     /*
1828      * Core system ioctls.
1829      */
1830     switch (cmd) {
1831     case ACPIIO_ENABLE:
1832         if (ACPI_FAILURE(acpi_Enable(sc)))
1833             error = ENXIO;
1834         break;
1835
1836     case ACPIIO_DISABLE:
1837         if (ACPI_FAILURE(acpi_Disable(sc)))
1838             error = ENXIO;
1839         break;
1840
1841     case ACPIIO_SETSLPSTATE:
1842         if (!sc->acpi_enabled) {
1843             error = ENXIO;
1844             break;
1845         }
1846         state = *(int *)addr;
1847         if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
1848             acpi_SetSleepState(sc, state);
1849         } else {
1850             error = EINVAL;
1851         }
1852         break;
1853
1854     default:
1855         if (error == 0)
1856             error = EINVAL;
1857         break;
1858     }
1859
1860 out:
1861     ACPI_UNLOCK;
1862     return(error);
1863 }
1864
1865 static int
1866 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
1867 {
1868     char sleep_state[10];
1869     int error;
1870     u_int new_state, old_state;
1871
1872     old_state = *(u_int *)oidp->oid_arg1;
1873     if (old_state > ACPI_S_STATES_MAX+1) {
1874         strcpy(sleep_state, "unknown");
1875     } else {
1876         bzero(sleep_state, sizeof(sleep_state));
1877         strncpy(sleep_state, sleep_state_names[old_state],
1878                 sizeof(sleep_state_names[old_state]));
1879     }
1880     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
1881     if (error == 0 && req->newptr != NULL) {
1882         for (new_state = ACPI_STATE_S0; new_state <= ACPI_S_STATES_MAX+1; new_state++) {
1883             if (strncmp(sleep_state, sleep_state_names[new_state],
1884                         sizeof(sleep_state)) == 0)
1885                 break;
1886         }
1887         if (new_state <= ACPI_S_STATES_MAX+1) {
1888             if (new_state != old_state) {
1889                 *(u_int *)oidp->oid_arg1 = new_state;
1890             }
1891         } else {
1892             error = EINVAL;
1893         }
1894     }
1895     return(error);
1896 }
1897
1898 #ifdef ACPI_DEBUG
1899 /*
1900  * Support for parsing debug options from the kernel environment.
1901  *
1902  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
1903  * by specifying the names of the bits in the debug.acpi.layer and
1904  * debug.acpi.level environment variables.  Bits may be unset by 
1905  * prefixing the bit name with !.
1906  */
1907 struct debugtag
1908 {
1909     char        *name;
1910     UINT32      value;
1911 };
1912
1913 static struct debugtag  dbg_layer[] = {
1914     {"ACPI_UTILITIES",          ACPI_UTILITIES},
1915     {"ACPI_HARDWARE",           ACPI_HARDWARE},
1916     {"ACPI_EVENTS",             ACPI_EVENTS},
1917     {"ACPI_TABLES",             ACPI_TABLES},
1918     {"ACPI_NAMESPACE",          ACPI_NAMESPACE},
1919     {"ACPI_PARSER",             ACPI_PARSER},
1920     {"ACPI_DISPATCHER",         ACPI_DISPATCHER},
1921     {"ACPI_EXECUTER",           ACPI_EXECUTER},
1922     {"ACPI_RESOURCES",          ACPI_RESOURCES},
1923     {"ACPI_CA_DEBUGGER",        ACPI_CA_DEBUGGER},
1924     {"ACPI_OS_SERVICES",        ACPI_OS_SERVICES},
1925     {"ACPI_CA_DISASSEMBLER",    ACPI_CA_DISASSEMBLER},
1926
1927     {"ACPI_BUS",                ACPI_BUS},
1928     {"ACPI_SYSTEM",             ACPI_SYSTEM},
1929     {"ACPI_POWER",              ACPI_POWER},
1930     {"ACPI_EC",                 ACPI_EC},
1931     {"ACPI_AC_ADAPTER",         ACPI_AC_ADAPTER},
1932     {"ACPI_BATTERY",            ACPI_BATTERY},
1933     {"ACPI_BUTTON",             ACPI_BUTTON},
1934     {"ACPI_PROCESSOR",          ACPI_PROCESSOR},
1935     {"ACPI_THERMAL",            ACPI_THERMAL},
1936     {"ACPI_FAN",                ACPI_FAN},
1937
1938     {"ACPI_ALL_DRIVERS",        ACPI_ALL_DRIVERS},
1939     {"ACPI_ALL_COMPONENTS",     ACPI_ALL_COMPONENTS},
1940     {NULL, 0}
1941 };
1942
1943 static struct debugtag dbg_level[] = {
1944     {"ACPI_LV_OK",              ACPI_LV_OK},
1945     {"ACPI_LV_INFO",            ACPI_LV_INFO},
1946     {"ACPI_LV_WARN",            ACPI_LV_WARN},
1947     {"ACPI_LV_ERROR",           ACPI_LV_ERROR},
1948     {"ACPI_LV_FATAL",           ACPI_LV_FATAL},
1949     {"ACPI_LV_DEBUG_OBJECT",    ACPI_LV_DEBUG_OBJECT},
1950     {"ACPI_LV_ALL_EXCEPTIONS",  ACPI_LV_ALL_EXCEPTIONS},
1951
1952     /* Trace verbosity level 1 [Standard Trace Level] */
1953     {"ACPI_LV_PARSE",           ACPI_LV_PARSE},
1954     {"ACPI_LV_LOAD",            ACPI_LV_LOAD},
1955     {"ACPI_LV_DISPATCH",        ACPI_LV_DISPATCH},
1956     {"ACPI_LV_EXEC",            ACPI_LV_EXEC},
1957     {"ACPI_LV_NAMES",           ACPI_LV_NAMES},
1958     {"ACPI_LV_OPREGION",        ACPI_LV_OPREGION},
1959     {"ACPI_LV_BFIELD",          ACPI_LV_BFIELD},
1960     {"ACPI_LV_TABLES",          ACPI_LV_TABLES},
1961     {"ACPI_LV_VALUES",          ACPI_LV_VALUES},
1962     {"ACPI_LV_OBJECTS",         ACPI_LV_OBJECTS},
1963     {"ACPI_LV_RESOURCES",       ACPI_LV_RESOURCES},
1964     {"ACPI_LV_USER_REQUESTS",   ACPI_LV_USER_REQUESTS},
1965     {"ACPI_LV_PACKAGE",         ACPI_LV_PACKAGE},
1966     {"ACPI_LV_INIT",            ACPI_LV_INIT},
1967     {"ACPI_LV_VERBOSITY1",      ACPI_LV_VERBOSITY1},
1968
1969     /* Trace verbosity level 2 [Function tracing and memory allocation] */
1970     {"ACPI_LV_ALLOCATIONS",     ACPI_LV_ALLOCATIONS},
1971     {"ACPI_LV_FUNCTIONS",       ACPI_LV_FUNCTIONS},
1972     {"ACPI_LV_OPTIMIZATIONS",   ACPI_LV_OPTIMIZATIONS},
1973     {"ACPI_LV_VERBOSITY2",      ACPI_LV_VERBOSITY2},
1974     {"ACPI_LV_ALL",             ACPI_LV_ALL},
1975
1976     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
1977     {"ACPI_LV_MUTEX",           ACPI_LV_MUTEX},
1978     {"ACPI_LV_THREADS",         ACPI_LV_THREADS},
1979     {"ACPI_LV_IO",              ACPI_LV_IO},
1980     {"ACPI_LV_INTERRUPTS",      ACPI_LV_INTERRUPTS},
1981     {"ACPI_LV_VERBOSITY3",      ACPI_LV_VERBOSITY3},
1982
1983     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
1984     {"ACPI_LV_AML_DISASSEMBLE", ACPI_LV_AML_DISASSEMBLE},
1985     {"ACPI_LV_VERBOSE_INFO",    ACPI_LV_VERBOSE_INFO},
1986     {"ACPI_LV_FULL_TABLES",     ACPI_LV_FULL_TABLES},
1987     {"ACPI_LV_EVENTS",          ACPI_LV_EVENTS},
1988     {"ACPI_LV_VERBOSE",         ACPI_LV_VERBOSE},
1989     {NULL, 0}
1990 };    
1991
1992 static void
1993 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
1994 {
1995     char        *ep;
1996     int         i, l;
1997     int         set;
1998
1999     while (*cp) {
2000         if (isspace(*cp)) {
2001             cp++;
2002             continue;
2003         }
2004         ep = cp;
2005         while (*ep && !isspace(*ep))
2006             ep++;
2007         if (*cp == '!') {
2008             set = 0;
2009             cp++;
2010             if (cp == ep)
2011                 continue;
2012         } else {
2013             set = 1;
2014         }
2015         l = ep - cp;
2016         for (i = 0; tag[i].name != NULL; i++) {
2017             if (!strncmp(cp, tag[i].name, l)) {
2018                 if (set) {
2019                     *flag |= tag[i].value;
2020                 } else {
2021                     *flag &= ~tag[i].value;
2022                 }
2023                 printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
2024             }
2025         }
2026         cp = ep;
2027     }
2028 }
2029
2030 static void
2031 acpi_set_debugging(void *junk)
2032 {
2033     char        *cp;
2034
2035     AcpiDbgLayer = 0;
2036     AcpiDbgLevel = 0;
2037     if ((cp = getenv("debug.acpi.layer")) != NULL) {
2038         acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
2039         freeenv(cp);
2040     }
2041     if ((cp = getenv("debug.acpi.level")) != NULL) {
2042         acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
2043         freeenv(cp);
2044     }
2045
2046     printf("ACPI debug layer 0x%x  debug level 0x%x\n", AcpiDbgLayer, AcpiDbgLevel);
2047 }
2048 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging, NULL);
2049 #endif
2050
2051 static int
2052 acpi_pm_func(u_long cmd, void *arg, ...)
2053 {
2054         int     state, acpi_state;
2055         int     error;
2056         struct  acpi_softc *sc;
2057         va_list ap;
2058
2059         error = 0;
2060         switch (cmd) {
2061         case POWER_CMD_SUSPEND:
2062                 sc = (struct acpi_softc *)arg;
2063                 if (sc == NULL) {
2064                         error = EINVAL;
2065                         goto out;
2066                 }
2067
2068                 va_start(ap, arg);
2069                 state = va_arg(ap, int);
2070                 va_end(ap);     
2071
2072                 switch (state) {
2073                 case POWER_SLEEP_STATE_STANDBY:
2074                         acpi_state = sc->acpi_standby_sx;
2075                         break;
2076                 case POWER_SLEEP_STATE_SUSPEND:
2077                         acpi_state = sc->acpi_suspend_sx;
2078                         break;
2079                 case POWER_SLEEP_STATE_HIBERNATE:
2080                         acpi_state = ACPI_STATE_S4;
2081                         break;
2082                 default:
2083                         error = EINVAL;
2084                         goto out;
2085                 }
2086
2087                 acpi_SetSleepState(sc, acpi_state);
2088                 break;
2089
2090         default:
2091                 error = EINVAL;
2092                 goto out;
2093         }
2094
2095 out:
2096         return (error);
2097 }
2098
2099 static void
2100 acpi_pm_register(void *arg)
2101 {
2102         int     error;
2103
2104     if (!resource_int_value("acpi", 0, "disabled", &error) &&
2105        (error != 0))
2106                 return;
2107
2108         power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2109 }
2110
2111 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
2112