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