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