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