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