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