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

Cache object: 941399cc7fc67c61cc5d619d3867adea


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