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