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
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/eventhandler.h>
37 #include <sys/kernel.h>
39 #include <sys/fcntl.h>
40 #include <sys/malloc.h>
41 #include <sys/module.h>
44 #include <sys/ioccom.h>
45 #include <sys/reboot.h>
46 #include <sys/sysctl.h>
47 #include <sys/ctype.h>
48 #include <sys/linker.h>
49 #include <sys/mount.h>
50 #include <sys/power.h>
52 #include <sys/sched.h>
54 #include <sys/timetc.h>
56 #if defined(__i386__) || defined(__amd64__)
57 #include <machine/clock.h>
58 #include <machine/pci_cfgreg.h>
60 #include <machine/resource.h>
61 #include <machine/bus.h>
63 #include <isa/isavar.h>
64 #include <isa/pnpvar.h>
66 #include <contrib/dev/acpica/include/acpi.h>
67 #include <contrib/dev/acpica/include/accommon.h>
68 #include <contrib/dev/acpica/include/acnamesp.h>
70 #include <dev/acpica/acpivar.h>
71 #include <dev/acpica/acpiio.h>
73 #include <dev/pci/pcivar.h>
75 #include <vm/vm_param.h>
77 static MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
79 /* Hooks for the ACPI CA debugging infrastructure */
80 #define _COMPONENT ACPI_BUS
81 ACPI_MODULE_NAME("ACPI")
83 static d_open_t acpiopen;
84 static d_close_t acpiclose;
85 static d_ioctl_t acpiioctl;
87 static struct cdevsw acpi_cdevsw = {
88 .d_version = D_VERSION,
95 struct acpi_interface {
100 static char *sysres_ids[] = { "PNP0C01", "PNP0C02", NULL };
101 static char *pcilink_ids[] = { "PNP0C0F", NULL };
103 /* Global mutex for locking access to the ACPI subsystem. */
104 struct mtx acpi_mutex;
105 struct callout acpi_sleep_timer;
107 /* Bitmap of device quirks. */
110 /* Supported sleep states. */
111 static BOOLEAN acpi_sleep_states[ACPI_S_STATE_COUNT];
113 static void acpi_lookup(void *arg, const char *name, device_t *dev);
114 static int acpi_modevent(struct module *mod, int event, void *junk);
115 static int acpi_probe(device_t dev);
116 static int acpi_attach(device_t dev);
117 static int acpi_suspend(device_t dev);
118 static int acpi_resume(device_t dev);
119 static int acpi_shutdown(device_t dev);
120 static device_t acpi_add_child(device_t bus, u_int order, const char *name,
122 static int acpi_print_child(device_t bus, device_t child);
123 static void acpi_probe_nomatch(device_t bus, device_t child);
124 static void acpi_driver_added(device_t dev, driver_t *driver);
125 static void acpi_child_deleted(device_t dev, device_t child);
126 static int acpi_read_ivar(device_t dev, device_t child, int index,
128 static int acpi_write_ivar(device_t dev, device_t child, int index,
130 static struct resource_list *acpi_get_rlist(device_t dev, device_t child);
131 static void acpi_reserve_resources(device_t dev);
132 static int acpi_sysres_alloc(device_t dev);
133 static int acpi_set_resource(device_t dev, device_t child, int type,
134 int rid, rman_res_t start, rman_res_t count);
135 static struct resource *acpi_alloc_resource(device_t bus, device_t child,
136 int type, int *rid, rman_res_t start, rman_res_t end,
137 rman_res_t count, u_int flags);
138 static int acpi_adjust_resource(device_t bus, device_t child, int type,
139 struct resource *r, rman_res_t start, rman_res_t end);
140 static int acpi_release_resource(device_t bus, device_t child, int type,
141 int rid, struct resource *r);
142 static void acpi_delete_resource(device_t bus, device_t child, int type,
144 static uint32_t acpi_isa_get_logicalid(device_t dev);
145 static int acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
146 static int acpi_device_id_probe(device_t bus, device_t dev, char **ids, char **match);
147 static ACPI_STATUS acpi_device_eval_obj(device_t bus, device_t dev,
148 ACPI_STRING pathname, ACPI_OBJECT_LIST *parameters,
150 static ACPI_STATUS acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level,
151 void *context, void **retval);
152 static ACPI_STATUS acpi_device_scan_children(device_t bus, device_t dev,
153 int max_depth, acpi_scan_cb_t user_fn, void *arg);
154 static int acpi_isa_pnp_probe(device_t bus, device_t child,
155 struct isa_pnp_id *ids);
156 static void acpi_platform_osc(device_t dev);
157 static void acpi_probe_children(device_t bus);
158 static void acpi_probe_order(ACPI_HANDLE handle, int *order);
159 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
160 void *context, void **status);
161 static void acpi_sleep_enable(void *arg);
162 static ACPI_STATUS acpi_sleep_disable(struct acpi_softc *sc);
163 static ACPI_STATUS acpi_EnterSleepState(struct acpi_softc *sc, int state);
164 static void acpi_shutdown_final(void *arg, int howto);
165 static void acpi_enable_fixed_events(struct acpi_softc *sc);
166 static void acpi_resync_clock(struct acpi_softc *sc);
167 static int acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate);
168 static int acpi_wake_run_prep(ACPI_HANDLE handle, int sstate);
169 static int acpi_wake_prep_walk(int sstate);
170 static int acpi_wake_sysctl_walk(device_t dev);
171 static int acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS);
172 static void acpi_system_eventhandler_sleep(void *arg, int state);
173 static void acpi_system_eventhandler_wakeup(void *arg, int state);
174 static int acpi_sname2sstate(const char *sname);
175 static const char *acpi_sstate2sname(int sstate);
176 static int acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
177 static int acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
178 static int acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS);
179 static int acpi_pm_func(u_long cmd, void *arg, ...);
180 static int acpi_child_location_str_method(device_t acdev, device_t child,
181 char *buf, size_t buflen);
182 static int acpi_child_pnpinfo_str_method(device_t acdev, device_t child,
183 char *buf, size_t buflen);
184 static void acpi_enable_pcie(void);
185 static void acpi_hint_device_unit(device_t acdev, device_t child,
186 const char *name, int *unitp);
187 static void acpi_reset_interfaces(device_t dev);
189 static device_method_t acpi_methods[] = {
190 /* Device interface */
191 DEVMETHOD(device_probe, acpi_probe),
192 DEVMETHOD(device_attach, acpi_attach),
193 DEVMETHOD(device_shutdown, acpi_shutdown),
194 DEVMETHOD(device_detach, bus_generic_detach),
195 DEVMETHOD(device_suspend, acpi_suspend),
196 DEVMETHOD(device_resume, acpi_resume),
199 DEVMETHOD(bus_add_child, acpi_add_child),
200 DEVMETHOD(bus_print_child, acpi_print_child),
201 DEVMETHOD(bus_probe_nomatch, acpi_probe_nomatch),
202 DEVMETHOD(bus_driver_added, acpi_driver_added),
203 DEVMETHOD(bus_child_deleted, acpi_child_deleted),
204 DEVMETHOD(bus_read_ivar, acpi_read_ivar),
205 DEVMETHOD(bus_write_ivar, acpi_write_ivar),
206 DEVMETHOD(bus_get_resource_list, acpi_get_rlist),
207 DEVMETHOD(bus_set_resource, acpi_set_resource),
208 DEVMETHOD(bus_get_resource, bus_generic_rl_get_resource),
209 DEVMETHOD(bus_alloc_resource, acpi_alloc_resource),
210 DEVMETHOD(bus_adjust_resource, acpi_adjust_resource),
211 DEVMETHOD(bus_release_resource, acpi_release_resource),
212 DEVMETHOD(bus_delete_resource, acpi_delete_resource),
213 DEVMETHOD(bus_child_pnpinfo_str, acpi_child_pnpinfo_str_method),
214 DEVMETHOD(bus_child_location_str, acpi_child_location_str_method),
215 DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
216 DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
217 DEVMETHOD(bus_setup_intr, bus_generic_setup_intr),
218 DEVMETHOD(bus_teardown_intr, bus_generic_teardown_intr),
219 DEVMETHOD(bus_hint_device_unit, acpi_hint_device_unit),
220 DEVMETHOD(bus_get_cpus, acpi_get_cpus),
221 DEVMETHOD(bus_get_domain, acpi_get_domain),
224 DEVMETHOD(acpi_id_probe, acpi_device_id_probe),
225 DEVMETHOD(acpi_evaluate_object, acpi_device_eval_obj),
226 DEVMETHOD(acpi_pwr_for_sleep, acpi_device_pwr_for_sleep),
227 DEVMETHOD(acpi_scan_children, acpi_device_scan_children),
230 DEVMETHOD(isa_pnp_probe, acpi_isa_pnp_probe),
235 static driver_t acpi_driver = {
238 sizeof(struct acpi_softc),
241 static devclass_t acpi_devclass;
242 EARLY_DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0,
243 BUS_PASS_BUS + BUS_PASS_ORDER_MIDDLE);
244 MODULE_VERSION(acpi, 1);
246 ACPI_SERIAL_DECL(acpi, "ACPI root bus");
248 /* Local pools for managing system resources for ACPI child devices. */
249 static struct rman acpi_rman_io, acpi_rman_mem;
251 #define ACPI_MINIMUM_AWAKETIME 5
253 /* Holds the description of the acpi0 device. */
254 static char acpi_desc[ACPI_OEM_ID_SIZE + ACPI_OEM_TABLE_ID_SIZE + 2];
256 SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
258 static char acpi_ca_version[12];
259 SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
260 acpi_ca_version, 0, "Version of Intel ACPI-CA");
263 * Allow overriding _OSI methods.
265 static char acpi_install_interface[256];
266 TUNABLE_STR("hw.acpi.install_interface", acpi_install_interface,
267 sizeof(acpi_install_interface));
268 static char acpi_remove_interface[256];
269 TUNABLE_STR("hw.acpi.remove_interface", acpi_remove_interface,
270 sizeof(acpi_remove_interface));
272 /* Allow users to dump Debug objects without ACPI debugger. */
273 static int acpi_debug_objects;
274 TUNABLE_INT("debug.acpi.enable_debug_objects", &acpi_debug_objects);
275 SYSCTL_PROC(_debug_acpi, OID_AUTO, enable_debug_objects,
276 CTLFLAG_RW | CTLTYPE_INT | CTLFLAG_NEEDGIANT, NULL, 0,
277 acpi_debug_objects_sysctl, "I",
278 "Enable Debug objects");
280 /* Allow the interpreter to ignore common mistakes in BIOS. */
281 static int acpi_interpreter_slack = 1;
282 TUNABLE_INT("debug.acpi.interpreter_slack", &acpi_interpreter_slack);
283 SYSCTL_INT(_debug_acpi, OID_AUTO, interpreter_slack, CTLFLAG_RDTUN,
284 &acpi_interpreter_slack, 1, "Turn on interpreter slack mode.");
286 /* Ignore register widths set by FADT and use default widths instead. */
287 static int acpi_ignore_reg_width = 1;
288 TUNABLE_INT("debug.acpi.default_register_width", &acpi_ignore_reg_width);
289 SYSCTL_INT(_debug_acpi, OID_AUTO, default_register_width, CTLFLAG_RDTUN,
290 &acpi_ignore_reg_width, 1, "Ignore register widths set by FADT");
292 /* Allow users to override quirks. */
293 TUNABLE_INT("debug.acpi.quirks", &acpi_quirks);
295 int acpi_susp_bounce;
296 SYSCTL_INT(_debug_acpi, OID_AUTO, suspend_bounce, CTLFLAG_RW,
297 &acpi_susp_bounce, 0, "Don't actually suspend, just test devices.");
300 * ACPI can only be loaded as a module by the loader; activating it after
301 * system bootstrap time is not useful, and can be fatal to the system.
302 * It also cannot be unloaded, since the entire system bus hierarchy hangs
306 acpi_modevent(struct module *mod, int event, void *junk)
311 printf("The ACPI driver cannot be loaded after boot.\n");
316 if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
326 * Perform early initialization.
331 static int started = 0;
335 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
337 /* Only run the startup code once. The MADT driver also calls this. */
339 return_VALUE (AE_OK);
343 * Initialize the ACPICA subsystem.
345 if (ACPI_FAILURE(status = AcpiInitializeSubsystem())) {
346 printf("ACPI: Could not initialize Subsystem: %s\n",
347 AcpiFormatException(status));
348 return_VALUE (status);
352 * Pre-allocate space for RSDT/XSDT and DSDT tables and allow resizing
353 * if more tables exist.
355 if (ACPI_FAILURE(status = AcpiInitializeTables(NULL, 2, TRUE))) {
356 printf("ACPI: Table initialisation failed: %s\n",
357 AcpiFormatException(status));
358 return_VALUE (status);
361 /* Set up any quirks we have for this system. */
362 if (acpi_quirks == ACPI_Q_OK)
363 acpi_table_quirks(&acpi_quirks);
365 /* If the user manually set the disabled hint to 0, force-enable ACPI. */
366 if (resource_int_value("acpi", 0, "disabled", &val) == 0 && val == 0)
367 acpi_quirks &= ~ACPI_Q_BROKEN;
368 if (acpi_quirks & ACPI_Q_BROKEN) {
369 printf("ACPI disabled by blacklist. Contact your BIOS vendor.\n");
373 return_VALUE (status);
377 * Detect ACPI and perform early initialisation.
382 ACPI_TABLE_RSDP *rsdp;
383 ACPI_TABLE_HEADER *rsdt;
384 ACPI_PHYSICAL_ADDRESS paddr;
387 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
392 /* Check that we haven't been disabled with a hint. */
393 if (resource_disabled("acpi", 0))
396 /* Check for other PM systems. */
397 if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
398 power_pm_get_type() != POWER_PM_TYPE_ACPI) {
399 printf("ACPI identify failed, other PM system enabled.\n");
403 /* Initialize root tables. */
404 if (ACPI_FAILURE(acpi_Startup())) {
405 printf("ACPI: Try disabling either ACPI or apic support.\n");
409 if ((paddr = AcpiOsGetRootPointer()) == 0 ||
410 (rsdp = AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_RSDP))) == NULL)
412 if (rsdp->Revision > 1 && rsdp->XsdtPhysicalAddress != 0)
413 paddr = (ACPI_PHYSICAL_ADDRESS)rsdp->XsdtPhysicalAddress;
415 paddr = (ACPI_PHYSICAL_ADDRESS)rsdp->RsdtPhysicalAddress;
416 AcpiOsUnmapMemory(rsdp, sizeof(ACPI_TABLE_RSDP));
418 if ((rsdt = AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_HEADER))) == NULL)
420 sbuf_new(&sb, acpi_desc, sizeof(acpi_desc), SBUF_FIXEDLEN);
421 sbuf_bcat(&sb, rsdt->OemId, ACPI_OEM_ID_SIZE);
424 sbuf_bcat(&sb, rsdt->OemTableId, ACPI_OEM_TABLE_ID_SIZE);
428 AcpiOsUnmapMemory(rsdt, sizeof(ACPI_TABLE_HEADER));
430 snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%x", ACPI_CA_VERSION);
436 * Fetch some descriptive data from ACPI to put in our attach message.
439 acpi_probe(device_t dev)
442 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
444 device_set_desc(dev, acpi_desc);
446 return_VALUE (BUS_PROBE_NOWILDCARD);
450 acpi_attach(device_t dev)
452 struct acpi_softc *sc;
459 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
461 sc = device_get_softc(dev);
463 callout_init(&sc->susp_force_to, 1);
467 /* Initialize resource manager. */
468 acpi_rman_io.rm_type = RMAN_ARRAY;
469 acpi_rman_io.rm_start = 0;
470 acpi_rman_io.rm_end = 0xffff;
471 acpi_rman_io.rm_descr = "ACPI I/O ports";
472 if (rman_init(&acpi_rman_io) != 0)
473 panic("acpi rman_init IO ports failed");
474 acpi_rman_mem.rm_type = RMAN_ARRAY;
475 acpi_rman_mem.rm_descr = "ACPI I/O memory addresses";
476 if (rman_init(&acpi_rman_mem) != 0)
477 panic("acpi rman_init memory failed");
479 /* Initialise the ACPI mutex */
480 mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
483 * Set the globals from our tunables. This is needed because ACPI-CA
484 * uses UINT8 for some values and we have no tunable_byte.
486 AcpiGbl_EnableInterpreterSlack = acpi_interpreter_slack ? TRUE : FALSE;
487 AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
488 AcpiGbl_UseDefaultRegisterWidths = acpi_ignore_reg_width ? TRUE : FALSE;
492 * Disable all debugging layers and levels.
498 /* Override OS interfaces if the user requested. */
499 acpi_reset_interfaces(dev);
501 /* Load ACPI name space. */
502 status = AcpiLoadTables();
503 if (ACPI_FAILURE(status)) {
504 device_printf(dev, "Could not load Namespace: %s\n",
505 AcpiFormatException(status));
509 /* Handle MCFG table if present. */
513 * Note that some systems (specifically, those with namespace evaluation
514 * issues that require the avoidance of parts of the namespace) must
515 * avoid running _INI and _STA on everything, as well as dodging the final
518 * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
520 * XXX We should arrange for the object init pass after we have attached
521 * all our child devices, but on many systems it works here.
524 if (testenv("debug.acpi.avoid"))
525 flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
527 /* Bring the hardware and basic handlers online. */
528 if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
529 device_printf(dev, "Could not enable ACPI: %s\n",
530 AcpiFormatException(status));
535 * Call the ECDT probe function to provide EC functionality before
536 * the namespace has been evaluated.
538 * XXX This happens before the sysresource devices have been probed and
539 * attached so its resources come from nexus0. In practice, this isn't
540 * a problem but should be addressed eventually.
542 acpi_ec_ecdt_probe(dev);
544 /* Bring device objects and regions online. */
545 if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
546 device_printf(dev, "Could not initialize ACPI objects: %s\n",
547 AcpiFormatException(status));
552 * Setup our sysctl tree.
554 * XXX: This doesn't check to make sure that none of these fail.
556 sysctl_ctx_init(&sc->acpi_sysctl_ctx);
557 sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
558 SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO, device_get_name(dev),
559 CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
560 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
561 OID_AUTO, "supported_sleep_state",
562 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
563 0, 0, acpi_supported_sleep_state_sysctl, "A",
564 "List supported ACPI sleep states.");
565 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
566 OID_AUTO, "power_button_state",
567 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
568 &sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A",
569 "Power button ACPI sleep state.");
570 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
571 OID_AUTO, "sleep_button_state",
572 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
573 &sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A",
574 "Sleep button ACPI sleep state.");
575 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
576 OID_AUTO, "lid_switch_state",
577 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
578 &sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A",
579 "Lid ACPI sleep state. Set to S3 if you want to suspend your laptop when close the Lid.");
580 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
581 OID_AUTO, "standby_state",
582 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
583 &sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
584 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
585 OID_AUTO, "suspend_state",
586 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
587 &sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
588 SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
589 OID_AUTO, "sleep_delay", CTLFLAG_RW, &sc->acpi_sleep_delay, 0,
590 "sleep delay in seconds");
591 SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
592 OID_AUTO, "s4bios", CTLFLAG_RW, &sc->acpi_s4bios, 0, "S4BIOS mode");
593 SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
594 OID_AUTO, "verbose", CTLFLAG_RW, &sc->acpi_verbose, 0, "verbose mode");
595 SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
596 OID_AUTO, "disable_on_reboot", CTLFLAG_RW,
597 &sc->acpi_do_disable, 0, "Disable ACPI when rebooting/halting system");
598 SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
599 OID_AUTO, "handle_reboot", CTLFLAG_RW,
600 &sc->acpi_handle_reboot, 0, "Use ACPI Reset Register to reboot");
603 * Default to 1 second before sleeping to give some machines time to
606 sc->acpi_sleep_delay = 1;
608 sc->acpi_verbose = 1;
609 if ((env = kern_getenv("hw.acpi.verbose")) != NULL) {
610 if (strcmp(env, "0") != 0)
611 sc->acpi_verbose = 1;
615 /* Only enable reboot by default if the FADT says it is available. */
616 if (AcpiGbl_FADT.Flags & ACPI_FADT_RESET_REGISTER)
617 sc->acpi_handle_reboot = 1;
619 #if !ACPI_REDUCED_HARDWARE
620 /* Only enable S4BIOS by default if the FACS says it is available. */
621 if (AcpiGbl_FACS != NULL && AcpiGbl_FACS->Flags & ACPI_FACS_S4_BIOS_PRESENT)
625 /* Probe all supported sleep states. */
626 acpi_sleep_states[ACPI_STATE_S0] = TRUE;
627 for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
628 if (ACPI_SUCCESS(AcpiEvaluateObject(ACPI_ROOT_OBJECT,
629 __DECONST(char *, AcpiGbl_SleepStateNames[state]), NULL, NULL)) &&
630 ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB)))
631 acpi_sleep_states[state] = TRUE;
634 * Dispatch the default sleep state to devices. The lid switch is set
635 * to UNKNOWN by default to avoid surprising users.
637 sc->acpi_power_button_sx = acpi_sleep_states[ACPI_STATE_S5] ?
638 ACPI_STATE_S5 : ACPI_STATE_UNKNOWN;
639 sc->acpi_lid_switch_sx = ACPI_STATE_UNKNOWN;
640 sc->acpi_standby_sx = acpi_sleep_states[ACPI_STATE_S1] ?
641 ACPI_STATE_S1 : ACPI_STATE_UNKNOWN;
642 sc->acpi_suspend_sx = acpi_sleep_states[ACPI_STATE_S3] ?
643 ACPI_STATE_S3 : ACPI_STATE_UNKNOWN;
645 /* Pick the first valid sleep state for the sleep button default. */
646 sc->acpi_sleep_button_sx = ACPI_STATE_UNKNOWN;
647 for (state = ACPI_STATE_S1; state <= ACPI_STATE_S4; state++)
648 if (acpi_sleep_states[state]) {
649 sc->acpi_sleep_button_sx = state;
653 acpi_enable_fixed_events(sc);
656 * Scan the namespace and attach/initialise children.
659 /* Register our shutdown handler. */
660 EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
664 * Register our acpi event handlers.
665 * XXX should be configurable eg. via userland policy manager.
667 EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
668 sc, ACPI_EVENT_PRI_LAST);
669 EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
670 sc, ACPI_EVENT_PRI_LAST);
672 /* Flag our initial states. */
673 sc->acpi_enabled = TRUE;
674 sc->acpi_sstate = ACPI_STATE_S0;
675 sc->acpi_sleep_disabled = TRUE;
677 /* Create the control device */
678 sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0664,
680 sc->acpi_dev_t->si_drv1 = sc;
682 if ((error = acpi_machdep_init(dev)))
685 /* Register ACPI again to pass the correct argument of pm_func. */
686 power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
688 acpi_platform_osc(dev);
690 if (!acpi_disabled("bus")) {
691 EVENTHANDLER_REGISTER(dev_lookup, acpi_lookup, NULL, 1000);
692 acpi_probe_children(dev);
695 /* Update all GPEs and enable runtime GPEs. */
696 status = AcpiUpdateAllGpes();
697 if (ACPI_FAILURE(status))
698 device_printf(dev, "Could not update all GPEs: %s\n",
699 AcpiFormatException(status));
701 /* Allow sleep request after a while. */
702 callout_init_mtx(&acpi_sleep_timer, &acpi_mutex, 0);
703 callout_reset(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME,
704 acpi_sleep_enable, sc);
709 return_VALUE (error);
713 acpi_set_power_children(device_t dev, int state)
717 int dstate, i, numdevs;
719 if (device_get_children(dev, &devlist, &numdevs) != 0)
723 * Retrieve and set D-state for the sleep state if _SxD is present.
724 * Skip children who aren't attached since they are handled separately.
726 for (i = 0; i < numdevs; i++) {
729 if (device_is_attached(child) &&
730 acpi_device_pwr_for_sleep(dev, child, &dstate) == 0)
731 acpi_set_powerstate(child, dstate);
733 free(devlist, M_TEMP);
737 acpi_suspend(device_t dev)
743 error = bus_generic_suspend(dev);
745 acpi_set_power_children(dev, ACPI_STATE_D3);
751 acpi_resume(device_t dev)
756 acpi_set_power_children(dev, ACPI_STATE_D0);
758 return (bus_generic_resume(dev));
762 acpi_shutdown(device_t dev)
767 /* Allow children to shutdown first. */
768 bus_generic_shutdown(dev);
771 * Enable any GPEs that are able to power-on the system (i.e., RTC).
772 * Also, disable any that are not valid for this state (most).
774 acpi_wake_prep_walk(ACPI_STATE_S5);
780 * Handle a new device being added
783 acpi_add_child(device_t bus, u_int order, const char *name, int unit)
785 struct acpi_device *ad;
788 if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT | M_ZERO)) == NULL)
791 resource_list_init(&ad->ad_rl);
793 child = device_add_child_ordered(bus, order, name, unit);
795 device_set_ivars(child, ad);
802 acpi_print_child(device_t bus, device_t child)
804 struct acpi_device *adev = device_get_ivars(child);
805 struct resource_list *rl = &adev->ad_rl;
808 retval += bus_print_child_header(bus, child);
809 retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#jx");
810 retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#jx");
811 retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%jd");
812 retval += resource_list_print_type(rl, "drq", SYS_RES_DRQ, "%jd");
813 if (device_get_flags(child))
814 retval += printf(" flags %#x", device_get_flags(child));
815 retval += bus_print_child_domain(bus, child);
816 retval += bus_print_child_footer(bus, child);
822 * If this device is an ACPI child but no one claimed it, attempt
823 * to power it off. We'll power it back up when a driver is added.
825 * XXX Disabled for now since many necessary devices (like fdc and
826 * ATA) don't claim the devices we created for them but still expect
827 * them to be powered up.
830 acpi_probe_nomatch(device_t bus, device_t child)
832 #ifdef ACPI_ENABLE_POWERDOWN_NODRIVER
833 acpi_set_powerstate(child, ACPI_STATE_D3);
838 * If a new driver has a chance to probe a child, first power it up.
840 * XXX Disabled for now (see acpi_probe_nomatch for details).
843 acpi_driver_added(device_t dev, driver_t *driver)
845 device_t child, *devlist;
848 DEVICE_IDENTIFY(driver, dev);
849 if (device_get_children(dev, &devlist, &numdevs))
851 for (i = 0; i < numdevs; i++) {
853 if (device_get_state(child) == DS_NOTPRESENT) {
854 #ifdef ACPI_ENABLE_POWERDOWN_NODRIVER
855 acpi_set_powerstate(child, ACPI_STATE_D0);
856 if (device_probe_and_attach(child) != 0)
857 acpi_set_powerstate(child, ACPI_STATE_D3);
859 device_probe_and_attach(child);
863 free(devlist, M_TEMP);
866 /* Location hint for devctl(8) */
868 acpi_child_location_str_method(device_t cbdev, device_t child, char *buf,
871 struct acpi_device *dinfo = device_get_ivars(child);
875 if (dinfo->ad_handle) {
876 snprintf(buf, buflen, "handle=%s", acpi_name(dinfo->ad_handle));
877 if (ACPI_SUCCESS(acpi_GetInteger(dinfo->ad_handle, "_PXM", &pxm))) {
878 snprintf(buf2, 32, " _PXM=%d", pxm);
879 strlcat(buf, buf2, buflen);
882 snprintf(buf, buflen, "");
887 /* PnP information for devctl(8) */
889 acpi_pnpinfo_str(ACPI_HANDLE handle, char *buf, size_t buflen)
891 ACPI_DEVICE_INFO *adinfo;
893 if (ACPI_FAILURE(AcpiGetObjectInfo(handle, &adinfo))) {
894 snprintf(buf, buflen, "unknown");
898 snprintf(buf, buflen, "_HID=%s _UID=%lu _CID=%s",
899 (adinfo->Valid & ACPI_VALID_HID) ?
900 adinfo->HardwareId.String : "none",
901 (adinfo->Valid & ACPI_VALID_UID) ?
902 strtoul(adinfo->UniqueId.String, NULL, 10) : 0UL,
903 ((adinfo->Valid & ACPI_VALID_CID) &&
904 adinfo->CompatibleIdList.Count > 0) ?
905 adinfo->CompatibleIdList.Ids[0].String : "none");
912 acpi_child_pnpinfo_str_method(device_t cbdev, device_t child, char *buf,
915 struct acpi_device *dinfo = device_get_ivars(child);
917 return (acpi_pnpinfo_str(dinfo->ad_handle, buf, buflen));
921 * Handle device deletion.
924 acpi_child_deleted(device_t dev, device_t child)
926 struct acpi_device *dinfo = device_get_ivars(child);
928 if (acpi_get_device(dinfo->ad_handle) == child)
929 AcpiDetachData(dinfo->ad_handle, acpi_fake_objhandler);
933 * Handle per-device ivars
936 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
938 struct acpi_device *ad;
940 if ((ad = device_get_ivars(child)) == NULL) {
941 device_printf(child, "device has no ivars\n");
945 /* ACPI and ISA compatibility ivars */
947 case ACPI_IVAR_HANDLE:
948 *(ACPI_HANDLE *)result = ad->ad_handle;
950 case ACPI_IVAR_PRIVATE:
951 *(void **)result = ad->ad_private;
953 case ACPI_IVAR_FLAGS:
954 *(int *)result = ad->ad_flags;
956 case ISA_IVAR_VENDORID:
957 case ISA_IVAR_SERIAL:
958 case ISA_IVAR_COMPATID:
961 case ISA_IVAR_LOGICALID:
962 *(int *)result = acpi_isa_get_logicalid(child);
965 *(uint8_t*)result = (ad->ad_cls_class >> 16) & 0xff;
967 case PCI_IVAR_SUBCLASS:
968 *(uint8_t*)result = (ad->ad_cls_class >> 8) & 0xff;
970 case PCI_IVAR_PROGIF:
971 *(uint8_t*)result = (ad->ad_cls_class >> 0) & 0xff;
981 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
983 struct acpi_device *ad;
985 if ((ad = device_get_ivars(child)) == NULL) {
986 device_printf(child, "device has no ivars\n");
991 case ACPI_IVAR_HANDLE:
992 ad->ad_handle = (ACPI_HANDLE)value;
994 case ACPI_IVAR_PRIVATE:
995 ad->ad_private = (void *)value;
997 case ACPI_IVAR_FLAGS:
998 ad->ad_flags = (int)value;
1001 panic("bad ivar write request (%d)", index);
1009 * Handle child resource allocation/removal
1011 static struct resource_list *
1012 acpi_get_rlist(device_t dev, device_t child)
1014 struct acpi_device *ad;
1016 ad = device_get_ivars(child);
1017 return (&ad->ad_rl);
1021 acpi_match_resource_hint(device_t dev, int type, long value)
1023 struct acpi_device *ad = device_get_ivars(dev);
1024 struct resource_list *rl = &ad->ad_rl;
1025 struct resource_list_entry *rle;
1027 STAILQ_FOREACH(rle, rl, link) {
1028 if (rle->type != type)
1030 if (rle->start <= value && rle->end >= value)
1037 * Wire device unit numbers based on resource matches in hints.
1040 acpi_hint_device_unit(device_t acdev, device_t child, const char *name,
1045 int line, matches, unit;
1048 * Iterate over all the hints for the devices with the specified
1049 * name to see if one's resources are a subset of this device.
1052 while (resource_find_dev(&line, name, &unit, "at", NULL) == 0) {
1053 /* Must have an "at" for acpi or isa. */
1054 resource_string_value(name, unit, "at", &s);
1055 if (!(strcmp(s, "acpi0") == 0 || strcmp(s, "acpi") == 0 ||
1056 strcmp(s, "isa0") == 0 || strcmp(s, "isa") == 0))
1060 * Check for matching resources. We must have at least one match.
1061 * Since I/O and memory resources cannot be shared, if we get a
1062 * match on either of those, ignore any mismatches in IRQs or DRQs.
1064 * XXX: We may want to revisit this to be more lenient and wire
1065 * as long as it gets one match.
1068 if (resource_long_value(name, unit, "port", &value) == 0) {
1070 * Floppy drive controllers are notorious for having a
1071 * wide variety of resources not all of which include the
1072 * first port that is specified by the hint (typically
1073 * 0x3f0) (see the comment above fdc_isa_alloc_resources()
1074 * in fdc_isa.c). However, they do all seem to include
1075 * port + 2 (e.g. 0x3f2) so for a floppy device, look for
1076 * 'value + 2' in the port resources instead of the hint
1079 if (strcmp(name, "fdc") == 0)
1081 if (acpi_match_resource_hint(child, SYS_RES_IOPORT, value))
1086 if (resource_long_value(name, unit, "maddr", &value) == 0) {
1087 if (acpi_match_resource_hint(child, SYS_RES_MEMORY, value))
1094 if (resource_long_value(name, unit, "irq", &value) == 0) {
1095 if (acpi_match_resource_hint(child, SYS_RES_IRQ, value))
1100 if (resource_long_value(name, unit, "drq", &value) == 0) {
1101 if (acpi_match_resource_hint(child, SYS_RES_DRQ, value))
1109 /* We have a winner! */
1117 * Fetch the NUMA domain for a device by mapping the value returned by
1118 * _PXM to a NUMA domain. If the device does not have a _PXM method,
1119 * -2 is returned. If any other error occurs, -1 is returned.
1122 acpi_parse_pxm(device_t dev)
1125 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1130 handle = acpi_get_handle(dev);
1133 status = acpi_GetInteger(handle, "_PXM", &pxm);
1134 if (ACPI_SUCCESS(status))
1135 return (acpi_map_pxm_to_vm_domainid(pxm));
1136 if (status == AE_NOT_FOUND)
1144 acpi_get_cpus(device_t dev, device_t child, enum cpu_sets op, size_t setsize,
1149 d = acpi_parse_pxm(child);
1151 return (bus_generic_get_cpus(dev, child, op, setsize, cpuset));
1155 if (setsize != sizeof(cpuset_t))
1157 *cpuset = cpuset_domain[d];
1160 error = bus_generic_get_cpus(dev, child, op, setsize, cpuset);
1163 if (setsize != sizeof(cpuset_t))
1165 CPU_AND(cpuset, &cpuset_domain[d]);
1168 return (bus_generic_get_cpus(dev, child, op, setsize, cpuset));
1173 * Fetch the NUMA domain for the given device 'dev'.
1175 * If a device has a _PXM method, map that to a NUMA domain.
1176 * Otherwise, pass the request up to the parent.
1177 * If there's no matching domain or the domain cannot be
1178 * determined, return ENOENT.
1181 acpi_get_domain(device_t dev, device_t child, int *domain)
1185 d = acpi_parse_pxm(child);
1193 /* No _PXM node; go up a level */
1194 return (bus_generic_get_domain(dev, child, domain));
1198 * Pre-allocate/manage all memory and IO resources. Since rman can't handle
1199 * duplicates, we merge any in the sysresource attach routine.
1202 acpi_sysres_alloc(device_t dev)
1204 struct resource *res;
1205 struct resource_list *rl;
1206 struct resource_list_entry *rle;
1212 * Probe/attach any sysresource devices. This would be unnecessary if we
1213 * had multi-pass probe/attach.
1215 if (device_get_children(dev, &children, &child_count) != 0)
1217 for (i = 0; i < child_count; i++) {
1218 if (ACPI_ID_PROBE(dev, children[i], sysres_ids, NULL) <= 0)
1219 device_probe_and_attach(children[i]);
1221 free(children, M_TEMP);
1223 rl = BUS_GET_RESOURCE_LIST(device_get_parent(dev), dev);
1224 STAILQ_FOREACH(rle, rl, link) {
1225 if (rle->res != NULL) {
1226 device_printf(dev, "duplicate resource for %jx\n", rle->start);
1230 /* Only memory and IO resources are valid here. */
1231 switch (rle->type) {
1232 case SYS_RES_IOPORT:
1235 case SYS_RES_MEMORY:
1236 rm = &acpi_rman_mem;
1242 /* Pre-allocate resource and add to our rman pool. */
1243 res = BUS_ALLOC_RESOURCE(device_get_parent(dev), dev, rle->type,
1244 &rle->rid, rle->start, rle->start + rle->count - 1, rle->count, 0);
1246 rman_manage_region(rm, rman_get_start(res), rman_get_end(res));
1248 } else if (bootverbose)
1249 device_printf(dev, "reservation of %jx, %jx (%d) failed\n",
1250 rle->start, rle->count, rle->type);
1256 * Reserve declared resources for devices found during attach once system
1257 * resources have been allocated.
1260 acpi_reserve_resources(device_t dev)
1262 struct resource_list_entry *rle;
1263 struct resource_list *rl;
1264 struct acpi_device *ad;
1265 struct acpi_softc *sc;
1269 sc = device_get_softc(dev);
1270 if (device_get_children(dev, &children, &child_count) != 0)
1272 for (i = 0; i < child_count; i++) {
1273 ad = device_get_ivars(children[i]);
1276 /* Don't reserve system resources. */
1277 if (ACPI_ID_PROBE(dev, children[i], sysres_ids, NULL) <= 0)
1280 STAILQ_FOREACH(rle, rl, link) {
1282 * Don't reserve IRQ resources. There are many sticky things
1283 * to get right otherwise (e.g. IRQs for psm, atkbd, and HPET
1284 * when using legacy routing).
1286 if (rle->type == SYS_RES_IRQ)
1290 * Don't reserve the resource if it is already allocated.
1291 * The acpi_ec(4) driver can allocate its resources early
1292 * if ECDT is present.
1294 if (rle->res != NULL)
1298 * Try to reserve the resource from our parent. If this
1299 * fails because the resource is a system resource, just
1300 * let it be. The resource range is already reserved so
1301 * that other devices will not use it. If the driver
1302 * needs to allocate the resource, then
1303 * acpi_alloc_resource() will sub-alloc from the system
1306 resource_list_reserve(rl, dev, children[i], rle->type, &rle->rid,
1307 rle->start, rle->end, rle->count, 0);
1310 free(children, M_TEMP);
1311 sc->acpi_resources_reserved = 1;
1315 acpi_set_resource(device_t dev, device_t child, int type, int rid,
1316 rman_res_t start, rman_res_t count)
1318 struct acpi_softc *sc = device_get_softc(dev);
1319 struct acpi_device *ad = device_get_ivars(child);
1320 struct resource_list *rl = &ad->ad_rl;
1321 ACPI_DEVICE_INFO *devinfo;
1325 /* Ignore IRQ resources for PCI link devices. */
1326 if (type == SYS_RES_IRQ &&
1327 ACPI_ID_PROBE(dev, child, pcilink_ids, NULL) <= 0)
1331 * Ignore most resources for PCI root bridges. Some BIOSes
1332 * incorrectly enumerate the memory ranges they decode as plain
1333 * memory resources instead of as ResourceProducer ranges. Other
1334 * BIOSes incorrectly list system resource entries for I/O ranges
1335 * under the PCI bridge. Do allow the one known-correct case on
1336 * x86 of a PCI bridge claiming the I/O ports used for PCI config
1339 if (type == SYS_RES_MEMORY || type == SYS_RES_IOPORT) {
1340 if (ACPI_SUCCESS(AcpiGetObjectInfo(ad->ad_handle, &devinfo))) {
1341 if ((devinfo->Flags & ACPI_PCI_ROOT_BRIDGE) != 0) {
1342 #if defined(__i386__) || defined(__amd64__)
1343 allow = (type == SYS_RES_IOPORT && start == CONF1_ADDR_PORT);
1348 AcpiOsFree(devinfo);
1352 AcpiOsFree(devinfo);
1357 /* map with default for now */
1358 if (type == SYS_RES_IRQ)
1359 start = (rman_res_t)acpi_map_intr(child, (u_int)start,
1360 acpi_get_handle(child));
1363 /* If the resource is already allocated, fail. */
1364 if (resource_list_busy(rl, type, rid))
1367 /* If the resource is already reserved, release it. */
1368 if (resource_list_reserved(rl, type, rid))
1369 resource_list_unreserve(rl, dev, child, type, rid);
1371 /* Add the resource. */
1372 end = (start + count - 1);
1373 resource_list_add(rl, type, rid, start, end, count);
1375 /* Don't reserve resources until the system resources are allocated. */
1376 if (!sc->acpi_resources_reserved)
1379 /* Don't reserve system resources. */
1380 if (ACPI_ID_PROBE(dev, child, sysres_ids, NULL) <= 0)
1384 * Don't reserve IRQ resources. There are many sticky things to
1385 * get right otherwise (e.g. IRQs for psm, atkbd, and HPET when
1386 * using legacy routing).
1388 if (type == SYS_RES_IRQ)
1392 * Don't reserve resources for CPU devices. Some of these
1393 * resources need to be allocated as shareable, but reservations
1394 * are always non-shareable.
1396 if (device_get_devclass(child) == devclass_find("cpu"))
1400 * Reserve the resource.
1402 * XXX: Ignores failure for now. Failure here is probably a
1403 * BIOS/firmware bug?
1405 resource_list_reserve(rl, dev, child, type, &rid, start, end, count, 0);
1409 static struct resource *
1410 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
1411 rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1416 struct acpi_device *ad;
1417 struct resource_list_entry *rle;
1418 struct resource_list *rl;
1419 struct resource *res;
1420 int isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
1423 * First attempt at allocating the resource. For direct children,
1424 * use resource_list_alloc() to handle reserved resources. For
1425 * other devices, pass the request up to our parent.
1427 if (bus == device_get_parent(child)) {
1428 ad = device_get_ivars(child);
1432 * Simulate the behavior of the ISA bus for direct children
1433 * devices. That is, if a non-default range is specified for
1434 * a resource that doesn't exist, use bus_set_resource() to
1435 * add the resource before allocating it. Note that these
1436 * resources will not be reserved.
1438 if (!isdefault && resource_list_find(rl, type, *rid) == NULL)
1439 resource_list_add(rl, type, *rid, start, end, count);
1440 res = resource_list_alloc(rl, bus, child, type, rid, start, end, count,
1443 if (res != NULL && type == SYS_RES_IRQ) {
1445 * Since bus_config_intr() takes immediate effect, we cannot
1446 * configure the interrupt associated with a device when we
1447 * parse the resources but have to defer it until a driver
1448 * actually allocates the interrupt via bus_alloc_resource().
1450 * XXX: Should we handle the lookup failing?
1452 if (ACPI_SUCCESS(acpi_lookup_irq_resource(child, *rid, res, &ares)))
1453 acpi_config_intr(child, &ares);
1458 * If this is an allocation of the "default" range for a given
1459 * RID, fetch the exact bounds for this resource from the
1460 * resource list entry to try to allocate the range from the
1461 * system resource regions.
1463 if (res == NULL && isdefault) {
1464 rle = resource_list_find(rl, type, *rid);
1472 res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child, type, rid,
1473 start, end, count, flags);
1476 * If the first attempt failed and this is an allocation of a
1477 * specific range, try to satisfy the request via a suballocation
1478 * from our system resource regions.
1480 if (res == NULL && start + count - 1 == end)
1481 res = acpi_alloc_sysres(child, type, rid, start, end, count, flags);
1486 * Attempt to allocate a specific resource range from the system
1487 * resource ranges. Note that we only handle memory and I/O port
1491 acpi_alloc_sysres(device_t child, int type, int *rid, rman_res_t start,
1492 rman_res_t end, rman_res_t count, u_int flags)
1495 struct resource *res;
1498 case SYS_RES_IOPORT:
1501 case SYS_RES_MEMORY:
1502 rm = &acpi_rman_mem;
1508 KASSERT(start + count - 1 == end, ("wildcard resource range"));
1509 res = rman_reserve_resource(rm, start, end, count, flags & ~RF_ACTIVE,
1514 rman_set_rid(res, *rid);
1516 /* If requested, activate the resource using the parent's method. */
1517 if (flags & RF_ACTIVE)
1518 if (bus_activate_resource(child, type, *rid, res) != 0) {
1519 rman_release_resource(res);
1527 acpi_is_resource_managed(int type, struct resource *r)
1530 /* We only handle memory and IO resources through rman. */
1532 case SYS_RES_IOPORT:
1533 return (rman_is_region_manager(r, &acpi_rman_io));
1534 case SYS_RES_MEMORY:
1535 return (rman_is_region_manager(r, &acpi_rman_mem));
1541 acpi_adjust_resource(device_t bus, device_t child, int type, struct resource *r,
1542 rman_res_t start, rman_res_t end)
1545 if (acpi_is_resource_managed(type, r))
1546 return (rman_adjust_resource(r, start, end));
1547 return (bus_generic_adjust_resource(bus, child, type, r, start, end));
1551 acpi_release_resource(device_t bus, device_t child, int type, int rid,
1557 * If this resource belongs to one of our internal managers,
1558 * deactivate it and release it to the local pool.
1560 if (acpi_is_resource_managed(type, r)) {
1561 if (rman_get_flags(r) & RF_ACTIVE) {
1562 ret = bus_deactivate_resource(child, type, rid, r);
1566 return (rman_release_resource(r));
1569 return (bus_generic_rl_release_resource(bus, child, type, rid, r));
1573 acpi_delete_resource(device_t bus, device_t child, int type, int rid)
1575 struct resource_list *rl;
1577 rl = acpi_get_rlist(bus, child);
1578 if (resource_list_busy(rl, type, rid)) {
1579 device_printf(bus, "delete_resource: Resource still owned by child"
1580 " (type=%d, rid=%d)\n", type, rid);
1583 resource_list_unreserve(rl, bus, child, type, rid);
1584 resource_list_delete(rl, type, rid);
1587 /* Allocate an IO port or memory resource, given its GAS. */
1589 acpi_bus_alloc_gas(device_t dev, int *type, int *rid, ACPI_GENERIC_ADDRESS *gas,
1590 struct resource **res, u_int flags)
1592 int error, res_type;
1595 if (type == NULL || rid == NULL || gas == NULL || res == NULL)
1598 /* We only support memory and IO spaces. */
1599 switch (gas->SpaceId) {
1600 case ACPI_ADR_SPACE_SYSTEM_MEMORY:
1601 res_type = SYS_RES_MEMORY;
1603 case ACPI_ADR_SPACE_SYSTEM_IO:
1604 res_type = SYS_RES_IOPORT;
1607 return (EOPNOTSUPP);
1611 * If the register width is less than 8, assume the BIOS author means
1612 * it is a bit field and just allocate a byte.
1614 if (gas->BitWidth && gas->BitWidth < 8)
1617 /* Validate the address after we're sure we support the space. */
1618 if (gas->Address == 0 || gas->BitWidth == 0)
1621 bus_set_resource(dev, res_type, *rid, gas->Address,
1623 *res = bus_alloc_resource_any(dev, res_type, rid, RF_ACTIVE | flags);
1628 bus_delete_resource(dev, res_type, *rid);
1633 /* Probe _HID and _CID for compatible ISA PNP ids. */
1635 acpi_isa_get_logicalid(device_t dev)
1637 ACPI_DEVICE_INFO *devinfo;
1641 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1643 /* Fetch and validate the HID. */
1644 if ((h = acpi_get_handle(dev)) == NULL ||
1645 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1648 pnpid = (devinfo->Valid & ACPI_VALID_HID) != 0 &&
1649 devinfo->HardwareId.Length >= ACPI_EISAID_STRING_SIZE ?
1650 PNP_EISAID(devinfo->HardwareId.String) : 0;
1651 AcpiOsFree(devinfo);
1653 return_VALUE (pnpid);
1657 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
1659 ACPI_DEVICE_INFO *devinfo;
1660 ACPI_PNP_DEVICE_ID *ids;
1665 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1669 /* Fetch and validate the CID */
1670 if ((h = acpi_get_handle(dev)) == NULL ||
1671 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1674 if ((devinfo->Valid & ACPI_VALID_CID) == 0) {
1675 AcpiOsFree(devinfo);
1679 if (devinfo->CompatibleIdList.Count < count)
1680 count = devinfo->CompatibleIdList.Count;
1681 ids = devinfo->CompatibleIdList.Ids;
1682 for (i = 0, valid = 0; i < count; i++)
1683 if (ids[i].Length >= ACPI_EISAID_STRING_SIZE &&
1684 strncmp(ids[i].String, "PNP", 3) == 0) {
1685 *pnpid++ = PNP_EISAID(ids[i].String);
1688 AcpiOsFree(devinfo);
1690 return_VALUE (valid);
1694 acpi_device_id_probe(device_t bus, device_t dev, char **ids, char **match)
1701 h = acpi_get_handle(dev);
1702 if (ids == NULL || h == NULL)
1704 t = acpi_get_type(dev);
1705 if (t != ACPI_TYPE_DEVICE && t != ACPI_TYPE_PROCESSOR)
1708 /* Try to match one of the array of IDs with a HID or CID. */
1709 for (i = 0; ids[i] != NULL; i++) {
1710 rv = acpi_MatchHid(h, ids[i]);
1711 if (rv == ACPI_MATCHHID_NOMATCH)
1714 if (match != NULL) {
1717 return ((rv == ACPI_MATCHHID_HID)?
1718 BUS_PROBE_DEFAULT : BUS_PROBE_LOW_PRIORITY);
1724 acpi_device_eval_obj(device_t bus, device_t dev, ACPI_STRING pathname,
1725 ACPI_OBJECT_LIST *parameters, ACPI_BUFFER *ret)
1730 h = ACPI_ROOT_OBJECT;
1731 else if ((h = acpi_get_handle(dev)) == NULL)
1732 return (AE_BAD_PARAMETER);
1733 return (AcpiEvaluateObject(h, pathname, parameters, ret));
1737 acpi_device_pwr_for_sleep(device_t bus, device_t dev, int *dstate)
1739 struct acpi_softc *sc;
1744 handle = acpi_get_handle(dev);
1747 * XXX If we find these devices, don't try to power them down.
1748 * The serial and IRDA ports on my T23 hang the system when
1749 * set to D3 and it appears that such legacy devices may
1750 * need special handling in their drivers.
1752 if (dstate == NULL || handle == NULL ||
1753 acpi_MatchHid(handle, "PNP0500") ||
1754 acpi_MatchHid(handle, "PNP0501") ||
1755 acpi_MatchHid(handle, "PNP0502") ||
1756 acpi_MatchHid(handle, "PNP0510") ||
1757 acpi_MatchHid(handle, "PNP0511"))
1761 * Override next state with the value from _SxD, if present.
1762 * Note illegal _S0D is evaluated because some systems expect this.
1764 sc = device_get_softc(bus);
1765 snprintf(sxd, sizeof(sxd), "_S%dD", sc->acpi_sstate);
1766 status = acpi_GetInteger(handle, sxd, dstate);
1767 if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
1768 device_printf(dev, "failed to get %s on %s: %s\n", sxd,
1769 acpi_name(handle), AcpiFormatException(status));
1776 /* Callback arg for our implementation of walking the namespace. */
1777 struct acpi_device_scan_ctx {
1778 acpi_scan_cb_t user_fn;
1784 acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level, void *arg, void **retval)
1786 struct acpi_device_scan_ctx *ctx;
1787 device_t dev, old_dev;
1789 ACPI_OBJECT_TYPE type;
1792 * Skip this device if we think we'll have trouble with it or it is
1793 * the parent where the scan began.
1795 ctx = (struct acpi_device_scan_ctx *)arg;
1796 if (acpi_avoid(h) || h == ctx->parent)
1799 /* If this is not a valid device type (e.g., a method), skip it. */
1800 if (ACPI_FAILURE(AcpiGetType(h, &type)))
1802 if (type != ACPI_TYPE_DEVICE && type != ACPI_TYPE_PROCESSOR &&
1803 type != ACPI_TYPE_THERMAL && type != ACPI_TYPE_POWER)
1807 * Call the user function with the current device. If it is unchanged
1808 * afterwards, return. Otherwise, we update the handle to the new dev.
1810 old_dev = acpi_get_device(h);
1812 status = ctx->user_fn(h, &dev, level, ctx->arg);
1813 if (ACPI_FAILURE(status) || old_dev == dev)
1816 /* Remove the old child and its connection to the handle. */
1817 if (old_dev != NULL)
1818 device_delete_child(device_get_parent(old_dev), old_dev);
1820 /* Recreate the handle association if the user created a device. */
1822 AcpiAttachData(h, acpi_fake_objhandler, dev);
1828 acpi_device_scan_children(device_t bus, device_t dev, int max_depth,
1829 acpi_scan_cb_t user_fn, void *arg)
1832 struct acpi_device_scan_ctx ctx;
1834 if (acpi_disabled("children"))
1838 h = ACPI_ROOT_OBJECT;
1839 else if ((h = acpi_get_handle(dev)) == NULL)
1840 return (AE_BAD_PARAMETER);
1841 ctx.user_fn = user_fn;
1844 return (AcpiWalkNamespace(ACPI_TYPE_ANY, h, max_depth,
1845 acpi_device_scan_cb, NULL, &ctx, NULL));
1849 * Even though ACPI devices are not PCI, we use the PCI approach for setting
1850 * device power states since it's close enough to ACPI.
1853 acpi_set_powerstate(device_t child, int state)
1858 h = acpi_get_handle(child);
1859 if (state < ACPI_STATE_D0 || state > ACPI_D_STATES_MAX)
1864 /* Ignore errors if the power methods aren't present. */
1865 status = acpi_pwr_switch_consumer(h, state);
1866 if (ACPI_SUCCESS(status)) {
1868 device_printf(child, "set ACPI power state D%d on %s\n",
1869 state, acpi_name(h));
1870 } else if (status != AE_NOT_FOUND)
1871 device_printf(child,
1872 "failed to set ACPI power state D%d on %s: %s\n", state,
1873 acpi_name(h), AcpiFormatException(status));
1879 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
1881 int result, cid_count, i;
1882 uint32_t lid, cids[8];
1884 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1887 * ISA-style drivers attached to ACPI may persist and
1888 * probe manually if we return ENOENT. We never want
1889 * that to happen, so don't ever return it.
1893 /* Scan the supplied IDs for a match */
1894 lid = acpi_isa_get_logicalid(child);
1895 cid_count = acpi_isa_get_compatid(child, cids, 8);
1896 while (ids && ids->ip_id) {
1897 if (lid == ids->ip_id) {
1901 for (i = 0; i < cid_count; i++) {
1902 if (cids[i] == ids->ip_id) {
1911 if (result == 0 && ids->ip_desc)
1912 device_set_desc(child, ids->ip_desc);
1914 return_VALUE (result);
1918 * Look for a MCFG table. If it is present, use the settings for
1919 * domain (segment) 0 to setup PCI config space access via the memory
1922 * On non-x86 architectures (arm64 for now), this will be done from the
1923 * PCI host bridge driver.
1926 acpi_enable_pcie(void)
1928 #if defined(__i386__) || defined(__amd64__)
1929 ACPI_TABLE_HEADER *hdr;
1930 ACPI_MCFG_ALLOCATION *alloc, *end;
1933 status = AcpiGetTable(ACPI_SIG_MCFG, 1, &hdr);
1934 if (ACPI_FAILURE(status))
1937 end = (ACPI_MCFG_ALLOCATION *)((char *)hdr + hdr->Length);
1938 alloc = (ACPI_MCFG_ALLOCATION *)((ACPI_TABLE_MCFG *)hdr + 1);
1939 while (alloc < end) {
1940 if (alloc->PciSegment == 0) {
1941 pcie_cfgregopen(alloc->Address, alloc->StartBusNumber,
1942 alloc->EndBusNumber);
1951 acpi_platform_osc(device_t dev)
1953 ACPI_HANDLE sb_handle;
1955 uint32_t cap_set[2];
1957 /* 0811B06E-4A27-44F9-8D60-3CBBC22E7B48 */
1958 static uint8_t acpi_platform_uuid[ACPI_UUID_LENGTH] = {
1959 0x6e, 0xb0, 0x11, 0x08, 0x27, 0x4a, 0xf9, 0x44,
1960 0x8d, 0x60, 0x3c, 0xbb, 0xc2, 0x2e, 0x7b, 0x48
1963 if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
1966 cap_set[1] = 0x10; /* APEI Support */
1967 status = acpi_EvaluateOSC(sb_handle, acpi_platform_uuid, 1,
1968 nitems(cap_set), cap_set, cap_set, false);
1969 if (ACPI_FAILURE(status)) {
1970 if (status == AE_NOT_FOUND)
1972 device_printf(dev, "_OSC failed: %s\n",
1973 AcpiFormatException(status));
1979 * Scan all of the ACPI namespace and attach child devices.
1981 * We should only expect to find devices in the \_PR, \_TZ, \_SI, and
1982 * \_SB scopes, and \_PR and \_TZ became obsolete in the ACPI 2.0 spec.
1983 * However, in violation of the spec, some systems place their PCI link
1984 * devices in \, so we have to walk the whole namespace. We check the
1985 * type of namespace nodes, so this should be ok.
1988 acpi_probe_children(device_t bus)
1991 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1994 * Scan the namespace and insert placeholders for all the devices that
1995 * we find. We also probe/attach any early devices.
1997 * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
1998 * we want to create nodes for all devices, not just those that are
1999 * currently present. (This assumes that we don't want to create/remove
2000 * devices as they appear, which might be smarter.)
2002 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
2003 AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, 100, acpi_probe_child,
2006 /* Pre-allocate resources for our rman from any sysresource devices. */
2007 acpi_sysres_alloc(bus);
2009 /* Reserve resources already allocated to children. */
2010 acpi_reserve_resources(bus);
2012 /* Create any static children by calling device identify methods. */
2013 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
2014 bus_generic_probe(bus);
2016 /* Probe/attach all children, created statically and from the namespace. */
2017 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "acpi bus_generic_attach\n"));
2018 bus_generic_attach(bus);
2020 /* Attach wake sysctls. */
2021 acpi_wake_sysctl_walk(bus);
2023 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
2028 * Determine the probe order for a given device.
2031 acpi_probe_order(ACPI_HANDLE handle, int *order)
2033 ACPI_OBJECT_TYPE type;
2037 * 1. I/O port and memory system resource holders
2038 * 2. Clocks and timers (to handle early accesses)
2039 * 3. Embedded controllers (to handle early accesses)
2040 * 4. PCI Link Devices
2042 AcpiGetType(handle, &type);
2043 if (type == ACPI_TYPE_PROCESSOR)
2045 else if (acpi_MatchHid(handle, "PNP0C01") ||
2046 acpi_MatchHid(handle, "PNP0C02"))
2048 else if (acpi_MatchHid(handle, "PNP0100") ||
2049 acpi_MatchHid(handle, "PNP0103") ||
2050 acpi_MatchHid(handle, "PNP0B00"))
2052 else if (acpi_MatchHid(handle, "PNP0C09"))
2054 else if (acpi_MatchHid(handle, "PNP0C0F"))
2059 * Evaluate a child device and determine whether we might attach a device to
2063 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2065 ACPI_DEVICE_INFO *devinfo;
2066 struct acpi_device *ad;
2067 struct acpi_prw_data prw;
2068 ACPI_OBJECT_TYPE type;
2070 device_t bus, child;
2074 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2076 if (acpi_disabled("children"))
2077 return_ACPI_STATUS (AE_OK);
2079 /* Skip this device if we think we'll have trouble with it. */
2080 if (acpi_avoid(handle))
2081 return_ACPI_STATUS (AE_OK);
2083 bus = (device_t)context;
2084 if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
2085 handle_str = acpi_name(handle);
2087 case ACPI_TYPE_DEVICE:
2089 * Since we scan from \, be sure to skip system scope objects.
2090 * \_SB_ and \_TZ_ are defined in ACPICA as devices to work around
2091 * BIOS bugs. For example, \_SB_ is to allow \_SB_._INI to be run
2092 * during the initialization and \_TZ_ is to support Notify() on it.
2094 if (strcmp(handle_str, "\\_SB_") == 0 ||
2095 strcmp(handle_str, "\\_TZ_") == 0)
2097 if (acpi_parse_prw(handle, &prw) == 0)
2098 AcpiSetupGpeForWake(handle, prw.gpe_handle, prw.gpe_bit);
2101 * Ignore devices that do not have a _HID or _CID. They should
2102 * be discovered by other buses (e.g. the PCI bus driver).
2104 if (!acpi_has_hid(handle))
2107 case ACPI_TYPE_PROCESSOR:
2108 case ACPI_TYPE_THERMAL:
2109 case ACPI_TYPE_POWER:
2111 * Create a placeholder device for this node. Sort the
2112 * placeholder so that the probe/attach passes will run
2113 * breadth-first. Orders less than ACPI_DEV_BASE_ORDER
2114 * are reserved for special objects (i.e., system
2117 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
2118 order = level * 10 + ACPI_DEV_BASE_ORDER;
2119 acpi_probe_order(handle, &order);
2120 child = BUS_ADD_CHILD(bus, order, NULL, -1);
2124 /* Associate the handle with the device_t and vice versa. */
2125 acpi_set_handle(child, handle);
2126 AcpiAttachData(handle, acpi_fake_objhandler, child);
2129 * Check that the device is present. If it's not present,
2130 * leave it disabled (so that we have a device_t attached to
2131 * the handle, but we don't probe it).
2133 * XXX PCI link devices sometimes report "present" but not
2134 * "functional" (i.e. if disabled). Go ahead and probe them
2135 * anyway since we may enable them later.
2137 if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
2138 /* Never disable PCI link devices. */
2139 if (acpi_MatchHid(handle, "PNP0C0F"))
2142 * Docking stations should remain enabled since the system
2143 * may be undocked at boot.
2145 if (ACPI_SUCCESS(AcpiGetHandle(handle, "_DCK", &h)))
2148 device_disable(child);
2153 * Get the device's resource settings and attach them.
2154 * Note that if the device has _PRS but no _CRS, we need
2155 * to decide when it's appropriate to try to configure the
2156 * device. Ignore the return value here; it's OK for the
2157 * device not to have any resources.
2159 acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
2161 ad = device_get_ivars(child);
2162 ad->ad_cls_class = 0xffffff;
2163 if (ACPI_SUCCESS(AcpiGetObjectInfo(handle, &devinfo))) {
2164 if ((devinfo->Valid & ACPI_VALID_CLS) != 0 &&
2165 devinfo->ClassCode.Length >= ACPI_PCICLS_STRING_SIZE) {
2166 ad->ad_cls_class = strtoul(devinfo->ClassCode.String,
2169 AcpiOsFree(devinfo);
2175 return_ACPI_STATUS (AE_OK);
2179 * AcpiAttachData() requires an object handler but never uses it. This is a
2180 * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
2183 acpi_fake_objhandler(ACPI_HANDLE h, void *data)
2188 acpi_shutdown_final(void *arg, int howto)
2190 struct acpi_softc *sc = (struct acpi_softc *)arg;
2195 * XXX Shutdown code should only run on the BSP (cpuid 0).
2196 * Some chipsets do not power off the system correctly if called from
2199 if ((howto & RB_POWEROFF) != 0) {
2200 status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
2201 if (ACPI_FAILURE(status)) {
2202 device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
2203 AcpiFormatException(status));
2206 device_printf(sc->acpi_dev, "Powering system off\n");
2207 intr = intr_disable();
2208 status = AcpiEnterSleepState(ACPI_STATE_S5);
2209 if (ACPI_FAILURE(status)) {
2211 device_printf(sc->acpi_dev, "power-off failed - %s\n",
2212 AcpiFormatException(status));
2216 device_printf(sc->acpi_dev, "power-off failed - timeout\n");
2218 } else if ((howto & RB_HALT) == 0 && sc->acpi_handle_reboot) {
2219 /* Reboot using the reset register. */
2220 status = AcpiReset();
2221 if (ACPI_SUCCESS(status)) {
2223 device_printf(sc->acpi_dev, "reset failed - timeout\n");
2224 } else if (status != AE_NOT_EXIST)
2225 device_printf(sc->acpi_dev, "reset failed - %s\n",
2226 AcpiFormatException(status));
2227 } else if (sc->acpi_do_disable && !KERNEL_PANICKED()) {
2229 * Only disable ACPI if the user requested. On some systems, writing
2230 * the disable value to SMI_CMD hangs the system.
2232 device_printf(sc->acpi_dev, "Shutting down\n");
2238 acpi_enable_fixed_events(struct acpi_softc *sc)
2240 static int first_time = 1;
2242 /* Enable and clear fixed events and install handlers. */
2243 if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
2244 AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
2245 AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
2246 acpi_event_power_button_sleep, sc);
2248 device_printf(sc->acpi_dev, "Power Button (fixed)\n");
2250 if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
2251 AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
2252 AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
2253 acpi_event_sleep_button_sleep, sc);
2255 device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
2262 * Returns true if the device is actually present and should
2263 * be attached to. This requires the present, enabled, UI-visible
2264 * and diagnostics-passed bits to be set.
2267 acpi_DeviceIsPresent(device_t dev)
2273 h = acpi_get_handle(dev);
2277 * Certain Treadripper boards always returns 0 for FreeBSD because it
2278 * only returns non-zero for the OS string "Windows 2015". Otherwise it
2279 * will return zero. Force them to always be treated as present.
2280 * Beata versions were worse: they always returned 0.
2282 if (acpi_MatchHid(h, "AMDI0020") || acpi_MatchHid(h, "AMDI0010"))
2285 status = acpi_GetInteger(h, "_STA", &s);
2288 * If no _STA method or if it failed, then assume that
2289 * the device is present.
2291 if (ACPI_FAILURE(status))
2294 return (ACPI_DEVICE_PRESENT(s) ? TRUE : FALSE);
2298 * Returns true if the battery is actually present and inserted.
2301 acpi_BatteryIsPresent(device_t dev)
2307 h = acpi_get_handle(dev);
2310 status = acpi_GetInteger(h, "_STA", &s);
2313 * If no _STA method or if it failed, then assume that
2314 * the device is present.
2316 if (ACPI_FAILURE(status))
2319 return (ACPI_BATTERY_PRESENT(s) ? TRUE : FALSE);
2323 * Returns true if a device has at least one valid device ID.
2326 acpi_has_hid(ACPI_HANDLE h)
2328 ACPI_DEVICE_INFO *devinfo;
2332 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2336 if ((devinfo->Valid & ACPI_VALID_HID) != 0)
2338 else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2339 if (devinfo->CompatibleIdList.Count > 0)
2342 AcpiOsFree(devinfo);
2347 * Match a HID string against a handle
2348 * returns ACPI_MATCHHID_HID if _HID match
2349 * ACPI_MATCHHID_CID if _CID match and not _HID match.
2350 * ACPI_MATCHHID_NOMATCH=0 if no match.
2353 acpi_MatchHid(ACPI_HANDLE h, const char *hid)
2355 ACPI_DEVICE_INFO *devinfo;
2359 if (hid == NULL || h == NULL ||
2360 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2361 return (ACPI_MATCHHID_NOMATCH);
2363 ret = ACPI_MATCHHID_NOMATCH;
2364 if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
2365 strcmp(hid, devinfo->HardwareId.String) == 0)
2366 ret = ACPI_MATCHHID_HID;
2367 else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2368 for (i = 0; i < devinfo->CompatibleIdList.Count; i++) {
2369 if (strcmp(hid, devinfo->CompatibleIdList.Ids[i].String) == 0) {
2370 ret = ACPI_MATCHHID_CID;
2375 AcpiOsFree(devinfo);
2380 * Return the handle of a named object within our scope, ie. that of (parent)
2381 * or one if its parents.
2384 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
2389 /* Walk back up the tree to the root */
2391 status = AcpiGetHandle(parent, path, &r);
2392 if (ACPI_SUCCESS(status)) {
2396 /* XXX Return error here? */
2397 if (status != AE_NOT_FOUND)
2399 if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
2400 return (AE_NOT_FOUND);
2406 * Allocate a buffer with a preset data size.
2409 acpi_AllocBuffer(int size)
2413 if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
2416 buf->Pointer = (void *)(buf + 1);
2421 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
2424 ACPI_OBJECT_LIST args;
2426 arg1.Type = ACPI_TYPE_INTEGER;
2427 arg1.Integer.Value = number;
2429 args.Pointer = &arg1;
2431 return (AcpiEvaluateObject(handle, path, &args, NULL));
2435 * Evaluate a path that should return an integer.
2438 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
2445 handle = ACPI_ROOT_OBJECT;
2448 * Assume that what we've been pointed at is an Integer object, or
2449 * a method that will return an Integer.
2451 buf.Pointer = ¶m;
2452 buf.Length = sizeof(param);
2453 status = AcpiEvaluateObject(handle, path, NULL, &buf);
2454 if (ACPI_SUCCESS(status)) {
2455 if (param.Type == ACPI_TYPE_INTEGER)
2456 *number = param.Integer.Value;
2462 * In some applications, a method that's expected to return an Integer
2463 * may instead return a Buffer (probably to simplify some internal
2464 * arithmetic). We'll try to fetch whatever it is, and if it's a Buffer,
2465 * convert it into an Integer as best we can.
2469 if (status == AE_BUFFER_OVERFLOW) {
2470 if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
2471 status = AE_NO_MEMORY;
2473 status = AcpiEvaluateObject(handle, path, NULL, &buf);
2474 if (ACPI_SUCCESS(status))
2475 status = acpi_ConvertBufferToInteger(&buf, number);
2476 AcpiOsFree(buf.Pointer);
2483 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
2489 p = (ACPI_OBJECT *)bufp->Pointer;
2490 if (p->Type == ACPI_TYPE_INTEGER) {
2491 *number = p->Integer.Value;
2494 if (p->Type != ACPI_TYPE_BUFFER)
2496 if (p->Buffer.Length > sizeof(int))
2497 return (AE_BAD_DATA);
2500 val = p->Buffer.Pointer;
2501 for (i = 0; i < p->Buffer.Length; i++)
2502 *number += val[i] << (i * 8);
2507 * Iterate over the elements of an a package object, calling the supplied
2508 * function for each element.
2510 * XXX possible enhancement might be to abort traversal on error.
2513 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
2514 void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
2519 if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
2520 return (AE_BAD_PARAMETER);
2522 /* Iterate over components */
2524 comp = pkg->Package.Elements;
2525 for (; i < pkg->Package.Count; i++, comp++)
2532 * Find the (index)th resource object in a set.
2535 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
2540 rp = (ACPI_RESOURCE *)buf->Pointer;
2544 if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2545 return (AE_BAD_PARAMETER);
2547 /* Check for terminator */
2548 if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2549 return (AE_NOT_FOUND);
2550 rp = ACPI_NEXT_RESOURCE(rp);
2559 * Append an ACPI_RESOURCE to an ACPI_BUFFER.
2561 * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
2562 * provided to contain it. If the ACPI_BUFFER is empty, allocate a sensible
2563 * backing block. If the ACPI_RESOURCE is NULL, return an empty set of
2566 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE 512
2569 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
2574 /* Initialise the buffer if necessary. */
2575 if (buf->Pointer == NULL) {
2576 buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
2577 if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
2578 return (AE_NO_MEMORY);
2579 rp = (ACPI_RESOURCE *)buf->Pointer;
2580 rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2581 rp->Length = ACPI_RS_SIZE_MIN;
2587 * Scan the current buffer looking for the terminator.
2588 * This will either find the terminator or hit the end
2589 * of the buffer and return an error.
2591 rp = (ACPI_RESOURCE *)buf->Pointer;
2593 /* Range check, don't go outside the buffer */
2594 if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2595 return (AE_BAD_PARAMETER);
2596 if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2598 rp = ACPI_NEXT_RESOURCE(rp);
2602 * Check the size of the buffer and expand if required.
2605 * size of existing resources before terminator +
2606 * size of new resource and header +
2607 * size of terminator.
2609 * Note that this loop should really only run once, unless
2610 * for some reason we are stuffing a *really* huge resource.
2612 while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
2613 res->Length + ACPI_RS_SIZE_NO_DATA +
2614 ACPI_RS_SIZE_MIN) >= buf->Length) {
2615 if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
2616 return (AE_NO_MEMORY);
2617 bcopy(buf->Pointer, newp, buf->Length);
2618 rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
2619 ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
2620 AcpiOsFree(buf->Pointer);
2621 buf->Pointer = newp;
2622 buf->Length += buf->Length;
2625 /* Insert the new resource. */
2626 bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
2628 /* And add the terminator. */
2629 rp = ACPI_NEXT_RESOURCE(rp);
2630 rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2631 rp->Length = ACPI_RS_SIZE_MIN;
2637 acpi_DSMQuery(ACPI_HANDLE h, const uint8_t *uuid, int revision)
2640 * ACPI spec 9.1.1 defines this.
2642 * "Arg2: Function Index Represents a specific function whose meaning is
2643 * specific to the UUID and Revision ID. Function indices should start
2644 * with 1. Function number zero is a query function (see the special
2645 * return code defined below)."
2652 if (!ACPI_SUCCESS(acpi_EvaluateDSM(h, uuid, revision, 0, NULL, &buf))) {
2653 ACPI_INFO(("Failed to enumerate DSM functions\n"));
2657 obj = (ACPI_OBJECT *)buf.Pointer;
2658 KASSERT(obj, ("Object not allowed to be NULL\n"));
2661 * From ACPI 6.2 spec 9.1.1:
2662 * If Function Index = 0, a Buffer containing a function index bitfield.
2663 * Otherwise, the return value and type depends on the UUID and revision
2666 switch (obj->Type) {
2667 case ACPI_TYPE_BUFFER:
2668 for (i = 0; i < MIN(obj->Buffer.Length, sizeof(ret)); i++)
2669 ret |= (((uint64_t)obj->Buffer.Pointer[i]) << (i * 8));
2671 case ACPI_TYPE_INTEGER:
2672 ACPI_BIOS_WARNING((AE_INFO,
2673 "Possibly buggy BIOS with ACPI_TYPE_INTEGER for function enumeration\n"));
2674 ret = obj->Integer.Value;
2677 ACPI_WARNING((AE_INFO, "Unexpected return type %u\n", obj->Type));
2685 * DSM may return multiple types depending on the function. It is therefore
2686 * unsafe to use the typed evaluation. It is highly recommended that the caller
2687 * check the type of the returned object.
2690 acpi_EvaluateDSM(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
2691 UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf)
2693 return (acpi_EvaluateDSMTyped(handle, uuid, revision, function,
2694 package, out_buf, ACPI_TYPE_ANY));
2698 acpi_EvaluateDSMTyped(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
2699 UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf,
2700 ACPI_OBJECT_TYPE type)
2703 ACPI_OBJECT_LIST arglist;
2707 if (out_buf == NULL)
2708 return (AE_NO_MEMORY);
2710 arg[0].Type = ACPI_TYPE_BUFFER;
2711 arg[0].Buffer.Length = ACPI_UUID_LENGTH;
2712 arg[0].Buffer.Pointer = __DECONST(uint8_t *, uuid);
2713 arg[1].Type = ACPI_TYPE_INTEGER;
2714 arg[1].Integer.Value = revision;
2715 arg[2].Type = ACPI_TYPE_INTEGER;
2716 arg[2].Integer.Value = function;
2720 arg[3].Type = ACPI_TYPE_PACKAGE;
2721 arg[3].Package.Count = 0;
2722 arg[3].Package.Elements = NULL;
2725 arglist.Pointer = arg;
2728 buf.Length = ACPI_ALLOCATE_BUFFER;
2729 status = AcpiEvaluateObjectTyped(handle, "_DSM", &arglist, &buf, type);
2730 if (ACPI_FAILURE(status))
2733 KASSERT(ACPI_SUCCESS(status), ("Unexpected status"));
2740 acpi_EvaluateOSC(ACPI_HANDLE handle, uint8_t *uuid, int revision, int count,
2741 uint32_t *caps_in, uint32_t *caps_out, bool query)
2743 ACPI_OBJECT arg[4], *ret;
2744 ACPI_OBJECT_LIST arglist;
2748 arglist.Pointer = arg;
2750 arg[0].Type = ACPI_TYPE_BUFFER;
2751 arg[0].Buffer.Length = ACPI_UUID_LENGTH;
2752 arg[0].Buffer.Pointer = uuid;
2753 arg[1].Type = ACPI_TYPE_INTEGER;
2754 arg[1].Integer.Value = revision;
2755 arg[2].Type = ACPI_TYPE_INTEGER;
2756 arg[2].Integer.Value = count;
2757 arg[3].Type = ACPI_TYPE_BUFFER;
2758 arg[3].Buffer.Length = count * sizeof(*caps_in);
2759 arg[3].Buffer.Pointer = (uint8_t *)caps_in;
2760 caps_in[0] = query ? 1 : 0;
2762 buf.Length = ACPI_ALLOCATE_BUFFER;
2763 status = AcpiEvaluateObjectTyped(handle, "_OSC", &arglist, &buf,
2765 if (ACPI_FAILURE(status))
2767 if (caps_out != NULL) {
2769 if (ret->Buffer.Length != count * sizeof(*caps_out)) {
2770 AcpiOsFree(buf.Pointer);
2771 return (AE_BUFFER_OVERFLOW);
2773 bcopy(ret->Buffer.Pointer, caps_out, ret->Buffer.Length);
2775 AcpiOsFree(buf.Pointer);
2780 * Set interrupt model.
2783 acpi_SetIntrModel(int model)
2786 return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
2790 * Walk subtables of a table and call a callback routine for each
2791 * subtable. The caller should provide the first subtable and a
2792 * pointer to the end of the table. This can be used to walk tables
2793 * such as MADT and SRAT that use subtable entries.
2796 acpi_walk_subtables(void *first, void *end, acpi_subtable_handler *handler,
2799 ACPI_SUBTABLE_HEADER *entry;
2801 for (entry = first; (void *)entry < end; ) {
2802 /* Avoid an infinite loop if we hit a bogus entry. */
2803 if (entry->Length < sizeof(ACPI_SUBTABLE_HEADER))
2806 handler(entry, arg);
2807 entry = ACPI_ADD_PTR(ACPI_SUBTABLE_HEADER, entry, entry->Length);
2812 * DEPRECATED. This interface has serious deficiencies and will be
2815 * Immediately enter the sleep state. In the old model, acpiconf(8) ran
2816 * rc.suspend and rc.resume so we don't have to notify devd(8) to do this.
2819 acpi_SetSleepState(struct acpi_softc *sc, int state)
2824 device_printf(sc->acpi_dev,
2825 "warning: acpi_SetSleepState() deprecated, need to update your software\n");
2828 return (acpi_EnterSleepState(sc, state));
2831 #if defined(__amd64__) || defined(__i386__)
2833 acpi_sleep_force_task(void *context)
2835 struct acpi_softc *sc = (struct acpi_softc *)context;
2837 if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
2838 device_printf(sc->acpi_dev, "force sleep state S%d failed\n",
2839 sc->acpi_next_sstate);
2843 acpi_sleep_force(void *arg)
2845 struct acpi_softc *sc = (struct acpi_softc *)arg;
2847 device_printf(sc->acpi_dev,
2848 "suspend request timed out, forcing sleep now\n");
2850 * XXX Suspending from callout causes freezes in DEVICE_SUSPEND().
2851 * Suspend from acpi_task thread instead.
2853 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
2854 acpi_sleep_force_task, sc)))
2855 device_printf(sc->acpi_dev, "AcpiOsExecute() for sleeping failed\n");
2860 * Request that the system enter the given suspend state. All /dev/apm
2861 * devices and devd(8) will be notified. Userland then has a chance to
2862 * save state and acknowledge the request. The system sleeps once all
2866 acpi_ReqSleepState(struct acpi_softc *sc, int state)
2868 #if defined(__amd64__) || defined(__i386__)
2869 struct apm_clone_data *clone;
2872 if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
2874 if (!acpi_sleep_states[state])
2875 return (EOPNOTSUPP);
2878 * If a reboot/shutdown/suspend request is already in progress or
2879 * suspend is blocked due to an upcoming shutdown, just return.
2881 if (rebooting || sc->acpi_next_sstate != 0 || suspend_blocked) {
2885 /* Wait until sleep is enabled. */
2886 while (sc->acpi_sleep_disabled) {
2892 sc->acpi_next_sstate = state;
2894 /* S5 (soft-off) should be entered directly with no waiting. */
2895 if (state == ACPI_STATE_S5) {
2897 status = acpi_EnterSleepState(sc, state);
2898 return (ACPI_SUCCESS(status) ? 0 : ENXIO);
2901 /* Record the pending state and notify all apm devices. */
2902 STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
2903 clone->notify_status = APM_EV_NONE;
2904 if ((clone->flags & ACPI_EVF_DEVD) == 0) {
2905 selwakeuppri(&clone->sel_read, PZERO);
2906 KNOTE_LOCKED(&clone->sel_read.si_note, 0);
2910 /* If devd(8) is not running, immediately enter the sleep state. */
2911 if (!devctl_process_running()) {
2913 status = acpi_EnterSleepState(sc, state);
2914 return (ACPI_SUCCESS(status) ? 0 : ENXIO);
2918 * Set a timeout to fire if userland doesn't ack the suspend request
2919 * in time. This way we still eventually go to sleep if we were
2920 * overheating or running low on battery, even if userland is hung.
2921 * We cancel this timeout once all userland acks are in or the
2922 * suspend request is aborted.
2924 callout_reset(&sc->susp_force_to, 10 * hz, acpi_sleep_force, sc);
2927 /* Now notify devd(8) also. */
2928 acpi_UserNotify("Suspend", ACPI_ROOT_OBJECT, state);
2932 /* This platform does not support acpi suspend/resume. */
2933 return (EOPNOTSUPP);
2938 * Acknowledge (or reject) a pending sleep state. The caller has
2939 * prepared for suspend and is now ready for it to proceed. If the
2940 * error argument is non-zero, it indicates suspend should be cancelled
2941 * and gives an errno value describing why. Once all votes are in,
2942 * we suspend the system.
2945 acpi_AckSleepState(struct apm_clone_data *clone, int error)
2947 #if defined(__amd64__) || defined(__i386__)
2948 struct acpi_softc *sc;
2951 /* If no pending sleep state, return an error. */
2953 sc = clone->acpi_sc;
2954 if (sc->acpi_next_sstate == 0) {
2959 /* Caller wants to abort suspend process. */
2961 sc->acpi_next_sstate = 0;
2962 callout_stop(&sc->susp_force_to);
2963 device_printf(sc->acpi_dev,
2964 "listener on %s cancelled the pending suspend\n",
2965 devtoname(clone->cdev));
2971 * Mark this device as acking the suspend request. Then, walk through
2972 * all devices, seeing if they agree yet. We only count devices that
2973 * are writable since read-only devices couldn't ack the request.
2976 clone->notify_status = APM_EV_ACKED;
2977 STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
2978 if ((clone->flags & ACPI_EVF_WRITE) != 0 &&
2979 clone->notify_status != APM_EV_ACKED) {
2985 /* If all devices have voted "yes", we will suspend now. */
2987 callout_stop(&sc->susp_force_to);
2991 if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
2996 /* This platform does not support acpi suspend/resume. */
2997 return (EOPNOTSUPP);
3002 acpi_sleep_enable(void *arg)
3004 struct acpi_softc *sc = (struct acpi_softc *)arg;
3006 ACPI_LOCK_ASSERT(acpi);
3008 /* Reschedule if the system is not fully up and running. */
3009 if (!AcpiGbl_SystemAwakeAndRunning) {
3010 callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3014 sc->acpi_sleep_disabled = FALSE;
3018 acpi_sleep_disable(struct acpi_softc *sc)
3022 /* Fail if the system is not fully up and running. */
3023 if (!AcpiGbl_SystemAwakeAndRunning)
3027 status = sc->acpi_sleep_disabled ? AE_ERROR : AE_OK;
3028 sc->acpi_sleep_disabled = TRUE;
3034 enum acpi_sleep_state {
3037 ACPI_SS_DEV_SUSPEND,
3043 * Enter the desired system sleep state.
3045 * Currently we support S1-S5 but S4 is only S4BIOS
3048 acpi_EnterSleepState(struct acpi_softc *sc, int state)
3052 ACPI_EVENT_STATUS power_button_status;
3053 enum acpi_sleep_state slp_state;
3056 ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3058 if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
3059 return_ACPI_STATUS (AE_BAD_PARAMETER);
3060 if (!acpi_sleep_states[state]) {
3061 device_printf(sc->acpi_dev, "Sleep state S%d not supported by BIOS\n",
3063 return (AE_SUPPORT);
3066 /* Re-entry once we're suspending is not allowed. */
3067 status = acpi_sleep_disable(sc);
3068 if (ACPI_FAILURE(status)) {
3069 device_printf(sc->acpi_dev,
3070 "suspend request ignored (not ready yet)\n");
3074 if (state == ACPI_STATE_S5) {
3076 * Shut down cleanly and power off. This will call us back through the
3077 * shutdown handlers.
3079 shutdown_nice(RB_POWEROFF);
3080 return_ACPI_STATUS (AE_OK);
3083 EVENTHANDLER_INVOKE(power_suspend_early);
3086 EVENTHANDLER_INVOKE(power_suspend);
3088 #ifdef EARLY_AP_STARTUP
3089 MPASS(mp_ncpus == 1 || smp_started);
3090 thread_lock(curthread);
3091 sched_bind(curthread, 0);
3092 thread_unlock(curthread);
3095 thread_lock(curthread);
3096 sched_bind(curthread, 0);
3097 thread_unlock(curthread);
3102 * Be sure to hold Giant across DEVICE_SUSPEND/RESUME since non-MPSAFE
3103 * drivers need this.
3107 slp_state = ACPI_SS_NONE;
3109 sc->acpi_sstate = state;
3111 /* Enable any GPEs as appropriate and requested by the user. */
3112 acpi_wake_prep_walk(state);
3113 slp_state = ACPI_SS_GPE_SET;
3116 * Inform all devices that we are going to sleep. If at least one
3117 * device fails, DEVICE_SUSPEND() automatically resumes the tree.
3119 * XXX Note that a better two-pass approach with a 'veto' pass
3120 * followed by a "real thing" pass would be better, but the current
3121 * bus interface does not provide for this.
3123 if (DEVICE_SUSPEND(root_bus) != 0) {
3124 device_printf(sc->acpi_dev, "device_suspend failed\n");
3127 slp_state = ACPI_SS_DEV_SUSPEND;
3129 status = AcpiEnterSleepStatePrep(state);
3130 if (ACPI_FAILURE(status)) {
3131 device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
3132 AcpiFormatException(status));
3135 slp_state = ACPI_SS_SLP_PREP;
3137 if (sc->acpi_sleep_delay > 0)
3138 DELAY(sc->acpi_sleep_delay * 1000000);
3141 intr = intr_disable();
3142 if (state != ACPI_STATE_S1) {
3143 sleep_result = acpi_sleep_machdep(sc, state);
3144 acpi_wakeup_machdep(sc, state, sleep_result, 0);
3147 * XXX According to ACPI specification SCI_EN bit should be restored
3148 * by ACPI platform (BIOS, firmware) to its pre-sleep state.
3149 * Unfortunately some BIOSes fail to do that and that leads to
3150 * unexpected and serious consequences during wake up like a system
3151 * getting stuck in SMI handlers.
3152 * This hack is picked up from Linux, which claims that it follows
3155 if (sleep_result == 1 && state != ACPI_STATE_S4)
3156 AcpiWriteBitRegister(ACPI_BITREG_SCI_ENABLE, ACPI_ENABLE_EVENT);
3158 if (sleep_result == 1 && state == ACPI_STATE_S3) {
3160 * Prevent mis-interpretation of the wakeup by power button
3161 * as a request for power off.
3162 * Ideally we should post an appropriate wakeup event,
3163 * perhaps using acpi_event_power_button_wake or alike.
3165 * Clearing of power button status after wakeup is mandated
3166 * by ACPI specification in section "Fixed Power Button".
3168 * XXX As of ACPICA 20121114 AcpiGetEventStatus provides
3169 * status as 0/1 corressponding to inactive/active despite
3170 * its type being ACPI_EVENT_STATUS. In other words,
3171 * we should not test for ACPI_EVENT_FLAG_SET for time being.
3173 if (ACPI_SUCCESS(AcpiGetEventStatus(ACPI_EVENT_POWER_BUTTON,
3174 &power_button_status)) && power_button_status != 0) {
3175 AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
3176 device_printf(sc->acpi_dev,
3177 "cleared fixed power button status\n");
3183 /* call acpi_wakeup_machdep() again with interrupt enabled */
3184 acpi_wakeup_machdep(sc, state, sleep_result, 1);
3186 AcpiLeaveSleepStatePrep(state);
3188 if (sleep_result == -1)
3191 /* Re-enable ACPI hardware on wakeup from sleep state 4. */
3192 if (state == ACPI_STATE_S4)
3195 status = AcpiEnterSleepState(state);
3197 AcpiLeaveSleepStatePrep(state);
3198 if (ACPI_FAILURE(status)) {
3199 device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
3200 AcpiFormatException(status));
3204 slp_state = ACPI_SS_SLEPT;
3207 * Back out state according to how far along we got in the suspend
3208 * process. This handles both the error and success cases.
3211 if (slp_state >= ACPI_SS_SLP_PREP)
3213 if (slp_state >= ACPI_SS_GPE_SET) {
3214 acpi_wake_prep_walk(state);
3215 sc->acpi_sstate = ACPI_STATE_S0;
3217 if (slp_state >= ACPI_SS_DEV_SUSPEND)
3218 DEVICE_RESUME(root_bus);
3219 if (slp_state >= ACPI_SS_SLP_PREP)
3220 AcpiLeaveSleepState(state);
3221 if (slp_state >= ACPI_SS_SLEPT) {
3222 #if defined(__i386__) || defined(__amd64__)
3223 /* NB: we are still using ACPI timecounter at this point. */
3226 acpi_resync_clock(sc);
3227 acpi_enable_fixed_events(sc);
3229 sc->acpi_next_sstate = 0;
3233 #ifdef EARLY_AP_STARTUP
3234 thread_lock(curthread);
3235 sched_unbind(curthread);
3236 thread_unlock(curthread);
3239 thread_lock(curthread);
3240 sched_unbind(curthread);
3241 thread_unlock(curthread);
3248 EVENTHANDLER_INVOKE(power_resume);
3250 /* Allow another sleep request after a while. */
3251 callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3253 /* Run /etc/rc.resume after we are back. */
3254 if (devctl_process_running())
3255 acpi_UserNotify("Resume", ACPI_ROOT_OBJECT, state);
3257 return_ACPI_STATUS (status);
3261 acpi_resync_clock(struct acpi_softc *sc)
3265 * Warm up timecounter again and reset system clock.
3267 (void)timecounter->tc_get_timecount(timecounter);
3268 inittodr(time_second + sc->acpi_sleep_delay);
3271 /* Enable or disable the device's wake GPE. */
3273 acpi_wake_set_enable(device_t dev, int enable)
3275 struct acpi_prw_data prw;
3279 /* Make sure the device supports waking the system and get the GPE. */
3280 if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
3283 flags = acpi_get_flags(dev);
3285 status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3287 if (ACPI_FAILURE(status)) {
3288 device_printf(dev, "enable wake failed\n");
3291 acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
3293 status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3295 if (ACPI_FAILURE(status)) {
3296 device_printf(dev, "disable wake failed\n");
3299 acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
3306 acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate)
3308 struct acpi_prw_data prw;
3311 /* Check that this is a wake-capable device and get its GPE. */
3312 if (acpi_parse_prw(handle, &prw) != 0)
3314 dev = acpi_get_device(handle);
3317 * The destination sleep state must be less than (i.e., higher power)
3318 * or equal to the value specified by _PRW. If this GPE cannot be
3319 * enabled for the next sleep state, then disable it. If it can and
3320 * the user requested it be enabled, turn on any required power resources
3323 if (sstate > prw.lowest_wake) {
3324 AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_DISABLE);
3326 device_printf(dev, "wake_prep disabled wake for %s (S%d)\n",
3327 acpi_name(handle), sstate);
3328 } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
3329 acpi_pwr_wake_enable(handle, 1);
3330 acpi_SetInteger(handle, "_PSW", 1);
3332 device_printf(dev, "wake_prep enabled for %s (S%d)\n",
3333 acpi_name(handle), sstate);
3340 acpi_wake_run_prep(ACPI_HANDLE handle, int sstate)
3342 struct acpi_prw_data prw;
3346 * Check that this is a wake-capable device and get its GPE. Return
3347 * now if the user didn't enable this device for wake.
3349 if (acpi_parse_prw(handle, &prw) != 0)
3351 dev = acpi_get_device(handle);
3352 if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
3356 * If this GPE couldn't be enabled for the previous sleep state, it was
3357 * disabled before going to sleep so re-enable it. If it was enabled,
3358 * clear _PSW and turn off any power resources it used.
3360 if (sstate > prw.lowest_wake) {
3361 AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_ENABLE);
3363 device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
3365 acpi_SetInteger(handle, "_PSW", 0);
3366 acpi_pwr_wake_enable(handle, 0);
3368 device_printf(dev, "run_prep cleaned up for %s\n",
3376 acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
3380 /* If suspending, run the sleep prep function, otherwise wake. */
3381 sstate = *(int *)context;
3382 if (AcpiGbl_SystemAwakeAndRunning)
3383 acpi_wake_sleep_prep(handle, sstate);
3385 acpi_wake_run_prep(handle, sstate);
3389 /* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
3391 acpi_wake_prep_walk(int sstate)
3393 ACPI_HANDLE sb_handle;
3395 if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
3396 AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
3397 acpi_wake_prep, NULL, &sstate, NULL);
3401 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
3403 acpi_wake_sysctl_walk(device_t dev)
3405 int error, i, numdevs;
3410 error = device_get_children(dev, &devlist, &numdevs);
3411 if (error != 0 || numdevs == 0) {
3413 free(devlist, M_TEMP);
3416 for (i = 0; i < numdevs; i++) {
3418 acpi_wake_sysctl_walk(child);
3419 if (!device_is_attached(child))
3421 status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
3422 if (ACPI_SUCCESS(status)) {
3423 SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
3424 SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
3425 "wake", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, child, 0,
3426 acpi_wake_set_sysctl, "I", "Device set to wake the system");
3429 free(devlist, M_TEMP);
3434 /* Enable or disable wake from userland. */
3436 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
3441 dev = (device_t)arg1;
3442 enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
3444 error = sysctl_handle_int(oidp, &enable, 0, req);
3445 if (error != 0 || req->newptr == NULL)
3447 if (enable != 0 && enable != 1)
3450 return (acpi_wake_set_enable(dev, enable));
3453 /* Parse a device's _PRW into a structure. */
3455 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
3458 ACPI_BUFFER prw_buffer;
3459 ACPI_OBJECT *res, *res2;
3460 int error, i, power_count;
3462 if (h == NULL || prw == NULL)
3466 * The _PRW object (7.2.9) is only required for devices that have the
3467 * ability to wake the system from a sleeping state.
3470 prw_buffer.Pointer = NULL;
3471 prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
3472 status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
3473 if (ACPI_FAILURE(status))
3475 res = (ACPI_OBJECT *)prw_buffer.Pointer;
3478 if (!ACPI_PKG_VALID(res, 2))
3482 * Element 1 of the _PRW object:
3483 * The lowest power system sleeping state that can be entered while still
3484 * providing wake functionality. The sleeping state being entered must
3485 * be less than (i.e., higher power) or equal to this value.
3487 if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
3491 * Element 0 of the _PRW object:
3493 switch (res->Package.Elements[0].Type) {
3494 case ACPI_TYPE_INTEGER:
3496 * If the data type of this package element is numeric, then this
3497 * _PRW package element is the bit index in the GPEx_EN, in the
3498 * GPE blocks described in the FADT, of the enable bit that is
3499 * enabled for the wake event.
3501 prw->gpe_handle = NULL;
3502 prw->gpe_bit = res->Package.Elements[0].Integer.Value;
3505 case ACPI_TYPE_PACKAGE:
3507 * If the data type of this package element is a package, then this
3508 * _PRW package element is itself a package containing two
3509 * elements. The first is an object reference to the GPE Block
3510 * device that contains the GPE that will be triggered by the wake
3511 * event. The second element is numeric and it contains the bit
3512 * index in the GPEx_EN, in the GPE Block referenced by the
3513 * first element in the package, of the enable bit that is enabled for
3516 * For example, if this field is a package then it is of the form:
3517 * Package() {\_SB.PCI0.ISA.GPE, 2}
3519 res2 = &res->Package.Elements[0];
3520 if (!ACPI_PKG_VALID(res2, 2))
3522 prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
3523 if (prw->gpe_handle == NULL)
3525 if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
3533 /* Elements 2 to N of the _PRW object are power resources. */
3534 power_count = res->Package.Count - 2;
3535 if (power_count > ACPI_PRW_MAX_POWERRES) {
3536 printf("ACPI device %s has too many power resources\n", acpi_name(h));
3539 prw->power_res_count = power_count;
3540 for (i = 0; i < power_count; i++)
3541 prw->power_res[i] = res->Package.Elements[i];
3544 if (prw_buffer.Pointer != NULL)
3545 AcpiOsFree(prw_buffer.Pointer);
3550 * ACPI Event Handlers
3553 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
3556 acpi_system_eventhandler_sleep(void *arg, int state)
3558 struct acpi_softc *sc = (struct acpi_softc *)arg;
3561 ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3563 /* Check if button action is disabled or unknown. */
3564 if (state == ACPI_STATE_UNKNOWN)
3567 /* Request that the system prepare to enter the given suspend state. */
3568 ret = acpi_ReqSleepState(sc, state);
3570 device_printf(sc->acpi_dev,
3571 "request to enter state S%d failed (err %d)\n", state, ret);
3577 acpi_system_eventhandler_wakeup(void *arg, int state)
3580 ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3582 /* Currently, nothing to do for wakeup. */
3588 * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
3591 acpi_invoke_sleep_eventhandler(void *context)
3594 EVENTHANDLER_INVOKE(acpi_sleep_event, *(int *)context);
3598 acpi_invoke_wake_eventhandler(void *context)
3601 EVENTHANDLER_INVOKE(acpi_wakeup_event, *(int *)context);
3605 acpi_event_power_button_sleep(void *context)
3607 struct acpi_softc *sc = (struct acpi_softc *)context;
3609 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3611 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3612 acpi_invoke_sleep_eventhandler, &sc->acpi_power_button_sx)))
3613 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3614 return_VALUE (ACPI_INTERRUPT_HANDLED);
3618 acpi_event_power_button_wake(void *context)
3620 struct acpi_softc *sc = (struct acpi_softc *)context;
3622 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3624 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3625 acpi_invoke_wake_eventhandler, &sc->acpi_power_button_sx)))
3626 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3627 return_VALUE (ACPI_INTERRUPT_HANDLED);
3631 acpi_event_sleep_button_sleep(void *context)
3633 struct acpi_softc *sc = (struct acpi_softc *)context;
3635 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3637 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3638 acpi_invoke_sleep_eventhandler, &sc->acpi_sleep_button_sx)))
3639 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3640 return_VALUE (ACPI_INTERRUPT_HANDLED);
3644 acpi_event_sleep_button_wake(void *context)
3646 struct acpi_softc *sc = (struct acpi_softc *)context;
3648 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3650 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3651 acpi_invoke_wake_eventhandler, &sc->acpi_sleep_button_sx)))
3652 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3653 return_VALUE (ACPI_INTERRUPT_HANDLED);
3657 * XXX This static buffer is suboptimal. There is no locking so only
3658 * use this for single-threaded callers.
3661 acpi_name(ACPI_HANDLE handle)
3664 static char data[256];
3666 buf.Length = sizeof(data);
3669 if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
3671 return ("(unknown)");
3675 * Debugging/bug-avoidance. Avoid trying to fetch info on various
3676 * parts of the namespace.
3679 acpi_avoid(ACPI_HANDLE handle)
3681 char *cp, *env, *np;
3684 np = acpi_name(handle);
3687 if ((env = kern_getenv("debug.acpi.avoid")) == NULL)
3690 /* Scan the avoid list checking for a match */
3693 while (*cp != 0 && isspace(*cp))
3698 while (cp[len] != 0 && !isspace(cp[len]))
3700 if (!strncmp(cp, np, len)) {
3712 * Debugging/bug-avoidance. Disable ACPI subsystem components.
3715 acpi_disabled(char *subsys)
3720 if ((env = kern_getenv("debug.acpi.disabled")) == NULL)
3722 if (strcmp(env, "all") == 0) {
3727 /* Scan the disable list, checking for a match. */
3730 while (*cp != '\0' && isspace(*cp))
3735 while (cp[len] != '\0' && !isspace(cp[len]))
3737 if (strncmp(cp, subsys, len) == 0) {
3749 acpi_lookup(void *arg, const char *name, device_t *dev)
3757 * Allow any handle name that is specified as an absolute path and
3758 * starts with '\'. We could restrict this to \_SB and friends,
3759 * but see acpi_probe_children() for notes on why we scan the entire
3760 * namespace for devices.
3762 * XXX: The pathname argument to AcpiGetHandle() should be fixed to
3765 if (name[0] != '\\')
3767 if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, __DECONST(char *, name),
3770 *dev = acpi_get_device(handle);
3774 * Control interface.
3776 * We multiplex ioctls for all participating ACPI devices here. Individual
3777 * drivers wanting to be accessible via /dev/acpi should use the
3778 * register/deregister interface to make their handlers visible.
3780 struct acpi_ioctl_hook
3782 TAILQ_ENTRY(acpi_ioctl_hook) link;
3788 static TAILQ_HEAD(,acpi_ioctl_hook) acpi_ioctl_hooks;
3789 static int acpi_ioctl_hooks_initted;
3792 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
3794 struct acpi_ioctl_hook *hp;
3796 if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
3803 if (acpi_ioctl_hooks_initted == 0) {
3804 TAILQ_INIT(&acpi_ioctl_hooks);
3805 acpi_ioctl_hooks_initted = 1;
3807 TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
3814 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
3816 struct acpi_ioctl_hook *hp;
3819 TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
3820 if (hp->cmd == cmd && hp->fn == fn)
3824 TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
3825 free(hp, M_ACPIDEV);
3831 acpiopen(struct cdev *dev, int flag, int fmt, struct thread *td)
3837 acpiclose(struct cdev *dev, int flag, int fmt, struct thread *td)
3843 acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
3845 struct acpi_softc *sc;
3846 struct acpi_ioctl_hook *hp;
3854 * Scan the list of registered ioctls, looking for handlers.
3857 if (acpi_ioctl_hooks_initted)
3858 TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
3864 return (hp->fn(cmd, addr, hp->arg));
3867 * Core ioctls are not permitted for non-writable user.
3868 * Currently, other ioctls just fetch information.
3869 * Not changing system behavior.
3871 if ((flag & FWRITE) == 0)
3874 /* Core system ioctls. */
3876 case ACPIIO_REQSLPSTATE:
3877 state = *(int *)addr;
3878 if (state != ACPI_STATE_S5)
3879 return (acpi_ReqSleepState(sc, state));
3880 device_printf(sc->acpi_dev, "power off via acpi ioctl not supported\n");
3883 case ACPIIO_ACKSLPSTATE:
3884 error = *(int *)addr;
3885 error = acpi_AckSleepState(sc->acpi_clone, error);
3887 case ACPIIO_SETSLPSTATE: /* DEPRECATED */
3888 state = *(int *)addr;
3889 if (state < ACPI_STATE_S0 || state > ACPI_S_STATES_MAX)
3891 if (!acpi_sleep_states[state])
3892 return (EOPNOTSUPP);
3893 if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
3905 acpi_sname2sstate(const char *sname)
3909 if (toupper(sname[0]) == 'S') {
3910 sstate = sname[1] - '0';
3911 if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5 &&
3914 } else if (strcasecmp(sname, "NONE") == 0)
3915 return (ACPI_STATE_UNKNOWN);
3920 acpi_sstate2sname(int sstate)
3922 static const char *snames[] = { "S0", "S1", "S2", "S3", "S4", "S5" };
3924 if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5)
3925 return (snames[sstate]);
3926 else if (sstate == ACPI_STATE_UNKNOWN)
3932 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
3938 sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
3939 for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
3940 if (acpi_sleep_states[state])
3941 sbuf_printf(&sb, "%s ", acpi_sstate2sname(state));
3944 error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
3950 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
3952 char sleep_state[10];
3953 int error, new_state, old_state;
3955 old_state = *(int *)oidp->oid_arg1;
3956 strlcpy(sleep_state, acpi_sstate2sname(old_state), sizeof(sleep_state));
3957 error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
3958 if (error == 0 && req->newptr != NULL) {
3959 new_state = acpi_sname2sstate(sleep_state);
3960 if (new_state < ACPI_STATE_S1)
3962 if (new_state < ACPI_S_STATE_COUNT && !acpi_sleep_states[new_state])
3963 return (EOPNOTSUPP);
3964 if (new_state != old_state)
3965 *(int *)oidp->oid_arg1 = new_state;
3970 /* Inform devctl(4) when we receive a Notify. */
3972 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
3974 char notify_buf[16];
3975 ACPI_BUFFER handle_buf;
3978 if (subsystem == NULL)
3981 handle_buf.Pointer = NULL;
3982 handle_buf.Length = ACPI_ALLOCATE_BUFFER;
3983 status = AcpiNsHandleToPathname(h, &handle_buf, FALSE);
3984 if (ACPI_FAILURE(status))
3986 snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
3987 devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
3988 AcpiOsFree(handle_buf.Pointer);
3993 * Support for parsing debug options from the kernel environment.
3995 * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
3996 * by specifying the names of the bits in the debug.acpi.layer and
3997 * debug.acpi.level environment variables. Bits may be unset by
3998 * prefixing the bit name with !.
4006 static struct debugtag dbg_layer[] = {
4007 {"ACPI_UTILITIES", ACPI_UTILITIES},
4008 {"ACPI_HARDWARE", ACPI_HARDWARE},
4009 {"ACPI_EVENTS", ACPI_EVENTS},
4010 {"ACPI_TABLES", ACPI_TABLES},
4011 {"ACPI_NAMESPACE", ACPI_NAMESPACE},
4012 {"ACPI_PARSER", ACPI_PARSER},
4013 {"ACPI_DISPATCHER", ACPI_DISPATCHER},
4014 {"ACPI_EXECUTER", ACPI_EXECUTER},
4015 {"ACPI_RESOURCES", ACPI_RESOURCES},
4016 {"ACPI_CA_DEBUGGER", ACPI_CA_DEBUGGER},
4017 {"ACPI_OS_SERVICES", ACPI_OS_SERVICES},
4018 {"ACPI_CA_DISASSEMBLER", ACPI_CA_DISASSEMBLER},
4019 {"ACPI_ALL_COMPONENTS", ACPI_ALL_COMPONENTS},
4021 {"ACPI_AC_ADAPTER", ACPI_AC_ADAPTER},
4022 {"ACPI_BATTERY", ACPI_BATTERY},
4023 {"ACPI_BUS", ACPI_BUS},
4024 {"ACPI_BUTTON", ACPI_BUTTON},
4025 {"ACPI_EC", ACPI_EC},
4026 {"ACPI_FAN", ACPI_FAN},
4027 {"ACPI_POWERRES", ACPI_POWERRES},
4028 {"ACPI_PROCESSOR", ACPI_PROCESSOR},
4029 {"ACPI_THERMAL", ACPI_THERMAL},
4030 {"ACPI_TIMER", ACPI_TIMER},
4031 {"ACPI_ALL_DRIVERS", ACPI_ALL_DRIVERS},
4035 static struct debugtag dbg_level[] = {
4036 {"ACPI_LV_INIT", ACPI_LV_INIT},
4037 {"ACPI_LV_DEBUG_OBJECT", ACPI_LV_DEBUG_OBJECT},
4038 {"ACPI_LV_INFO", ACPI_LV_INFO},
4039 {"ACPI_LV_REPAIR", ACPI_LV_REPAIR},
4040 {"ACPI_LV_ALL_EXCEPTIONS", ACPI_LV_ALL_EXCEPTIONS},
4042 /* Trace verbosity level 1 [Standard Trace Level] */
4043 {"ACPI_LV_INIT_NAMES", ACPI_LV_INIT_NAMES},
4044 {"ACPI_LV_PARSE", ACPI_LV_PARSE},
4045 {"ACPI_LV_LOAD", ACPI_LV_LOAD},
4046 {"ACPI_LV_DISPATCH", ACPI_LV_DISPATCH},
4047 {"ACPI_LV_EXEC", ACPI_LV_EXEC},
4048 {"ACPI_LV_NAMES", ACPI_LV_NAMES},
4049 {"ACPI_LV_OPREGION", ACPI_LV_OPREGION},
4050 {"ACPI_LV_BFIELD", ACPI_LV_BFIELD},
4051 {"ACPI_LV_TABLES", ACPI_LV_TABLES},
4052 {"ACPI_LV_VALUES", ACPI_LV_VALUES},
4053 {"ACPI_LV_OBJECTS", ACPI_LV_OBJECTS},
4054 {"ACPI_LV_RESOURCES", ACPI_LV_RESOURCES},
4055 {"ACPI_LV_USER_REQUESTS", ACPI_LV_USER_REQUESTS},
4056 {"ACPI_LV_PACKAGE", ACPI_LV_PACKAGE},
4057 {"ACPI_LV_VERBOSITY1", ACPI_LV_VERBOSITY1},
4059 /* Trace verbosity level 2 [Function tracing and memory allocation] */
4060 {"ACPI_LV_ALLOCATIONS", ACPI_LV_ALLOCATIONS},
4061 {"ACPI_LV_FUNCTIONS", ACPI_LV_FUNCTIONS},
4062 {"ACPI_LV_OPTIMIZATIONS", ACPI_LV_OPTIMIZATIONS},
4063 {"ACPI_LV_VERBOSITY2", ACPI_LV_VERBOSITY2},
4064 {"ACPI_LV_ALL", ACPI_LV_ALL},
4066 /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
4067 {"ACPI_LV_MUTEX", ACPI_LV_MUTEX},
4068 {"ACPI_LV_THREADS", ACPI_LV_THREADS},
4069 {"ACPI_LV_IO", ACPI_LV_IO},
4070 {"ACPI_LV_INTERRUPTS", ACPI_LV_INTERRUPTS},
4071 {"ACPI_LV_VERBOSITY3", ACPI_LV_VERBOSITY3},
4073 /* Exceptionally verbose output -- also used in the global "DebugLevel" */
4074 {"ACPI_LV_AML_DISASSEMBLE", ACPI_LV_AML_DISASSEMBLE},
4075 {"ACPI_LV_VERBOSE_INFO", ACPI_LV_VERBOSE_INFO},
4076 {"ACPI_LV_FULL_TABLES", ACPI_LV_FULL_TABLES},
4077 {"ACPI_LV_EVENTS", ACPI_LV_EVENTS},
4078 {"ACPI_LV_VERBOSE", ACPI_LV_VERBOSE},
4083 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
4095 while (*ep && !isspace(*ep))
4106 for (i = 0; tag[i].name != NULL; i++) {
4107 if (!strncmp(cp, tag[i].name, l)) {
4109 *flag |= tag[i].value;
4111 *flag &= ~tag[i].value;
4119 acpi_set_debugging(void *junk)
4121 char *layer, *level;
4128 layer = kern_getenv("debug.acpi.layer");
4129 level = kern_getenv("debug.acpi.level");
4130 if (layer == NULL && level == NULL)
4133 printf("ACPI set debug");
4134 if (layer != NULL) {
4135 if (strcmp("NONE", layer) != 0)
4136 printf(" layer '%s'", layer);
4137 acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
4140 if (level != NULL) {
4141 if (strcmp("NONE", level) != 0)
4142 printf(" level '%s'", level);
4143 acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
4149 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
4153 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
4156 struct debugtag *tag;
4160 if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
4162 if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
4163 tag = &dbg_layer[0];
4164 dbg = &AcpiDbgLayer;
4166 tag = &dbg_level[0];
4167 dbg = &AcpiDbgLevel;
4170 /* Get old values if this is a get request. */
4171 ACPI_SERIAL_BEGIN(acpi);
4173 sbuf_cpy(&sb, "NONE");
4174 } else if (req->newptr == NULL) {
4175 for (; tag->name != NULL; tag++) {
4176 if ((*dbg & tag->value) == tag->value)
4177 sbuf_printf(&sb, "%s ", tag->name);
4182 strlcpy(temp, sbuf_data(&sb), sizeof(temp));
4185 error = sysctl_handle_string(oidp, temp, sizeof(temp), req);
4187 /* Check for error or no change */
4188 if (error == 0 && req->newptr != NULL) {
4190 kern_setenv((char *)oidp->oid_arg1, temp);
4191 acpi_set_debugging(NULL);
4193 ACPI_SERIAL_END(acpi);
4198 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer,
4199 CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_NEEDGIANT, "debug.acpi.layer", 0,
4200 acpi_debug_sysctl, "A",
4202 SYSCTL_PROC(_debug_acpi, OID_AUTO, level,
4203 CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_NEEDGIANT, "debug.acpi.level", 0,
4204 acpi_debug_sysctl, "A",
4206 #endif /* ACPI_DEBUG */
4209 acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)
4214 old = acpi_debug_objects;
4215 error = sysctl_handle_int(oidp, &acpi_debug_objects, 0, req);
4216 if (error != 0 || req->newptr == NULL)
4218 if (old == acpi_debug_objects || (old && acpi_debug_objects))
4221 ACPI_SERIAL_BEGIN(acpi);
4222 AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
4223 ACPI_SERIAL_END(acpi);
4229 acpi_parse_interfaces(char *str, struct acpi_interface *iface)
4236 while (isspace(*p) || *p == ',')
4241 p = strdup(p, M_TEMP);
4242 for (i = 0; i < len; i++)
4247 if (isspace(p[i]) || p[i] == '\0')
4250 i += strlen(p + i) + 1;
4257 iface->data = malloc(sizeof(*iface->data) * j, M_TEMP, M_WAITOK);
4261 if (isspace(p[i]) || p[i] == '\0')
4264 iface->data[j] = p + i;
4265 i += strlen(p + i) + 1;
4273 acpi_free_interfaces(struct acpi_interface *iface)
4276 free(iface->data[0], M_TEMP);
4277 free(iface->data, M_TEMP);
4281 acpi_reset_interfaces(device_t dev)
4283 struct acpi_interface list;
4287 if (acpi_parse_interfaces(acpi_install_interface, &list) > 0) {
4288 for (i = 0; i < list.num; i++) {
4289 status = AcpiInstallInterface(list.data[i]);
4290 if (ACPI_FAILURE(status))
4292 "failed to install _OSI(\"%s\"): %s\n",
4293 list.data[i], AcpiFormatException(status));
4294 else if (bootverbose)
4295 device_printf(dev, "installed _OSI(\"%s\")\n",
4298 acpi_free_interfaces(&list);
4300 if (acpi_parse_interfaces(acpi_remove_interface, &list) > 0) {
4301 for (i = 0; i < list.num; i++) {
4302 status = AcpiRemoveInterface(list.data[i]);
4303 if (ACPI_FAILURE(status))
4305 "failed to remove _OSI(\"%s\"): %s\n",
4306 list.data[i], AcpiFormatException(status));
4307 else if (bootverbose)
4308 device_printf(dev, "removed _OSI(\"%s\")\n",
4311 acpi_free_interfaces(&list);
4316 acpi_pm_func(u_long cmd, void *arg, ...)
4318 int state, acpi_state;
4320 struct acpi_softc *sc;
4325 case POWER_CMD_SUSPEND:
4326 sc = (struct acpi_softc *)arg;
4333 state = va_arg(ap, int);
4337 case POWER_SLEEP_STATE_STANDBY:
4338 acpi_state = sc->acpi_standby_sx;
4340 case POWER_SLEEP_STATE_SUSPEND:
4341 acpi_state = sc->acpi_suspend_sx;
4343 case POWER_SLEEP_STATE_HIBERNATE:
4344 acpi_state = ACPI_STATE_S4;
4351 if (ACPI_FAILURE(acpi_EnterSleepState(sc, acpi_state)))
4364 acpi_pm_register(void *arg)
4366 if (!cold || resource_disabled("acpi", 0))
4369 power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
4372 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, NULL);