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