The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/dev/acpica/acpi.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    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$
   30  */
   31 
   32 #include "opt_acpi.h"
   33 #include <sys/param.h>
   34 #include <sys/kernel.h>
   35 #include <sys/proc.h>
   36 #include <sys/fcntl.h>
   37 #include <sys/malloc.h>
   38 #include <sys/bus.h>
   39 #include <sys/conf.h>
   40 #include <sys/ioccom.h>
   41 #include <sys/reboot.h>
   42 #include <sys/sysctl.h>
   43 #include <sys/ctype.h>
   44 #include <sys/linker.h>
   45 #include <sys/power.h>
   46 
   47 #include <machine/clock.h>
   48 #include <machine/resource.h>
   49 
   50 #include <isa/isavar.h>
   51 
   52 #include "acpi.h"
   53 
   54 #include <dev/acpica/acpica_support.h>
   55 
   56 #include <dev/acpica/acpivar.h>
   57 #include <dev/acpica/acpiio.h>
   58 
   59 MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
   60 
   61 /*
   62  * Hooks for the ACPI CA debugging infrastructure
   63  */
   64 #define _COMPONENT      ACPI_BUS
   65 ACPI_MODULE_NAME("ACPI")
   66 
   67 /*
   68  * Character device 
   69  */
   70 
   71 static d_open_t         acpiopen;
   72 static d_close_t        acpiclose;
   73 static d_ioctl_t        acpiioctl;
   74 
   75 #define CDEV_MAJOR 152
   76 static struct cdevsw acpi_cdevsw = {
   77         .d_open =       acpiopen,
   78         .d_close =      acpiclose,
   79         .d_ioctl =      acpiioctl,
   80         .d_name =       "acpi",
   81         .d_maj =        CDEV_MAJOR,
   82 };
   83 
   84 static const char* sleep_state_names[] = {
   85     "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
   86 
   87 /* this has to be static, as the softc is gone when we need it */
   88 static int acpi_off_state = ACPI_STATE_S5;
   89 
   90 #if __FreeBSD_version >= 500000
   91 struct mtx      acpi_mutex;
   92 #endif
   93 
   94 static int      acpi_modevent(struct module *mod, int event, void *junk);
   95 static void     acpi_identify(driver_t *driver, device_t parent);
   96 static int      acpi_probe(device_t dev);
   97 static int      acpi_attach(device_t dev);
   98 static device_t acpi_add_child(device_t bus, int order, const char *name, int unit);
   99 static int      acpi_print_child(device_t bus, device_t child);
  100 static int      acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result);
  101 static int      acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value);
  102 static int      acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start,
  103                                   u_long count);
  104 static int      acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp,
  105                                   u_long *countp);
  106 static struct resource *acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
  107                                             u_long start, u_long end, u_long count, u_int flags);
  108 static int      acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r);
  109 static u_int32_t acpi_isa_get_logicalid(device_t dev);
  110 static u_int32_t acpi_isa_get_compatid(device_t dev);
  111 static int      acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids);
  112 
  113 static void     acpi_probe_children(device_t bus);
  114 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status);
  115 
  116 static void     acpi_shutdown_pre_sync(void *arg, int howto);
  117 static void     acpi_shutdown_final(void *arg, int howto);
  118 
  119 static void     acpi_enable_fixed_events(struct acpi_softc *sc);
  120 
  121 static void     acpi_system_eventhandler_sleep(void *arg, int state);
  122 static void     acpi_system_eventhandler_wakeup(void *arg, int state);
  123 static int      acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
  124 static int      acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
  125 
  126 static int      acpi_pm_func(u_long cmd, void *arg, ...);
  127 
  128 static device_method_t acpi_methods[] = {
  129     /* Device interface */
  130     DEVMETHOD(device_identify,          acpi_identify),
  131     DEVMETHOD(device_probe,             acpi_probe),
  132     DEVMETHOD(device_attach,            acpi_attach),
  133     DEVMETHOD(device_shutdown,          bus_generic_shutdown),
  134     DEVMETHOD(device_suspend,           bus_generic_suspend),
  135     DEVMETHOD(device_resume,            bus_generic_resume),
  136 
  137     /* Bus interface */
  138     DEVMETHOD(bus_add_child,            acpi_add_child),
  139     DEVMETHOD(bus_print_child,          acpi_print_child),
  140     DEVMETHOD(bus_read_ivar,            acpi_read_ivar),
  141     DEVMETHOD(bus_write_ivar,           acpi_write_ivar),
  142     DEVMETHOD(bus_set_resource,         acpi_set_resource),
  143     DEVMETHOD(bus_get_resource,         acpi_get_resource),
  144     DEVMETHOD(bus_alloc_resource,       acpi_alloc_resource),
  145     DEVMETHOD(bus_release_resource,     acpi_release_resource),
  146     DEVMETHOD(bus_driver_added,         bus_generic_driver_added),
  147     DEVMETHOD(bus_activate_resource,    bus_generic_activate_resource),
  148     DEVMETHOD(bus_deactivate_resource,  bus_generic_deactivate_resource),
  149     DEVMETHOD(bus_setup_intr,           bus_generic_setup_intr),
  150     DEVMETHOD(bus_teardown_intr,        bus_generic_teardown_intr),
  151 
  152     /* ISA emulation */
  153     DEVMETHOD(isa_pnp_probe,            acpi_isa_pnp_probe),
  154 
  155     {0, 0}
  156 };
  157 
  158 static driver_t acpi_driver = {
  159     "acpi",
  160     acpi_methods,
  161     sizeof(struct acpi_softc),
  162 };
  163 
  164 static devclass_t acpi_devclass;
  165 DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
  166 MODULE_VERSION(acpi, 100);
  167 
  168 SYSCTL_INT(_debug, OID_AUTO, acpi_debug_layer, CTLFLAG_RW, &AcpiDbgLayer, 0, "");
  169 SYSCTL_INT(_debug, OID_AUTO, acpi_debug_level, CTLFLAG_RW, &AcpiDbgLevel, 0, "");
  170 static int acpi_ca_version = ACPI_CA_VERSION;
  171 SYSCTL_INT(_debug, OID_AUTO, acpi_ca_version, CTLFLAG_RD, &acpi_ca_version, 0, "");
  172 
  173 /*
  174  * ACPI can only be loaded as a module by the loader; activating it after
  175  * system bootstrap time is not useful, and can be fatal to the system.
  176  * It also cannot be unloaded, since the entire system bus heirarchy hangs off it.
  177  */
  178 static int
  179 acpi_modevent(struct module *mod, int event, void *junk)
  180 {
  181     switch(event) {
  182     case MOD_LOAD:
  183         if (!cold) {
  184             printf("The ACPI driver cannot be loaded after boot.\n");
  185             return(EPERM);
  186         }
  187         break;
  188     case MOD_UNLOAD:
  189         if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
  190             return(EBUSY);
  191         break;
  192     default:
  193         break;
  194     }
  195     return(0);
  196 }
  197 
  198 /*
  199  * Detect ACPI, perform early initialisation
  200  */
  201 static void
  202 acpi_identify(driver_t *driver, device_t parent)
  203 {
  204     device_t                    child;
  205     int                         error;
  206 #ifdef ACPI_DEBUGGER
  207     char                        *debugpoint;
  208 #endif
  209 
  210     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
  211 
  212     if (!cold)
  213         return_VOID;
  214 
  215     /*
  216      * Check that we haven't been disabled with a hint.
  217      */
  218     if (!resource_int_value("acpi", 0, "disabled", &error) &&
  219         (error != 0))
  220         return_VOID;
  221 
  222     /*
  223      * Make sure we're not being doubly invoked.
  224      */
  225     if (device_find_child(parent, "acpi", 0) != NULL)
  226         return_VOID;
  227 
  228 #if __FreeBSD_version >= 500000
  229     /* initialise the ACPI mutex */
  230     mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
  231 #endif
  232 
  233     /*
  234      * Start up the ACPI CA subsystem.
  235      */
  236 #ifdef ACPI_DEBUGGER
  237     debugpoint = getenv("debug.acpi.debugger");
  238     if (debugpoint) {
  239         if (!strcmp(debugpoint, "init"))
  240             acpi_EnterDebugger();
  241         freeenv(debugpoint);
  242     }
  243 #endif
  244     if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
  245         printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
  246         return_VOID;
  247     }
  248 #ifdef ACPI_DEBUGGER
  249     debugpoint = getenv("debug.acpi.debugger");
  250     if (debugpoint) {
  251         if (!strcmp(debugpoint, "tables"))
  252             acpi_EnterDebugger();
  253         freeenv(debugpoint);
  254     }
  255 #endif
  256 
  257     if (ACPI_FAILURE(error = AcpiLoadTables())) {
  258         printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
  259         return_VOID;
  260     }
  261     
  262     /*
  263      * Attach the actual ACPI device.
  264      */
  265     if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
  266             device_printf(parent, "ACPI: could not attach\n");
  267             return_VOID;
  268     }
  269 }
  270 
  271 /*
  272  * Fetch some descriptive data from ACPI to put in our attach message
  273  */
  274 static int
  275 acpi_probe(device_t dev)
  276 {
  277     ACPI_TABLE_HEADER   th;
  278     char                buf[20];
  279     ACPI_STATUS         status;
  280     int                 error;
  281     ACPI_LOCK_DECL;
  282 
  283     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
  284 
  285     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
  286         power_pm_get_type() != POWER_PM_TYPE_ACPI) {
  287         device_printf(dev, "Other PM system enabled.\n");
  288         return_VALUE(ENXIO);
  289     }
  290 
  291     ACPI_LOCK;
  292 
  293     if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
  294         device_printf(dev, "couldn't get XSDT header: %s\n", AcpiFormatException(status));
  295         error = ENXIO;
  296     } else {
  297         sprintf(buf, "%.6s %.8s", th.OemId, th.OemTableId);
  298         device_set_desc_copy(dev, buf);
  299         error = 0;
  300     }
  301     ACPI_UNLOCK;
  302     return_VALUE(error);
  303 }
  304 
  305 static int
  306 acpi_attach(device_t dev)
  307 {
  308     struct acpi_softc   *sc;
  309     ACPI_STATUS         status;
  310     int                 error;
  311     UINT32              flags;
  312     char                *env;
  313 #ifdef ACPI_DEBUGGER
  314     char                *debugpoint;
  315 #endif
  316     ACPI_LOCK_DECL;
  317 
  318     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
  319     ACPI_LOCK;
  320     sc = device_get_softc(dev);
  321     bzero(sc, sizeof(*sc));
  322     sc->acpi_dev = dev;
  323 
  324 #ifdef ACPI_DEBUGGER
  325     debugpoint = getenv("debug.acpi.debugger");
  326     if (debugpoint) {
  327         if (!strcmp(debugpoint, "spaces"))
  328             acpi_EnterDebugger();
  329         freeenv(debugpoint);
  330     }
  331 #endif
  332 
  333     /*
  334      * Install the default address space handlers.
  335      */
  336     error = ENXIO;
  337     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
  338                                                 ACPI_ADR_SPACE_SYSTEM_MEMORY,
  339                                                 ACPI_DEFAULT_HANDLER,
  340                                                 NULL, NULL))) {
  341         device_printf(dev, "could not initialise SystemMemory handler: %s\n", AcpiFormatException(status));
  342         goto out;
  343     }
  344     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
  345                                                 ACPI_ADR_SPACE_SYSTEM_IO,
  346                                                 ACPI_DEFAULT_HANDLER,
  347                                                 NULL, NULL))) {
  348         device_printf(dev, "could not initialise SystemIO handler: %s\n", AcpiFormatException(status));
  349         goto out;
  350     }
  351     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
  352                                                 ACPI_ADR_SPACE_PCI_CONFIG,
  353                                                 ACPI_DEFAULT_HANDLER,
  354                                                 NULL, NULL))) {
  355         device_printf(dev, "could not initialise PciConfig handler: %s\n", AcpiFormatException(status));
  356         goto out;
  357     }
  358 
  359     /*
  360      * Bring ACPI fully online.
  361      *
  362      * Note that some systems (specifically, those with namespace evaluation issues
  363      * that require the avoidance of parts of the namespace) must avoid running _INI
  364      * and _STA on everything, as well as dodging the final object init pass.
  365      *
  366      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
  367      *
  368      * XXX We should arrange for the object init pass after we have attached all our 
  369      *     child devices, but on many systems it works here.
  370      */
  371 #ifdef ACPI_DEBUGGER
  372     debugpoint = getenv("debug.acpi.debugger");
  373     if (debugpoint) {
  374         if (!strcmp(debugpoint, "enable"))
  375             acpi_EnterDebugger();
  376         freeenv(debugpoint);
  377     }
  378 #endif
  379     flags = 0;
  380     if (testenv("debug.acpi.avoid"))
  381         flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
  382     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
  383         device_printf(dev, "could not enable ACPI: %s\n", AcpiFormatException(status));
  384         goto out;
  385     }
  386 
  387     if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
  388         device_printf(dev, "could not initialize ACPI objects: %s\n", AcpiFormatException(status));
  389         goto out;
  390     }
  391 
  392     /*
  393      * Setup our sysctl tree.
  394      *
  395      * XXX: This doesn't check to make sure that none of these fail.
  396      */
  397     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
  398     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
  399                                SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
  400                                device_get_name(dev), CTLFLAG_RD, 0, "");
  401     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
  402         OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
  403         0, 0, acpi_supported_sleep_state_sysctl, "A", "");
  404     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
  405         OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
  406         &sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
  407     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
  408         OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
  409         &sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
  410     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
  411         OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
  412         &sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
  413     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
  414         OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
  415         &sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
  416     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
  417         OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
  418         &sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
  419     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
  420         OID_AUTO, "sleep_delay", CTLFLAG_RD | CTLFLAG_RW,
  421         &sc->acpi_sleep_delay, 0, "sleep delay");
  422     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
  423         OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
  424         &sc->acpi_s4bios, 0, "S4BIOS mode");
  425     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
  426         OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
  427         &sc->acpi_verbose, 0, "verbose mode");
  428     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
  429                    OID_AUTO, "disable_on_poweroff", CTLFLAG_RD | CTLFLAG_RW,
  430                    &sc->acpi_disable_on_poweroff, 0, "ACPI subsystem disable on poweroff");
  431     sc->acpi_disable_on_poweroff = 1;
  432     sc->acpi_sleep_delay = 0;
  433     sc->acpi_s4bios = 1;
  434     if (bootverbose)
  435         sc->acpi_verbose = 1;
  436     if ((env = getenv("hw.acpi.verbose")) && strcmp(env, "")) {
  437         sc->acpi_verbose = 1;
  438         freeenv(env);
  439     }
  440 
  441     /*
  442      * Dispatch the default sleep state to devices.
  443      * TBD: should be configured from userland policy manager.
  444      */
  445     sc->acpi_power_button_sx = ACPI_POWER_BUTTON_DEFAULT_SX;
  446     sc->acpi_sleep_button_sx = ACPI_SLEEP_BUTTON_DEFAULT_SX;
  447     sc->acpi_lid_switch_sx = ACPI_LID_SWITCH_DEFAULT_SX;
  448     sc->acpi_standby_sx = ACPI_STATE_S1;
  449     sc->acpi_suspend_sx = ACPI_STATE_S3;
  450 
  451     acpi_enable_fixed_events(sc);
  452 
  453     /*
  454      * Scan the namespace and attach/initialise children.
  455      */
  456 #ifdef ACPI_DEBUGGER
  457     debugpoint = getenv("debug.acpi.debugger");
  458     if (debugpoint) {
  459         if (!strcmp(debugpoint, "probe"))
  460             acpi_EnterDebugger();
  461         freeenv(debugpoint);
  462     }
  463 #endif
  464 
  465     /*
  466      * Register our shutdown handlers
  467      */
  468     EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc, SHUTDOWN_PRI_LAST);
  469     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc, SHUTDOWN_PRI_LAST);
  470 
  471     /*
  472      * Register our acpi event handlers.
  473      * XXX should be configurable eg. via userland policy manager.
  474      */
  475     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep, sc, ACPI_EVENT_PRI_LAST);
  476     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup, sc, ACPI_EVENT_PRI_LAST);
  477 
  478     /*
  479      * Flag our initial states.
  480      */
  481     sc->acpi_enabled = 1;
  482     sc->acpi_sstate = ACPI_STATE_S0;
  483     sc->acpi_sleep_disabled = 0;
  484 
  485     /*
  486      * Create the control device
  487      */
  488     sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_WHEEL, 0644,
  489         "acpi");
  490     sc->acpi_dev_t->si_drv1 = sc;
  491 
  492 #ifdef ACPI_DEBUGGER
  493     debugpoint = getenv("debug.acpi.debugger");
  494     if (debugpoint) {
  495         if (!strcmp(debugpoint, "running"))
  496             acpi_EnterDebugger();
  497         freeenv(debugpoint);
  498     }
  499 #endif
  500 
  501 #ifdef ACPI_USE_THREADS
  502     if ((error = acpi_task_thread_init())) {
  503         goto out;
  504     }
  505 #endif
  506 
  507     if ((error = acpi_machdep_init(dev))) {
  508         goto out;
  509     }
  510 
  511     /* Register ACPI again to pass the correct argument of pm_func. */
  512     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
  513 
  514     if (!acpi_disabled("bus"))
  515         acpi_probe_children(dev);
  516 
  517     error = 0;
  518 
  519  out:
  520     ACPI_UNLOCK;
  521     return_VALUE(error);
  522 }
  523 
  524 /*
  525  * Handle a new device being added
  526  */
  527 static device_t
  528 acpi_add_child(device_t bus, int order, const char *name, int unit)
  529 {
  530     struct acpi_device  *ad;
  531     device_t            child;
  532 
  533     if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT)) == NULL)
  534         return(NULL);
  535     bzero(ad, sizeof(*ad));
  536 
  537     resource_list_init(&ad->ad_rl);
  538     
  539     child = device_add_child_ordered(bus, order, name, unit);
  540     if (child != NULL)
  541         device_set_ivars(child, ad);
  542     return(child);
  543 }
  544 
  545 static int
  546 acpi_print_child(device_t bus, device_t child)
  547 {
  548     struct acpi_device          *adev = device_get_ivars(child);
  549     struct resource_list        *rl = &adev->ad_rl;
  550     int retval = 0;
  551 
  552     retval += bus_print_child_header(bus, child);
  553     retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
  554     retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
  555     retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
  556     retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
  557     retval += bus_print_child_footer(bus, child);
  558 
  559     return(retval);
  560 }
  561 
  562 
  563 /*
  564  * Handle per-device ivars
  565  */
  566 static int
  567 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
  568 {
  569     struct acpi_device  *ad;
  570 
  571     if ((ad = device_get_ivars(child)) == NULL) {
  572         printf("device has no ivars\n");
  573         return(ENOENT);
  574     }
  575 
  576     switch(index) {
  577         /* ACPI ivars */
  578     case ACPI_IVAR_HANDLE:
  579         *(ACPI_HANDLE *)result = ad->ad_handle;
  580         break;
  581     case ACPI_IVAR_MAGIC:
  582         *(int *)result = ad->ad_magic;
  583         break;
  584     case ACPI_IVAR_PRIVATE:
  585         *(void **)result = ad->ad_private;
  586         break;
  587 
  588         /* ISA compatibility */
  589     case ISA_IVAR_VENDORID:
  590     case ISA_IVAR_SERIAL:
  591     case ISA_IVAR_COMPATID:
  592         *(int *)result = -1;
  593         break;
  594 
  595     case ISA_IVAR_LOGICALID:
  596         *(int *)result = acpi_isa_get_logicalid(child);
  597         break;
  598 
  599     default:
  600         return(ENOENT);
  601     }
  602     return(0);
  603 }
  604 
  605 static int
  606 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
  607 {
  608     struct acpi_device  *ad;
  609 
  610     if ((ad = device_get_ivars(child)) == NULL) {
  611         printf("device has no ivars\n");
  612         return(ENOENT);
  613     }
  614 
  615     switch(index) {
  616         /* ACPI ivars */
  617     case ACPI_IVAR_HANDLE:
  618         ad->ad_handle = (ACPI_HANDLE)value;
  619         break;
  620     case ACPI_IVAR_MAGIC:
  621         ad->ad_magic = (int )value;
  622         break;
  623     case ACPI_IVAR_PRIVATE:
  624         ad->ad_private = (void *)value;
  625         break;
  626 
  627     default:
  628         panic("bad ivar write request (%d)", index);
  629         return(ENOENT);
  630     }
  631     return(0);
  632 }
  633 
  634 /*
  635  * Handle child resource allocation/removal
  636  */
  637 static int
  638 acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start, u_long count)
  639 {
  640     struct acpi_device          *ad = device_get_ivars(child);
  641     struct resource_list        *rl = &ad->ad_rl;
  642 
  643     resource_list_add(rl, type, rid, start, start + count -1, count);
  644 
  645     return(0);
  646 }
  647 
  648 static int
  649 acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp, u_long *countp)
  650 {
  651     struct acpi_device          *ad = device_get_ivars(child);
  652     struct resource_list        *rl = &ad->ad_rl;
  653     struct resource_list_entry  *rle;
  654 
  655     rle = resource_list_find(rl, type, rid);
  656     if (!rle)
  657         return(ENOENT);
  658         
  659     if (startp)
  660         *startp = rle->start;
  661     if (countp)
  662         *countp = rle->count;
  663 
  664     return(0);
  665 }
  666 
  667 static struct resource *
  668 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
  669                     u_long start, u_long end, u_long count, u_int flags)
  670 {
  671     struct acpi_device *ad = device_get_ivars(child);
  672     struct resource_list *rl = &ad->ad_rl;
  673 
  674     return(resource_list_alloc(rl, bus, child, type, rid, start, end, count, flags));
  675 }
  676 
  677 static int
  678 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
  679 {
  680     struct acpi_device *ad = device_get_ivars(child);
  681     struct resource_list *rl = &ad->ad_rl;
  682 
  683     return(resource_list_release(rl, bus, child, type, rid, r));
  684 }
  685 
  686 /*
  687  * Handle ISA-like devices probing for a PnP ID to match.
  688  */
  689 #define PNP_EISAID(s)                           \
  690         ((((s[0] - '@') & 0x1f) << 2)           \
  691          | (((s[1] - '@') & 0x18) >> 3)         \
  692          | (((s[1] - '@') & 0x07) << 13)        \
  693          | (((s[2] - '@') & 0x1f) << 8)         \
  694          | (PNP_HEXTONUM(s[4]) << 16)           \
  695          | (PNP_HEXTONUM(s[3]) << 20)           \
  696          | (PNP_HEXTONUM(s[6]) << 24)           \
  697          | (PNP_HEXTONUM(s[5]) << 28))
  698 
  699 static u_int32_t
  700 acpi_isa_get_logicalid(device_t dev)
  701 {
  702     ACPI_HANDLE         h;
  703     ACPI_DEVICE_INFO    devinfo;
  704     ACPI_STATUS         error;
  705     u_int32_t           pnpid;
  706     ACPI_LOCK_DECL;
  707 
  708     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
  709 
  710     pnpid = 0;
  711     ACPI_LOCK;
  712     
  713     /* fetch and validate the HID */
  714     if ((h = acpi_get_handle(dev)) == NULL)
  715         goto out;
  716     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
  717         goto out;
  718     if (!(devinfo.Valid & ACPI_VALID_HID))
  719         goto out;
  720 
  721     pnpid = PNP_EISAID(devinfo.HardwareId);
  722 out:
  723     ACPI_UNLOCK;
  724     return_VALUE(pnpid);
  725 }
  726 
  727 static u_int32_t
  728 acpi_isa_get_compatid(device_t dev)
  729 {
  730     ACPI_HANDLE         h;
  731     ACPI_DEVICE_INFO    devinfo;
  732     ACPI_STATUS         error;
  733     u_int32_t           pnpid;
  734     ACPI_LOCK_DECL;
  735 
  736     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
  737 
  738     pnpid = 0;
  739     ACPI_LOCK;
  740     
  741     /* fetch and validate the HID */
  742     if ((h = acpi_get_handle(dev)) == NULL)
  743         goto out;
  744     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
  745         goto out;
  746     if (ACPI_FAILURE(error = acpi_EvaluateInteger(h, "_CID", &pnpid)))
  747         goto out;
  748 
  749 out:
  750     ACPI_UNLOCK;
  751     return_VALUE(pnpid);
  752 }
  753 
  754 
  755 static int
  756 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
  757 {
  758     int                 result;
  759     u_int32_t           lid, cid;
  760 
  761     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
  762 
  763     /*
  764      * ISA-style drivers attached to ACPI may persist and
  765      * probe manually if we return ENOENT.  We never want
  766      * that to happen, so don't ever return it.
  767      */
  768     result = ENXIO;
  769 
  770     /* scan the supplied IDs for a match */
  771     lid = acpi_isa_get_logicalid(child);
  772     cid = acpi_isa_get_compatid(child);
  773     while (ids && ids->ip_id) {
  774         if (lid == ids->ip_id || cid == ids->ip_id) {
  775             result = 0;
  776             goto out;
  777         }
  778         ids++;
  779     }
  780  out:
  781     return_VALUE(result);
  782 }
  783 
  784 /*
  785  * Scan relevant portions of the ACPI namespace and attach child devices.
  786  *
  787  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and \_SB_ scopes, 
  788  * and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
  789  */
  790 static void
  791 acpi_probe_children(device_t bus)
  792 {
  793     ACPI_HANDLE         parent;
  794     static char         *scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
  795     int                 i;
  796 
  797     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
  798     ACPI_ASSERTLOCK;
  799 
  800     /*
  801      * Create any static children by calling device identify methods.
  802      */
  803     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
  804     bus_generic_probe(bus);
  805 
  806     /*
  807      * Scan the namespace and insert placeholders for all the devices that
  808      * we find.
  809      *
  810      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
  811      * we want to create nodes for all devices, not just those that are currently
  812      * present. (This assumes that we don't want to create/remove devices as they
  813      * appear, which might be smarter.)
  814      */
  815     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
  816     for (i = 0; scopes[i] != NULL; i++)
  817         if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent)))
  818             AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child, bus, NULL);
  819 
  820     /*
  821      * Scan all of the child devices we have created and let them probe/attach.
  822      */
  823     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
  824     bus_generic_attach(bus);
  825 
  826     /*
  827      * Some of these children may have attached others as part of their attach
  828      * process (eg. the root PCI bus driver), so rescan.
  829      */
  830     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
  831     bus_generic_attach(bus);
  832 
  833     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
  834     return_VOID;
  835 }
  836 
  837 /*
  838  * Evaluate a child device and determine whether we might attach a device to
  839  * it.
  840  */
  841 static ACPI_STATUS
  842 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
  843 {
  844     ACPI_OBJECT_TYPE    type;
  845     device_t            child, bus = (device_t)context;
  846 
  847     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
  848 
  849     /*
  850      * Skip this device if we think we'll have trouble with it.
  851      */
  852     if (acpi_avoid(handle))
  853         return_ACPI_STATUS(AE_OK);
  854 
  855     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
  856         switch(type) {
  857         case ACPI_TYPE_DEVICE:
  858         case ACPI_TYPE_PROCESSOR:
  859         case ACPI_TYPE_THERMAL:
  860         case ACPI_TYPE_POWER:
  861             if (acpi_disabled("children"))
  862                 break;
  863             /* 
  864              * Create a placeholder device for this node.  Sort the placeholder
  865              * so that the probe/attach passes will run breadth-first.
  866              */
  867             ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", acpi_name(handle)));
  868             child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
  869             if (child == NULL)
  870                 break;
  871             acpi_set_handle(child, handle);
  872 
  873             /*
  874              * Check that the device is present.  If it's not present,
  875              * leave it disabled (so that we have a device_t attached to
  876              * the handle, but we don't probe it).
  877              */
  878             if ((type == ACPI_TYPE_DEVICE) && (!acpi_DeviceIsPresent(child))) {
  879                 device_disable(child);
  880                 break;
  881             }
  882 
  883             /*
  884              * Get the device's resource settings and attach them.
  885              * Note that if the device has _PRS but no _CRS, we need
  886              * to decide when it's appropriate to try to configure the
  887              * device.  Ignore the return value here; it's OK for the
  888              * device not to have any resources.
  889              */
  890             acpi_parse_resources(child, handle, &acpi_res_parse_set);
  891 
  892             /* if we're debugging, probe/attach now rather than later */
  893             ACPI_DEBUG_EXEC(device_probe_and_attach(child));
  894             break;
  895         }
  896     }
  897     return_ACPI_STATUS(AE_OK);
  898 }
  899 
  900 static void
  901 acpi_shutdown_pre_sync(void *arg, int howto)
  902 {
  903 
  904     struct acpi_softc *sc = arg;
  905 
  906     ACPI_ASSERTLOCK;
  907 
  908     /*
  909      * Disable all ACPI events before soft off, otherwise the system
  910      * will be turned on again on some laptops.
  911      *
  912      * XXX this should probably be restricted to masking some events just
  913      *     before powering down, since we may still need ACPI during the
  914      *     shutdown process.
  915      */
  916     if (sc->acpi_disable_on_poweroff)
  917         acpi_Disable(sc);
  918 }
  919 
  920 static void
  921 acpi_shutdown_final(void *arg, int howto)
  922 {
  923     ACPI_STATUS status;
  924 
  925     ACPI_ASSERTLOCK;
  926 
  927     if (howto & RB_POWEROFF) {
  928         printf("Power system off using ACPI...\n");
  929         if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(acpi_off_state))) {
  930             printf("AcpiEnterSleepStatePrep failed - %s\n",
  931                    AcpiFormatException(status));
  932             return;
  933         }
  934         if (ACPI_FAILURE(status = AcpiEnterSleepState(acpi_off_state))) {
  935             printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
  936         } else {
  937             DELAY(1000000);
  938             printf("ACPI power-off failed - timeout\n");
  939         }
  940     } else {
  941         printf("Terminate ACPI\n");
  942         AcpiTerminate();
  943     }
  944 }
  945 
  946 static void
  947 acpi_enable_fixed_events(struct acpi_softc *sc)
  948 {
  949     static int  first_time = 1;
  950 #define MSGFORMAT "%s button is handled as a fixed feature programming model.\n"
  951 
  952     ACPI_ASSERTLOCK;
  953 
  954     /* Enable and clear fixed events and install handlers. */
  955     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->PwrButton == 0)) {
  956         AcpiEnableEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED, 0);
  957         AcpiClearEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
  958         AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
  959                                      acpi_eventhandler_power_button_for_sleep, sc);
  960         if (first_time) {
  961             device_printf(sc->acpi_dev, MSGFORMAT, "power");
  962         }
  963     }
  964     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->SleepButton == 0)) {
  965         AcpiEnableEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED, 0);
  966         AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
  967         AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
  968                                      acpi_eventhandler_sleep_button_for_sleep, sc);
  969         if (first_time) {
  970             device_printf(sc->acpi_dev, MSGFORMAT, "sleep");
  971         }
  972     }
  973 
  974     first_time = 0;
  975 }
  976 
  977 /*
  978  * Returns true if the device is actually present and should
  979  * be attached to.  This requires the present, enabled, UI-visible 
  980  * and diagnostics-passed bits to be set.
  981  */
  982 BOOLEAN
  983 acpi_DeviceIsPresent(device_t dev)
  984 {
  985     ACPI_HANDLE         h;
  986     ACPI_DEVICE_INFO    devinfo;
  987     ACPI_STATUS         error;
  988 
  989     ACPI_ASSERTLOCK;
  990     
  991     if ((h = acpi_get_handle(dev)) == NULL)
  992         return(FALSE);
  993     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
  994         return(FALSE);
  995     /* if no _STA method, must be present */
  996     if (!(devinfo.Valid & ACPI_VALID_STA))
  997         return(TRUE);
  998     /* return true for 'present' and 'functioning' */
  999     if ((devinfo.CurrentStatus & 0x9) == 0x9)
 1000         return(TRUE);
 1001     return(FALSE);
 1002 }
 1003 
 1004 /*
 1005  * Returns true if the battery is actually present and inserted.
 1006  */
 1007 BOOLEAN
 1008 acpi_BatteryIsPresent(device_t dev)
 1009 {
 1010     ACPI_HANDLE         h;
 1011     ACPI_DEVICE_INFO    devinfo;
 1012     ACPI_STATUS         error;
 1013 
 1014     ACPI_ASSERTLOCK;
 1015     
 1016     if ((h = acpi_get_handle(dev)) == NULL)
 1017         return(FALSE);
 1018     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
 1019         return(FALSE);
 1020     /* if no _STA method, must be present */
 1021     if (!(devinfo.Valid & ACPI_VALID_STA))
 1022         return(TRUE);
 1023     /* return true for 'present' and 'functioning' */
 1024     if ((devinfo.CurrentStatus & 0x19) == 0x19)
 1025         return(TRUE);
 1026     return(FALSE);
 1027 }
 1028 
 1029 /*
 1030  * Match a HID string against a device
 1031  */
 1032 BOOLEAN
 1033 acpi_MatchHid(device_t dev, char *hid) 
 1034 {
 1035     ACPI_HANDLE         h;
 1036     ACPI_DEVICE_INFO    devinfo;
 1037     ACPI_STATUS         error;
 1038     int                 cid;
 1039 
 1040     ACPI_ASSERTLOCK;
 1041 
 1042     if (hid == NULL)
 1043         return(FALSE);
 1044     if ((h = acpi_get_handle(dev)) == NULL)
 1045         return(FALSE);
 1046     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
 1047         return(FALSE);
 1048     if ((devinfo.Valid & ACPI_VALID_HID) && !strcmp(hid, devinfo.HardwareId))
 1049         return(TRUE);
 1050     if (ACPI_FAILURE(error = acpi_EvaluateInteger(h, "_CID", &cid)))
 1051         return(FALSE);
 1052     if (cid == PNP_EISAID(hid))
 1053         return(TRUE);
 1054     return(FALSE);
 1055 }
 1056 
 1057 /*
 1058  * Return the handle of a named object within our scope, ie. that of (parent)
 1059  * or one if its parents.
 1060  */
 1061 ACPI_STATUS
 1062 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
 1063 {
 1064     ACPI_HANDLE         r;
 1065     ACPI_STATUS         status;
 1066 
 1067     ACPI_ASSERTLOCK;
 1068 
 1069     /* walk back up the tree to the root */
 1070     for (;;) {
 1071         if (ACPI_SUCCESS(status = AcpiGetHandle(parent, path, &r))) {
 1072             *result = r;
 1073             return(AE_OK);
 1074         }
 1075         if (status != AE_NOT_FOUND)
 1076             return(AE_OK);
 1077         if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
 1078             return(AE_NOT_FOUND);
 1079         parent = r;
 1080     }
 1081 }
 1082 
 1083 /*
 1084  * Allocate a buffer with a preset data size.
 1085  */
 1086 ACPI_BUFFER *
 1087 acpi_AllocBuffer(int size)
 1088 {
 1089     ACPI_BUFFER *buf;
 1090 
 1091     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
 1092         return(NULL);
 1093     buf->Length = size;
 1094     buf->Pointer = (void *)(buf + 1);
 1095     return(buf);
 1096 }
 1097 
 1098 /*
 1099  * Evaluate a path that should return an integer.
 1100  */
 1101 ACPI_STATUS
 1102 acpi_EvaluateInteger(ACPI_HANDLE handle, char *path, int *number)
 1103 {
 1104     ACPI_STATUS error;
 1105     ACPI_BUFFER buf;
 1106     ACPI_OBJECT param;
 1107 
 1108     ACPI_ASSERTLOCK;
 1109 
 1110     if (handle == NULL)
 1111         handle = ACPI_ROOT_OBJECT;
 1112 
 1113     /*
 1114      * Assume that what we've been pointed at is an Integer object, or
 1115      * a method that will return an Integer.
 1116      */
 1117     buf.Pointer = &param;
 1118     buf.Length = sizeof(param);
 1119     if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
 1120         if (param.Type == ACPI_TYPE_INTEGER) {
 1121             *number = param.Integer.Value;
 1122         } else {
 1123             error = AE_TYPE;
 1124         }
 1125     }
 1126 
 1127     /* 
 1128      * In some applications, a method that's expected to return an Integer
 1129      * may instead return a Buffer (probably to simplify some internal
 1130      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
 1131      * convert it into an Integer as best we can.
 1132      *
 1133      * This is a hack.
 1134      */
 1135     if (error == AE_BUFFER_OVERFLOW) {
 1136         if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
 1137             error = AE_NO_MEMORY;
 1138         } else {
 1139             if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
 1140                 error = acpi_ConvertBufferToInteger(&buf, number);
 1141             }
 1142         }
 1143         AcpiOsFree(buf.Pointer);
 1144     }
 1145     return(error);
 1146 }
 1147 
 1148 ACPI_STATUS
 1149 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, int *number)
 1150 {
 1151     ACPI_OBJECT *p;
 1152     int         i;
 1153 
 1154     p = (ACPI_OBJECT *)bufp->Pointer;
 1155     if (p->Type == ACPI_TYPE_INTEGER) {
 1156         *number = p->Integer.Value;
 1157         return(AE_OK);
 1158     }
 1159     if (p->Type != ACPI_TYPE_BUFFER)
 1160         return(AE_TYPE);
 1161     if (p->Buffer.Length > sizeof(int))
 1162         return(AE_BAD_DATA);
 1163     *number = 0;
 1164     for (i = 0; i < p->Buffer.Length; i++)
 1165         *number += (*(p->Buffer.Pointer + i) << (i * 8));
 1166     return(AE_OK);
 1167 }
 1168 
 1169 /*
 1170  * Iterate over the elements of an a package object, calling the supplied
 1171  * function for each element.
 1172  *
 1173  * XXX possible enhancement might be to abort traversal on error.
 1174  */
 1175 ACPI_STATUS
 1176 acpi_ForeachPackageObject(ACPI_OBJECT *pkg, void (* func)(ACPI_OBJECT *comp, void *arg), void *arg)
 1177 {
 1178     ACPI_OBJECT *comp;
 1179     int         i;
 1180     
 1181     if ((pkg == NULL) || (pkg->Type != ACPI_TYPE_PACKAGE))
 1182         return(AE_BAD_PARAMETER);
 1183 
 1184     /* iterate over components */
 1185     for (i = 0, comp = pkg->Package.Elements; i < pkg->Package.Count; i++, comp++)
 1186         func(comp, arg);
 1187 
 1188     return(AE_OK);
 1189 }
 1190 
 1191 /*
 1192  * Find the (index)th resource object in a set.
 1193  */
 1194 ACPI_STATUS
 1195 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
 1196 {
 1197     ACPI_RESOURCE       *rp;
 1198     int                 i;
 1199 
 1200     rp = (ACPI_RESOURCE *)buf->Pointer;
 1201     i = index;
 1202     while (i-- > 0) {
 1203         /* range check */       
 1204         if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
 1205             return(AE_BAD_PARAMETER);
 1206         /* check for terminator */
 1207         if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
 1208             (rp->Length == 0))
 1209             return(AE_NOT_FOUND);
 1210         rp = ACPI_RESOURCE_NEXT(rp);
 1211     }
 1212     if (resp != NULL)
 1213         *resp = rp;
 1214     return(AE_OK);
 1215 }
 1216 
 1217 /*
 1218  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
 1219  *
 1220  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
 1221  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
 1222  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
 1223  * resources.
 1224  */
 1225 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE       512
 1226 
 1227 ACPI_STATUS
 1228 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
 1229 {
 1230     ACPI_RESOURCE       *rp;
 1231     void                *newp;
 1232     
 1233     /*
 1234      * Initialise the buffer if necessary.
 1235      */
 1236     if (buf->Pointer == NULL) {
 1237         buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
 1238         if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
 1239             return(AE_NO_MEMORY);
 1240         rp = (ACPI_RESOURCE *)buf->Pointer;
 1241         rp->Id = ACPI_RSTYPE_END_TAG;
 1242         rp->Length = 0;
 1243     }
 1244     if (res == NULL)
 1245         return(AE_OK);
 1246     
 1247     /*
 1248      * Scan the current buffer looking for the terminator.
 1249      * This will either find the terminator or hit the end
 1250      * of the buffer and return an error.
 1251      */
 1252     rp = (ACPI_RESOURCE *)buf->Pointer;
 1253     for (;;) {
 1254         /* range check, don't go outside the buffer */
 1255         if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
 1256             return(AE_BAD_PARAMETER);
 1257         if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
 1258             (rp->Length == 0)) {
 1259             break;
 1260         }
 1261         rp = ACPI_RESOURCE_NEXT(rp);
 1262     }
 1263 
 1264     /*
 1265      * Check the size of the buffer and expand if required.
 1266      *
 1267      * Required size is:
 1268      *  size of existing resources before terminator + 
 1269      *  size of new resource and header +
 1270      *  size of terminator.
 1271      *
 1272      * Note that this loop should really only run once, unless
 1273      * for some reason we are stuffing a *really* huge resource.
 1274      */
 1275     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) + 
 1276             res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
 1277             ACPI_RESOURCE_LENGTH) >= buf->Length) {
 1278         if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
 1279             return(AE_NO_MEMORY);
 1280         bcopy(buf->Pointer, newp, buf->Length);
 1281         rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
 1282                                ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
 1283         AcpiOsFree(buf->Pointer);
 1284         buf->Pointer = newp;
 1285         buf->Length += buf->Length;
 1286     }
 1287     
 1288     /*
 1289      * Insert the new resource.
 1290      */
 1291     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
 1292     
 1293     /*
 1294      * And add the terminator.
 1295      */
 1296     rp = ACPI_RESOURCE_NEXT(rp);
 1297     rp->Id = ACPI_RSTYPE_END_TAG;
 1298     rp->Length = 0;
 1299 
 1300     return(AE_OK);
 1301 }
 1302 
 1303 /*
 1304  * Set interrupt model.
 1305  */
 1306 ACPI_STATUS
 1307 acpi_SetIntrModel(int model)
 1308 {
 1309         ACPI_OBJECT_LIST ArgList;
 1310         ACPI_OBJECT Arg;
 1311 
 1312         Arg.Type = ACPI_TYPE_INTEGER;
 1313         Arg.Integer.Value = model;
 1314         ArgList.Count = 1;
 1315         ArgList.Pointer = &Arg;
 1316         return (AcpiEvaluateObject(ACPI_ROOT_OBJECT, "_PIC", &ArgList, NULL));
 1317 }
 1318 
 1319 #define ACPI_MINIMUM_AWAKETIME  5
 1320 
 1321 static void
 1322 acpi_sleep_enable(void *arg)
 1323 {
 1324     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
 1325 }
 1326 
 1327 /*
 1328  * Set the system sleep state
 1329  *
 1330  * Currently we only support S1 and S5
 1331  */
 1332 ACPI_STATUS
 1333 acpi_SetSleepState(struct acpi_softc *sc, int state)
 1334 {
 1335     ACPI_STATUS status = AE_OK;
 1336     UINT8       TypeA;
 1337     UINT8       TypeB;
 1338 
 1339     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
 1340     ACPI_ASSERTLOCK;
 1341 
 1342     if (sc->acpi_sstate != ACPI_STATE_S0)
 1343         return_ACPI_STATUS(AE_BAD_PARAMETER);   /* avoid reentry */
 1344 
 1345     if (sc->acpi_sleep_disabled)
 1346         return_ACPI_STATUS(AE_OK);
 1347 
 1348     switch (state) {
 1349     case ACPI_STATE_S0: /* XXX only for testing */
 1350         if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
 1351             device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
 1352         }
 1353         break;
 1354 
 1355     case ACPI_STATE_S1:
 1356     case ACPI_STATE_S2:
 1357     case ACPI_STATE_S3:
 1358     case ACPI_STATE_S4:
 1359         if (ACPI_FAILURE(status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB))) {
 1360             device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n", AcpiFormatException(status));
 1361             break;
 1362         }
 1363 
 1364         sc->acpi_sstate = state;
 1365         sc->acpi_sleep_disabled = 1;
 1366 
 1367         /*
 1368          * Inform all devices that we are going to sleep.
 1369          */
 1370         if (DEVICE_SUSPEND(root_bus) != 0) {
 1371             /*
 1372              * Re-wake the system.
 1373              *
 1374              * XXX note that a better two-pass approach with a 'veto' pass
 1375              *     followed by a "real thing" pass would be better, but the
 1376              *     current bus interface does not provide for this.
 1377              */
 1378             DEVICE_RESUME(root_bus);
 1379             return_ACPI_STATUS(AE_ERROR);
 1380         }
 1381 
 1382         if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(state))) {
 1383             device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
 1384                           AcpiFormatException(status));
 1385             break;
 1386         }
 1387 
 1388         if (sc->acpi_sleep_delay > 0) {
 1389             DELAY(sc->acpi_sleep_delay * 1000000);
 1390         }
 1391 
 1392         if (state != ACPI_STATE_S1) {
 1393             acpi_sleep_machdep(sc, state);
 1394 
 1395             /* AcpiEnterSleepState() maybe incompleted, unlock here if locked. */
 1396             if (AcpiGbl_AcpiMutexInfo[ACPI_MTX_HARDWARE].OwnerId != ACPI_MUTEX_NOT_ACQUIRED) {
 1397                 AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
 1398             }
 1399 
 1400             /* Re-enable ACPI hardware on wakeup from sleep state 4. */
 1401             if (state == ACPI_STATE_S4) {
 1402                 AcpiEnable();
 1403             }
 1404         } else {
 1405             if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
 1406                 device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
 1407                 break;
 1408             }
 1409         }
 1410         AcpiLeaveSleepState((UINT8)state);
 1411         DEVICE_RESUME(root_bus);
 1412         sc->acpi_sstate = ACPI_STATE_S0;
 1413         acpi_enable_fixed_events(sc);
 1414         break;
 1415 
 1416     case ACPI_STATE_S5:
 1417         /*
 1418          * Shut down cleanly and power off.  This will call us back through the
 1419          * shutdown handlers.
 1420          */
 1421         shutdown_nice(RB_POWEROFF);
 1422         break;
 1423 
 1424     default:
 1425         status = AE_BAD_PARAMETER;
 1426         break;
 1427     }
 1428 
 1429     if (sc->acpi_sleep_disabled)
 1430         timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
 1431 
 1432     return_ACPI_STATUS(status);
 1433 }
 1434 
 1435 /*
 1436  * Enable/Disable ACPI
 1437  */
 1438 ACPI_STATUS
 1439 acpi_Enable(struct acpi_softc *sc)
 1440 {
 1441     ACPI_STATUS status;
 1442     u_int32_t   flags;
 1443 
 1444     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
 1445     ACPI_ASSERTLOCK;
 1446 
 1447     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
 1448             ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
 1449     if (!sc->acpi_enabled) {
 1450         status = AcpiEnableSubsystem(flags);
 1451     } else {
 1452         status = AE_OK;
 1453     }
 1454     if (status == AE_OK)
 1455         sc->acpi_enabled = 1;
 1456     return_ACPI_STATUS(status);
 1457 }
 1458 
 1459 ACPI_STATUS
 1460 acpi_Disable(struct acpi_softc *sc)
 1461 {
 1462     ACPI_STATUS status;
 1463 
 1464     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
 1465     ACPI_ASSERTLOCK;
 1466 
 1467     if (sc->acpi_enabled) {
 1468         status = AcpiDisable();
 1469     } else {
 1470         status = AE_OK;
 1471     }
 1472     if (status == AE_OK)
 1473         sc->acpi_enabled = 0;
 1474     return_ACPI_STATUS(status);
 1475 }
 1476 
 1477 /*
 1478  * ACPI Event Handlers
 1479  */
 1480 
 1481 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
 1482 
 1483 static void
 1484 acpi_system_eventhandler_sleep(void *arg, int state)
 1485 {
 1486     ACPI_LOCK_DECL;
 1487     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
 1488 
 1489     ACPI_LOCK;
 1490     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
 1491         acpi_SetSleepState((struct acpi_softc *)arg, state);
 1492     ACPI_UNLOCK;
 1493     return_VOID;
 1494 }
 1495 
 1496 static void
 1497 acpi_system_eventhandler_wakeup(void *arg, int state)
 1498 {
 1499     ACPI_LOCK_DECL;
 1500     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
 1501 
 1502     /* Well, what to do? :-) */
 1503 
 1504     ACPI_LOCK;
 1505     ACPI_UNLOCK;
 1506 
 1507     return_VOID;
 1508 }
 1509 
 1510 /* 
 1511  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
 1512  */
 1513 UINT32
 1514 acpi_eventhandler_power_button_for_sleep(void *context)
 1515 {
 1516     struct acpi_softc   *sc = (struct acpi_softc *)context;
 1517 
 1518     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
 1519 
 1520     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
 1521 
 1522     return_VALUE(ACPI_INTERRUPT_HANDLED);
 1523 }
 1524 
 1525 UINT32
 1526 acpi_eventhandler_power_button_for_wakeup(void *context)
 1527 {
 1528     struct acpi_softc   *sc = (struct acpi_softc *)context;
 1529 
 1530     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
 1531 
 1532     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
 1533 
 1534     return_VALUE(ACPI_INTERRUPT_HANDLED);
 1535 }
 1536 
 1537 UINT32
 1538 acpi_eventhandler_sleep_button_for_sleep(void *context)
 1539 {
 1540     struct acpi_softc   *sc = (struct acpi_softc *)context;
 1541 
 1542     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
 1543 
 1544     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
 1545 
 1546     return_VALUE(ACPI_INTERRUPT_HANDLED);
 1547 }
 1548 
 1549 UINT32
 1550 acpi_eventhandler_sleep_button_for_wakeup(void *context)
 1551 {
 1552     struct acpi_softc   *sc = (struct acpi_softc *)context;
 1553 
 1554     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
 1555 
 1556     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
 1557 
 1558     return_VALUE(ACPI_INTERRUPT_HANDLED);
 1559 }
 1560 
 1561 /*
 1562  * XXX This is kinda ugly, and should not be here.
 1563  */
 1564 struct acpi_staticbuf {
 1565     ACPI_BUFFER buffer;
 1566     char        data[512];
 1567 };
 1568 
 1569 char *
 1570 acpi_name(ACPI_HANDLE handle)
 1571 {
 1572     static struct acpi_staticbuf        buf;
 1573 
 1574     ACPI_ASSERTLOCK;
 1575 
 1576     buf.buffer.Length = 512;
 1577     buf.buffer.Pointer = &buf.data[0];
 1578 
 1579     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
 1580         return(buf.buffer.Pointer);
 1581     return("(unknown path)");
 1582 }
 1583 
 1584 /*
 1585  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
 1586  * parts of the namespace.
 1587  */
 1588 int
 1589 acpi_avoid(ACPI_HANDLE handle)
 1590 {
 1591     char        *cp, *env, *np;
 1592     int         len;
 1593 
 1594     np = acpi_name(handle);
 1595     if (*np == '\\')
 1596         np++;
 1597     if ((env = getenv("debug.acpi.avoid")) == NULL)
 1598         return(0);
 1599 
 1600     /* scan the avoid list checking for a match */
 1601     cp = env;
 1602     for (;;) {
 1603         while ((*cp != 0) && isspace(*cp))
 1604             cp++;
 1605         if (*cp == 0)
 1606             break;
 1607         len = 0;
 1608         while ((cp[len] != 0) && !isspace(cp[len]))
 1609             len++;
 1610         if (!strncmp(cp, np, len)) {
 1611             freeenv(env);
 1612             return(1);
 1613         }
 1614         cp += len;
 1615     }
 1616     freeenv(env);
 1617     return(0);
 1618 }
 1619 
 1620 /*
 1621  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
 1622  */
 1623 int
 1624 acpi_disabled(char *subsys)
 1625 {
 1626     char        *cp, *env;
 1627     int         len;
 1628 
 1629     if ((env = getenv("debug.acpi.disable")) == NULL)
 1630         return(0);
 1631     if (!strcmp(env, "all")) {
 1632         freeenv(env);
 1633         return(1);
 1634     }
 1635 
 1636     /* scan the disable list checking for a match */
 1637     cp = env;
 1638     for (;;) {
 1639         while ((*cp != 0) && isspace(*cp))
 1640             cp++;
 1641         if (*cp == 0)
 1642             break;
 1643         len = 0;
 1644         while ((cp[len] != 0) && !isspace(cp[len]))
 1645             len++;
 1646         if (!strncmp(cp, subsys, len)) {
 1647             freeenv(env);
 1648             return(1);
 1649         }
 1650         cp += len;
 1651     }
 1652     freeenv(env);
 1653     return(0);
 1654 }
 1655 
 1656 /*
 1657  * Device wake capability enable/disable.
 1658  */
 1659 void
 1660 acpi_device_enable_wake_capability(ACPI_HANDLE h, int enable)
 1661 {
 1662     ACPI_OBJECT_LIST            ArgList;
 1663     ACPI_OBJECT                 Arg;
 1664 
 1665     /*
 1666      * TBD: All Power Resources referenced by elements 2 through N
 1667      *      of the _PRW object are put into the ON state.
 1668      */
 1669 
 1670     /*
 1671      * enable/disable device wake function.
 1672      */
 1673 
 1674     ArgList.Count = 1;
 1675     ArgList.Pointer = &Arg;
 1676 
 1677     Arg.Type = ACPI_TYPE_INTEGER;
 1678     Arg.Integer.Value = enable;
 1679 
 1680     (void)AcpiEvaluateObject(h, "_PSW", &ArgList, NULL);
 1681 }
 1682 
 1683 void
 1684 acpi_device_enable_wake_event(ACPI_HANDLE h)
 1685 {
 1686     struct acpi_softc           *sc;
 1687     ACPI_STATUS                 status;
 1688     ACPI_BUFFER                 prw_buffer;
 1689     ACPI_OBJECT                 *res;
 1690 
 1691     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
 1692 
 1693     if ((sc = devclass_get_softc(acpi_devclass, 0)) == NULL) {
 1694         return;
 1695     }
 1696 
 1697     /*
 1698      * _PRW object is only required for devices that have the ability
 1699      * to wake the system from a system sleeping state.
 1700      */
 1701     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
 1702     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
 1703     if (ACPI_FAILURE(status)) {
 1704         return;
 1705     }
 1706 
 1707     res = (ACPI_OBJECT *)prw_buffer.Pointer;
 1708     if (res == NULL) {
 1709         return;
 1710     }
 1711 
 1712     if ((res->Type != ACPI_TYPE_PACKAGE) || (res->Package.Count < 2)) {
 1713         goto out;
 1714     }
 1715 
 1716     /*
 1717      * The element 1 of the _PRW object:
 1718      * The lowest power system sleeping state that can be entered
 1719      * while still providing wake functionality.
 1720      * The sleeping state being entered must be greater or equal to
 1721      * the power state declared in element 1 of the _PRW object.
 1722      */
 1723     if (res->Package.Elements[1].Type != ACPI_TYPE_INTEGER) {
 1724         goto out;
 1725     }
 1726 
 1727     if (sc->acpi_sstate > res->Package.Elements[1].Integer.Value) {
 1728         goto out;
 1729     }
 1730 
 1731     /*
 1732      * The element 0 of the _PRW object:
 1733      */
 1734     switch(res->Package.Elements[0].Type) {
 1735     case ACPI_TYPE_INTEGER:
 1736         /* 
 1737          * If the data type of this package element is numeric, then this
 1738          * _PRW package element is the bit index in the GPEx_EN, in the
 1739          * GPE blocks described in the FADT, of the enable bit that is
 1740          * enabled for the wake event.
 1741          */
 1742 
 1743         status = AcpiEnableEvent(res->Package.Elements[0].Integer.Value,
 1744                                  ACPI_EVENT_GPE, ACPI_EVENT_WAKE_ENABLE);
 1745         if (ACPI_FAILURE(status))
 1746             printf("%s: EnableEvent Failed\n", __func__);
 1747         break;
 1748 
 1749     case ACPI_TYPE_PACKAGE:
 1750         /* XXX TBD */
 1751 
 1752         /*
 1753          * If the data type of this package element is a package, then this
 1754          * _PRW package element is itself a package containing two
 1755          * elements. The first is an object reference to the GPE Block
 1756          * device that contains the GPE that will be triggered by the wake
 1757          * event. The second element is numeric and it contains the bit
 1758          * index in the GPEx_EN, in the GPE Block referenced by the
 1759          * first element in the package, of the enable bit that is enabled for
 1760          * the wake event.
 1761          * For example, if this field is a package then it is of the form:
 1762          * Package() {\_SB.PCI0.ISA.GPE, 2}
 1763          */
 1764 
 1765         break;
 1766 
 1767     default:
 1768         break;
 1769     }
 1770 
 1771 out:
 1772     if (prw_buffer.Pointer != NULL)
 1773         AcpiOsFree(prw_buffer.Pointer);
 1774     return;
 1775 }
 1776 
 1777 /*
 1778  * Control interface.
 1779  *
 1780  * We multiplex ioctls for all participating ACPI devices here.  Individual 
 1781  * drivers wanting to be accessible via /dev/acpi should use the register/deregister
 1782  * interface to make their handlers visible.
 1783  */
 1784 struct acpi_ioctl_hook
 1785 {
 1786     TAILQ_ENTRY(acpi_ioctl_hook)        link;
 1787     u_long                              cmd;
 1788     int                                 (* fn)(u_long cmd, caddr_t addr, void *arg);
 1789     void                                *arg;
 1790 };
 1791 
 1792 static TAILQ_HEAD(,acpi_ioctl_hook)     acpi_ioctl_hooks;
 1793 static int                              acpi_ioctl_hooks_initted;
 1794 
 1795 /*
 1796  * Register an ioctl handler.
 1797  */
 1798 int
 1799 acpi_register_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg), void *arg)
 1800 {
 1801     struct acpi_ioctl_hook      *hp;
 1802 
 1803     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
 1804         return(ENOMEM);
 1805     hp->cmd = cmd;
 1806     hp->fn = fn;
 1807     hp->arg = arg;
 1808     if (acpi_ioctl_hooks_initted == 0) {
 1809         TAILQ_INIT(&acpi_ioctl_hooks);
 1810         acpi_ioctl_hooks_initted = 1;
 1811     }
 1812     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
 1813     return(0);
 1814 }
 1815 
 1816 /*
 1817  * Deregister an ioctl handler.
 1818  */
 1819 void    
 1820 acpi_deregister_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg))
 1821 {
 1822     struct acpi_ioctl_hook      *hp;
 1823 
 1824     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
 1825         if ((hp->cmd == cmd) && (hp->fn == fn))
 1826             break;
 1827 
 1828     if (hp != NULL) {
 1829         TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
 1830         free(hp, M_ACPIDEV);
 1831     }
 1832 }
 1833 
 1834 static int
 1835 acpiopen(dev_t dev, int flag, int fmt, d_thread_t *td)
 1836 {
 1837     return(0);
 1838 }
 1839 
 1840 static int
 1841 acpiclose(dev_t dev, int flag, int fmt, d_thread_t *td)
 1842 {
 1843     return(0);
 1844 }
 1845 
 1846 static int
 1847 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
 1848 {
 1849     struct acpi_softc           *sc;
 1850     struct acpi_ioctl_hook      *hp;
 1851     int                         error, xerror, state;
 1852     ACPI_LOCK_DECL;
 1853 
 1854     ACPI_LOCK;
 1855 
 1856     error = state = 0;
 1857     sc = dev->si_drv1;
 1858 
 1859     /*
 1860      * Scan the list of registered ioctls, looking for handlers.
 1861      */
 1862     if (acpi_ioctl_hooks_initted) {
 1863         TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
 1864             if (hp->cmd == cmd) {
 1865                 xerror = hp->fn(cmd, addr, hp->arg);
 1866                 if (xerror != 0)
 1867                     error = xerror;
 1868                 goto out;
 1869             }
 1870         }
 1871     }
 1872 
 1873     /*
 1874      * Core ioctls are  not permitted for non-writable user.
 1875      * Currently, other ioctls just fetch information.
 1876      * Not changing system behavior.
 1877      */
 1878     if(!(flag & FWRITE)){
 1879             return EPERM;
 1880     }
 1881 
 1882     /*
 1883      * Core system ioctls.
 1884      */
 1885     switch (cmd) {
 1886     case ACPIIO_ENABLE:
 1887         if (ACPI_FAILURE(acpi_Enable(sc)))
 1888             error = ENXIO;
 1889         break;
 1890 
 1891     case ACPIIO_DISABLE:
 1892         if (ACPI_FAILURE(acpi_Disable(sc)))
 1893             error = ENXIO;
 1894         break;
 1895 
 1896     case ACPIIO_SETSLPSTATE:
 1897         if (!sc->acpi_enabled) {
 1898             error = ENXIO;
 1899             break;
 1900         }
 1901         state = *(int *)addr;
 1902         if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
 1903             acpi_SetSleepState(sc, state);
 1904         } else {
 1905             error = EINVAL;
 1906         }
 1907         break;
 1908 
 1909     default:
 1910         if (error == 0)
 1911             error = EINVAL;
 1912         break;
 1913     }
 1914 
 1915 out:
 1916     ACPI_UNLOCK;
 1917     return(error);
 1918 }
 1919 
 1920 static int
 1921 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
 1922 {
 1923     char sleep_state[4];
 1924     char buf[16];
 1925     int error;
 1926     UINT8 state, TypeA, TypeB;
 1927 
 1928     buf[0] = '\0';
 1929     for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX+1; state++) {
 1930         if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
 1931             sprintf(sleep_state, "S%d ", state);
 1932             strcat(buf, sleep_state);
 1933         }
 1934     }
 1935     error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
 1936     return(error);
 1937 }
 1938 
 1939 static int
 1940 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
 1941 {
 1942     char sleep_state[10];
 1943     int error;
 1944     u_int new_state, old_state;
 1945 
 1946     old_state = *(u_int *)oidp->oid_arg1;
 1947     if (old_state > ACPI_S_STATES_MAX+1) {
 1948         strcpy(sleep_state, "unknown");
 1949     } else {
 1950         bzero(sleep_state, sizeof(sleep_state));
 1951         strncpy(sleep_state, sleep_state_names[old_state],
 1952                 sizeof(sleep_state_names[old_state]));
 1953     }
 1954     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
 1955     if (error == 0 && req->newptr != NULL) {
 1956         for (new_state = ACPI_STATE_S0; new_state <= ACPI_S_STATES_MAX+1; new_state++) {
 1957             if (strncmp(sleep_state, sleep_state_names[new_state],
 1958                         sizeof(sleep_state)) == 0)
 1959                 break;
 1960         }
 1961         if (new_state <= ACPI_S_STATES_MAX+1) {
 1962             if (new_state != old_state) {
 1963                 *(u_int *)oidp->oid_arg1 = new_state;
 1964             }
 1965         } else {
 1966             error = EINVAL;
 1967         }
 1968     }
 1969     return(error);
 1970 }
 1971 
 1972 #ifdef ACPI_DEBUG
 1973 /*
 1974  * Support for parsing debug options from the kernel environment.
 1975  *
 1976  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
 1977  * by specifying the names of the bits in the debug.acpi.layer and
 1978  * debug.acpi.level environment variables.  Bits may be unset by 
 1979  * prefixing the bit name with !.
 1980  */
 1981 struct debugtag
 1982 {
 1983     char        *name;
 1984     UINT32      value;
 1985 };
 1986 
 1987 static struct debugtag  dbg_layer[] = {
 1988     {"ACPI_UTILITIES",          ACPI_UTILITIES},
 1989     {"ACPI_HARDWARE",           ACPI_HARDWARE},
 1990     {"ACPI_EVENTS",             ACPI_EVENTS},
 1991     {"ACPI_TABLES",             ACPI_TABLES},
 1992     {"ACPI_NAMESPACE",          ACPI_NAMESPACE},
 1993     {"ACPI_PARSER",             ACPI_PARSER},
 1994     {"ACPI_DISPATCHER",         ACPI_DISPATCHER},
 1995     {"ACPI_EXECUTER",           ACPI_EXECUTER},
 1996     {"ACPI_RESOURCES",          ACPI_RESOURCES},
 1997     {"ACPI_CA_DEBUGGER",        ACPI_CA_DEBUGGER},
 1998     {"ACPI_OS_SERVICES",        ACPI_OS_SERVICES},
 1999     {"ACPI_CA_DISASSEMBLER",    ACPI_CA_DISASSEMBLER},
 2000 
 2001     {"ACPI_BUS",                ACPI_BUS},
 2002     {"ACPI_SYSTEM",             ACPI_SYSTEM},
 2003     {"ACPI_POWER",              ACPI_POWER},
 2004     {"ACPI_EC",                 ACPI_EC},
 2005     {"ACPI_AC_ADAPTER",         ACPI_AC_ADAPTER},
 2006     {"ACPI_BATTERY",            ACPI_BATTERY},
 2007     {"ACPI_BUTTON",             ACPI_BUTTON},
 2008     {"ACPI_PROCESSOR",          ACPI_PROCESSOR},
 2009     {"ACPI_THERMAL",            ACPI_THERMAL},
 2010     {"ACPI_FAN",                ACPI_FAN},
 2011 
 2012     {"ACPI_ALL_DRIVERS",        ACPI_ALL_DRIVERS},
 2013     {"ACPI_ALL_COMPONENTS",     ACPI_ALL_COMPONENTS},
 2014     {NULL, 0}
 2015 };
 2016 
 2017 static struct debugtag dbg_level[] = {
 2018     {"ACPI_LV_ERROR",           ACPI_LV_ERROR},
 2019     {"ACPI_LV_WARN",            ACPI_LV_WARN},
 2020     {"ACPI_LV_INIT",            ACPI_LV_INIT},
 2021     {"ACPI_LV_DEBUG_OBJECT",    ACPI_LV_DEBUG_OBJECT},
 2022     {"ACPI_LV_INFO",            ACPI_LV_INFO},
 2023     {"ACPI_LV_ALL_EXCEPTIONS",  ACPI_LV_ALL_EXCEPTIONS},
 2024 
 2025     /* Trace verbosity level 1 [Standard Trace Level] */
 2026     {"ACPI_LV_PARSE",           ACPI_LV_PARSE},
 2027     {"ACPI_LV_LOAD",            ACPI_LV_LOAD},
 2028     {"ACPI_LV_DISPATCH",        ACPI_LV_DISPATCH},
 2029     {"ACPI_LV_EXEC",            ACPI_LV_EXEC},
 2030     {"ACPI_LV_NAMES",           ACPI_LV_NAMES},
 2031     {"ACPI_LV_OPREGION",        ACPI_LV_OPREGION},
 2032     {"ACPI_LV_BFIELD",          ACPI_LV_BFIELD},
 2033     {"ACPI_LV_TABLES",          ACPI_LV_TABLES},
 2034     {"ACPI_LV_VALUES",          ACPI_LV_VALUES},
 2035     {"ACPI_LV_OBJECTS",         ACPI_LV_OBJECTS},
 2036     {"ACPI_LV_RESOURCES",       ACPI_LV_RESOURCES},
 2037     {"ACPI_LV_USER_REQUESTS",   ACPI_LV_USER_REQUESTS},
 2038     {"ACPI_LV_PACKAGE",         ACPI_LV_PACKAGE},
 2039     {"ACPI_LV_INIT_NAMES",      ACPI_LV_INIT_NAMES},
 2040     {"ACPI_LV_VERBOSITY1",      ACPI_LV_VERBOSITY1},
 2041 
 2042     /* Trace verbosity level 2 [Function tracing and memory allocation] */
 2043     {"ACPI_LV_ALLOCATIONS",     ACPI_LV_ALLOCATIONS},
 2044     {"ACPI_LV_FUNCTIONS",       ACPI_LV_FUNCTIONS},
 2045     {"ACPI_LV_OPTIMIZATIONS",   ACPI_LV_OPTIMIZATIONS},
 2046     {"ACPI_LV_VERBOSITY2",      ACPI_LV_VERBOSITY2},
 2047     {"ACPI_LV_ALL",             ACPI_LV_ALL},
 2048 
 2049     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
 2050     {"ACPI_LV_MUTEX",           ACPI_LV_MUTEX},
 2051     {"ACPI_LV_THREADS",         ACPI_LV_THREADS},
 2052     {"ACPI_LV_IO",              ACPI_LV_IO},
 2053     {"ACPI_LV_INTERRUPTS",      ACPI_LV_INTERRUPTS},
 2054     {"ACPI_LV_VERBOSITY3",      ACPI_LV_VERBOSITY3},
 2055 
 2056     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
 2057     {"ACPI_LV_AML_DISASSEMBLE", ACPI_LV_AML_DISASSEMBLE},
 2058     {"ACPI_LV_VERBOSE_INFO",    ACPI_LV_VERBOSE_INFO},
 2059     {"ACPI_LV_FULL_TABLES",     ACPI_LV_FULL_TABLES},
 2060     {"ACPI_LV_EVENTS",          ACPI_LV_EVENTS},
 2061     {"ACPI_LV_VERBOSE",         ACPI_LV_VERBOSE},
 2062     {NULL, 0}
 2063 };    
 2064 
 2065 static void
 2066 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
 2067 {
 2068     char        *ep;
 2069     int         i, l;
 2070     int         set;
 2071 
 2072     while (*cp) {
 2073         if (isspace(*cp)) {
 2074             cp++;
 2075             continue;
 2076         }
 2077         ep = cp;
 2078         while (*ep && !isspace(*ep))
 2079             ep++;
 2080         if (*cp == '!') {
 2081             set = 0;
 2082             cp++;
 2083             if (cp == ep)
 2084                 continue;
 2085         } else {
 2086             set = 1;
 2087         }
 2088         l = ep - cp;
 2089         for (i = 0; tag[i].name != NULL; i++) {
 2090             if (!strncmp(cp, tag[i].name, l)) {
 2091                 if (set) {
 2092                     *flag |= tag[i].value;
 2093                 } else {
 2094                     *flag &= ~tag[i].value;
 2095                 }
 2096                 printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
 2097             }
 2098         }
 2099         cp = ep;
 2100     }
 2101 }
 2102 
 2103 static void
 2104 acpi_set_debugging(void *junk)
 2105 {
 2106     char        *cp;
 2107 
 2108     if (!cold)
 2109         return;
 2110 
 2111     AcpiDbgLayer = 0;
 2112     AcpiDbgLevel = 0;
 2113     if ((cp = getenv("debug.acpi.layer")) != NULL) {
 2114         acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
 2115         freeenv(cp);
 2116     }
 2117     if ((cp = getenv("debug.acpi.level")) != NULL) {
 2118         acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
 2119         freeenv(cp);
 2120     }
 2121 
 2122     printf("ACPI debug layer 0x%x  debug level 0x%x\n", AcpiDbgLayer, AcpiDbgLevel);
 2123 }
 2124 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging, NULL);
 2125 #endif
 2126 
 2127 static int
 2128 acpi_pm_func(u_long cmd, void *arg, ...)
 2129 {
 2130         int     state, acpi_state;
 2131         int     error;
 2132         struct  acpi_softc *sc;
 2133         va_list ap;
 2134 
 2135         error = 0;
 2136         switch (cmd) {
 2137         case POWER_CMD_SUSPEND:
 2138                 sc = (struct acpi_softc *)arg;
 2139                 if (sc == NULL) {
 2140                         error = EINVAL;
 2141                         goto out;
 2142                 }
 2143 
 2144                 va_start(ap, arg);
 2145                 state = va_arg(ap, int);
 2146                 va_end(ap);     
 2147 
 2148                 switch (state) {
 2149                 case POWER_SLEEP_STATE_STANDBY:
 2150                         acpi_state = sc->acpi_standby_sx;
 2151                         break;
 2152                 case POWER_SLEEP_STATE_SUSPEND:
 2153                         acpi_state = sc->acpi_suspend_sx;
 2154                         break;
 2155                 case POWER_SLEEP_STATE_HIBERNATE:
 2156                         acpi_state = ACPI_STATE_S4;
 2157                         break;
 2158                 default:
 2159                         error = EINVAL;
 2160                         goto out;
 2161                 }
 2162 
 2163                 acpi_SetSleepState(sc, acpi_state);
 2164                 break;
 2165 
 2166         default:
 2167                 error = EINVAL;
 2168                 goto out;
 2169         }
 2170 
 2171 out:
 2172         return (error);
 2173 }
 2174 
 2175 static void
 2176 acpi_pm_register(void *arg)
 2177 {
 2178     int error;
 2179 
 2180     if (!cold)
 2181         return;
 2182 
 2183     if (!resource_int_value("acpi", 0, "disabled", &error) &&
 2184        (error != 0))
 2185                 return;
 2186 
 2187     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
 2188 }
 2189 
 2190 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
 2191 

Cache object: 3a47c60a12a2a931ed710b396591e9f0


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.