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