Rename malloc->kmalloc, free->kfree, and realloc->krealloc. Pass 1
[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.22 2006/09/05 00:55:36 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/device.h>
42 #include <sys/ioccom.h>
43 #include <sys/reboot.h>
44 #include <sys/sysctl.h>
45 #include <sys/ctype.h>
46 #include <sys/linker.h>
47 #include <sys/power.h>
48 #include <sys/sbuf.h>
49 #include <sys/thread2.h>
50
51 #include <machine/clock.h>
52 #include <machine/globaldata.h>
53 #include <machine/resource.h>
54 #include <machine/bus.h>
55 #include <sys/rman.h>
56 #include <bus/isa/isavar.h>
57
58 #include "acpi.h"
59 #include <dev/acpica5/acpivar.h>
60 #include <dev/acpica5/acpiio.h>
61 #include <acnamesp.h>
62
63 MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
64
65 /* Hooks for the ACPI CA debugging infrastructure */
66 #define _COMPONENT      ACPI_BUS
67 ACPI_MODULE_NAME("ACPI")
68
69 static d_open_t         acpiopen;
70 static d_close_t        acpiclose;
71 static d_ioctl_t        acpiioctl;
72
73 #define CDEV_MAJOR 152
74 static struct dev_ops acpi_ops = {
75         { "acpi", CDEV_MAJOR, 0 },
76         .d_open = acpiopen,
77         .d_close = acpiclose,
78         .d_ioctl = acpiioctl
79 };
80
81 #if __FreeBSD_version >= 500000
82 struct mtx      acpi_mutex;
83 #endif
84
85 struct acpi_quirks {
86     char        *OemId;
87     uint32_t    OemRevision;
88     char        *value;
89 };
90
91 #define ACPI_OEM_REV_ANY        0
92
93 static struct acpi_quirks acpi_quirks_table[] = {
94 #ifdef notyet
95     /* Bad PCI routing table.  Used on some SuperMicro boards. */
96     { "PTLTD ", 0x06040000, "pci_link" },
97 #endif
98
99     { NULL, 0, NULL }
100 };
101
102 static int      acpi_modevent(struct module *mod, int event, void *junk);
103 static int      acpi_identify(driver_t *driver, device_t parent);
104 static int      acpi_probe(device_t dev);
105 static int      acpi_attach(device_t dev);
106 static int      acpi_shutdown(device_t dev);
107 static void     acpi_quirks_set(void);
108 static device_t acpi_add_child(device_t bus, device_t parent, int order,
109                         const char *name, int unit);
110 static int      acpi_print_child(device_t bus, device_t child);
111 static int      acpi_read_ivar(device_t dev, device_t child, int index,
112                         uintptr_t *result);
113 static int      acpi_write_ivar(device_t dev, device_t child, int index,
114                         uintptr_t value);
115 static int      acpi_set_resource(device_t dev, device_t child, int type,
116                         int rid, u_long start, u_long count);
117 static int      acpi_get_resource(device_t dev, device_t child, int type,
118                         int rid, u_long *startp, u_long *countp);
119 static struct resource *acpi_alloc_resource(device_t bus, device_t child,
120                         int type, int *rid, u_long start, u_long end,
121                         u_long count, u_int flags);
122 static int      acpi_release_resource(device_t bus, device_t child, int type,
123                         int rid, struct resource *r);
124 static uint32_t acpi_isa_get_logicalid(device_t dev);
125 static int      acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
126 static int      acpi_isa_pnp_probe(device_t bus, device_t child,
127                         struct isa_pnp_id *ids);
128 static void     acpi_probe_children(device_t bus);
129 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
130                         void *context, void **status);
131 static void     acpi_shutdown_pre_sync(void *arg, int howto);
132 static void     acpi_shutdown_final(void *arg, int howto);
133 static void     acpi_shutdown_poweroff(void *arg);
134 static void     acpi_enable_fixed_events(struct acpi_softc *sc);
135 static int      acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw);
136 static ACPI_STATUS acpi_wake_limit(ACPI_HANDLE h, UINT32 level, void *context,
137                     void **status);
138 static int      acpi_wake_limit_walk(int sstate);
139 static int      acpi_wake_sysctl_walk(device_t dev);
140 #ifdef dfly_notyet
141 static int      acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS);
142 #endif
143 static void     acpi_system_eventhandler_sleep(void *arg, int state);
144 static void     acpi_system_eventhandler_wakeup(void *arg, int state);
145 static int      acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
146 static int      acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
147 static int      acpi_pm_func(u_long cmd, void *arg, ...);
148 static int      acpi_child_location_str_method(device_t acdev, device_t child,
149                                                char *buf, size_t buflen);
150 static int      acpi_child_pnpinfo_str_method(device_t acdev, device_t child,
151                                               char *buf, size_t buflen);
152
153 static device_method_t acpi_methods[] = {
154     /* Device interface */
155     DEVMETHOD(device_identify,          acpi_identify),
156     DEVMETHOD(device_probe,             acpi_probe),
157     DEVMETHOD(device_attach,            acpi_attach),
158     DEVMETHOD(device_shutdown,          acpi_shutdown),
159     DEVMETHOD(device_detach,            bus_generic_detach),
160     DEVMETHOD(device_suspend,           bus_generic_suspend),
161     DEVMETHOD(device_resume,            bus_generic_resume),
162
163     /* Bus interface */
164     DEVMETHOD(bus_add_child,            acpi_add_child),
165     DEVMETHOD(bus_print_child,          acpi_print_child),
166     DEVMETHOD(bus_read_ivar,            acpi_read_ivar),
167     DEVMETHOD(bus_write_ivar,           acpi_write_ivar),
168     DEVMETHOD(bus_set_resource,         acpi_set_resource),
169     DEVMETHOD(bus_get_resource,         acpi_get_resource),
170     DEVMETHOD(bus_alloc_resource,       acpi_alloc_resource),
171     DEVMETHOD(bus_release_resource,     acpi_release_resource),
172     DEVMETHOD(bus_child_pnpinfo_str,    acpi_child_pnpinfo_str_method),
173     DEVMETHOD(bus_child_location_str,   acpi_child_location_str_method),
174     DEVMETHOD(bus_driver_added,         bus_generic_driver_added),
175     DEVMETHOD(bus_activate_resource,    bus_generic_activate_resource),
176     DEVMETHOD(bus_deactivate_resource,  bus_generic_deactivate_resource),
177     DEVMETHOD(bus_setup_intr,           bus_generic_setup_intr),
178     DEVMETHOD(bus_teardown_intr,        bus_generic_teardown_intr),
179
180     /* ISA emulation */
181     DEVMETHOD(isa_pnp_probe,            acpi_isa_pnp_probe),
182
183     {0, 0}
184 };
185
186 static driver_t acpi_driver = {
187     "acpi",
188     acpi_methods,
189     sizeof(struct acpi_softc),
190 };
191
192 static devclass_t acpi_devclass;
193 DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
194 MODULE_VERSION(acpi, 1);
195
196 static const char* sleep_state_names[] = {
197     "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
198
199 SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RW, NULL, "ACPI debugging");
200 static char acpi_ca_version[12];
201 SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
202               acpi_ca_version, 0, "Version of Intel ACPI-CA");
203
204 /*
205  * Allow override of whether methods execute in parallel or not.
206  * Enable this for serial behavior, which fixes "AE_ALREADY_EXISTS"
207  * errors for AML that really can't handle parallel method execution.
208  * It is off by default since this breaks recursive methods and
209  * some IBMs use such code.
210  */
211 static int acpi_serialize_methods;
212 TUNABLE_INT("hw.acpi.serialize_methods", &acpi_serialize_methods);
213
214 /*
215  * ACPI can only be loaded as a module by the loader; activating it after
216  * system bootstrap time is not useful, and can be fatal to the system.
217  * It also cannot be unloaded, since the entire system bus heirarchy hangs
218  * off it.
219  */
220 static int
221 acpi_modevent(struct module *mod, int event, void *junk)
222 {
223     switch(event) {
224     case MOD_LOAD:
225         if (!cold) {
226             printf("The ACPI driver cannot be loaded after boot.\n");
227             return (EPERM);
228         }
229         break;
230     case MOD_UNLOAD:
231         if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
232             return (EBUSY);
233         break;
234     default:
235         break;
236     }
237     return (0);
238 }
239
240 /*
241  * Perform early initialization.
242  */
243 ACPI_STATUS
244 acpi_Startup(void)
245 {
246 #ifdef ACPI_DEBUGGER
247     char *debugpoint;
248 #endif
249     static int error, started = 0;
250
251     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
252
253     if (started)
254         return_VALUE (error);
255     started = 1;
256
257 #if __FreeBSD_version >= 500000
258     /* Initialise the ACPI mutex */
259     mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
260 #endif
261
262     /*
263      * Set the globals from our tunables.  This is needed because ACPI-CA
264      * uses UINT8 for some values and we have no tunable_byte.
265      */
266     AcpiGbl_AllMethodsSerialized = (UINT8)acpi_serialize_methods;
267
268     /* Start up the ACPI CA subsystem. */
269 #ifdef ACPI_DEBUGGER
270     debugpoint = kgetenv("debug.acpi.debugger");
271     if (debugpoint) {
272         if (!strcmp(debugpoint, "init"))
273             acpi_EnterDebugger();
274         freeenv(debugpoint);
275     }
276 #endif
277     if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
278         printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
279         return_VALUE (error);
280     }
281 #ifdef ACPI_DEBUGGER
282     debugpoint = kgetenv("debug.acpi.debugger");
283     if (debugpoint) {
284         if (!strcmp(debugpoint, "tables"))
285             acpi_EnterDebugger();
286         freeenv(debugpoint);
287     }
288 #endif
289
290     if (ACPI_FAILURE(error = AcpiLoadTables())) {
291         printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
292         return_VALUE(error);
293     }
294
295     /* Set up any quirks we have for this XSDT. */
296     acpi_quirks_set();
297     if (acpi_disabled("acpi"))
298         return_VALUE (AE_ERROR);
299
300     return_VALUE (AE_OK);
301 }
302
303 /*
304  * Detect ACPI, perform early initialisation
305  */
306 static int
307 acpi_identify(driver_t *driver, device_t parent)
308 {
309     device_t    child;
310
311     /*
312      * No sense rescanning an ACPI 'bus'.
313      */
314     if (device_get_state(parent) == DS_ATTACHED)
315         return(0);
316
317     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
318
319     if (!cold)
320         return (ENXIO);
321
322     /* Check that we haven't been disabled with a hint. */
323     if (resource_disabled("acpi", 0))
324         return (ENXIO);
325
326     /* Make sure we're not being doubly invoked. */
327     if (device_find_child(parent, "acpi", 0) != NULL)
328         return (ENXIO);
329
330     /* Initialize ACPI-CA. */
331     if (ACPI_FAILURE(acpi_Startup()))
332         return (ENXIO);
333
334     snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%#x", ACPI_CA_VERSION);
335
336     /* Attach the actual ACPI device. */
337     if ((child = BUS_ADD_CHILD(parent, parent, 0, "acpi", 0)) == NULL) {
338         device_printf(parent, "ACPI: could not attach\n");
339         return (ENXIO);
340     }
341     return (0);
342 }
343
344 /*
345  * Fetch some descriptive data from ACPI to put in our attach message
346  */
347 static int
348 acpi_probe(device_t dev)
349 {
350     ACPI_TABLE_HEADER   th;
351     char                buf[20];
352     int                 error;
353     struct sbuf         sb;
354     ACPI_STATUS         status;
355     ACPI_LOCK_DECL;
356
357     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
358
359     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
360         power_pm_get_type() != POWER_PM_TYPE_ACPI) {
361
362         device_printf(dev, "Other PM system enabled.\n");
363         return_VALUE(ENXIO);
364     }
365
366     ACPI_LOCK;
367
368     if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
369         device_printf(dev, "couldn't get XSDT header: %s\n",
370                       AcpiFormatException(status));
371         error = ENXIO;
372     } else {
373         sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
374         sbuf_bcat(&sb, th.OemId, 6);
375         sbuf_trim(&sb);
376         sbuf_putc(&sb, ' ');
377         sbuf_bcat(&sb, th.OemTableId, 8);
378         sbuf_trim(&sb);
379         sbuf_finish(&sb);
380         device_set_desc_copy(dev, sbuf_data(&sb));
381         sbuf_delete(&sb);
382         error = 0;
383     }
384     ACPI_UNLOCK;
385     return_VALUE(error);
386 }
387
388 static int
389 acpi_attach(device_t dev)
390 {
391     struct acpi_softc   *sc;
392     ACPI_STATUS         status;
393     int                 error, state;
394     UINT32              flags;
395     UINT8               TypeA, TypeB;
396     char                *env;
397 #ifdef ACPI_DEBUGGER
398     char                *debugpoint;
399 #endif
400     ACPI_LOCK_DECL;
401
402     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
403     ACPI_LOCK;
404     sc = device_get_softc(dev);
405     bzero(sc, sizeof(*sc));
406     sc->acpi_dev = dev;
407     callout_init(&sc->acpi_sleep_timer);
408
409 #ifdef ACPI_DEBUGGER
410     debugpoint = kgetenv("debug.acpi.debugger");
411     if (debugpoint) {
412         if (!strcmp(debugpoint, "spaces"))
413             acpi_EnterDebugger();
414         freeenv(debugpoint);
415     }
416 #endif
417
418     /* Install the default address space handlers. */
419     error = ENXIO;
420     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
421                 ACPI_ADR_SPACE_SYSTEM_MEMORY, ACPI_DEFAULT_HANDLER, NULL, NULL);
422     if (ACPI_FAILURE(status)) {
423         device_printf(dev, "Could not initialise SystemMemory handler: %s\n",
424                       AcpiFormatException(status));
425         goto out;
426     }
427     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
428                 ACPI_ADR_SPACE_SYSTEM_IO, ACPI_DEFAULT_HANDLER, NULL, NULL);
429     if (ACPI_FAILURE(status)) {
430         device_printf(dev, "Could not initialise SystemIO handler: %s\n",
431                       AcpiFormatException(status));
432         goto out;
433     }
434     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
435                 ACPI_ADR_SPACE_PCI_CONFIG, ACPI_DEFAULT_HANDLER, NULL, NULL);
436     if (ACPI_FAILURE(status)) {
437         device_printf(dev, "could not initialise PciConfig handler: %s\n",
438                       AcpiFormatException(status));
439         goto out;
440     }
441
442     /*
443      * Bring ACPI fully online.
444      *
445      * Note that some systems (specifically, those with namespace evaluation
446      * issues that require the avoidance of parts of the namespace) must
447      * avoid running _INI and _STA on everything, as well as dodging the final
448      * object init pass.
449      *
450      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
451      * For avoiding portions of the namespace without totally disabling _INI
452      * and _STA, use "debug.acpi.avoid.paths".
453      *
454      * XXX We should arrange for the object init pass after we have attached
455      *     all our child devices, but on many systems it works here.
456      */
457 #ifdef ACPI_DEBUGGER
458     debugpoint = kgetenv("debug.acpi.debugger");
459     if (debugpoint) {
460         if (!strcmp(debugpoint, "enable"))
461             acpi_EnterDebugger();
462         freeenv(debugpoint);
463     }
464 #endif
465     flags = 0;
466     if (testenv("debug.acpi.avoid"))
467         flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
468     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
469         device_printf(dev, "Could not enable ACPI: %s\n",
470                       AcpiFormatException(status));
471         goto out;
472     }
473
474     /*
475      * Call the ECDT probe function to provide EC functionality before
476      * the namespace has been evaluated.
477      */
478     acpi_ec_ecdt_probe(dev);
479
480     if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
481         device_printf(dev, "Could not initialize ACPI objects: %s\n",
482                       AcpiFormatException(status));
483         goto out;
484     }
485
486     /*
487      * Setup our sysctl tree.
488      *
489      * XXX: This doesn't check to make sure that none of these fail.
490      */
491     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
492     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
493                                SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
494                                device_get_name(dev), CTLFLAG_RD, 0, "");
495     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
496         OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
497         0, 0, acpi_supported_sleep_state_sysctl, "A", "");
498     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
499         OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
500         &sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
501     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
502         OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
503         &sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
504     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
505         OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
506         &sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
507     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
508         OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
509         &sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
510     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
511         OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
512         &sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
513     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
514         OID_AUTO, "sleep_delay", CTLFLAG_RD | CTLFLAG_RW,
515         &sc->acpi_sleep_delay, 0, "sleep delay");
516     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
517         OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
518         &sc->acpi_s4bios, 0, "S4BIOS mode");
519     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
520         OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
521         &sc->acpi_verbose, 0, "verbose mode");
522     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
523         OID_AUTO, "disable_on_poweroff", CTLFLAG_RD | CTLFLAG_RW,
524         &sc->acpi_disable_on_poweroff, 0, "ACPI subsystem disable on poweroff");
525
526     /*
527      * Default to 1 second before sleeping to give some machines time to
528      * stabilize.
529      */
530     sc->acpi_sleep_delay = 1;
531     sc->acpi_disable_on_poweroff = 0;
532     if (bootverbose)
533         sc->acpi_verbose = 1;
534     if ((env = kgetenv("hw.acpi.verbose")) && strcmp(env, "0")) {
535         sc->acpi_verbose = 1;
536         freeenv(env);
537     }
538
539     /* Only enable S4BIOS by default if the FACS says it is available. */
540     if (AcpiGbl_FACS->S4Bios_f != 0)
541             sc->acpi_s4bios = 1;
542
543     /*
544      * Dispatch the default sleep state to devices.  The lid switch is set
545      * to NONE by default to avoid surprising users.
546      */
547     sc->acpi_power_button_sx = ACPI_STATE_S5;
548     sc->acpi_lid_switch_sx = ACPI_S_STATES_MAX + 1;
549     sc->acpi_standby_sx = ACPI_STATE_S1;
550     sc->acpi_suspend_sx = ACPI_STATE_S3;
551
552     /* Pick the first valid sleep state for the sleep button default. */
553     sc->acpi_sleep_button_sx = ACPI_S_STATES_MAX + 1;
554     for (state = ACPI_STATE_S1; state < ACPI_STATE_S5; state++)
555         if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
556             sc->acpi_sleep_button_sx = state;
557             break;
558         }
559
560     acpi_enable_fixed_events(sc);
561
562     /*
563      * Scan the namespace and attach/initialise children.
564      */
565 #ifdef ACPI_DEBUGGER
566     debugpoint = kgetenv("debug.acpi.debugger");
567     if (debugpoint) {
568         if (!strcmp(debugpoint, "probe"))
569             acpi_EnterDebugger();
570         freeenv(debugpoint);
571     }
572 #endif
573
574     /* Register our shutdown handlers */
575     EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc,
576         SHUTDOWN_PRI_LAST);
577     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
578         SHUTDOWN_PRI_LAST);
579
580     /*
581      * Register our acpi event handlers.
582      * XXX should be configurable eg. via userland policy manager.
583      */
584     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
585         sc, ACPI_EVENT_PRI_LAST);
586     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
587         sc, ACPI_EVENT_PRI_LAST);
588
589     /* Flag our initial states. */
590     sc->acpi_enabled = 1;
591     sc->acpi_sstate = ACPI_STATE_S0;
592     sc->acpi_sleep_disabled = 0;
593
594     /* Create the control device */
595     dev_ops_add(&acpi_ops, 0, 0);
596     sc->acpi_dev_t = make_dev(&acpi_ops, 0, UID_ROOT, GID_WHEEL, 0644,
597                               "acpi");
598     sc->acpi_dev_t->si_drv1 = sc;
599
600 #ifdef ACPI_DEBUGGER
601     debugpoint = kgetenv("debug.acpi.debugger");
602     if (debugpoint) {
603         if (strcmp(debugpoint, "running") == 0)
604             acpi_EnterDebugger();
605         freeenv(debugpoint);
606     }
607 #endif
608
609     if ((error = acpi_task_thread_init()))
610         goto out;
611
612     if ((error = acpi_machdep_init(dev)))
613         goto out;
614
615     /* Register ACPI again to pass the correct argument of pm_func. */
616     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
617
618     if (!acpi_disabled("bus"))
619         acpi_probe_children(dev);
620
621     error = 0;
622
623  out:
624     ACPI_UNLOCK;
625     return_VALUE (error);
626 }
627
628 static int
629 acpi_shutdown(device_t dev)
630 {
631     /* Allow children to shutdown first. */
632     bus_generic_shutdown(dev);
633
634     /* Disable all wake GPEs not appropriate for reboot/poweroff. */
635     acpi_wake_limit_walk(ACPI_STATE_S5);
636     return (0);
637 }
638
639 static void
640 acpi_quirks_set(void)
641 {
642     XSDT_DESCRIPTOR *xsdt;
643     struct acpi_quirks *quirk;
644     char *env, *tmp;
645     int len;
646
647     /*
648      * If the user loaded a custom table or disabled "quirks", leave
649      * the settings alone.
650      */
651     len = 0;
652     if ((env = kgetenv("acpi_dsdt_load")) != NULL) {
653         /* XXX No strcasecmp but this is good enough. */
654         if (*env == 'Y' || *env == 'y')
655             goto out;
656         freeenv(env);
657     }
658     if ((env = kgetenv("debug.acpi.disabled")) != NULL) {
659         if (strstr("quirks", env) != NULL)
660             goto out;
661         len = strlen(env);
662     }
663
664     /*
665      * Search through our quirk table and concatenate the disabled
666      * values with whatever we find.
667      */
668     xsdt = AcpiGbl_XSDT;
669     for (quirk = acpi_quirks_table; quirk->OemId; quirk++) {
670         if (!strncmp(xsdt->OemId, quirk->OemId, strlen(quirk->OemId)) &&
671             (xsdt->OemRevision == quirk->OemRevision ||
672             quirk->OemRevision == ACPI_OEM_REV_ANY)) {
673                 len += strlen(quirk->value) + 2;
674                 if ((tmp = kmalloc(len, M_TEMP, M_NOWAIT)) == NULL)
675                     goto out;
676                 sprintf(tmp, "%s %s", env ? env : "", quirk->value);
677 #ifdef notyet
678                 setenv("debug.acpi.disabled", tmp);
679 #endif /* notyet */
680                 kfree(tmp, M_TEMP);
681                 break;
682         }
683     }
684
685 out:
686     if (env)
687         freeenv(env);
688 }
689
690 /*
691  * Handle a new device being added
692  */
693 static device_t
694 acpi_add_child(device_t bus, device_t parent, int order,
695                 const char *name, int unit)
696 {
697     struct acpi_device  *ad;
698     device_t            child;
699
700     ad = kmalloc(sizeof(*ad), M_ACPIDEV, M_INTWAIT | M_ZERO);
701
702     resource_list_init(&ad->ad_rl);
703
704     child = device_add_child_ordered(parent, 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, 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 = kmalloc(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     kfree(devlist, M_TEMP);
2002
2003     return (0);
2004 }
2005
2006 #ifdef dfly_notyet
2007 /* Enable or disable wake from userland. */
2008 static int
2009 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
2010 {
2011     int enable, error;
2012     device_t dev;
2013
2014     dev = (device_t)arg1;
2015     enable = (device_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
2016
2017     error = sysctl_handle_int(oidp, &enable, 0, req);
2018     if (error != 0 || req->newptr == NULL)
2019         return (error);
2020     if (enable != 0 && enable != 1)
2021         return (EINVAL);
2022
2023     return (acpi_wake_set_enable(dev, enable));
2024 }
2025 #endif /* dfly_notyet */
2026
2027 /* Parse a device's _PRW into a structure. */
2028 static int
2029 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
2030 {
2031     ACPI_STATUS                 status;
2032     ACPI_BUFFER                 prw_buffer;
2033     ACPI_OBJECT                 *res, *res2;
2034     int error;
2035
2036     if (h == NULL || prw == NULL)
2037         return (EINVAL);
2038
2039     /*
2040      * The _PRW object (7.2.9) is only required for devices that have the
2041      * ability to wake the system from a sleeping state.
2042      */
2043     error = EINVAL;
2044     prw_buffer.Pointer = NULL;
2045     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
2046     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
2047     if (ACPI_FAILURE(status))
2048         return (ENOENT);
2049     res = (ACPI_OBJECT *)prw_buffer.Pointer;
2050     if (res == NULL)
2051         return (ENOENT);
2052     if (!ACPI_PKG_VALID(res, 2))
2053         goto out;
2054
2055     /*
2056      * Element 1 of the _PRW object:
2057      * The lowest power system sleeping state that can be entered while still
2058      * providing wake functionality.  The sleeping state being entered must
2059      * be less than (i.e., higher power) or equal to this value.
2060      */
2061     if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
2062         goto out;
2063
2064     /*
2065      * Element 0 of the _PRW object:
2066      */
2067     switch (res->Package.Elements[0].Type) {
2068     case ACPI_TYPE_INTEGER:
2069         /*
2070          * If the data type of this package element is numeric, then this
2071          * _PRW package element is the bit index in the GPEx_EN, in the
2072          * GPE blocks described in the FADT, of the enable bit that is
2073          * enabled for the wake event.
2074          */
2075         prw->gpe_handle = NULL;
2076         prw->gpe_bit = res->Package.Elements[0].Integer.Value;
2077         error = 0;
2078         break;
2079     case ACPI_TYPE_PACKAGE:
2080         /*
2081          * If the data type of this package element is a package, then this
2082          * _PRW package element is itself a package containing two
2083          * elements.  The first is an object reference to the GPE Block
2084          * device that contains the GPE that will be triggered by the wake
2085          * event.  The second element is numeric and it contains the bit
2086          * index in the GPEx_EN, in the GPE Block referenced by the
2087          * first element in the package, of the enable bit that is enabled for
2088          * the wake event.
2089          *
2090          * For example, if this field is a package then it is of the form:
2091          * Package() {\_SB.PCI0.ISA.GPE, 2}
2092          */
2093         res2 = &res->Package.Elements[0];
2094         if (!ACPI_PKG_VALID(res2, 2))
2095             goto out;
2096         prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
2097         if (prw->gpe_handle == NULL)
2098             goto out;
2099         if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
2100             goto out;
2101         error = 0;
2102         break;
2103     default:
2104         goto out;
2105     }
2106
2107     /* XXX No power resource handling yet. */
2108     prw->power_res = NULL;
2109
2110 out:
2111     if (prw_buffer.Pointer != NULL)
2112         AcpiOsFree(prw_buffer.Pointer);
2113     return (error);
2114 }
2115
2116 /*
2117  * Enable/Disable ACPI
2118  */
2119 ACPI_STATUS
2120 acpi_Enable(struct acpi_softc *sc)
2121 {
2122     ACPI_STATUS status;
2123     u_int32_t   flags;
2124
2125     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2126     ACPI_ASSERTLOCK;
2127
2128     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
2129             ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
2130     if (!sc->acpi_enabled)
2131         status = AcpiEnableSubsystem(flags);
2132     else
2133         status = AE_OK;
2134
2135     if (status == AE_OK)
2136         sc->acpi_enabled = 1;
2137
2138     return_ACPI_STATUS (status);
2139 }
2140
2141 ACPI_STATUS
2142 acpi_Disable(struct acpi_softc *sc)
2143 {
2144     ACPI_STATUS status;
2145
2146     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2147     ACPI_ASSERTLOCK;
2148
2149     if (sc->acpi_enabled)
2150         status = AcpiDisable();
2151     else
2152         status = AE_OK;
2153
2154     if (status == AE_OK)
2155         sc->acpi_enabled = 0;
2156
2157     return_ACPI_STATUS (status);
2158 }
2159
2160 /*
2161  * ACPI Event Handlers
2162  */
2163
2164 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
2165
2166 static void
2167 acpi_system_eventhandler_sleep(void *arg, int state)
2168 {
2169     ACPI_LOCK_DECL;
2170     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2171
2172     ACPI_LOCK;
2173     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
2174         acpi_SetSleepState((struct acpi_softc *)arg, state);
2175     ACPI_UNLOCK;
2176     return_VOID;
2177 }
2178
2179 static void
2180 acpi_system_eventhandler_wakeup(void *arg, int state)
2181 {
2182     ACPI_LOCK_DECL;
2183     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2184
2185     /* Well, what to do? :-) */
2186
2187     ACPI_LOCK;
2188     ACPI_UNLOCK;
2189
2190     return_VOID;
2191 }
2192
2193 /* 
2194  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
2195  */
2196 UINT32
2197 acpi_event_power_button_sleep(void *context)
2198 {
2199     struct acpi_softc   *sc = (struct acpi_softc *)context;
2200
2201     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2202
2203     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
2204
2205     return_VALUE (ACPI_INTERRUPT_HANDLED);
2206 }
2207
2208 UINT32
2209 acpi_event_power_button_wake(void *context)
2210 {
2211     struct acpi_softc   *sc = (struct acpi_softc *)context;
2212
2213     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2214
2215     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
2216
2217     return_VALUE (ACPI_INTERRUPT_HANDLED);
2218 }
2219
2220 UINT32
2221 acpi_event_sleep_button_sleep(void *context)
2222 {
2223     struct acpi_softc   *sc = (struct acpi_softc *)context;
2224
2225     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2226
2227     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
2228
2229     return_VALUE (ACPI_INTERRUPT_HANDLED);
2230 }
2231
2232 UINT32
2233 acpi_event_sleep_button_wake(void *context)
2234 {
2235     struct acpi_softc   *sc = (struct acpi_softc *)context;
2236
2237     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2238
2239     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
2240
2241     return_VALUE (ACPI_INTERRUPT_HANDLED);
2242 }
2243
2244 /*
2245  * XXX This is kinda ugly, and should not be here.
2246  */
2247 struct acpi_staticbuf {
2248     ACPI_BUFFER buffer;
2249     char        data[512];
2250 };
2251
2252 char *
2253 acpi_name(ACPI_HANDLE handle)
2254 {
2255     static struct acpi_staticbuf        buf;
2256
2257     ACPI_ASSERTLOCK;
2258
2259     buf.buffer.Length = 512;
2260     buf.buffer.Pointer = &buf.data[0];
2261
2262     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
2263         return (buf.buffer.Pointer);
2264
2265     return ("(unknown path)");
2266 }
2267
2268 /*
2269  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
2270  * parts of the namespace.
2271  */
2272 int
2273 acpi_avoid(ACPI_HANDLE handle)
2274 {
2275     char        *cp, *env, *np;
2276     int         len;
2277
2278     np = acpi_name(handle);
2279     if (*np == '\\')
2280         np++;
2281     if ((env = kgetenv("debug.acpi.avoid.paths")) == NULL &&
2282         (env = kgetenv("debug.acpi.avoid")) == NULL)
2283         return (0);
2284
2285     /* Scan the avoid list checking for a match */
2286     cp = env;
2287     for (;;) {
2288         while ((*cp != 0) && isspace(*cp))
2289             cp++;
2290         if (*cp == 0)
2291             break;
2292         len = 0;
2293         while ((cp[len] != 0) && !isspace(cp[len]))
2294             len++;
2295         if (!strncmp(cp, np, len)) {
2296             freeenv(env);
2297             return(1);
2298         }
2299         cp += len;
2300     }
2301     freeenv(env);
2302
2303     return (0);
2304 }
2305
2306 /*
2307  * Debugging/bug-avoidance.  Disable ACPI subsystem components.   Note that
2308  * some components may be disabled by default and can only be enabled
2309  * via acpi_enabled() (debug.acpi.enabled).
2310  */
2311 int
2312 acpi_disabled(char *subsys)
2313 {
2314     char        *cp, *env;
2315     int         len;
2316
2317     if ((env = kgetenv("debug.acpi.disabled")) == NULL)
2318         return (0);
2319     if (strcmp(env, "all") == 0) {
2320         freeenv(env);
2321         return (1);
2322     }
2323
2324     /* Scan the disable list, checking for a match. */
2325     cp = env;
2326     for (;;) {
2327         while (*cp != '\0' && isspace(*cp))
2328             cp++;
2329         if (*cp == '\0')
2330             break;
2331         len = 0;
2332         while (cp[len] != '\0' && !isspace(cp[len]))
2333             len++;
2334         if (strncmp(cp, subsys, len) == 0) {
2335             freeenv(env);
2336             return (1);
2337         }
2338         cp += len;
2339     }
2340     freeenv(env);
2341
2342     return (0);
2343 }
2344
2345 /*
2346  * Debugging/bug-avoidance.  Enable ACPI subsystem components.  Most 
2347  * components are enabled by default.  The ones that are not have to be 
2348  * enabled via debug.acpi.enabled.
2349  */
2350 int
2351 acpi_enabled(char *subsys)
2352 {
2353     char        *cp, *env;
2354     int         len;
2355
2356     if ((env = kgetenv("debug.acpi.enabled")) == NULL)
2357         return (0);
2358     if (strcmp(env, "all") == 0) {
2359         freeenv(env);
2360         return (1);
2361     }
2362
2363     /* Scan the enable list, checking for a match. */
2364     cp = env;
2365     for (;;) {
2366         while (*cp != '\0' && isspace(*cp))
2367             cp++;
2368         if (*cp == '\0')
2369             break;
2370         len = 0;
2371         while (cp[len] != '\0' && !isspace(cp[len]))
2372             len++;
2373         if (strncmp(cp, subsys, len) == 0) {
2374             freeenv(env);
2375             return (1);
2376         }
2377         cp += len;
2378     }
2379     freeenv(env);
2380
2381     return (0);
2382 }
2383
2384 /*
2385  * Control interface.
2386  *
2387  * We multiplex ioctls for all participating ACPI devices here.  Individual 
2388  * drivers wanting to be accessible via /dev/acpi should use the
2389  * register/deregister interface to make their handlers visible.
2390  */
2391 struct acpi_ioctl_hook
2392 {
2393     TAILQ_ENTRY(acpi_ioctl_hook) link;
2394     u_long                       cmd;
2395     acpi_ioctl_fn                fn;
2396     void                         *arg;
2397 };
2398
2399 static TAILQ_HEAD(,acpi_ioctl_hook)     acpi_ioctl_hooks;
2400 static int                              acpi_ioctl_hooks_initted;
2401
2402 /*
2403  * Register an ioctl handler.
2404  */
2405 int
2406 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
2407 {
2408     struct acpi_ioctl_hook      *hp;
2409
2410     hp = kmalloc(sizeof(*hp), M_ACPIDEV, M_INTWAIT);
2411     hp->cmd = cmd;
2412     hp->fn = fn;
2413     hp->arg = arg;
2414     if (acpi_ioctl_hooks_initted == 0) {
2415         TAILQ_INIT(&acpi_ioctl_hooks);
2416         acpi_ioctl_hooks_initted = 1;
2417     }
2418     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
2419     return (0);
2420 }
2421
2422 /*
2423  * Deregister an ioctl handler.
2424  */
2425 void    
2426 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
2427 {
2428     struct acpi_ioctl_hook      *hp;
2429
2430     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
2431         if ((hp->cmd == cmd) && (hp->fn == fn))
2432             break;
2433
2434     if (hp != NULL) {
2435         TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
2436         kfree(hp, M_ACPIDEV);
2437     }
2438 }
2439
2440 static int
2441 acpiopen(struct dev_open_args *ap)
2442 {
2443     return (0);
2444 }
2445
2446 static int
2447 acpiclose(struct dev_close_args *ap)
2448 {
2449     return (0);
2450 }
2451
2452 static int
2453 acpiioctl(struct dev_ioctl_args *ap)
2454 {
2455     struct acpi_softc           *sc;
2456     struct acpi_ioctl_hook      *hp;
2457     int                         error, xerror, state;
2458     ACPI_LOCK_DECL;
2459
2460     ACPI_LOCK;
2461
2462     error = state = 0;
2463     sc = ap->a_head.a_dev->si_drv1;
2464
2465     /*
2466      * Scan the list of registered ioctls, looking for handlers.
2467      */
2468     if (acpi_ioctl_hooks_initted) {
2469         TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
2470             if (hp->cmd == ap->a_cmd) {
2471                 xerror = hp->fn(ap->a_cmd, ap->a_data, hp->arg);
2472                 if (xerror != 0)
2473                     error = xerror;
2474                 goto out;
2475             }
2476         }
2477     }
2478
2479     /*
2480      * Core ioctls are not permitted for non-writable user.
2481      * Currently, other ioctls just fetch information.
2482      * Not changing system behavior.
2483      */
2484     if((ap->a_fflag & FWRITE) == 0)
2485         return (EPERM);
2486
2487     /* Core system ioctls. */
2488     switch (ap->a_cmd) {
2489     case ACPIIO_ENABLE:
2490         if (ACPI_FAILURE(acpi_Enable(sc)))
2491             error = ENXIO;
2492         break;
2493     case ACPIIO_DISABLE:
2494         if (ACPI_FAILURE(acpi_Disable(sc)))
2495             error = ENXIO;
2496         break;
2497     case ACPIIO_SETSLPSTATE:
2498         if (!sc->acpi_enabled) {
2499             error = ENXIO;
2500             break;
2501         }
2502         state = *(int *)ap->a_data;
2503         if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
2504             if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
2505                 error = EINVAL;
2506         } else {
2507             error = EINVAL;
2508         }
2509         break;
2510     default:
2511         if (error == 0)
2512             error = EINVAL;
2513         break;
2514     }
2515
2516 out:
2517     ACPI_UNLOCK;
2518     return (error);
2519 }
2520
2521 static int
2522 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2523 {
2524     char sleep_state[4];
2525     char buf[16];
2526     int error;
2527     UINT8 state, TypeA, TypeB;
2528
2529     buf[0] = '\0';
2530     for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX + 1; state++) {
2531         if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
2532             sprintf(sleep_state, "S%d ", state);
2533             strcat(buf, sleep_state);
2534         }
2535     }
2536     error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2537     return (error);
2538 }
2539
2540 static int
2541 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2542 {
2543     char sleep_state[10];
2544     int error;
2545     u_int new_state, old_state;
2546
2547     old_state = *(u_int *)oidp->oid_arg1;
2548     if (old_state > ACPI_S_STATES_MAX + 1) {
2549         strcpy(sleep_state, "unknown");
2550     } else {
2551         bzero(sleep_state, sizeof(sleep_state));
2552         strncpy(sleep_state, sleep_state_names[old_state],
2553                 sizeof(sleep_state_names[old_state]));
2554     }
2555     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
2556     if (error == 0 && req->newptr != NULL) {
2557         new_state = ACPI_STATE_S0;
2558         for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++) {
2559             if (strncmp(sleep_state, sleep_state_names[new_state],
2560                         sizeof(sleep_state)) == 0)
2561                 break;
2562         }
2563         if (new_state <= ACPI_S_STATES_MAX + 1) {
2564             if (new_state != old_state)
2565                 *(u_int *)oidp->oid_arg1 = new_state;
2566         } else {
2567             error = EINVAL;
2568         }
2569     }
2570
2571     return (error);
2572 }
2573
2574 /* Inform devctl(4) when we receive a Notify. */
2575 void
2576 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
2577 {
2578     char                notify_buf[16];
2579     ACPI_BUFFER         handle_buf;
2580     ACPI_STATUS         status;
2581
2582     if (subsystem == NULL)
2583         return;
2584
2585     handle_buf.Pointer = NULL;
2586     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
2587     status = AcpiNsHandleToPathname(h, &handle_buf);
2588     if (ACPI_FAILURE(status))
2589         return;
2590     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
2591 #if 0
2592     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
2593 #endif
2594     AcpiOsFree(handle_buf.Pointer);
2595 }
2596
2597 #ifdef ACPI_DEBUG
2598 /*
2599  * Support for parsing debug options from the kernel environment.
2600  *
2601  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
2602  * by specifying the names of the bits in the debug.acpi.layer and
2603  * debug.acpi.level environment variables.  Bits may be unset by 
2604  * prefixing the bit name with !.
2605  */
2606 struct debugtag
2607 {
2608     char        *name;
2609     UINT32      value;
2610 };
2611
2612 static struct debugtag  dbg_layer[] = {
2613     {"ACPI_UTILITIES",          ACPI_UTILITIES},
2614     {"ACPI_HARDWARE",           ACPI_HARDWARE},
2615     {"ACPI_EVENTS",             ACPI_EVENTS},
2616     {"ACPI_TABLES",             ACPI_TABLES},
2617     {"ACPI_NAMESPACE",          ACPI_NAMESPACE},
2618     {"ACPI_PARSER",             ACPI_PARSER},
2619     {"ACPI_DISPATCHER",         ACPI_DISPATCHER},
2620     {"ACPI_EXECUTER",           ACPI_EXECUTER},
2621     {"ACPI_RESOURCES",          ACPI_RESOURCES},
2622     {"ACPI_CA_DEBUGGER",        ACPI_CA_DEBUGGER},
2623     {"ACPI_OS_SERVICES",        ACPI_OS_SERVICES},
2624     {"ACPI_CA_DISASSEMBLER",    ACPI_CA_DISASSEMBLER},
2625     {"ACPI_ALL_COMPONENTS",     ACPI_ALL_COMPONENTS},
2626
2627     {"ACPI_AC_ADAPTER",         ACPI_AC_ADAPTER},
2628     {"ACPI_BATTERY",            ACPI_BATTERY},
2629     {"ACPI_BUS",                ACPI_BUS},
2630     {"ACPI_BUTTON",             ACPI_BUTTON},
2631     {"ACPI_EC",                 ACPI_EC},
2632     {"ACPI_FAN",                ACPI_FAN},
2633     {"ACPI_POWERRES",           ACPI_POWERRES},
2634     {"ACPI_PROCESSOR",          ACPI_PROCESSOR},
2635     {"ACPI_THERMAL",            ACPI_THERMAL},
2636     {"ACPI_TIMER",              ACPI_TIMER},
2637     {"ACPI_ALL_DRIVERS",        ACPI_ALL_DRIVERS},
2638     {NULL, 0}
2639 };
2640
2641 static struct debugtag dbg_level[] = {
2642     {"ACPI_LV_ERROR",           ACPI_LV_ERROR},
2643     {"ACPI_LV_WARN",            ACPI_LV_WARN},
2644     {"ACPI_LV_INIT",            ACPI_LV_INIT},
2645     {"ACPI_LV_DEBUG_OBJECT",    ACPI_LV_DEBUG_OBJECT},
2646     {"ACPI_LV_INFO",            ACPI_LV_INFO},
2647     {"ACPI_LV_ALL_EXCEPTIONS",  ACPI_LV_ALL_EXCEPTIONS},
2648
2649     /* Trace verbosity level 1 [Standard Trace Level] */
2650     {"ACPI_LV_INIT_NAMES",      ACPI_LV_INIT_NAMES},
2651     {"ACPI_LV_PARSE",           ACPI_LV_PARSE},
2652     {"ACPI_LV_LOAD",            ACPI_LV_LOAD},
2653     {"ACPI_LV_DISPATCH",        ACPI_LV_DISPATCH},
2654     {"ACPI_LV_EXEC",            ACPI_LV_EXEC},
2655     {"ACPI_LV_NAMES",           ACPI_LV_NAMES},
2656     {"ACPI_LV_OPREGION",        ACPI_LV_OPREGION},
2657     {"ACPI_LV_BFIELD",          ACPI_LV_BFIELD},
2658     {"ACPI_LV_TABLES",          ACPI_LV_TABLES},
2659     {"ACPI_LV_VALUES",          ACPI_LV_VALUES},
2660     {"ACPI_LV_OBJECTS",         ACPI_LV_OBJECTS},
2661     {"ACPI_LV_RESOURCES",       ACPI_LV_RESOURCES},
2662     {"ACPI_LV_USER_REQUESTS",   ACPI_LV_USER_REQUESTS},
2663     {"ACPI_LV_PACKAGE",         ACPI_LV_PACKAGE},
2664     {"ACPI_LV_VERBOSITY1",      ACPI_LV_VERBOSITY1},
2665
2666     /* Trace verbosity level 2 [Function tracing and memory allocation] */
2667     {"ACPI_LV_ALLOCATIONS",     ACPI_LV_ALLOCATIONS},
2668     {"ACPI_LV_FUNCTIONS",       ACPI_LV_FUNCTIONS},
2669     {"ACPI_LV_OPTIMIZATIONS",   ACPI_LV_OPTIMIZATIONS},
2670     {"ACPI_LV_VERBOSITY2",      ACPI_LV_VERBOSITY2},
2671     {"ACPI_LV_ALL",             ACPI_LV_ALL},
2672
2673     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2674     {"ACPI_LV_MUTEX",           ACPI_LV_MUTEX},
2675     {"ACPI_LV_THREADS",         ACPI_LV_THREADS},
2676     {"ACPI_LV_IO",              ACPI_LV_IO},
2677     {"ACPI_LV_INTERRUPTS",      ACPI_LV_INTERRUPTS},
2678     {"ACPI_LV_VERBOSITY3",      ACPI_LV_VERBOSITY3},
2679
2680     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2681     {"ACPI_LV_AML_DISASSEMBLE", ACPI_LV_AML_DISASSEMBLE},
2682     {"ACPI_LV_VERBOSE_INFO",    ACPI_LV_VERBOSE_INFO},
2683     {"ACPI_LV_FULL_TABLES",     ACPI_LV_FULL_TABLES},
2684     {"ACPI_LV_EVENTS",          ACPI_LV_EVENTS},
2685     {"ACPI_LV_VERBOSE",         ACPI_LV_VERBOSE},
2686     {NULL, 0}
2687 };    
2688
2689 static void
2690 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2691 {
2692     char        *ep;
2693     int         i, l;
2694     int         set;
2695
2696     while (*cp) {
2697         if (isspace(*cp)) {
2698             cp++;
2699             continue;
2700         }
2701         ep = cp;
2702         while (*ep && !isspace(*ep))
2703             ep++;
2704         if (*cp == '!') {
2705             set = 0;
2706             cp++;
2707             if (cp == ep)
2708                 continue;
2709         } else {
2710             set = 1;
2711         }
2712         l = ep - cp;
2713         for (i = 0; tag[i].name != NULL; i++) {
2714             if (!strncmp(cp, tag[i].name, l)) {
2715                 if (set)
2716                     *flag |= tag[i].value;
2717                 else
2718                     *flag &= ~tag[i].value;
2719             }
2720         }
2721         cp = ep;
2722     }
2723 }
2724
2725 static void
2726 acpi_set_debugging(void *junk)
2727 {
2728     char        *layer, *level;
2729
2730     if (cold) {
2731         AcpiDbgLayer = 0;
2732         AcpiDbgLevel = 0;
2733     }
2734
2735     layer = kgetenv("debug.acpi.layer");
2736     level = kgetenv("debug.acpi.level");
2737     if (layer == NULL && level == NULL)
2738         return;
2739
2740     printf("ACPI set debug");
2741     if (layer != NULL) {
2742         if (strcmp("NONE", layer) != 0)
2743             printf(" layer '%s'", layer);
2744         acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
2745         freeenv(layer);
2746     }
2747     if (level != NULL) {
2748         if (strcmp("NONE", level) != 0)
2749             printf(" level '%s'", level);
2750         acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
2751         freeenv(level);
2752     }
2753     printf("\n");
2754 }
2755 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
2756         NULL);
2757
2758 static int
2759 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
2760 {
2761     int          error, *dbg;
2762     struct       debugtag *tag;
2763     struct       sbuf sb;
2764
2765     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
2766         return (ENOMEM);
2767     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
2768         tag = &dbg_layer[0];
2769         dbg = &AcpiDbgLayer;
2770     } else {
2771         tag = &dbg_level[0];
2772         dbg = &AcpiDbgLevel;
2773     }
2774
2775     /* Get old values if this is a get request. */
2776     if (*dbg == 0) {
2777         sbuf_cpy(&sb, "NONE");
2778     } else if (req->newptr == NULL) {
2779         for (; tag->name != NULL; tag++) {
2780             if ((*dbg & tag->value) == tag->value)
2781                 sbuf_printf(&sb, "%s ", tag->name);
2782         }
2783     }
2784     sbuf_trim(&sb);
2785     sbuf_finish(&sb);
2786
2787     /* Copy out the old values to the user. */
2788     error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
2789     sbuf_delete(&sb);
2790
2791     /* If the user is setting a string, parse it. */
2792     if (error == 0 && req->newptr != NULL) {
2793         *dbg = 0;
2794         /* XXX setenv((char *)oidp->oid_arg1, (char *)req->newptr); */
2795         acpi_set_debugging(NULL);
2796     }
2797
2798     return (error);
2799 }
2800 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
2801             "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
2802 SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
2803             "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
2804 #endif
2805
2806 static int
2807 acpi_pm_func(u_long cmd, void *arg, ...)
2808 {
2809         int     state, acpi_state;
2810         int     error;
2811         struct  acpi_softc *sc;
2812         va_list ap;
2813
2814         error = 0;
2815         switch (cmd) {
2816         case POWER_CMD_SUSPEND:
2817                 sc = (struct acpi_softc *)arg;
2818                 if (sc == NULL) {
2819                         error = EINVAL;
2820                         goto out;
2821                 }
2822
2823                 va_start(ap, arg);
2824                 state = va_arg(ap, int);
2825                 va_end(ap);     
2826
2827                 switch (state) {
2828                 case POWER_SLEEP_STATE_STANDBY:
2829                         acpi_state = sc->acpi_standby_sx;
2830                         break;
2831                 case POWER_SLEEP_STATE_SUSPEND:
2832                         acpi_state = sc->acpi_suspend_sx;
2833                         break;
2834                 case POWER_SLEEP_STATE_HIBERNATE:
2835                         acpi_state = ACPI_STATE_S4;
2836                         break;
2837                 default:
2838                         error = EINVAL;
2839                         goto out;
2840                 }
2841
2842                 acpi_SetSleepState(sc, acpi_state);
2843                 break;
2844         default:
2845                 error = EINVAL;
2846                 goto out;
2847         }
2848
2849 out:
2850         return (error);
2851 }
2852
2853 static void
2854 acpi_pm_register(void *arg)
2855 {
2856     if (!cold || resource_disabled("acpi", 0))
2857         return;
2858
2859     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2860 }
2861
2862 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);