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