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

Cache object: f806ae45737e3408abeac18564ee9017


[ 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.