timeout/untimeout ==> callout_*
[dragonfly.git] / sys / dev / acpica5 / 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: src/sys/dev/acpica/acpi.c,v 1.156 2004/06/05 07:25:58 njl Exp $
30  *      $DragonFly: src/sys/dev/acpica5/acpi.c,v 1.9 2004/09/15 16:46:19 joerg Exp $
31  */
32
33 #include "opt_acpi.h"
34 #include <sys/param.h>
35 #include <sys/kernel.h>
36 #include <sys/proc.h>
37 #include <sys/fcntl.h>
38 #include <sys/malloc.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 #include <sys/sbuf.h>
48
49 #include <machine/clock.h>
50 #include <machine/globaldata.h>
51 #include <machine/resource.h>
52 #include <machine/bus.h>
53 #include <sys/rman.h>
54 #include <bus/isa/isavar.h>
55
56 #include "acpi.h"
57 #include <dev/acpica5/acpivar.h>
58 #include <dev/acpica5/acpiio.h>
59 #include <acnamesp.h>
60
61 MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
62
63 /* Hooks for the ACPI CA debugging infrastructure */
64 #define _COMPONENT      ACPI_BUS
65 ACPI_MODULE_NAME("ACPI")
66
67 static d_open_t         acpiopen;
68 static d_close_t        acpiclose;
69 static d_ioctl_t        acpiioctl;
70
71 #define CDEV_MAJOR 152
72 static struct cdevsw acpi_cdevsw = {
73         .d_name = "acpi",
74         .d_maj  = CDEV_MAJOR,
75         .d_flags = 0,
76         .d_port = NULL,
77         .d_clone = NULL,
78         .old_open = acpiopen,
79         .old_close = acpiclose,
80         .old_ioctl = acpiioctl
81 };
82
83 #if __FreeBSD_version >= 500000
84 struct mtx      acpi_mutex;
85 #endif
86
87 struct acpi_quirks {
88     char        *OemId;
89     uint32_t    OemRevision;
90     char        *value;
91 };
92
93 #define ACPI_OEM_REV_ANY        0
94
95 static struct acpi_quirks acpi_quirks_table[] = {
96 #ifdef notyet
97     /* Bad PCI routing table.  Used on some SuperMicro boards. */
98     { "PTLTD ", 0x06040000, "pci_link" },
99 #endif
100
101     { NULL, 0, NULL }
102 };
103
104 static int      acpi_modevent(struct module *mod, int event, void *junk);
105 static void     acpi_identify(driver_t *driver, device_t parent);
106 static int      acpi_probe(device_t dev);
107 static int      acpi_attach(device_t dev);
108 static int      acpi_shutdown(device_t dev);
109 static void     acpi_quirks_set(void);
110 static device_t acpi_add_child(device_t bus, int order, const char *name,
111                         int unit);
112 static int      acpi_print_child(device_t bus, device_t child);
113 static int      acpi_read_ivar(device_t dev, device_t child, int index,
114                         uintptr_t *result);
115 static int      acpi_write_ivar(device_t dev, device_t child, int index,
116                         uintptr_t value);
117 static int      acpi_set_resource(device_t dev, device_t child, int type,
118                         int rid, u_long start, u_long count);
119 static int      acpi_get_resource(device_t dev, device_t child, int type,
120                         int rid, u_long *startp, u_long *countp);
121 static struct resource *acpi_alloc_resource(device_t bus, device_t child,
122                         int type, int *rid, u_long start, u_long end,
123                         u_long count, u_int flags);
124 static int      acpi_release_resource(device_t bus, device_t child, int type,
125                         int rid, struct resource *r);
126 static uint32_t acpi_isa_get_logicalid(device_t dev);
127 static int      acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
128 static int      acpi_isa_pnp_probe(device_t bus, device_t child,
129                         struct isa_pnp_id *ids);
130 static void     acpi_probe_children(device_t bus);
131 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
132                         void *context, void **status);
133 static void     acpi_shutdown_pre_sync(void *arg, int howto);
134 static void     acpi_shutdown_final(void *arg, int howto);
135 static void     acpi_shutdown_poweroff(void *arg);
136 static void     acpi_enable_fixed_events(struct acpi_softc *sc);
137 static int      acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw);
138 static ACPI_STATUS acpi_wake_limit(ACPI_HANDLE h, UINT32 level, void *context,
139                     void **status);
140 static int      acpi_wake_limit_walk(int sstate);
141 static int      acpi_wake_sysctl_walk(device_t dev);
142 static int      acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS);
143 static void     acpi_system_eventhandler_sleep(void *arg, int state);
144 static void     acpi_system_eventhandler_wakeup(void *arg, int state);
145 static int      acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
146 static int      acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
147 static int      acpi_pm_func(u_long cmd, void *arg, ...);
148 static int      acpi_child_location_str_method(device_t acdev, device_t child,
149                                                char *buf, size_t buflen);
150 static int      acpi_child_pnpinfo_str_method(device_t acdev, device_t child,
151                                               char *buf, size_t buflen);
152
153 static device_method_t acpi_methods[] = {
154     /* Device interface */
155     DEVMETHOD(device_identify,          acpi_identify),
156     DEVMETHOD(device_probe,             acpi_probe),
157     DEVMETHOD(device_attach,            acpi_attach),
158     DEVMETHOD(device_shutdown,          acpi_shutdown),
159     DEVMETHOD(device_detach,            bus_generic_detach),
160     DEVMETHOD(device_suspend,           bus_generic_suspend),
161     DEVMETHOD(device_resume,            bus_generic_resume),
162
163     /* Bus interface */
164     DEVMETHOD(bus_add_child,            acpi_add_child),
165     DEVMETHOD(bus_print_child,          acpi_print_child),
166     DEVMETHOD(bus_read_ivar,            acpi_read_ivar),
167     DEVMETHOD(bus_write_ivar,           acpi_write_ivar),
168     DEVMETHOD(bus_set_resource,         acpi_set_resource),
169     DEVMETHOD(bus_get_resource,         acpi_get_resource),
170     DEVMETHOD(bus_alloc_resource,       acpi_alloc_resource),
171     DEVMETHOD(bus_release_resource,     acpi_release_resource),
172     DEVMETHOD(bus_child_pnpinfo_str,    acpi_child_pnpinfo_str_method),
173     DEVMETHOD(bus_child_location_str,   acpi_child_location_str_method),
174     DEVMETHOD(bus_driver_added,         bus_generic_driver_added),
175     DEVMETHOD(bus_activate_resource,    bus_generic_activate_resource),
176     DEVMETHOD(bus_deactivate_resource,  bus_generic_deactivate_resource),
177     DEVMETHOD(bus_setup_intr,           bus_generic_setup_intr),
178     DEVMETHOD(bus_teardown_intr,        bus_generic_teardown_intr),
179
180     /* ISA emulation */
181     DEVMETHOD(isa_pnp_probe,            acpi_isa_pnp_probe),
182
183     {0, 0}
184 };
185
186 static driver_t acpi_driver = {
187     "acpi",
188     acpi_methods,
189     sizeof(struct acpi_softc),
190 };
191
192 static devclass_t acpi_devclass;
193 DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
194 MODULE_VERSION(acpi, 1);
195
196 static const char* sleep_state_names[] = {
197     "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
198
199 SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RW, NULL, "ACPI debugging");
200 static char acpi_ca_version[12];
201 SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
202               acpi_ca_version, 0, "Version of Intel ACPI-CA");
203
204 /*
205  * Allow override of whether methods execute in parallel or not.
206  * Enable this for serial behavior, which fixes "AE_ALREADY_EXISTS"
207  * errors for AML that really can't handle parallel method execution.
208  * It is off by default since this breaks recursive methods and
209  * some IBMs use such code.
210  */
211 static int acpi_serialize_methods;
212 TUNABLE_INT("hw.acpi.serialize_methods", &acpi_serialize_methods);
213
214 /*
215  * ACPI can only be loaded as a module by the loader; activating it after
216  * system bootstrap time is not useful, and can be fatal to the system.
217  * It also cannot be unloaded, since the entire system bus heirarchy hangs
218  * off it.
219  */
220 static int
221 acpi_modevent(struct module *mod, int event, void *junk)
222 {
223     switch(event) {
224     case MOD_LOAD:
225         if (!cold) {
226             printf("The ACPI driver cannot be loaded after boot.\n");
227             return (EPERM);
228         }
229         break;
230     case MOD_UNLOAD:
231         if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
232             return (EBUSY);
233         break;
234     default:
235         break;
236     }
237     return (0);
238 }
239
240 /*
241  * Perform early initialization.
242  */
243 ACPI_STATUS
244 acpi_Startup(void)
245 {
246 #ifdef ACPI_DEBUGGER
247     char *debugpoint;
248 #endif
249     static int error, started = 0;
250
251     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
252
253     if (started)
254         return_VALUE (error);
255     started = 1;
256
257 #if __FreeBSD_version >= 500000
258     /* Initialise the ACPI mutex */
259     mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
260 #endif
261
262     /*
263      * Set the globals from our tunables.  This is needed because ACPI-CA
264      * uses UINT8 for some values and we have no tunable_byte.
265      */
266     AcpiGbl_AllMethodsSerialized = (UINT8)acpi_serialize_methods;
267
268     /* Start up the ACPI CA subsystem. */
269 #ifdef ACPI_DEBUGGER
270     debugpoint = getenv("debug.acpi.debugger");
271     if (debugpoint) {
272         if (!strcmp(debugpoint, "init"))
273             acpi_EnterDebugger();
274         freeenv(debugpoint);
275     }
276 #endif
277     if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
278         printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
279         return_VALUE (error);
280     }
281 #ifdef ACPI_DEBUGGER
282     debugpoint = getenv("debug.acpi.debugger");
283     if (debugpoint) {
284         if (!strcmp(debugpoint, "tables"))
285             acpi_EnterDebugger();
286         freeenv(debugpoint);
287     }
288 #endif
289
290     if (ACPI_FAILURE(error = AcpiLoadTables())) {
291         printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
292         return_VALUE(error);
293     }
294
295     /* Set up any quirks we have for this XSDT. */
296     acpi_quirks_set();
297     if (acpi_disabled("acpi"))
298         return_VALUE (AE_ERROR);
299
300     return_VALUE (AE_OK);
301 }
302
303 /*
304  * Detect ACPI, perform early initialisation
305  */
306 static void
307 acpi_identify(driver_t *driver, device_t parent)
308 {
309     device_t    child;
310
311     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
312
313     if (!cold)
314         return_VOID;
315
316     /* Check that we haven't been disabled with a hint. */
317     if (resource_disabled("acpi", 0))
318         return_VOID;
319
320     /* Make sure we're not being doubly invoked. */
321     if (device_find_child(parent, "acpi", 0) != NULL)
322         return_VOID;
323
324     /* Initialize ACPI-CA. */
325     if (ACPI_FAILURE(acpi_Startup()))
326         return_VOID;
327
328     snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%#x", ACPI_CA_VERSION);
329
330     /* Attach the actual ACPI device. */
331     if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
332         device_printf(parent, "ACPI: could not attach\n");
333         return_VOID;
334     }
335 }
336
337 /*
338  * Fetch some descriptive data from ACPI to put in our attach message
339  */
340 static int
341 acpi_probe(device_t dev)
342 {
343     ACPI_TABLE_HEADER   th;
344     char                buf[20];
345     int                 error;
346     struct sbuf         sb;
347     ACPI_STATUS         status;
348     ACPI_LOCK_DECL;
349
350     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
351
352     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
353         power_pm_get_type() != POWER_PM_TYPE_ACPI) {
354
355         device_printf(dev, "Other PM system enabled.\n");
356         return_VALUE(ENXIO);
357     }
358
359     ACPI_LOCK;
360
361     if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
362         device_printf(dev, "couldn't get XSDT header: %s\n",
363                       AcpiFormatException(status));
364         error = ENXIO;
365     } else {
366         sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
367         sbuf_bcat(&sb, th.OemId, 6);
368         sbuf_trim(&sb);
369         sbuf_putc(&sb, ' ');
370         sbuf_bcat(&sb, th.OemTableId, 8);
371         sbuf_trim(&sb);
372         sbuf_finish(&sb);
373         device_set_desc_copy(dev, sbuf_data(&sb));
374         sbuf_delete(&sb);
375         error = 0;
376     }
377     ACPI_UNLOCK;
378     return_VALUE(error);
379 }
380
381 static int
382 acpi_attach(device_t dev)
383 {
384     struct acpi_softc   *sc;
385     ACPI_STATUS         status;
386     int                 error, state;
387     UINT32              flags;
388     UINT8               TypeA, TypeB;
389     char                *env;
390 #ifdef ACPI_DEBUGGER
391     char                *debugpoint;
392 #endif
393     ACPI_LOCK_DECL;
394
395     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
396     ACPI_LOCK;
397     sc = device_get_softc(dev);
398     bzero(sc, sizeof(*sc));
399     sc->acpi_dev = dev;
400     callout_init(&sc->acpi_sleep_timer);
401
402 #ifdef ACPI_DEBUGGER
403     debugpoint = getenv("debug.acpi.debugger");
404     if (debugpoint) {
405         if (!strcmp(debugpoint, "spaces"))
406             acpi_EnterDebugger();
407         freeenv(debugpoint);
408     }
409 #endif
410
411     /* Install the default address space handlers. */
412     error = ENXIO;
413     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
414                 ACPI_ADR_SPACE_SYSTEM_MEMORY, ACPI_DEFAULT_HANDLER, NULL, NULL);
415     if (ACPI_FAILURE(status)) {
416         device_printf(dev, "Could not initialise SystemMemory handler: %s\n",
417                       AcpiFormatException(status));
418         goto out;
419     }
420     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
421                 ACPI_ADR_SPACE_SYSTEM_IO, ACPI_DEFAULT_HANDLER, NULL, NULL);
422     if (ACPI_FAILURE(status)) {
423         device_printf(dev, "Could not initialise SystemIO handler: %s\n",
424                       AcpiFormatException(status));
425         goto out;
426     }
427     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
428                 ACPI_ADR_SPACE_PCI_CONFIG, ACPI_DEFAULT_HANDLER, NULL, NULL);
429     if (ACPI_FAILURE(status)) {
430         device_printf(dev, "could not initialise PciConfig handler: %s\n",
431                       AcpiFormatException(status));
432         goto out;
433     }
434
435     /*
436      * Bring ACPI fully online.
437      *
438      * Note that some systems (specifically, those with namespace evaluation
439      * issues that require the avoidance of parts of the namespace) must
440      * avoid running _INI and _STA on everything, as well as dodging the final
441      * object init pass.
442      *
443      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
444      *
445      * XXX We should arrange for the object init pass after we have attached
446      *     all our child devices, but on many systems it works here.
447      */
448 #ifdef ACPI_DEBUGGER
449     debugpoint = getenv("debug.acpi.debugger");
450     if (debugpoint) {
451         if (!strcmp(debugpoint, "enable"))
452             acpi_EnterDebugger();
453         freeenv(debugpoint);
454     }
455 #endif
456     flags = 0;
457     if (testenv("debug.acpi.avoid"))
458         flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
459     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
460         device_printf(dev, "Could not enable ACPI: %s\n",
461                       AcpiFormatException(status));
462         goto out;
463     }
464
465     /*
466      * Call the ECDT probe function to provide EC functionality before
467      * the namespace has been evaluated.
468      */
469     acpi_ec_ecdt_probe(dev);
470
471     if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
472         device_printf(dev, "Could not initialize ACPI objects: %s\n",
473                       AcpiFormatException(status));
474         goto out;
475     }
476
477     /*
478      * Setup our sysctl tree.
479      *
480      * XXX: This doesn't check to make sure that none of these fail.
481      */
482     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
483     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
484                                SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
485                                device_get_name(dev), CTLFLAG_RD, 0, "");
486     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
487         OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
488         0, 0, acpi_supported_sleep_state_sysctl, "A", "");
489     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
490         OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
491         &sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
492     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
493         OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
494         &sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
495     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
496         OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
497         &sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
498     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
499         OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
500         &sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
501     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
502         OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
503         &sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
504     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
505         OID_AUTO, "sleep_delay", CTLFLAG_RD | CTLFLAG_RW,
506         &sc->acpi_sleep_delay, 0, "sleep delay");
507     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
508         OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
509         &sc->acpi_s4bios, 0, "S4BIOS mode");
510     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
511         OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
512         &sc->acpi_verbose, 0, "verbose mode");
513     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
514         OID_AUTO, "disable_on_poweroff", CTLFLAG_RD | CTLFLAG_RW,
515         &sc->acpi_disable_on_poweroff, 0, "ACPI subsystem disable on poweroff");
516
517     /*
518      * Default to 1 second before sleeping to give some machines time to
519      * stabilize.
520      */
521     sc->acpi_sleep_delay = 1;
522     sc->acpi_disable_on_poweroff = 0;
523     if (bootverbose)
524         sc->acpi_verbose = 1;
525     if ((env = getenv("hw.acpi.verbose")) && strcmp(env, "0")) {
526         sc->acpi_verbose = 1;
527         freeenv(env);
528     }
529
530     /* Only enable S4BIOS by default if the FACS says it is available. */
531     if (AcpiGbl_FACS->S4Bios_f != 0)
532             sc->acpi_s4bios = 1;
533
534     /*
535      * Dispatch the default sleep state to devices.  The lid switch is set
536      * to NONE by default to avoid surprising users.
537      */
538     sc->acpi_power_button_sx = ACPI_STATE_S5;
539     sc->acpi_lid_switch_sx = ACPI_S_STATES_MAX + 1;
540     sc->acpi_standby_sx = ACPI_STATE_S1;
541     sc->acpi_suspend_sx = ACPI_STATE_S3;
542
543     /* Pick the first valid sleep state for the sleep button default. */
544     sc->acpi_sleep_button_sx = ACPI_S_STATES_MAX + 1;
545     for (state = ACPI_STATE_S1; state < ACPI_STATE_S5; state++)
546         if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
547             sc->acpi_sleep_button_sx = state;
548             break;
549         }
550
551     acpi_enable_fixed_events(sc);
552
553     /*
554      * Scan the namespace and attach/initialise children.
555      */
556 #ifdef ACPI_DEBUGGER
557     debugpoint = getenv("debug.acpi.debugger");
558     if (debugpoint) {
559         if (!strcmp(debugpoint, "probe"))
560             acpi_EnterDebugger();
561         freeenv(debugpoint);
562     }
563 #endif
564
565     /* Register our shutdown handlers */
566     EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc,
567         SHUTDOWN_PRI_LAST);
568     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
569         SHUTDOWN_PRI_LAST);
570
571     /*
572      * Register our acpi event handlers.
573      * XXX should be configurable eg. via userland policy manager.
574      */
575     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
576         sc, ACPI_EVENT_PRI_LAST);
577     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
578         sc, ACPI_EVENT_PRI_LAST);
579
580     /* Flag our initial states. */
581     sc->acpi_enabled = 1;
582     sc->acpi_sstate = ACPI_STATE_S0;
583     sc->acpi_sleep_disabled = 0;
584
585     /* Create the control device */
586     cdevsw_add(&acpi_cdevsw, 0, 0);
587     sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_WHEEL, 0644,
588                               "acpi");
589     sc->acpi_dev_t->si_drv1 = sc;
590
591 #ifdef ACPI_DEBUGGER
592     debugpoint = getenv("debug.acpi.debugger");
593     if (debugpoint) {
594         if (strcmp(debugpoint, "running") == 0)
595             acpi_EnterDebugger();
596         freeenv(debugpoint);
597     }
598 #endif
599
600     if ((error = acpi_task_thread_init()))
601         goto out;
602
603     if ((error = acpi_machdep_init(dev)))
604         goto out;
605
606     /* Register ACPI again to pass the correct argument of pm_func. */
607     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
608
609     if (!acpi_disabled("bus"))
610         acpi_probe_children(dev);
611
612     error = 0;
613
614  out:
615     ACPI_UNLOCK;
616     return_VALUE (error);
617 }
618
619 static int
620 acpi_shutdown(device_t dev)
621 {
622
623     /* Disable all wake GPEs not appropriate for reboot/poweroff. */
624     acpi_wake_limit_walk(ACPI_STATE_S5);
625     return (0);
626 }
627
628 static void
629 acpi_quirks_set()
630 {
631     XSDT_DESCRIPTOR *xsdt;
632     struct acpi_quirks *quirk;
633     char *env, *tmp;
634     int len;
635
636     /*
637      * If the user loaded a custom table or disabled "quirks", leave
638      * the settings alone.
639      */
640     len = 0;
641     if ((env = getenv("acpi_dsdt_load")) != NULL) {
642         /* XXX No strcasecmp but this is good enough. */
643         if (*env == 'Y' || *env == 'y')
644             goto out;
645         freeenv(env);
646     }
647     if ((env = getenv("debug.acpi.disabled")) != NULL) {
648         if (strstr("quirks", env) != NULL)
649             goto out;
650         len = strlen(env);
651     }
652
653     /*
654      * Search through our quirk table and concatenate the disabled
655      * values with whatever we find.
656      */
657     xsdt = AcpiGbl_XSDT;
658     for (quirk = acpi_quirks_table; quirk->OemId; quirk++) {
659         if (!strncmp(xsdt->OemId, quirk->OemId, strlen(quirk->OemId)) &&
660             (xsdt->OemRevision == quirk->OemRevision ||
661             quirk->OemRevision == ACPI_OEM_REV_ANY)) {
662                 len += strlen(quirk->value) + 2;
663                 if ((tmp = malloc(len, M_TEMP, M_NOWAIT)) == NULL)
664                     goto out;
665                 sprintf(tmp, "%s %s", env ? env : "", quirk->value);
666 #ifdef notyet
667                 setenv("debug.acpi.disabled", tmp);
668 #endif /* notyet */
669                 free(tmp, M_TEMP);
670                 break;
671         }
672     }
673
674 out:
675     if (env)
676         freeenv(env);
677 }
678
679 /*
680  * Handle a new device being added
681  */
682 static device_t
683 acpi_add_child(device_t bus, int order, const char *name, int unit)
684 {
685     struct acpi_device  *ad;
686     device_t            child;
687
688     ad = malloc(sizeof(*ad), M_ACPIDEV, M_INTWAIT | M_ZERO);
689
690     resource_list_init(&ad->ad_rl);
691
692     child = device_add_child_ordered(bus, order, name, unit);
693     if (child != NULL)
694         device_set_ivars(child, ad);
695     return (child);
696 }
697
698 static int
699 acpi_print_child(device_t bus, device_t child)
700 {
701     struct acpi_device   *adev = device_get_ivars(child);
702     struct resource_list *rl = &adev->ad_rl;
703     int retval = 0;
704
705     retval += bus_print_child_header(bus, child);
706     retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
707     retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
708     retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
709     retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
710     retval += bus_print_child_footer(bus, child);
711
712     return (retval);
713 }
714
715 /* Location hint for devctl(8) */
716 static int
717 acpi_child_location_str_method(device_t cbdev, device_t child, char *buf,
718     size_t buflen)
719 {
720     struct acpi_device *dinfo = device_get_ivars(child);
721
722     if (dinfo->ad_handle)
723         snprintf(buf, buflen, "path=%s", acpi_name(dinfo->ad_handle));
724     else
725         snprintf(buf, buflen, "magic=unknown");
726     return (0);
727 }
728
729 /* PnP information for devctl(8) */
730 static int
731 acpi_child_pnpinfo_str_method(device_t cbdev, device_t child, char *buf,
732     size_t buflen)
733 {
734     ACPI_BUFFER adbuf = {ACPI_ALLOCATE_BUFFER, NULL};
735     ACPI_DEVICE_INFO *adinfo;
736     struct acpi_device *dinfo = device_get_ivars(child);
737     char *end;
738     int error;
739
740     error = AcpiGetObjectInfo(dinfo->ad_handle, &adbuf);
741     adinfo = (ACPI_DEVICE_INFO *) adbuf.Pointer;
742
743     if (error)
744         snprintf(buf, buflen, "Unknown");
745     else
746         snprintf(buf, buflen, "_HID=%s _UID=%lu",
747                 (adinfo->Valid & ACPI_VALID_HID) ?
748                 adinfo->HardwareId.Value : "UNKNOWN",
749                 (adinfo->Valid & ACPI_VALID_UID) ?
750                 strtoul(adinfo->UniqueId.Value, &end, 10) : 0);
751
752     if (adinfo)
753         AcpiOsFree(adinfo);
754
755     return (0);
756 }
757
758 /*
759  * Handle per-device ivars
760  */
761 static int
762 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
763 {
764     struct acpi_device  *ad;
765
766     if ((ad = device_get_ivars(child)) == NULL) {
767         printf("device has no ivars\n");
768         return (ENOENT);
769     }
770
771     /* ACPI and ISA compatibility ivars */
772     switch(index) {
773     case ACPI_IVAR_HANDLE:
774         *(ACPI_HANDLE *)result = ad->ad_handle;
775         break;
776     case ACPI_IVAR_MAGIC:
777         *(int *)result = ad->ad_magic;
778         break;
779     case ACPI_IVAR_PRIVATE:
780         *(void **)result = ad->ad_private;
781         break;
782     case ISA_IVAR_VENDORID:
783     case ISA_IVAR_SERIAL:
784     case ISA_IVAR_COMPATID:
785         *(int *)result = -1;
786         break;
787     case ISA_IVAR_LOGICALID:
788         *(int *)result = acpi_isa_get_logicalid(child);
789         break;
790     default:
791         return (ENOENT);
792     }
793
794     return (0);
795 }
796
797 static int
798 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
799 {
800     struct acpi_device  *ad;
801
802     if ((ad = device_get_ivars(child)) == NULL) {
803         printf("device has no ivars\n");
804         return (ENOENT);
805     }
806
807     switch(index) {
808     case ACPI_IVAR_HANDLE:
809         ad->ad_handle = (ACPI_HANDLE)value;
810         break;
811     case ACPI_IVAR_MAGIC:
812         ad->ad_magic = (int)value;
813         break;
814     case ACPI_IVAR_PRIVATE:
815         ad->ad_private = (void *)value;
816         break;
817     default:
818         panic("bad ivar write request (%d)", index);
819         return (ENOENT);
820     }
821
822     return (0);
823 }
824
825 /*
826  * Handle child resource allocation/removal
827  */
828 static int
829 acpi_set_resource(device_t dev, device_t child, int type, int rid,
830                   u_long start, u_long count)
831 {
832     struct acpi_device          *ad = device_get_ivars(child);
833     struct resource_list        *rl = &ad->ad_rl;
834
835     resource_list_add(rl, type, rid, start, start + count -1, count);
836
837     return(0);
838 }
839
840 static int
841 acpi_get_resource(device_t dev, device_t child, int type, int rid,
842                   u_long *startp, u_long *countp)
843 {
844     struct acpi_device          *ad = device_get_ivars(child);
845     struct resource_list        *rl = &ad->ad_rl;
846     struct resource_list_entry  *rle;
847
848     rle = resource_list_find(rl, type, rid);
849     if (!rle)
850         return(ENOENT);
851         
852     if (startp)
853         *startp = rle->start;
854     if (countp)
855         *countp = rle->count;
856
857     return (0);
858 }
859
860 static struct resource *
861 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
862                     u_long start, u_long end, u_long count, u_int flags)
863 {
864     struct acpi_device *ad = device_get_ivars(child);
865     struct resource_list *rl = &ad->ad_rl;
866
867     return (resource_list_alloc(rl, bus, child, type, rid, start, end, count,
868             flags));
869 }
870
871 static int
872 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
873 {
874     struct acpi_device *ad = device_get_ivars(child);
875     struct resource_list *rl = &ad->ad_rl;
876
877     return (resource_list_release(rl, bus, child, type, rid, r));
878 }
879
880 /* Allocate an IO port or memory resource, given its GAS. */
881 struct resource *
882 acpi_bus_alloc_gas(device_t dev, int *rid, ACPI_GENERIC_ADDRESS *gas)
883 {
884     int type;
885
886     if (gas == NULL || !ACPI_VALID_ADDRESS(gas->Address) ||
887         gas->RegisterBitWidth < 8)
888         return (NULL);
889
890     switch (gas->AddressSpaceId) {
891     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
892         type = SYS_RES_MEMORY;
893         break;
894     case ACPI_ADR_SPACE_SYSTEM_IO:
895         type = SYS_RES_IOPORT;
896         break;
897     default:
898         return (NULL);
899     }
900
901     bus_set_resource(dev, type, *rid, gas->Address, gas->RegisterBitWidth / 8);
902     return (bus_alloc_resource_any(dev, type, rid, RF_ACTIVE));
903 }
904
905 /*
906  * Handle ISA-like devices probing for a PnP ID to match.
907  */
908 #define PNP_EISAID(s)                           \
909         ((((s[0] - '@') & 0x1f) << 2)           \
910          | (((s[1] - '@') & 0x18) >> 3)         \
911          | (((s[1] - '@') & 0x07) << 13)        \
912          | (((s[2] - '@') & 0x1f) << 8)         \
913          | (PNP_HEXTONUM(s[4]) << 16)           \
914          | (PNP_HEXTONUM(s[3]) << 20)           \
915          | (PNP_HEXTONUM(s[6]) << 24)           \
916          | (PNP_HEXTONUM(s[5]) << 28))
917
918 static uint32_t
919 acpi_isa_get_logicalid(device_t dev)
920 {
921     ACPI_DEVICE_INFO    *devinfo;
922     ACPI_BUFFER         buf;
923     ACPI_HANDLE         h;
924     ACPI_STATUS         error;
925     u_int32_t           pnpid;
926     ACPI_LOCK_DECL;
927
928     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
929
930     pnpid = 0;
931     buf.Pointer = NULL;
932     buf.Length = ACPI_ALLOCATE_BUFFER;
933
934     ACPI_LOCK;
935     
936     /* Fetch and validate the HID. */
937     if ((h = acpi_get_handle(dev)) == NULL)
938         goto out;
939     error = AcpiGetObjectInfo(h, &buf);
940     if (ACPI_FAILURE(error))
941         goto out;
942     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
943
944     if ((devinfo->Valid & ACPI_VALID_HID) != 0)
945         pnpid = PNP_EISAID(devinfo->HardwareId.Value);
946
947 out:
948     if (buf.Pointer != NULL)
949         AcpiOsFree(buf.Pointer);
950     ACPI_UNLOCK;
951     return_VALUE (pnpid);
952 }
953
954 static int
955 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
956 {
957     ACPI_DEVICE_INFO    *devinfo;
958     ACPI_BUFFER         buf;
959     ACPI_HANDLE         h;
960     ACPI_STATUS         error;
961     uint32_t            *pnpid;
962     int                 valid, i;
963     ACPI_LOCK_DECL;
964
965     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
966
967     pnpid = cids;
968     valid = 0;
969     buf.Pointer = NULL;
970     buf.Length = ACPI_ALLOCATE_BUFFER;
971
972     ACPI_LOCK;
973     
974     /* Fetch and validate the CID */
975     if ((h = acpi_get_handle(dev)) == NULL)
976         goto out;
977     error = AcpiGetObjectInfo(h, &buf);
978     if (ACPI_FAILURE(error))
979         goto out;
980     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
981     if ((devinfo->Valid & ACPI_VALID_CID) == 0)
982         goto out;
983
984     if (devinfo->CompatibilityId.Count < count)
985         count = devinfo->CompatibilityId.Count;
986     for (i = 0; i < count; i++) {
987         if (strncmp(devinfo->CompatibilityId.Id[i].Value, "PNP", 3) != 0)
988             continue;
989         *pnpid++ = PNP_EISAID(devinfo->CompatibilityId.Id[i].Value);
990         valid++;
991     }
992
993 out:
994     if (buf.Pointer != NULL)
995         AcpiOsFree(buf.Pointer);
996     ACPI_UNLOCK;
997     return_VALUE (valid);
998 }
999
1000 static int
1001 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
1002 {
1003     int                 result, cid_count, i;
1004     uint32_t            lid, cids[8];
1005
1006     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1007
1008     /*
1009      * ISA-style drivers attached to ACPI may persist and
1010      * probe manually if we return ENOENT.  We never want
1011      * that to happen, so don't ever return it.
1012      */
1013     result = ENXIO;
1014
1015     /* Scan the supplied IDs for a match */
1016     lid = acpi_isa_get_logicalid(child);
1017     cid_count = acpi_isa_get_compatid(child, cids, 8);
1018     while (ids && ids->ip_id) {
1019         if (lid == ids->ip_id) {
1020             result = 0;
1021             goto out;
1022         }
1023         for (i = 0; i < cid_count; i++) {
1024             if (cids[i] == ids->ip_id) {
1025                 result = 0;
1026                 goto out;
1027             }
1028         }
1029         ids++;
1030     }
1031
1032  out:
1033     return_VALUE (result);
1034 }
1035
1036 /*
1037  * Scan relevant portions of the ACPI namespace and attach child devices.
1038  *
1039  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and
1040  * \_SB_ scopes, and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
1041  */
1042 static void
1043 acpi_probe_children(device_t bus)
1044 {
1045     ACPI_HANDLE parent;
1046     ACPI_STATUS status;
1047     static char *scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
1048     int         i;
1049
1050     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1051     ACPI_ASSERTLOCK;
1052
1053     /* Create any static children by calling device identify methods. */
1054     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
1055     bus_generic_probe(bus);
1056
1057     /*
1058      * Scan the namespace and insert placeholders for all the devices that
1059      * we find.
1060      *
1061      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
1062      * we want to create nodes for all devices, not just those that are
1063      * currently present. (This assumes that we don't want to create/remove
1064      * devices as they appear, which might be smarter.)
1065      */
1066     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
1067     for (i = 0; scopes[i] != NULL; i++) {
1068         status = AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent);
1069         if (ACPI_SUCCESS(status)) {
1070             AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child,
1071                               bus, NULL);
1072         }
1073     }
1074
1075     /*
1076      * Scan all of the child devices we have created and let them probe/attach.
1077      */
1078     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
1079     bus_generic_attach(bus);
1080
1081     /*
1082      * Some of these children may have attached others as part of their attach
1083      * process (eg. the root PCI bus driver), so rescan.
1084      */
1085     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
1086     bus_generic_attach(bus);
1087
1088     /* Attach wake sysctls. */
1089     acpi_wake_sysctl_walk(bus);
1090
1091     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
1092     return_VOID;
1093 }
1094
1095 /*
1096  * Evaluate a child device and determine whether we might attach a device to
1097  * it.
1098  */
1099 static ACPI_STATUS
1100 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
1101 {
1102     ACPI_OBJECT_TYPE    type;
1103     device_t            child, bus = (device_t)context;
1104
1105     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1106
1107     /* Skip this device if we think we'll have trouble with it. */
1108     if (acpi_avoid(handle))
1109         return_ACPI_STATUS (AE_OK);
1110
1111     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
1112         switch(type) {
1113         case ACPI_TYPE_DEVICE:
1114         case ACPI_TYPE_PROCESSOR:
1115         case ACPI_TYPE_THERMAL:
1116         case ACPI_TYPE_POWER:
1117             if (acpi_disabled("children"))
1118                 break;
1119
1120             /* 
1121              * Create a placeholder device for this node.  Sort the placeholder
1122              * so that the probe/attach passes will run breadth-first.
1123              */
1124             ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n",
1125                              acpi_name(handle)));
1126             child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
1127             if (child == NULL)
1128                 break;
1129             acpi_set_handle(child, handle);
1130
1131             /* Check if the device can generate wake events. */
1132             if (ACPI_SUCCESS(AcpiEvaluateObject(handle, "_PRW", NULL, NULL)))
1133                 device_set_flags(child, ACPI_FLAG_WAKE_CAPABLE);
1134
1135             /*
1136              * Check that the device is present.  If it's not present,
1137              * leave it disabled (so that we have a device_t attached to
1138              * the handle, but we don't probe it).
1139              */
1140             if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1141                 device_disable(child);
1142                 break;
1143             }
1144
1145             /*
1146              * Get the device's resource settings and attach them.
1147              * Note that if the device has _PRS but no _CRS, we need
1148              * to decide when it's appropriate to try to configure the
1149              * device.  Ignore the return value here; it's OK for the
1150              * device not to have any resources.
1151              */
1152             acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
1153
1154             /* If we're debugging, probe/attach now rather than later */
1155             ACPI_DEBUG_EXEC(device_probe_and_attach(child));
1156             break;
1157         }
1158     }
1159
1160     return_ACPI_STATUS (AE_OK);
1161 }
1162
1163 static void
1164 acpi_shutdown_pre_sync(void *arg, int howto)
1165 {
1166     struct acpi_softc *sc = arg;
1167
1168     ACPI_ASSERTLOCK;
1169
1170     /*
1171      * Disable all ACPI events before soft off, otherwise the system
1172      * will be turned on again on some laptops.
1173      *
1174      * XXX this should probably be restricted to masking some events just
1175      *     before powering down, since we may still need ACPI during the
1176      *     shutdown process.
1177      */
1178     if (sc->acpi_disable_on_poweroff)
1179         acpi_Disable(sc);
1180 }
1181
1182 static void
1183 acpi_shutdown_final(void *arg, int howto)
1184 {
1185     ACPI_STATUS status;
1186     ACPI_ASSERTLOCK;
1187
1188     /*
1189      * If powering off, run the actual shutdown code on each processor.
1190      * It will only perform the shutdown on the BSP.  Some chipsets do
1191      * not power off the system correctly if called from an AP.
1192      */
1193     if ((howto & RB_POWEROFF) != 0) {
1194         status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
1195         if (ACPI_FAILURE(status)) {
1196             printf("AcpiEnterSleepStatePrep failed - %s\n",
1197                    AcpiFormatException(status));
1198             return;
1199         }
1200         printf("Powering system off using ACPI\n");
1201 #ifdef notyet
1202         smp_rendezvous(NULL, acpi_shutdown_poweroff, NULL, NULL);
1203 #else
1204         acpi_shutdown_poweroff(NULL);
1205 #endif /* notyet */
1206     } else {
1207         printf("Shutting down ACPI\n");
1208         AcpiTerminate();
1209     }
1210 }
1211
1212 /*
1213  * Since this function may be called with locks held or in an unknown
1214  * context, it cannot allocate memory, acquire locks, sleep, etc.
1215  */
1216 static void
1217 acpi_shutdown_poweroff(void *arg)
1218 {
1219     ACPI_STATUS status;
1220
1221     ACPI_ASSERTLOCK;
1222
1223     /* Only attempt to power off if this is the BSP (cpuid 0). */
1224     if (mdcpu->mi.gd_cpuid != 0)
1225         return;
1226
1227     ACPI_DISABLE_IRQS();
1228     status = AcpiEnterSleepState(ACPI_STATE_S5);
1229     if (ACPI_FAILURE(status)) {
1230         printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
1231     } else {
1232         DELAY(1000000);
1233         printf("ACPI power-off failed - timeout\n");
1234     }
1235 }
1236
1237 static void
1238 acpi_enable_fixed_events(struct acpi_softc *sc)
1239 {
1240     static int  first_time = 1;
1241
1242     ACPI_ASSERTLOCK;
1243
1244     /* Enable and clear fixed events and install handlers. */
1245     if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->PwrButton == 0) {
1246         AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
1247         AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
1248                                      acpi_event_power_button_sleep, sc);
1249         if (first_time)
1250             device_printf(sc->acpi_dev, "Power Button (fixed)\n");
1251     }
1252     if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->SleepButton == 0) {
1253         AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
1254         AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
1255                                      acpi_event_sleep_button_sleep, sc);
1256         if (first_time)
1257             device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
1258     }
1259
1260     first_time = 0;
1261 }
1262
1263 /*
1264  * Returns true if the device is actually present and should
1265  * be attached to.  This requires the present, enabled, UI-visible 
1266  * and diagnostics-passed bits to be set.
1267  */
1268 BOOLEAN
1269 acpi_DeviceIsPresent(device_t dev)
1270 {
1271     ACPI_DEVICE_INFO    *devinfo;
1272     ACPI_HANDLE         h;
1273     ACPI_BUFFER         buf;
1274     ACPI_STATUS         error;
1275     int                 ret;
1276
1277     ACPI_ASSERTLOCK;
1278     
1279     ret = FALSE;
1280     if ((h = acpi_get_handle(dev)) == NULL)
1281         return (FALSE);
1282     buf.Pointer = NULL;
1283     buf.Length = ACPI_ALLOCATE_BUFFER;
1284     error = AcpiGetObjectInfo(h, &buf);
1285     if (ACPI_FAILURE(error))
1286         return (FALSE);
1287     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1288
1289     /* If no _STA method, must be present */
1290     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1291         ret = TRUE;
1292
1293     /* Return true for 'present' and 'functioning' */
1294     if ((devinfo->CurrentStatus & 0x9) == 0x9)
1295         ret = TRUE;
1296
1297     AcpiOsFree(buf.Pointer);
1298     return (ret);
1299 }
1300
1301 /*
1302  * Returns true if the battery is actually present and inserted.
1303  */
1304 BOOLEAN
1305 acpi_BatteryIsPresent(device_t dev)
1306 {
1307     ACPI_DEVICE_INFO    *devinfo;
1308     ACPI_HANDLE         h;
1309     ACPI_BUFFER         buf;
1310     ACPI_STATUS         error;
1311     int                 ret;
1312
1313     ACPI_ASSERTLOCK;
1314     
1315     ret = FALSE;
1316     if ((h = acpi_get_handle(dev)) == NULL)
1317         return (FALSE);
1318     buf.Pointer = NULL;
1319     buf.Length = ACPI_ALLOCATE_BUFFER;
1320     error = AcpiGetObjectInfo(h, &buf);
1321     if (ACPI_FAILURE(error))
1322         return (FALSE);
1323     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1324
1325     /* If no _STA method, must be present */
1326     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1327         ret = TRUE;
1328
1329     /* Return true for 'present' and 'functioning' */
1330     if ((devinfo->CurrentStatus & 0x19) == 0x19)
1331         ret = TRUE;
1332
1333     AcpiOsFree(buf.Pointer);
1334     return (ret);
1335 }
1336
1337 /*
1338  * Match a HID string against a device
1339  */
1340 BOOLEAN
1341 acpi_MatchHid(device_t dev, char *hid) 
1342 {
1343     ACPI_DEVICE_INFO    *devinfo;
1344     ACPI_HANDLE         h;
1345     ACPI_BUFFER         buf;
1346     ACPI_STATUS         error;
1347     int                 ret, i;
1348
1349     ACPI_ASSERTLOCK;
1350
1351     ret = FALSE;
1352     if (hid == NULL)
1353         return (FALSE);
1354     if ((h = acpi_get_handle(dev)) == NULL)
1355         return (FALSE);
1356     buf.Pointer = NULL;
1357     buf.Length = ACPI_ALLOCATE_BUFFER;
1358     error = AcpiGetObjectInfo(h, &buf);
1359     if (ACPI_FAILURE(error))
1360         return (FALSE);
1361     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1362
1363     if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
1364         strcmp(hid, devinfo->HardwareId.Value) == 0)
1365             ret = TRUE;
1366     else if ((devinfo->Valid & ACPI_VALID_CID) != 0) {
1367         for (i = 0; i < devinfo->CompatibilityId.Count; i++) {
1368             if (strcmp(hid, devinfo->CompatibilityId.Id[i].Value) == 0) {
1369                 ret = TRUE;
1370                 break;
1371             }
1372         }
1373     }
1374
1375     AcpiOsFree(buf.Pointer);
1376     return (ret);
1377 }
1378
1379 /*
1380  * Return the handle of a named object within our scope, ie. that of (parent)
1381  * or one if its parents.
1382  */
1383 ACPI_STATUS
1384 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1385 {
1386     ACPI_HANDLE         r;
1387     ACPI_STATUS         status;
1388
1389     ACPI_ASSERTLOCK;
1390
1391     /* Walk back up the tree to the root */
1392     for (;;) {
1393         status = AcpiGetHandle(parent, path, &r);
1394         if (ACPI_SUCCESS(status)) {
1395             *result = r;
1396             return (AE_OK);
1397         }
1398         if (status != AE_NOT_FOUND)
1399             return (AE_OK);
1400         if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1401             return (AE_NOT_FOUND);
1402         parent = r;
1403     }
1404 }
1405
1406 /* Find the difference between two PM tick counts. */
1407 uint32_t
1408 acpi_TimerDelta(uint32_t end, uint32_t start)
1409 {
1410     uint32_t delta;
1411
1412     if (end >= start)
1413         delta = end - start;
1414     else if (AcpiGbl_FADT->TmrValExt == 0)
1415         delta = ((0x00FFFFFF - start) + end + 1) & 0x00FFFFFF;
1416     else
1417         delta = ((0xFFFFFFFF - start) + end + 1);
1418     return (delta);
1419 }
1420
1421 /*
1422  * Allocate a buffer with a preset data size.
1423  */
1424 ACPI_BUFFER *
1425 acpi_AllocBuffer(int size)
1426 {
1427     ACPI_BUFFER *buf;
1428
1429     buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_INTWAIT);
1430     buf->Length = size;
1431     buf->Pointer = (void *)(buf + 1);
1432     return (buf);
1433 }
1434
1435 ACPI_STATUS
1436 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
1437 {
1438     ACPI_OBJECT arg1;
1439     ACPI_OBJECT_LIST args;
1440
1441     ACPI_ASSERTLOCK;
1442
1443     arg1.Type = ACPI_TYPE_INTEGER;
1444     arg1.Integer.Value = number;
1445     args.Count = 1;
1446     args.Pointer = &arg1;
1447
1448     return (AcpiEvaluateObject(handle, path, &args, NULL));
1449 }
1450
1451 /*
1452  * Evaluate a path that should return an integer.
1453  */
1454 ACPI_STATUS
1455 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
1456 {
1457     ACPI_STATUS status;
1458     ACPI_BUFFER buf;
1459     ACPI_OBJECT param;
1460
1461     ACPI_ASSERTLOCK;
1462
1463     if (handle == NULL)
1464         handle = ACPI_ROOT_OBJECT;
1465
1466     /*
1467      * Assume that what we've been pointed at is an Integer object, or
1468      * a method that will return an Integer.
1469      */
1470     buf.Pointer = &param;
1471     buf.Length = sizeof(param);
1472     status = AcpiEvaluateObject(handle, path, NULL, &buf);
1473     if (ACPI_SUCCESS(status)) {
1474         if (param.Type == ACPI_TYPE_INTEGER)
1475             *number = param.Integer.Value;
1476         else
1477             status = AE_TYPE;
1478     }
1479
1480     /* 
1481      * In some applications, a method that's expected to return an Integer
1482      * may instead return a Buffer (probably to simplify some internal
1483      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1484      * convert it into an Integer as best we can.
1485      *
1486      * This is a hack.
1487      */
1488     if (status == AE_BUFFER_OVERFLOW) {
1489         if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1490             status = AE_NO_MEMORY;
1491         } else {
1492             status = AcpiEvaluateObject(handle, path, NULL, &buf);
1493             if (ACPI_SUCCESS(status))
1494                 status = acpi_ConvertBufferToInteger(&buf, number);
1495             AcpiOsFree(buf.Pointer);
1496         }
1497     }
1498     return (status);
1499 }
1500
1501 ACPI_STATUS
1502 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
1503 {
1504     ACPI_OBJECT *p;
1505     UINT8       *val;
1506     int         i;
1507
1508     p = (ACPI_OBJECT *)bufp->Pointer;
1509     if (p->Type == ACPI_TYPE_INTEGER) {
1510         *number = p->Integer.Value;
1511         return (AE_OK);
1512     }
1513     if (p->Type != ACPI_TYPE_BUFFER)
1514         return (AE_TYPE);
1515     if (p->Buffer.Length > sizeof(int))
1516         return (AE_BAD_DATA);
1517
1518     *number = 0;
1519     val = p->Buffer.Pointer;
1520     for (i = 0; i < p->Buffer.Length; i++)
1521         *number += val[i] << (i * 8);
1522     return (AE_OK);
1523 }
1524
1525 /*
1526  * Iterate over the elements of an a package object, calling the supplied
1527  * function for each element.
1528  *
1529  * XXX possible enhancement might be to abort traversal on error.
1530  */
1531 ACPI_STATUS
1532 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
1533         void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
1534 {
1535     ACPI_OBJECT *comp;
1536     int         i;
1537     
1538     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
1539         return (AE_BAD_PARAMETER);
1540
1541     /* Iterate over components */
1542     i = 0;
1543     comp = pkg->Package.Elements;
1544     for (; i < pkg->Package.Count; i++, comp++)
1545         func(comp, arg);
1546
1547     return (AE_OK);
1548 }
1549
1550 /*
1551  * Find the (index)th resource object in a set.
1552  */
1553 ACPI_STATUS
1554 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1555 {
1556     ACPI_RESOURCE       *rp;
1557     int                 i;
1558
1559     rp = (ACPI_RESOURCE *)buf->Pointer;
1560     i = index;
1561     while (i-- > 0) {
1562         /* Range check */       
1563         if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1564             return (AE_BAD_PARAMETER);
1565
1566         /* Check for terminator */
1567         if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1568             return (AE_NOT_FOUND);
1569         rp = ACPI_NEXT_RESOURCE(rp);
1570     }
1571     if (resp != NULL)
1572         *resp = rp;
1573
1574     return (AE_OK);
1575 }
1576
1577 /*
1578  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1579  *
1580  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1581  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1582  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1583  * resources.
1584  */
1585 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE       512
1586
1587 ACPI_STATUS
1588 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1589 {
1590     ACPI_RESOURCE       *rp;
1591     void                *newp;
1592     
1593     /* Initialise the buffer if necessary. */
1594     if (buf->Pointer == NULL) {
1595         buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1596         if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1597             return (AE_NO_MEMORY);
1598         rp = (ACPI_RESOURCE *)buf->Pointer;
1599         rp->Id = ACPI_RSTYPE_END_TAG;
1600         rp->Length = 0;
1601     }
1602     if (res == NULL)
1603         return (AE_OK);
1604     
1605     /*
1606      * Scan the current buffer looking for the terminator.
1607      * This will either find the terminator or hit the end
1608      * of the buffer and return an error.
1609      */
1610     rp = (ACPI_RESOURCE *)buf->Pointer;
1611     for (;;) {
1612         /* Range check, don't go outside the buffer */
1613         if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1614             return (AE_BAD_PARAMETER);
1615         if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1616             break;
1617         rp = ACPI_NEXT_RESOURCE(rp);
1618     }
1619
1620     /*
1621      * Check the size of the buffer and expand if required.
1622      *
1623      * Required size is:
1624      *  size of existing resources before terminator + 
1625      *  size of new resource and header +
1626      *  size of terminator.
1627      *
1628      * Note that this loop should really only run once, unless
1629      * for some reason we are stuffing a *really* huge resource.
1630      */
1631     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) + 
1632             res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1633             ACPI_RESOURCE_LENGTH) >= buf->Length) {
1634         if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1635             return (AE_NO_MEMORY);
1636         bcopy(buf->Pointer, newp, buf->Length);
1637         rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1638                                ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1639         AcpiOsFree(buf->Pointer);
1640         buf->Pointer = newp;
1641         buf->Length += buf->Length;
1642     }
1643     
1644     /* Insert the new resource. */
1645     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1646     
1647     /* And add the terminator. */
1648     rp = ACPI_NEXT_RESOURCE(rp);
1649     rp->Id = ACPI_RSTYPE_END_TAG;
1650     rp->Length = 0;
1651
1652     return (AE_OK);
1653 }
1654
1655 /*
1656  * Set interrupt model.
1657  */
1658 ACPI_STATUS
1659 acpi_SetIntrModel(int model)
1660 {
1661     return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
1662 }
1663
1664 #define ACPI_MINIMUM_AWAKETIME  5
1665
1666 static void
1667 acpi_sleep_enable(void *arg)
1668 {
1669     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1670 }
1671
1672 /*
1673  * Set the system sleep state
1674  *
1675  * Currently we support S1-S5 but S4 is only S4BIOS
1676  */
1677 ACPI_STATUS
1678 acpi_SetSleepState(struct acpi_softc *sc, int state)
1679 {
1680     ACPI_STATUS status = AE_OK;
1681     UINT8       TypeA;
1682     UINT8       TypeB;
1683
1684     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1685     ACPI_ASSERTLOCK;
1686
1687     /* Avoid reentry if already attempting to suspend. */
1688     if (sc->acpi_sstate != ACPI_STATE_S0)
1689         return_ACPI_STATUS (AE_BAD_PARAMETER);
1690
1691     /* We recently woke up so don't suspend again for a while. */
1692     if (sc->acpi_sleep_disabled)
1693         return_ACPI_STATUS (AE_OK);
1694
1695     switch (state) {
1696     case ACPI_STATE_S1:
1697     case ACPI_STATE_S2:
1698     case ACPI_STATE_S3:
1699     case ACPI_STATE_S4:
1700         status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB);
1701         if (status == AE_NOT_FOUND) {
1702             device_printf(sc->acpi_dev,
1703                           "Sleep state S%d not supported by BIOS\n", state);
1704             break;
1705         } else if (ACPI_FAILURE(status)) {
1706             device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n",
1707                           AcpiFormatException(status));
1708             break;
1709         }
1710
1711         sc->acpi_sstate = state;
1712         sc->acpi_sleep_disabled = 1;
1713
1714         /* Disable all wake GPEs not appropriate for this state. */
1715         acpi_wake_limit_walk(state);
1716
1717         /* Inform all devices that we are going to sleep. */
1718         if (DEVICE_SUSPEND(root_bus) != 0) {
1719             /*
1720              * Re-wake the system.
1721              *
1722              * XXX note that a better two-pass approach with a 'veto' pass
1723              *     followed by a "real thing" pass would be better, but the
1724              *     current bus interface does not provide for this.
1725              */
1726             DEVICE_RESUME(root_bus);
1727             return_ACPI_STATUS (AE_ERROR);
1728         }
1729
1730         status = AcpiEnterSleepStatePrep(state);
1731         if (ACPI_FAILURE(status)) {
1732             device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1733                           AcpiFormatException(status));
1734             break;
1735         }
1736
1737         if (sc->acpi_sleep_delay > 0)
1738             DELAY(sc->acpi_sleep_delay * 1000000);
1739
1740         if (state != ACPI_STATE_S1) {
1741             acpi_sleep_machdep(sc, state);
1742
1743             /* AcpiEnterSleepState() may be incomplete, unlock if locked. */
1744             if (AcpiGbl_MutexInfo[ACPI_MTX_HARDWARE].OwnerId !=
1745                 ACPI_MUTEX_NOT_ACQUIRED) {
1746
1747                 AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1748             }
1749
1750             /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1751             if (state == ACPI_STATE_S4)
1752                 AcpiEnable();
1753         } else {
1754             status = AcpiEnterSleepState((UINT8)state);
1755             if (ACPI_FAILURE(status)) {
1756                 device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
1757                               AcpiFormatException(status));
1758                 break;
1759             }
1760         }
1761         AcpiLeaveSleepState((UINT8)state);
1762         DEVICE_RESUME(root_bus);
1763         sc->acpi_sstate = ACPI_STATE_S0;
1764         acpi_enable_fixed_events(sc);
1765         break;
1766     case ACPI_STATE_S5:
1767         /*
1768          * Shut down cleanly and power off.  This will call us back through the
1769          * shutdown handlers.
1770          */
1771         shutdown_nice(RB_POWEROFF);
1772         break;
1773     case ACPI_STATE_S0:
1774     default:
1775         status = AE_BAD_PARAMETER;
1776         break;
1777     }
1778
1779     /* Disable a second sleep request for a short period */
1780     if (sc->acpi_sleep_disabled)
1781         callout_reset(&sc->acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME,
1782                       acpi_sleep_enable, sc);
1783
1784     return_ACPI_STATUS (status);
1785 }
1786
1787 /* Initialize a device's wake GPE. */
1788 int
1789 acpi_wake_init(device_t dev, int type)
1790 {
1791     struct acpi_prw_data prw;
1792
1793     /* Check that the device can wake the system. */
1794     if ((device_get_flags(dev) & ACPI_FLAG_WAKE_CAPABLE) == 0)
1795         return (ENXIO);
1796
1797     /* Evaluate _PRW to find the GPE. */
1798     if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
1799         return (ENXIO);
1800
1801     /* Set the requested type for the GPE (runtime, wake, or both). */
1802     if (ACPI_FAILURE(AcpiSetGpeType(prw.gpe_handle, prw.gpe_bit, type))) {
1803         device_printf(dev, "set GPE type failed\n");
1804         return (ENXIO);
1805     }
1806
1807     return (0);
1808 }
1809
1810 /* Enable or disable the device's wake GPE. */
1811 int
1812 acpi_wake_set_enable(device_t dev, int enable)
1813 {
1814     struct acpi_prw_data prw;
1815     ACPI_HANDLE handle;
1816     ACPI_STATUS status;
1817     int flags;
1818
1819     /* Make sure the device supports waking the system. */
1820     flags = device_get_flags(dev);
1821     handle = acpi_get_handle(dev);
1822     if ((flags & ACPI_FLAG_WAKE_CAPABLE) == 0 || handle == NULL)
1823         return (ENXIO);
1824
1825     /* Evaluate _PRW to find the GPE. */
1826     if (acpi_parse_prw(handle, &prw) != 0)
1827         return (ENXIO);
1828
1829     if (enable) {
1830         status = AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1831         if (ACPI_FAILURE(status)) {
1832             device_printf(dev, "enable wake failed\n");
1833             return (ENXIO);
1834         }
1835         device_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
1836     } else {
1837         status = AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1838         if (ACPI_FAILURE(status)) {
1839             device_printf(dev, "disable wake failed\n");
1840             return (ENXIO);
1841         }
1842         device_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
1843     }
1844
1845     return (0);
1846 }
1847
1848 /* Configure a device's GPE appropriately for the new sleep state. */
1849 int
1850 acpi_wake_sleep_prep(device_t dev, int sstate)
1851 {
1852     struct acpi_prw_data prw;
1853     ACPI_HANDLE handle;
1854     int flags;
1855
1856     /* Check that this is an ACPI device and get its GPE. */
1857     flags = device_get_flags(dev);
1858     handle = acpi_get_handle(dev);
1859     if ((flags & ACPI_FLAG_WAKE_CAPABLE) == 0 || handle == NULL)
1860         return (ENXIO);
1861
1862     /* Evaluate _PRW to find the GPE. */
1863     if (acpi_parse_prw(handle, &prw) != 0)
1864         return (ENXIO);
1865
1866     /*
1867      * TBD: All Power Resources referenced by elements 2 through N
1868      *      of the _PRW object are put into the ON state.
1869      */
1870
1871     /*
1872      * If the user requested that this device wake the system and the next
1873      * sleep state is valid for this GPE, enable it and the device's wake
1874      * capability.  The sleep state must be less than (i.e., higher power)
1875      * or equal to the value specified by _PRW.  Return early, leaving
1876      * the appropriate power resources enabled.
1877      */
1878     if ((flags & ACPI_FLAG_WAKE_ENABLED) != 0 &&
1879         sstate <= prw.lowest_wake) {
1880         if (bootverbose)
1881             device_printf(dev, "wake_prep enabled gpe %#x for state %d\n",
1882                 prw.gpe_bit, sstate);
1883         AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1884         acpi_SetInteger(handle, "_PSW", 1);
1885         return (0);
1886     }
1887
1888     /*
1889      * If the device wake was disabled or this sleep state is too low for
1890      * this device, disable its wake capability and GPE.
1891      */
1892     AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1893     acpi_SetInteger(handle, "_PSW", 0);
1894     if (bootverbose)
1895         device_printf(dev, "wake_prep disabled gpe %#x for state %d\n",
1896             prw.gpe_bit, sstate);
1897
1898     /*
1899      * TBD: All Power Resources referenced by elements 2 through N
1900      *      of the _PRW object are put into the OFF state.
1901      */
1902
1903     return (0);
1904 }
1905
1906 /* Re-enable GPEs after wake. */
1907 int
1908 acpi_wake_run_prep(device_t dev)
1909 {
1910     struct acpi_prw_data prw;
1911     ACPI_HANDLE handle;
1912     int flags;
1913
1914     /* Check that this is an ACPI device and get its GPE. */
1915     flags = device_get_flags(dev);
1916     handle = acpi_get_handle(dev);
1917     if ((flags & ACPI_FLAG_WAKE_CAPABLE) == 0 || handle == NULL)
1918         return (ENXIO);
1919
1920     /* Evaluate _PRW to find the GPE. */
1921     if (acpi_parse_prw(handle, &prw) != 0)
1922         return (ENXIO);
1923
1924     /*
1925      * TBD: Be sure all Power Resources referenced by elements 2 through N
1926      *      of the _PRW object are in the ON state.
1927      */
1928
1929     /* Disable wake capability and if the user requested, enable the GPE. */
1930     acpi_SetInteger(handle, "_PSW", 0);
1931     if ((flags & ACPI_FLAG_WAKE_ENABLED) != 0)
1932         AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1933     return (0);
1934 }
1935
1936 static ACPI_STATUS
1937 acpi_wake_limit(ACPI_HANDLE h, UINT32 level, void *context, void **status)
1938 {
1939     struct acpi_prw_data prw;
1940     int *sstate;
1941
1942     /* It's ok not to have _PRW if the device can't wake the system. */
1943     if (acpi_parse_prw(h, &prw) != 0)
1944         return (AE_OK);
1945
1946     sstate = (int *)context;
1947     if (*sstate > prw.lowest_wake)
1948         AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1949
1950     return (AE_OK);
1951 }
1952
1953 /* Walk all system devices, disabling them if necessary for sstate. */
1954 static int
1955 acpi_wake_limit_walk(int sstate)
1956 {
1957     ACPI_HANDLE sb_handle;
1958
1959     if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
1960         AcpiWalkNamespace(ACPI_TYPE_ANY, sb_handle, 100,
1961             acpi_wake_limit, &sstate, NULL);
1962     return (0);
1963 }
1964
1965 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
1966 static int
1967 acpi_wake_sysctl_walk(device_t dev)
1968 {
1969     int error, i, numdevs;
1970     device_t *devlist;
1971     device_t child;
1972
1973     error = device_get_children(dev, &devlist, &numdevs);
1974     if (error != 0 || numdevs == 0)
1975         return (error);
1976     for (i = 0; i < numdevs; i++) {
1977         child = devlist[i];
1978         if (!device_is_attached(child))
1979             continue;
1980         if (device_get_flags(child) & ACPI_FLAG_WAKE_CAPABLE) {
1981 #ifdef dfly_notyet
1982             SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
1983                 SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
1984                 "wake", CTLTYPE_INT | CTLFLAG_RW, child, 0,
1985                 acpi_wake_set_sysctl, "I", "Device set to wake the system");
1986 #endif /* dfly_notyet */
1987         }
1988         acpi_wake_sysctl_walk(child);
1989     }
1990     free(devlist, M_TEMP);
1991
1992     return (0);
1993 }
1994
1995 /* Enable or disable wake from userland. */
1996 static int
1997 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
1998 {
1999     int enable, error;
2000     device_t dev;
2001
2002     dev = (device_t)arg1;
2003     enable = (device_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
2004
2005     error = sysctl_handle_int(oidp, &enable, 0, req);
2006     if (error != 0 || req->newptr == NULL)
2007         return (error);
2008     if (enable != 0 && enable != 1)
2009         return (EINVAL);
2010
2011     return (acpi_wake_set_enable(dev, enable));
2012 }
2013
2014 /* Parse a device's _PRW into a structure. */
2015 static int
2016 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
2017 {
2018     ACPI_STATUS                 status;
2019     ACPI_BUFFER                 prw_buffer;
2020     ACPI_OBJECT                 *res, *res2;
2021     int error;
2022
2023     if (h == NULL || prw == NULL)
2024         return (EINVAL);
2025
2026     /*
2027      * The _PRW object (7.2.9) is only required for devices that have the
2028      * ability to wake the system from a sleeping state.
2029      */
2030     error = EINVAL;
2031     prw_buffer.Pointer = NULL;
2032     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
2033     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
2034     if (ACPI_FAILURE(status))
2035         return (ENOENT);
2036     res = (ACPI_OBJECT *)prw_buffer.Pointer;
2037     if (res == NULL)
2038         return (ENOENT);
2039     if (!ACPI_PKG_VALID(res, 2))
2040         goto out;
2041
2042     /*
2043      * Element 1 of the _PRW object:
2044      * The lowest power system sleeping state that can be entered while still
2045      * providing wake functionality.  The sleeping state being entered must
2046      * be less than (i.e., higher power) or equal to this value.
2047      */
2048     if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
2049         goto out;
2050
2051     /*
2052      * Element 0 of the _PRW object:
2053      */
2054     switch (res->Package.Elements[0].Type) {
2055     case ACPI_TYPE_INTEGER:
2056         /*
2057          * If the data type of this package element is numeric, then this
2058          * _PRW package element is the bit index in the GPEx_EN, in the
2059          * GPE blocks described in the FADT, of the enable bit that is
2060          * enabled for the wake event.
2061          */
2062         prw->gpe_handle = NULL;
2063         prw->gpe_bit = res->Package.Elements[0].Integer.Value;
2064         error = 0;
2065         break;
2066     case ACPI_TYPE_PACKAGE:
2067         /*
2068          * If the data type of this package element is a package, then this
2069          * _PRW package element is itself a package containing two
2070          * elements.  The first is an object reference to the GPE Block
2071          * device that contains the GPE that will be triggered by the wake
2072          * event.  The second element is numeric and it contains the bit
2073          * index in the GPEx_EN, in the GPE Block referenced by the
2074          * first element in the package, of the enable bit that is enabled for
2075          * the wake event.
2076          *
2077          * For example, if this field is a package then it is of the form:
2078          * Package() {\_SB.PCI0.ISA.GPE, 2}
2079          */
2080         res2 = &res->Package.Elements[0];
2081         if (!ACPI_PKG_VALID(res2, 2))
2082             goto out;
2083         prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
2084         if (prw->gpe_handle == NULL)
2085             goto out;
2086         if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
2087             goto out;
2088         error = 0;
2089         break;
2090     default:
2091         goto out;
2092     }
2093
2094     /* XXX No power resource handling yet. */
2095     prw->power_res = NULL;
2096
2097 out:
2098     if (prw_buffer.Pointer != NULL)
2099         AcpiOsFree(prw_buffer.Pointer);
2100     return (error);
2101 }
2102
2103 /*
2104  * Enable/Disable ACPI
2105  */
2106 ACPI_STATUS
2107 acpi_Enable(struct acpi_softc *sc)
2108 {
2109     ACPI_STATUS status;
2110     u_int32_t   flags;
2111
2112     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2113     ACPI_ASSERTLOCK;
2114
2115     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
2116             ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
2117     if (!sc->acpi_enabled)
2118         status = AcpiEnableSubsystem(flags);
2119     else
2120         status = AE_OK;
2121
2122     if (status == AE_OK)
2123         sc->acpi_enabled = 1;
2124
2125     return_ACPI_STATUS (status);
2126 }
2127
2128 ACPI_STATUS
2129 acpi_Disable(struct acpi_softc *sc)
2130 {
2131     ACPI_STATUS status;
2132
2133     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2134     ACPI_ASSERTLOCK;
2135
2136     if (sc->acpi_enabled)
2137         status = AcpiDisable();
2138     else
2139         status = AE_OK;
2140
2141     if (status == AE_OK)
2142         sc->acpi_enabled = 0;
2143
2144     return_ACPI_STATUS (status);
2145 }
2146
2147 /*
2148  * ACPI Event Handlers
2149  */
2150
2151 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
2152
2153 static void
2154 acpi_system_eventhandler_sleep(void *arg, int state)
2155 {
2156     ACPI_LOCK_DECL;
2157     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2158
2159     ACPI_LOCK;
2160     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
2161         acpi_SetSleepState((struct acpi_softc *)arg, state);
2162     ACPI_UNLOCK;
2163     return_VOID;
2164 }
2165
2166 static void
2167 acpi_system_eventhandler_wakeup(void *arg, int state)
2168 {
2169     ACPI_LOCK_DECL;
2170     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2171
2172     /* Well, what to do? :-) */
2173
2174     ACPI_LOCK;
2175     ACPI_UNLOCK;
2176
2177     return_VOID;
2178 }
2179
2180 /* 
2181  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
2182  */
2183 UINT32
2184 acpi_event_power_button_sleep(void *context)
2185 {
2186     struct acpi_softc   *sc = (struct acpi_softc *)context;
2187
2188     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2189
2190     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
2191
2192     return_VALUE (ACPI_INTERRUPT_HANDLED);
2193 }
2194
2195 UINT32
2196 acpi_event_power_button_wake(void *context)
2197 {
2198     struct acpi_softc   *sc = (struct acpi_softc *)context;
2199
2200     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2201
2202     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
2203
2204     return_VALUE (ACPI_INTERRUPT_HANDLED);
2205 }
2206
2207 UINT32
2208 acpi_event_sleep_button_sleep(void *context)
2209 {
2210     struct acpi_softc   *sc = (struct acpi_softc *)context;
2211
2212     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2213
2214     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
2215
2216     return_VALUE (ACPI_INTERRUPT_HANDLED);
2217 }
2218
2219 UINT32
2220 acpi_event_sleep_button_wake(void *context)
2221 {
2222     struct acpi_softc   *sc = (struct acpi_softc *)context;
2223
2224     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2225
2226     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
2227
2228     return_VALUE (ACPI_INTERRUPT_HANDLED);
2229 }
2230
2231 /*
2232  * XXX This is kinda ugly, and should not be here.
2233  */
2234 struct acpi_staticbuf {
2235     ACPI_BUFFER buffer;
2236     char        data[512];
2237 };
2238
2239 char *
2240 acpi_name(ACPI_HANDLE handle)
2241 {
2242     static struct acpi_staticbuf        buf;
2243
2244     ACPI_ASSERTLOCK;
2245
2246     buf.buffer.Length = 512;
2247     buf.buffer.Pointer = &buf.data[0];
2248
2249     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
2250         return (buf.buffer.Pointer);
2251
2252     return ("(unknown path)");
2253 }
2254
2255 /*
2256  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
2257  * parts of the namespace.
2258  */
2259 int
2260 acpi_avoid(ACPI_HANDLE handle)
2261 {
2262     char        *cp, *env, *np;
2263     int         len;
2264
2265     np = acpi_name(handle);
2266     if (*np == '\\')
2267         np++;
2268     if ((env = getenv("debug.acpi.avoid")) == NULL)
2269         return (0);
2270
2271     /* Scan the avoid list checking for a match */
2272     cp = env;
2273     for (;;) {
2274         while ((*cp != 0) && isspace(*cp))
2275             cp++;
2276         if (*cp == 0)
2277             break;
2278         len = 0;
2279         while ((cp[len] != 0) && !isspace(cp[len]))
2280             len++;
2281         if (!strncmp(cp, np, len)) {
2282             freeenv(env);
2283             return(1);
2284         }
2285         cp += len;
2286     }
2287     freeenv(env);
2288
2289     return (0);
2290 }
2291
2292 /*
2293  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
2294  */
2295 int
2296 acpi_disabled(char *subsys)
2297 {
2298     char        *cp, *env;
2299     int         len;
2300
2301     if ((env = getenv("debug.acpi.disabled")) == NULL)
2302         return (0);
2303     if (strcmp(env, "all") == 0) {
2304         freeenv(env);
2305         return (1);
2306     }
2307
2308     /* Scan the disable list, checking for a match. */
2309     cp = env;
2310     for (;;) {
2311         while (*cp != '\0' && isspace(*cp))
2312             cp++;
2313         if (*cp == '\0')
2314             break;
2315         len = 0;
2316         while (cp[len] != '\0' && !isspace(cp[len]))
2317             len++;
2318         if (strncmp(cp, subsys, len) == 0) {
2319             freeenv(env);
2320             return (1);
2321         }
2322         cp += len;
2323     }
2324     freeenv(env);
2325
2326     return (0);
2327 }
2328
2329 /*
2330  * Control interface.
2331  *
2332  * We multiplex ioctls for all participating ACPI devices here.  Individual 
2333  * drivers wanting to be accessible via /dev/acpi should use the
2334  * register/deregister interface to make their handlers visible.
2335  */
2336 struct acpi_ioctl_hook
2337 {
2338     TAILQ_ENTRY(acpi_ioctl_hook) link;
2339     u_long                       cmd;
2340     acpi_ioctl_fn                fn;
2341     void                         *arg;
2342 };
2343
2344 static TAILQ_HEAD(,acpi_ioctl_hook)     acpi_ioctl_hooks;
2345 static int                              acpi_ioctl_hooks_initted;
2346
2347 /*
2348  * Register an ioctl handler.
2349  */
2350 int
2351 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
2352 {
2353     struct acpi_ioctl_hook      *hp;
2354
2355     hp = malloc(sizeof(*hp), M_ACPIDEV, M_INTWAIT);
2356     hp->cmd = cmd;
2357     hp->fn = fn;
2358     hp->arg = arg;
2359     if (acpi_ioctl_hooks_initted == 0) {
2360         TAILQ_INIT(&acpi_ioctl_hooks);
2361         acpi_ioctl_hooks_initted = 1;
2362     }
2363     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
2364     return (0);
2365 }
2366
2367 /*
2368  * Deregister an ioctl handler.
2369  */
2370 void    
2371 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
2372 {
2373     struct acpi_ioctl_hook      *hp;
2374
2375     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
2376         if ((hp->cmd == cmd) && (hp->fn == fn))
2377             break;
2378
2379     if (hp != NULL) {
2380         TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
2381         free(hp, M_ACPIDEV);
2382     }
2383 }
2384
2385 static int
2386 acpiopen(dev_t dev, int flag, int fmt, d_thread_t *td)
2387 {
2388     return (0);
2389 }
2390
2391 static int
2392 acpiclose(dev_t dev, int flag, int fmt, d_thread_t *td)
2393 {
2394     return (0);
2395 }
2396
2397 static int
2398 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
2399 {
2400     struct acpi_softc           *sc;
2401     struct acpi_ioctl_hook      *hp;
2402     int                         error, xerror, state;
2403     ACPI_LOCK_DECL;
2404
2405     ACPI_LOCK;
2406
2407     error = state = 0;
2408     sc = dev->si_drv1;
2409
2410     /*
2411      * Scan the list of registered ioctls, looking for handlers.
2412      */
2413     if (acpi_ioctl_hooks_initted) {
2414         TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
2415             if (hp->cmd == cmd) {
2416                 xerror = hp->fn(cmd, addr, hp->arg);
2417                 if (xerror != 0)
2418                     error = xerror;
2419                 goto out;
2420             }
2421         }
2422     }
2423
2424     /*
2425      * Core ioctls are not permitted for non-writable user.
2426      * Currently, other ioctls just fetch information.
2427      * Not changing system behavior.
2428      */
2429     if((flag & FWRITE) == 0)
2430         return (EPERM);
2431
2432     /* Core system ioctls. */
2433     switch (cmd) {
2434     case ACPIIO_ENABLE:
2435         if (ACPI_FAILURE(acpi_Enable(sc)))
2436             error = ENXIO;
2437         break;
2438     case ACPIIO_DISABLE:
2439         if (ACPI_FAILURE(acpi_Disable(sc)))
2440             error = ENXIO;
2441         break;
2442     case ACPIIO_SETSLPSTATE:
2443         if (!sc->acpi_enabled) {
2444             error = ENXIO;
2445             break;
2446         }
2447         state = *(int *)addr;
2448         if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
2449             if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
2450                 error = EINVAL;
2451         } else {
2452             error = EINVAL;
2453         }
2454         break;
2455     default:
2456         if (error == 0)
2457             error = EINVAL;
2458         break;
2459     }
2460
2461 out:
2462     ACPI_UNLOCK;
2463     return (error);
2464 }
2465
2466 static int
2467 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2468 {
2469     char sleep_state[4];
2470     char buf[16];
2471     int error;
2472     UINT8 state, TypeA, TypeB;
2473
2474     buf[0] = '\0';
2475     for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX + 1; state++) {
2476         if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
2477             sprintf(sleep_state, "S%d ", state);
2478             strcat(buf, sleep_state);
2479         }
2480     }
2481     error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2482     return (error);
2483 }
2484
2485 static int
2486 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2487 {
2488     char sleep_state[10];
2489     int error;
2490     u_int new_state, old_state;
2491
2492     old_state = *(u_int *)oidp->oid_arg1;
2493     if (old_state > ACPI_S_STATES_MAX + 1) {
2494         strcpy(sleep_state, "unknown");
2495     } else {
2496         bzero(sleep_state, sizeof(sleep_state));
2497         strncpy(sleep_state, sleep_state_names[old_state],
2498                 sizeof(sleep_state_names[old_state]));
2499     }
2500     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
2501     if (error == 0 && req->newptr != NULL) {
2502         new_state = ACPI_STATE_S0;
2503         for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++) {
2504             if (strncmp(sleep_state, sleep_state_names[new_state],
2505                         sizeof(sleep_state)) == 0)
2506                 break;
2507         }
2508         if (new_state <= ACPI_S_STATES_MAX + 1) {
2509             if (new_state != old_state)
2510                 *(u_int *)oidp->oid_arg1 = new_state;
2511         } else {
2512             error = EINVAL;
2513         }
2514     }
2515
2516     return (error);
2517 }
2518
2519 /* Inform devctl(4) when we receive a Notify. */
2520 void
2521 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
2522 {
2523     char                notify_buf[16];
2524     ACPI_BUFFER         handle_buf;
2525     ACPI_STATUS         status;
2526
2527     if (subsystem == NULL)
2528         return;
2529
2530     handle_buf.Pointer = NULL;
2531     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
2532     status = AcpiNsHandleToPathname(h, &handle_buf);
2533     if (ACPI_FAILURE(status))
2534         return;
2535     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
2536 #if 0
2537     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
2538 #endif
2539     AcpiOsFree(handle_buf.Pointer);
2540 }
2541
2542 #ifdef ACPI_DEBUG
2543 /*
2544  * Support for parsing debug options from the kernel environment.
2545  *
2546  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
2547  * by specifying the names of the bits in the debug.acpi.layer and
2548  * debug.acpi.level environment variables.  Bits may be unset by 
2549  * prefixing the bit name with !.
2550  */
2551 struct debugtag
2552 {
2553     char        *name;
2554     UINT32      value;
2555 };
2556
2557 static struct debugtag  dbg_layer[] = {
2558     {"ACPI_UTILITIES",          ACPI_UTILITIES},
2559     {"ACPI_HARDWARE",           ACPI_HARDWARE},
2560     {"ACPI_EVENTS",             ACPI_EVENTS},
2561     {"ACPI_TABLES",             ACPI_TABLES},
2562     {"ACPI_NAMESPACE",          ACPI_NAMESPACE},
2563     {"ACPI_PARSER",             ACPI_PARSER},
2564     {"ACPI_DISPATCHER",         ACPI_DISPATCHER},
2565     {"ACPI_EXECUTER",           ACPI_EXECUTER},
2566     {"ACPI_RESOURCES",          ACPI_RESOURCES},
2567     {"ACPI_CA_DEBUGGER",        ACPI_CA_DEBUGGER},
2568     {"ACPI_OS_SERVICES",        ACPI_OS_SERVICES},
2569     {"ACPI_CA_DISASSEMBLER",    ACPI_CA_DISASSEMBLER},
2570     {"ACPI_ALL_COMPONENTS",     ACPI_ALL_COMPONENTS},
2571
2572     {"ACPI_AC_ADAPTER",         ACPI_AC_ADAPTER},
2573     {"ACPI_BATTERY",            ACPI_BATTERY},
2574     {"ACPI_BUS",                ACPI_BUS},
2575     {"ACPI_BUTTON",             ACPI_BUTTON},
2576     {"ACPI_EC",                 ACPI_EC},
2577     {"ACPI_FAN",                ACPI_FAN},
2578     {"ACPI_POWERRES",           ACPI_POWERRES},
2579     {"ACPI_PROCESSOR",          ACPI_PROCESSOR},
2580     {"ACPI_THERMAL",            ACPI_THERMAL},
2581     {"ACPI_TIMER",              ACPI_TIMER},
2582     {"ACPI_ALL_DRIVERS",        ACPI_ALL_DRIVERS},
2583     {NULL, 0}
2584 };
2585
2586 static struct debugtag dbg_level[] = {
2587     {"ACPI_LV_ERROR",           ACPI_LV_ERROR},
2588     {"ACPI_LV_WARN",            ACPI_LV_WARN},
2589     {"ACPI_LV_INIT",            ACPI_LV_INIT},
2590     {"ACPI_LV_DEBUG_OBJECT",    ACPI_LV_DEBUG_OBJECT},
2591     {"ACPI_LV_INFO",            ACPI_LV_INFO},
2592     {"ACPI_LV_ALL_EXCEPTIONS",  ACPI_LV_ALL_EXCEPTIONS},
2593
2594     /* Trace verbosity level 1 [Standard Trace Level] */
2595     {"ACPI_LV_INIT_NAMES",      ACPI_LV_INIT_NAMES},
2596     {"ACPI_LV_PARSE",           ACPI_LV_PARSE},
2597     {"ACPI_LV_LOAD",            ACPI_LV_LOAD},
2598     {"ACPI_LV_DISPATCH",        ACPI_LV_DISPATCH},
2599     {"ACPI_LV_EXEC",            ACPI_LV_EXEC},
2600     {"ACPI_LV_NAMES",           ACPI_LV_NAMES},
2601     {"ACPI_LV_OPREGION",        ACPI_LV_OPREGION},
2602     {"ACPI_LV_BFIELD",          ACPI_LV_BFIELD},
2603     {"ACPI_LV_TABLES",          ACPI_LV_TABLES},
2604     {"ACPI_LV_VALUES",          ACPI_LV_VALUES},
2605     {"ACPI_LV_OBJECTS",         ACPI_LV_OBJECTS},
2606     {"ACPI_LV_RESOURCES",       ACPI_LV_RESOURCES},
2607     {"ACPI_LV_USER_REQUESTS",   ACPI_LV_USER_REQUESTS},
2608     {"ACPI_LV_PACKAGE",         ACPI_LV_PACKAGE},
2609     {"ACPI_LV_VERBOSITY1",      ACPI_LV_VERBOSITY1},
2610
2611     /* Trace verbosity level 2 [Function tracing and memory allocation] */
2612     {"ACPI_LV_ALLOCATIONS",     ACPI_LV_ALLOCATIONS},
2613     {"ACPI_LV_FUNCTIONS",       ACPI_LV_FUNCTIONS},
2614     {"ACPI_LV_OPTIMIZATIONS",   ACPI_LV_OPTIMIZATIONS},
2615     {"ACPI_LV_VERBOSITY2",      ACPI_LV_VERBOSITY2},
2616     {"ACPI_LV_ALL",             ACPI_LV_ALL},
2617
2618     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2619     {"ACPI_LV_MUTEX",           ACPI_LV_MUTEX},
2620     {"ACPI_LV_THREADS",         ACPI_LV_THREADS},
2621     {"ACPI_LV_IO",              ACPI_LV_IO},
2622     {"ACPI_LV_INTERRUPTS",      ACPI_LV_INTERRUPTS},
2623     {"ACPI_LV_VERBOSITY3",      ACPI_LV_VERBOSITY3},
2624
2625     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2626     {"ACPI_LV_AML_DISASSEMBLE", ACPI_LV_AML_DISASSEMBLE},
2627     {"ACPI_LV_VERBOSE_INFO",    ACPI_LV_VERBOSE_INFO},
2628     {"ACPI_LV_FULL_TABLES",     ACPI_LV_FULL_TABLES},
2629     {"ACPI_LV_EVENTS",          ACPI_LV_EVENTS},
2630     {"ACPI_LV_VERBOSE",         ACPI_LV_VERBOSE},
2631     {NULL, 0}
2632 };    
2633
2634 static void
2635 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2636 {
2637     char        *ep;
2638     int         i, l;
2639     int         set;
2640
2641     while (*cp) {
2642         if (isspace(*cp)) {
2643             cp++;
2644             continue;
2645         }
2646         ep = cp;
2647         while (*ep && !isspace(*ep))
2648             ep++;
2649         if (*cp == '!') {
2650             set = 0;
2651             cp++;
2652             if (cp == ep)
2653                 continue;
2654         } else {
2655             set = 1;
2656         }
2657         l = ep - cp;
2658         for (i = 0; tag[i].name != NULL; i++) {
2659             if (!strncmp(cp, tag[i].name, l)) {
2660                 if (set)
2661                     *flag |= tag[i].value;
2662                 else
2663                     *flag &= ~tag[i].value;
2664             }
2665         }
2666         cp = ep;
2667     }
2668 }
2669
2670 static void
2671 acpi_set_debugging(void *junk)
2672 {
2673     char        *layer, *level;
2674
2675     if (cold) {
2676         AcpiDbgLayer = 0;
2677         AcpiDbgLevel = 0;
2678     }
2679
2680     layer = getenv("debug.acpi.layer");
2681     level = getenv("debug.acpi.level");
2682     if (layer == NULL && level == NULL)
2683         return;
2684
2685     printf("ACPI set debug");
2686     if (layer != NULL) {
2687         if (strcmp("NONE", layer) != 0)
2688             printf(" layer '%s'", layer);
2689         acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
2690         freeenv(layer);
2691     }
2692     if (level != NULL) {
2693         if (strcmp("NONE", level) != 0)
2694             printf(" level '%s'", level);
2695         acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
2696         freeenv(level);
2697     }
2698     printf("\n");
2699 }
2700 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
2701         NULL);
2702
2703 static int
2704 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
2705 {
2706     int          error, *dbg;
2707     struct       debugtag *tag;
2708     struct       sbuf sb;
2709
2710     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
2711         return (ENOMEM);
2712     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
2713         tag = &dbg_layer[0];
2714         dbg = &AcpiDbgLayer;
2715     } else {
2716         tag = &dbg_level[0];
2717         dbg = &AcpiDbgLevel;
2718     }
2719
2720     /* Get old values if this is a get request. */
2721     if (*dbg == 0) {
2722         sbuf_cpy(&sb, "NONE");
2723     } else if (req->newptr == NULL) {
2724         for (; tag->name != NULL; tag++) {
2725             if ((*dbg & tag->value) == tag->value)
2726                 sbuf_printf(&sb, "%s ", tag->name);
2727         }
2728     }
2729     sbuf_trim(&sb);
2730     sbuf_finish(&sb);
2731
2732     /* Copy out the old values to the user. */
2733     error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
2734     sbuf_delete(&sb);
2735
2736     /* If the user is setting a string, parse it. */
2737     if (error == 0 && req->newptr != NULL) {
2738         *dbg = 0;
2739         /* XXX setenv((char *)oidp->oid_arg1, (char *)req->newptr); */
2740         acpi_set_debugging(NULL);
2741     }
2742
2743     return (error);
2744 }
2745 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
2746             "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
2747 SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
2748             "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
2749 #endif
2750
2751 static int
2752 acpi_pm_func(u_long cmd, void *arg, ...)
2753 {
2754         int     state, acpi_state;
2755         int     error;
2756         struct  acpi_softc *sc;
2757         va_list ap;
2758
2759         error = 0;
2760         switch (cmd) {
2761         case POWER_CMD_SUSPEND:
2762                 sc = (struct acpi_softc *)arg;
2763                 if (sc == NULL) {
2764                         error = EINVAL;
2765                         goto out;
2766                 }
2767
2768                 va_start(ap, arg);
2769                 state = va_arg(ap, int);
2770                 va_end(ap);     
2771
2772                 switch (state) {
2773                 case POWER_SLEEP_STATE_STANDBY:
2774                         acpi_state = sc->acpi_standby_sx;
2775                         break;
2776                 case POWER_SLEEP_STATE_SUSPEND:
2777                         acpi_state = sc->acpi_suspend_sx;
2778                         break;
2779                 case POWER_SLEEP_STATE_HIBERNATE:
2780                         acpi_state = ACPI_STATE_S4;
2781                         break;
2782                 default:
2783                         error = EINVAL;
2784                         goto out;
2785                 }
2786
2787                 acpi_SetSleepState(sc, acpi_state);
2788                 break;
2789         default:
2790                 error = EINVAL;
2791                 goto out;
2792         }
2793
2794 out:
2795         return (error);
2796 }
2797
2798 static void
2799 acpi_pm_register(void *arg)
2800 {
2801     if (!cold || resource_disabled("acpi", 0))
2802         return;
2803
2804     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2805 }
2806
2807 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);