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