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