1 /*-
2 * Copyright (c) 2000 Takanori Watanabe <takawata@jp.freebsd.org>
3 * Copyright (c) 2000 Mitsuru IWASAKI <iwasaki@jp.freebsd.org>
4 * Copyright (c) 2000, 2001 Michael Smith
5 * Copyright (c) 2000 BSDi
6 * All rights reserved.
7 * Copyright (c) 2025 The FreeBSD Foundation
8 *
9 * Portions of this software were developed by Aymeric Wibo
10 * <obiwac@freebsd.org> under sponsorship from the FreeBSD Foundation.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34 #include <sys/cdefs.h>
35 #include "opt_acpi.h"
36
37 #include <sys/param.h>
38 #include <sys/eventhandler.h>
39 #include <sys/kernel.h>
40 #include <sys/proc.h>
41 #include <sys/fcntl.h>
42 #include <sys/malloc.h>
43 #include <sys/module.h>
44 #include <sys/bus.h>
45 #include <sys/conf.h>
46 #include <sys/ioccom.h>
47 #include <sys/reboot.h>
48 #include <sys/sysctl.h>
49 #include <sys/ctype.h>
50 #include <sys/linker.h>
51 #include <sys/mount.h>
52 #include <sys/power.h>
53 #include <sys/sbuf.h>
54 #include <sys/sched.h>
55 #include <sys/smp.h>
56 #include <sys/timetc.h>
57 #include <sys/uuid.h>
58
59 #if defined(__i386__) || defined(__amd64__)
60 #include <machine/clock.h>
61 #include <machine/intr_machdep.h>
62 #include <machine/pci_cfgreg.h>
63 #include <x86/cputypes.h>
64 #include <x86/x86_var.h>
65 #endif
66 #include <machine/resource.h>
67 #include <machine/bus.h>
68 #include <sys/rman.h>
69 #include <isa/isavar.h>
70 #include <isa/pnpvar.h>
71
72 #include <contrib/dev/acpica/include/acpi.h>
73 #include <contrib/dev/acpica/include/accommon.h>
74 #include <contrib/dev/acpica/include/acnamesp.h>
75
76 #include <dev/acpica/acpivar.h>
77 #include <dev/acpica/acpiio.h>
78
79 #include <dev/pci/pcivar.h>
80
81 #include <vm/vm_param.h>
82
83 static MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
84
85 /* Hooks for the ACPI CA debugging infrastructure */
86 #define _COMPONENT ACPI_BUS
87 ACPI_MODULE_NAME("ACPI")
88
89 static d_open_t acpiopen;
90 static d_close_t acpiclose;
91 static d_ioctl_t acpiioctl;
92
93 static struct cdevsw acpi_cdevsw = {
94 .d_version = D_VERSION,
95 .d_open = acpiopen,
96 .d_close = acpiclose,
97 .d_ioctl = acpiioctl,
98 .d_name = "acpi",
99 };
100
101 struct acpi_interface {
102 ACPI_STRING *data;
103 int num;
104 };
105
106 struct acpi_wake_prep_context {
107 struct acpi_softc *sc;
108 enum power_stype stype;
109 };
110
111 static char *sysres_ids[] = { "PNP0C01", "PNP0C02", NULL };
112
113 /* Global mutex for locking access to the ACPI subsystem. */
114 struct mtx acpi_mutex;
115 struct callout acpi_sleep_timer;
116
117 /* Bitmap of device quirks. */
118 int acpi_quirks;
119
120 /* Supported sleep states and types. */
121 static bool acpi_supported_stypes[POWER_STYPE_COUNT];
122 static bool acpi_supported_sstates[ACPI_S_STATE_COUNT];
123
124 static void acpi_lookup(void *arg, const char *name, device_t *dev);
125 static int acpi_modevent(struct module *mod, int event, void *junk);
126
127 static device_probe_t acpi_probe;
128 static device_attach_t acpi_attach;
129 static device_suspend_t acpi_suspend;
130 static device_resume_t acpi_resume;
131 static device_shutdown_t acpi_shutdown;
132
133 static bus_add_child_t acpi_add_child;
134 static bus_print_child_t acpi_print_child;
135 static bus_probe_nomatch_t acpi_probe_nomatch;
136 static bus_driver_added_t acpi_driver_added;
137 static bus_child_deleted_t acpi_child_deleted;
138 static bus_read_ivar_t acpi_read_ivar;
139 static bus_write_ivar_t acpi_write_ivar;
140 static bus_get_resource_list_t acpi_get_rlist;
141 static bus_get_rman_t acpi_get_rman;
142 static bus_set_resource_t acpi_set_resource;
143 static bus_alloc_resource_t acpi_alloc_resource;
144 static bus_adjust_resource_t acpi_adjust_resource;
145 static bus_release_resource_t acpi_release_resource;
146 static bus_delete_resource_t acpi_delete_resource;
147 static bus_activate_resource_t acpi_activate_resource;
148 static bus_deactivate_resource_t acpi_deactivate_resource;
149 static bus_map_resource_t acpi_map_resource;
150 static bus_unmap_resource_t acpi_unmap_resource;
151 static bus_child_pnpinfo_t acpi_child_pnpinfo_method;
152 static bus_child_location_t acpi_child_location_method;
153 static bus_hint_device_unit_t acpi_hint_device_unit;
154 static bus_get_property_t acpi_bus_get_prop;
155 static bus_get_device_path_t acpi_get_device_path;
156 static bus_get_domain_t acpi_get_domain_method;
157
158 static acpi_id_probe_t acpi_device_id_probe;
159 static acpi_evaluate_object_t acpi_device_eval_obj;
160 static acpi_get_property_t acpi_device_get_prop;
161 static acpi_scan_children_t acpi_device_scan_children;
162
163 static isa_pnp_probe_t acpi_isa_pnp_probe;
164
165 static void acpi_reserve_resources(device_t dev);
166 static int acpi_sysres_alloc(device_t dev);
167 static uint32_t acpi_isa_get_logicalid(device_t dev);
168 static int acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
169 static ACPI_STATUS acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level,
170 void *context, void **retval);
171 static ACPI_STATUS acpi_find_dsd(struct acpi_device *ad);
172 static void acpi_platform_osc(device_t dev);
173 static void acpi_probe_children(device_t bus);
174 static void acpi_probe_order(ACPI_HANDLE handle, int *order);
175 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
176 void *context, void **status);
177 static void acpi_sleep_enable(void *arg);
178 static ACPI_STATUS acpi_sleep_disable(struct acpi_softc *sc);
179 static ACPI_STATUS acpi_EnterSleepState(struct acpi_softc *sc,
180 enum power_stype stype);
181 static void acpi_shutdown_final(void *arg, int howto);
182 static void acpi_enable_fixed_events(struct acpi_softc *sc);
183 static void acpi_resync_clock(struct acpi_softc *sc);
184 static int acpi_wake_sleep_prep(struct acpi_softc *sc, ACPI_HANDLE handle,
185 enum power_stype stype);
186 static int acpi_wake_run_prep(struct acpi_softc *sc, ACPI_HANDLE handle,
187 enum power_stype stype);
188 static int acpi_wake_prep_walk(struct acpi_softc *sc, enum power_stype stype);
189 static int acpi_wake_sysctl_walk(device_t dev);
190 static int acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS);
191 static int acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
192 static void acpi_system_eventhandler_sleep(void *arg,
193 enum power_stype stype);
194 static void acpi_system_eventhandler_wakeup(void *arg,
195 enum power_stype stype);
196 static int acpi_s4bios_sysctl(SYSCTL_HANDLER_ARGS);
197 static enum power_stype acpi_sstate_to_stype(int sstate);
198 static int acpi_sname_to_sstate(const char *sname);
199 static const char *acpi_sstate_to_sname(int sstate);
200 static int acpi_suspend_state_sysctl(SYSCTL_HANDLER_ARGS);
201 static int acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
202 static int acpi_stype_sysctl(SYSCTL_HANDLER_ARGS);
203 static int acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS);
204 static int acpi_stype_to_sstate(struct acpi_softc *sc, enum power_stype stype);
205 static int acpi_pm_func(u_long cmd, void *arg, enum power_stype stype);
206 static void acpi_enable_pcie(void);
207 static void acpi_reset_interfaces(device_t dev);
208
209 static device_method_t acpi_methods[] = {
210 /* Device interface */
211 DEVMETHOD(device_probe, acpi_probe),
212 DEVMETHOD(device_attach, acpi_attach),
213 DEVMETHOD(device_shutdown, acpi_shutdown),
214 DEVMETHOD(device_detach, bus_generic_detach),
215 DEVMETHOD(device_suspend, acpi_suspend),
216 DEVMETHOD(device_resume, acpi_resume),
217
218 /* Bus interface */
219 DEVMETHOD(bus_add_child, acpi_add_child),
220 DEVMETHOD(bus_print_child, acpi_print_child),
221 DEVMETHOD(bus_probe_nomatch, acpi_probe_nomatch),
222 DEVMETHOD(bus_driver_added, acpi_driver_added),
223 DEVMETHOD(bus_child_deleted, acpi_child_deleted),
224 DEVMETHOD(bus_read_ivar, acpi_read_ivar),
225 DEVMETHOD(bus_write_ivar, acpi_write_ivar),
226 DEVMETHOD(bus_get_resource_list, acpi_get_rlist),
227 DEVMETHOD(bus_get_rman, acpi_get_rman),
228 DEVMETHOD(bus_set_resource, acpi_set_resource),
229 DEVMETHOD(bus_get_resource, bus_generic_rl_get_resource),
230 DEVMETHOD(bus_alloc_resource, acpi_alloc_resource),
231 DEVMETHOD(bus_adjust_resource, acpi_adjust_resource),
232 DEVMETHOD(bus_release_resource, acpi_release_resource),
233 DEVMETHOD(bus_delete_resource, acpi_delete_resource),
234 DEVMETHOD(bus_activate_resource, acpi_activate_resource),
235 DEVMETHOD(bus_deactivate_resource, acpi_deactivate_resource),
236 DEVMETHOD(bus_map_resource, acpi_map_resource),
237 DEVMETHOD(bus_unmap_resource, acpi_unmap_resource),
238 DEVMETHOD(bus_child_pnpinfo, acpi_child_pnpinfo_method),
239 DEVMETHOD(bus_child_location, acpi_child_location_method),
240 DEVMETHOD(bus_setup_intr, bus_generic_setup_intr),
241 DEVMETHOD(bus_teardown_intr, bus_generic_teardown_intr),
242 DEVMETHOD(bus_hint_device_unit, acpi_hint_device_unit),
243 DEVMETHOD(bus_get_cpus, acpi_get_cpus),
244 DEVMETHOD(bus_get_domain, acpi_get_domain_method),
245 DEVMETHOD(bus_get_property, acpi_bus_get_prop),
246 DEVMETHOD(bus_get_device_path, acpi_get_device_path),
247
248 /* ACPI bus */
249 DEVMETHOD(acpi_id_probe, acpi_device_id_probe),
250 DEVMETHOD(acpi_evaluate_object, acpi_device_eval_obj),
251 DEVMETHOD(acpi_get_property, acpi_device_get_prop),
252 DEVMETHOD(acpi_pwr_for_sleep, acpi_device_pwr_for_sleep),
253 DEVMETHOD(acpi_scan_children, acpi_device_scan_children),
254
255 /* ISA emulation */
256 DEVMETHOD(isa_pnp_probe, acpi_isa_pnp_probe),
257
258 DEVMETHOD_END
259 };
260
261 static driver_t acpi_driver = {
262 "acpi",
263 acpi_methods,
264 sizeof(struct acpi_softc),
265 };
266
267 EARLY_DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_modevent, 0,
268 BUS_PASS_BUS + BUS_PASS_ORDER_MIDDLE);
269 MODULE_VERSION(acpi, 1);
270
271 ACPI_SERIAL_DECL(acpi, "ACPI root bus");
272
273 /* Local pools for managing system resources for ACPI child devices. */
274 static struct rman acpi_rman_io, acpi_rman_mem;
275
276 #define ACPI_MINIMUM_AWAKETIME 5
277
278 /* Holds the description of the acpi0 device. */
279 static char acpi_desc[ACPI_OEM_ID_SIZE + ACPI_OEM_TABLE_ID_SIZE + 2];
280
281 SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
282 "ACPI debugging");
283 static char acpi_ca_version[12];
284 SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
285 acpi_ca_version, 0, "Version of Intel ACPI-CA");
286
287 /*
288 * Allow overriding _OSI methods.
289 */
290 static char acpi_install_interface[256];
291 TUNABLE_STR("hw.acpi.install_interface", acpi_install_interface,
292 sizeof(acpi_install_interface));
293 static char acpi_remove_interface[256];
294 TUNABLE_STR("hw.acpi.remove_interface", acpi_remove_interface,
295 sizeof(acpi_remove_interface));
296
297 /*
298 * Automatically apply the Darwin OSI on Apple Mac hardware to obtain
299 * access to full ACPI hardware support on supported platforms.
300 *
301 * This flag automatically overrides any values set by
302 * `hw.acpi.acpi_install_interface` and unset by
303 * `hw.acpi.acpi_remove_interface`.
304 */
305 static int acpi_apple_darwin_osi = 1;
306 TUNABLE_INT("hw.acpi.apple_darwin_osi", &acpi_apple_darwin_osi);
307
308 /* Allow users to dump Debug objects without ACPI debugger. */
309 static int acpi_debug_objects;
310 TUNABLE_INT("debug.acpi.enable_debug_objects", &acpi_debug_objects);
311 SYSCTL_PROC(_debug_acpi, OID_AUTO, enable_debug_objects,
312 CTLFLAG_RW | CTLTYPE_INT | CTLFLAG_MPSAFE, NULL, 0,
313 acpi_debug_objects_sysctl, "I",
314 "Enable Debug objects");
315
316 /* Allow the interpreter to ignore common mistakes in BIOS. */
317 static int acpi_interpreter_slack = 1;
318 TUNABLE_INT("debug.acpi.interpreter_slack", &acpi_interpreter_slack);
319 SYSCTL_INT(_debug_acpi, OID_AUTO, interpreter_slack, CTLFLAG_RDTUN,
320 &acpi_interpreter_slack, 1, "Turn on interpreter slack mode.");
321
322 /* Ignore register widths set by FADT and use default widths instead. */
323 static int acpi_ignore_reg_width = 1;
324 TUNABLE_INT("debug.acpi.default_register_width", &acpi_ignore_reg_width);
325 SYSCTL_INT(_debug_acpi, OID_AUTO, default_register_width, CTLFLAG_RDTUN,
326 &acpi_ignore_reg_width, 1, "Ignore register widths set by FADT");
327
328 /* Allow users to override quirks. */
329 TUNABLE_INT("debug.acpi.quirks", &acpi_quirks);
330
331 int acpi_susp_bounce;
332 SYSCTL_INT(_debug_acpi, OID_AUTO, suspend_bounce, CTLFLAG_RW,
333 &acpi_susp_bounce, 0, "Don't actually suspend, just test devices.");
334
335 #if defined(__amd64__) || defined(__i386__)
336 int acpi_override_isa_irq_polarity;
337 #endif
338
339 /*
340 * ACPI standard UUID for Device Specific Data Package
341 * "Device Properties UUID for _DSD" Rev. 2.0
342 */
343 static const struct uuid acpi_dsd_uuid = {
344 0xdaffd814, 0x6eba, 0x4d8c, 0x8a, 0x91,
345 { 0xbc, 0x9b, 0xbf, 0x4a, 0xa3, 0x01 }
346 };
347
348 /*
349 * ACPI can only be loaded as a module by the loader; activating it after
350 * system bootstrap time is not useful, and can be fatal to the system.
351 * It also cannot be unloaded, since the entire system bus hierarchy hangs
352 * off it.
353 */
354 static int
acpi_modevent(struct module * mod,int event,void * junk)355 acpi_modevent(struct module *mod, int event, void *junk)
356 {
357 switch (event) {
358 case MOD_LOAD:
359 if (!cold) {
360 printf("The ACPI driver cannot be loaded after boot.\n");
361 return (EPERM);
362 }
363 break;
364 case MOD_UNLOAD:
365 if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
366 return (EBUSY);
367 break;
368 default:
369 break;
370 }
371 return (0);
372 }
373
374 /*
375 * Perform early initialization.
376 */
377 ACPI_STATUS
acpi_Startup(void)378 acpi_Startup(void)
379 {
380 static int started = 0;
381 ACPI_STATUS status;
382 int val;
383
384 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
385
386 /* Only run the startup code once. The MADT driver also calls this. */
387 if (started)
388 return_VALUE (AE_OK);
389 started = 1;
390
391 /*
392 * Initialize the ACPICA subsystem.
393 */
394 if (ACPI_FAILURE(status = AcpiInitializeSubsystem())) {
395 printf("ACPI: Could not initialize Subsystem: %s\n",
396 AcpiFormatException(status));
397 return_VALUE (status);
398 }
399
400 /*
401 * Pre-allocate space for RSDT/XSDT and DSDT tables and allow resizing
402 * if more tables exist.
403 */
404 if (ACPI_FAILURE(status = AcpiInitializeTables(NULL, 2, TRUE))) {
405 printf("ACPI: Table initialisation failed: %s\n",
406 AcpiFormatException(status));
407 return_VALUE (status);
408 }
409
410 /* Set up any quirks we have for this system. */
411 if (acpi_quirks == ACPI_Q_OK)
412 acpi_table_quirks(&acpi_quirks);
413
414 /* If the user manually set the disabled hint to 0, force-enable ACPI. */
415 if (resource_int_value("acpi", 0, "disabled", &val) == 0 && val == 0)
416 acpi_quirks &= ~ACPI_Q_BROKEN;
417 if (acpi_quirks & ACPI_Q_BROKEN) {
418 printf("ACPI disabled by blacklist. Contact your BIOS vendor.\n");
419 status = AE_SUPPORT;
420 }
421
422 return_VALUE (status);
423 }
424
425 /*
426 * Detect ACPI and perform early initialisation.
427 */
428 int
acpi_identify(void)429 acpi_identify(void)
430 {
431 ACPI_TABLE_RSDP *rsdp;
432 ACPI_TABLE_HEADER *rsdt;
433 ACPI_PHYSICAL_ADDRESS paddr;
434 struct sbuf sb;
435
436 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
437
438 if (!cold)
439 return (ENXIO);
440
441 /* Check that we haven't been disabled with a hint. */
442 if (resource_disabled("acpi", 0))
443 return (ENXIO);
444
445 /* Check for other PM systems. */
446 if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
447 power_pm_get_type() != POWER_PM_TYPE_ACPI) {
448 printf("ACPI identify failed, other PM system enabled.\n");
449 return (ENXIO);
450 }
451
452 /* Initialize root tables. */
453 if (ACPI_FAILURE(acpi_Startup())) {
454 printf("ACPI: Try disabling either ACPI or apic support.\n");
455 return (ENXIO);
456 }
457
458 if ((paddr = AcpiOsGetRootPointer()) == 0 ||
459 (rsdp = AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_RSDP))) == NULL)
460 return (ENXIO);
461 if (rsdp->Revision > 1 && rsdp->XsdtPhysicalAddress != 0)
462 paddr = (ACPI_PHYSICAL_ADDRESS)rsdp->XsdtPhysicalAddress;
463 else
464 paddr = (ACPI_PHYSICAL_ADDRESS)rsdp->RsdtPhysicalAddress;
465 AcpiOsUnmapMemory(rsdp, sizeof(ACPI_TABLE_RSDP));
466
467 if ((rsdt = AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_HEADER))) == NULL)
468 return (ENXIO);
469 sbuf_new(&sb, acpi_desc, sizeof(acpi_desc), SBUF_FIXEDLEN);
470 sbuf_bcat(&sb, rsdt->OemId, ACPI_OEM_ID_SIZE);
471 sbuf_trim(&sb);
472 sbuf_putc(&sb, ' ');
473 sbuf_bcat(&sb, rsdt->OemTableId, ACPI_OEM_TABLE_ID_SIZE);
474 sbuf_trim(&sb);
475 sbuf_finish(&sb);
476 sbuf_delete(&sb);
477 AcpiOsUnmapMemory(rsdt, sizeof(ACPI_TABLE_HEADER));
478
479 snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%x", ACPI_CA_VERSION);
480
481 return (0);
482 }
483
484 /*
485 * Fetch some descriptive data from ACPI to put in our attach message.
486 */
487 static int
acpi_probe(device_t dev)488 acpi_probe(device_t dev)
489 {
490
491 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
492
493 device_set_desc(dev, acpi_desc);
494
495 return_VALUE (BUS_PROBE_NOWILDCARD);
496 }
497
498 static int
acpi_attach(device_t dev)499 acpi_attach(device_t dev)
500 {
501 struct acpi_softc *sc;
502 ACPI_STATUS status;
503 int error, state;
504 UINT32 flags;
505 char *env;
506 enum power_stype stype;
507
508 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
509
510 sc = device_get_softc(dev);
511 sc->acpi_dev = dev;
512 callout_init(&sc->susp_force_to, 1);
513
514 error = ENXIO;
515
516 /* Initialize resource manager. */
517 acpi_rman_io.rm_type = RMAN_ARRAY;
518 acpi_rman_io.rm_start = 0;
519 acpi_rman_io.rm_end = 0xffff;
520 acpi_rman_io.rm_descr = "ACPI I/O ports";
521 if (rman_init(&acpi_rman_io) != 0)
522 panic("acpi rman_init IO ports failed");
523 acpi_rman_mem.rm_type = RMAN_ARRAY;
524 acpi_rman_mem.rm_descr = "ACPI I/O memory addresses";
525 if (rman_init(&acpi_rman_mem) != 0)
526 panic("acpi rman_init memory failed");
527
528 resource_list_init(&sc->sysres_rl);
529
530 /* Initialise the ACPI mutex */
531 mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
532
533 /*
534 * Set the globals from our tunables. This is needed because ACPI-CA
535 * uses UINT8 for some values and we have no tunable_byte.
536 */
537 AcpiGbl_EnableInterpreterSlack = acpi_interpreter_slack ? TRUE : FALSE;
538 AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
539 AcpiGbl_UseDefaultRegisterWidths = acpi_ignore_reg_width ? TRUE : FALSE;
540
541 #ifndef ACPI_DEBUG
542 /*
543 * Disable all debugging layers and levels.
544 */
545 AcpiDbgLayer = 0;
546 AcpiDbgLevel = 0;
547 #endif
548
549 /* Override OS interfaces if the user requested. */
550 acpi_reset_interfaces(dev);
551
552 /* Load ACPI name space. */
553 status = AcpiLoadTables();
554 if (ACPI_FAILURE(status)) {
555 device_printf(dev, "Could not load Namespace: %s\n",
556 AcpiFormatException(status));
557 goto out;
558 }
559
560 /* Handle MCFG table if present. */
561 acpi_enable_pcie();
562
563 /*
564 * Note that some systems (specifically, those with namespace evaluation
565 * issues that require the avoidance of parts of the namespace) must
566 * avoid running _INI and _STA on everything, as well as dodging the final
567 * object init pass.
568 *
569 * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
570 *
571 * XXX We should arrange for the object init pass after we have attached
572 * all our child devices, but on many systems it works here.
573 */
574 flags = 0;
575 if (testenv("debug.acpi.avoid"))
576 flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
577
578 /* Bring the hardware and basic handlers online. */
579 if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
580 device_printf(dev, "Could not enable ACPI: %s\n",
581 AcpiFormatException(status));
582 goto out;
583 }
584
585 /*
586 * Call the ECDT probe function to provide EC functionality before
587 * the namespace has been evaluated.
588 *
589 * XXX This happens before the sysresource devices have been probed and
590 * attached so its resources come from nexus0. In practice, this isn't
591 * a problem but should be addressed eventually.
592 */
593 acpi_ec_ecdt_probe(dev);
594
595 /* Bring device objects and regions online. */
596 if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
597 device_printf(dev, "Could not initialize ACPI objects: %s\n",
598 AcpiFormatException(status));
599 goto out;
600 }
601
602 #if defined(__amd64__) || defined(__i386__)
603 /*
604 * Enable workaround for incorrect ISA IRQ polarity by default on
605 * systems with Intel CPUs.
606 */
607 if (cpu_vendor_id == CPU_VENDOR_INTEL)
608 acpi_override_isa_irq_polarity = 1;
609 #endif
610
611 /*
612 * Default to 1 second before sleeping to give some machines time to
613 * stabilize.
614 */
615 sc->acpi_sleep_delay = 1;
616 if (bootverbose)
617 sc->acpi_verbose = 1;
618 if ((env = kern_getenv("hw.acpi.verbose")) != NULL) {
619 if (strcmp(env, "0") != 0)
620 sc->acpi_verbose = 1;
621 freeenv(env);
622 }
623
624 /* Only enable reboot by default if the FADT says it is available. */
625 if (AcpiGbl_FADT.Flags & ACPI_FADT_RESET_REGISTER)
626 sc->acpi_handle_reboot = 1;
627
628 /*
629 * Mark whether S4BIOS is available according to the FACS, and if it is,
630 * enable it by default.
631 */
632 if (AcpiGbl_FACS != NULL && AcpiGbl_FACS->Flags & ACPI_FACS_S4_BIOS_PRESENT)
633 sc->acpi_s4bios = sc->acpi_s4bios_supported = true;
634
635 /*
636 * Probe all supported ACPI sleep states. Awake (S0) is always supported,
637 * and suspend-to-idle is always supported on x86 only (at the moment).
638 */
639 acpi_supported_sstates[ACPI_STATE_S0] = true;
640 acpi_supported_stypes[POWER_STYPE_AWAKE] = true;
641 #if defined(__i386__) || defined(__amd64__)
642 acpi_supported_stypes[POWER_STYPE_SUSPEND_TO_IDLE] = true;
643 #endif
644 for (state = ACPI_STATE_S1; state <= ACPI_STATE_S5; state++) {
645 UINT8 TypeA, TypeB;
646
647 if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
648 acpi_supported_sstates[state] = true;
649 acpi_supported_stypes[acpi_sstate_to_stype(state)] = true;
650 }
651 }
652
653 /*
654 * Dispatch the default sleep type to devices. The lid switch is set
655 * to UNKNOWN by default to avoid surprising users.
656 */
657 sc->acpi_power_button_stype = acpi_supported_stypes[POWER_STYPE_POWEROFF] ?
658 POWER_STYPE_POWEROFF : POWER_STYPE_UNKNOWN;
659 sc->acpi_lid_switch_stype = POWER_STYPE_UNKNOWN;
660
661 sc->acpi_standby_sx = ACPI_STATE_UNKNOWN;
662 if (acpi_supported_sstates[ACPI_STATE_S1])
663 sc->acpi_standby_sx = ACPI_STATE_S1;
664 else if (acpi_supported_sstates[ACPI_STATE_S2])
665 sc->acpi_standby_sx = ACPI_STATE_S2;
666
667 /*
668 * Pick the first valid sleep type for the sleep button default. If that
669 * type was hibernate and we support suspend_to_idle , set it to that. The
670 * sleep button prefers fw_suspend instead of suspend_to_idle at the moment
671 * as suspend_to_idle may not yet work reliably on all machines. In the
672 * future, we should set this to suspend_to_idle when
673 * ACPI_FADT_LOW_POWER_S0 is set.
674 */
675 sc->acpi_sleep_button_stype = POWER_STYPE_UNKNOWN;
676 for (stype = POWER_STYPE_STANDBY; stype <= POWER_STYPE_FW_HIBERNATE; stype++)
677 if (acpi_supported_stypes[stype]) {
678 sc->acpi_sleep_button_stype = stype;
679 break;
680 }
681 if (sc->acpi_sleep_button_stype == POWER_STYPE_FW_HIBERNATE ||
682 sc->acpi_sleep_button_stype == POWER_STYPE_UNKNOWN) {
683 if (acpi_supported_stypes[POWER_STYPE_SUSPEND_TO_IDLE])
684 sc->acpi_sleep_button_stype = POWER_STYPE_SUSPEND_TO_IDLE;
685 }
686
687 acpi_enable_fixed_events(sc);
688
689 /*
690 * Scan the namespace and attach/initialise children.
691 */
692
693 /* Register our shutdown handler. */
694 EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
695 SHUTDOWN_PRI_LAST + 150);
696
697 /*
698 * Register our acpi event handlers.
699 * XXX should be configurable eg. via userland policy manager.
700 */
701 EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
702 sc, ACPI_EVENT_PRI_LAST);
703 EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
704 sc, ACPI_EVENT_PRI_LAST);
705
706 /* Flag our initial states. */
707 sc->acpi_enabled = TRUE;
708 sc->acpi_stype = POWER_STYPE_AWAKE;
709 sc->acpi_sleep_disabled = TRUE;
710
711 /* Create the control device */
712 sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0664,
713 "acpi");
714 sc->acpi_dev_t->si_drv1 = sc;
715
716 if ((error = acpi_machdep_init(dev)))
717 goto out;
718
719 /*
720 * Setup our sysctl tree.
721 *
722 * XXX: This doesn't check to make sure that none of these fail.
723 */
724 sysctl_ctx_init(&sc->acpi_sysctl_ctx);
725 sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
726 SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO, device_get_name(dev),
727 CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
728 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
729 OID_AUTO, "supported_sleep_state",
730 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
731 0, 0, acpi_supported_sleep_state_sysctl, "A",
732 "List supported ACPI sleep states.");
733 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
734 OID_AUTO, "power_button_state",
735 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
736 &sc->acpi_power_button_stype, 0, acpi_stype_sysctl, "A",
737 "Power button ACPI sleep state.");
738 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
739 OID_AUTO, "sleep_button_state",
740 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
741 &sc->acpi_sleep_button_stype, 0, acpi_stype_sysctl, "A",
742 "Sleep button ACPI sleep state.");
743 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
744 OID_AUTO, "lid_switch_state",
745 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
746 &sc->acpi_lid_switch_stype, 0, acpi_stype_sysctl, "A",
747 "Lid ACPI sleep state. Set to suspend_to_idle or fw_suspend if you want to suspend "
748 "your laptop when you close the lid.");
749 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
750 OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
751 NULL, 0, acpi_suspend_state_sysctl, "A",
752 "Current ACPI suspend state. This sysctl is deprecated; you probably "
753 "want to use kern.power.suspend instead.");
754 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
755 OID_AUTO, "standby_state",
756 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
757 &sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A",
758 "ACPI Sx state to use when going standby (usually S1 or S2).");
759 SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
760 OID_AUTO, "sleep_delay", CTLFLAG_RW, &sc->acpi_sleep_delay, 0,
761 "sleep delay in seconds");
762 SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
763 OID_AUTO, "s4bios", CTLTYPE_U8 | CTLFLAG_RW | CTLFLAG_MPSAFE,
764 sc, 0, acpi_s4bios_sysctl, "CU",
765 "On hibernate, have the firmware save/restore the machine state (S4BIOS).");
766 SYSCTL_ADD_BOOL(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
767 OID_AUTO, "s4bios_supported", CTLFLAG_RD, &sc->acpi_s4bios_supported, 0,
768 "Whether firmware supports saving/restoring the machine state (S4BIOS).");
769 SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
770 OID_AUTO, "verbose", CTLFLAG_RW, &sc->acpi_verbose, 0, "verbose mode");
771 SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
772 OID_AUTO, "disable_on_reboot", CTLFLAG_RW,
773 &sc->acpi_do_disable, 0, "Disable ACPI when rebooting/halting system");
774 SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
775 OID_AUTO, "handle_reboot", CTLFLAG_RW,
776 &sc->acpi_handle_reboot, 0, "Use ACPI Reset Register to reboot");
777 #if defined(__amd64__) || defined(__i386__)
778 SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
779 OID_AUTO, "override_isa_irq_polarity", CTLFLAG_RDTUN,
780 &acpi_override_isa_irq_polarity, 0,
781 "Force active-hi polarity for edge-triggered ISA IRQs");
782 #endif
783
784 /* Register ACPI again to pass the correct argument of pm_func. */
785 power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc,
786 acpi_supported_stypes);
787
788 acpi_platform_osc(dev);
789
790 if (!acpi_disabled("bus")) {
791 EVENTHANDLER_REGISTER(dev_lookup, acpi_lookup, NULL, 1000);
792 acpi_probe_children(dev);
793 }
794
795 /* Update all GPEs and enable runtime GPEs. */
796 status = AcpiUpdateAllGpes();
797 if (ACPI_FAILURE(status))
798 device_printf(dev, "Could not update all GPEs: %s\n",
799 AcpiFormatException(status));
800
801 /* Allow sleep request after a while. */
802 callout_init_mtx(&acpi_sleep_timer, &acpi_mutex, 0);
803 callout_reset(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME,
804 acpi_sleep_enable, sc);
805
806 error = 0;
807
808 out:
809 return_VALUE (error);
810 }
811
812 static int
acpi_stype_to_sstate(struct acpi_softc * sc,enum power_stype stype)813 acpi_stype_to_sstate(struct acpi_softc *sc, enum power_stype stype)
814 {
815 switch (stype) {
816 case POWER_STYPE_AWAKE:
817 return (ACPI_STATE_S0);
818 case POWER_STYPE_STANDBY:
819 return (sc->acpi_standby_sx);
820 case POWER_STYPE_FW_SUSPEND:
821 return (ACPI_STATE_S3);
822 case POWER_STYPE_FW_HIBERNATE:
823 return (ACPI_STATE_S4);
824 case POWER_STYPE_POWEROFF:
825 return (ACPI_STATE_S5);
826 case POWER_STYPE_SUSPEND_TO_IDLE:
827 case POWER_STYPE_COUNT:
828 case POWER_STYPE_UNKNOWN:
829 return (ACPI_STATE_UNKNOWN);
830 }
831 return (ACPI_STATE_UNKNOWN);
832 }
833
834 /*
835 * XXX It would be nice if we didn't need this function, but we'd need
836 * acpi_EnterSleepState and acpi_ReqSleepState to take in actual ACPI S-states,
837 * which won't be possible at the moment because suspend-to-idle (which is not
838 * an ACPI S-state nor maps to one) will be implemented here.
839 *
840 * In the future, we should make generic a lot of the logic in these functions
841 * to enable suspend-to-idle on non-ACPI builds, and then make
842 * acpi_EnterSleepState and acpi_ReqSleepState truly take in ACPI S-states
843 * again.
844 */
845 static enum power_stype
acpi_sstate_to_stype(int sstate)846 acpi_sstate_to_stype(int sstate)
847 {
848 switch (sstate) {
849 case ACPI_STATE_S0:
850 return (POWER_STYPE_AWAKE);
851 case ACPI_STATE_S1:
852 case ACPI_STATE_S2:
853 return (POWER_STYPE_STANDBY);
854 case ACPI_STATE_S3:
855 return (POWER_STYPE_FW_SUSPEND);
856 case ACPI_STATE_S4:
857 return (POWER_STYPE_FW_HIBERNATE);
858 case ACPI_STATE_S5:
859 return (POWER_STYPE_POWEROFF);
860 }
861 return (POWER_STYPE_UNKNOWN);
862 }
863
864 static void
acpi_set_power_children(device_t dev,int state)865 acpi_set_power_children(device_t dev, int state)
866 {
867 device_t child;
868 device_t *devlist;
869 int dstate, i, numdevs;
870
871 if (device_get_children(dev, &devlist, &numdevs) != 0)
872 return;
873
874 /*
875 * Retrieve and set D-state for the sleep state if _SxD is present.
876 * Skip children who aren't attached since they are handled separately.
877 */
878 for (i = 0; i < numdevs; i++) {
879 child = devlist[i];
880 dstate = state;
881 if (device_is_attached(child) &&
882 acpi_device_pwr_for_sleep(dev, child, &dstate) == 0)
883 acpi_set_powerstate(child, dstate);
884 }
885 free(devlist, M_TEMP);
886 }
887
888 static int
acpi_suspend(device_t dev)889 acpi_suspend(device_t dev)
890 {
891 int error;
892
893 bus_topo_assert();
894
895 error = bus_generic_suspend(dev);
896 if (error == 0)
897 acpi_set_power_children(dev, ACPI_STATE_D3);
898
899 return (error);
900 }
901
902 static int
acpi_resume(device_t dev)903 acpi_resume(device_t dev)
904 {
905
906 bus_topo_assert();
907
908 acpi_set_power_children(dev, ACPI_STATE_D0);
909
910 return (bus_generic_resume(dev));
911 }
912
913 static int
acpi_shutdown(device_t dev)914 acpi_shutdown(device_t dev)
915 {
916 struct acpi_softc *sc = device_get_softc(dev);
917
918 bus_topo_assert();
919
920 /* Allow children to shutdown first. */
921 bus_generic_shutdown(dev);
922
923 /*
924 * Enable any GPEs that are able to power-on the system (i.e., RTC).
925 * Also, disable any that are not valid for this state (most).
926 */
927 acpi_wake_prep_walk(sc, POWER_STYPE_POWEROFF);
928
929 return (0);
930 }
931
932 /*
933 * Handle a new device being added
934 */
935 static device_t
acpi_add_child(device_t bus,u_int order,const char * name,int unit)936 acpi_add_child(device_t bus, u_int order, const char *name, int unit)
937 {
938 struct acpi_device *ad;
939 device_t child;
940
941 if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT | M_ZERO)) == NULL)
942 return (NULL);
943
944 ad->ad_domain = ACPI_DEV_DOMAIN_UNKNOWN;
945 resource_list_init(&ad->ad_rl);
946
947 child = device_add_child_ordered(bus, order, name, unit);
948 if (child != NULL)
949 device_set_ivars(child, ad);
950 else
951 free(ad, M_ACPIDEV);
952 return (child);
953 }
954
955 static int
acpi_print_child(device_t bus,device_t child)956 acpi_print_child(device_t bus, device_t child)
957 {
958 struct acpi_device *adev = device_get_ivars(child);
959 struct resource_list *rl = &adev->ad_rl;
960 int retval = 0;
961
962 retval += bus_print_child_header(bus, child);
963 retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#jx");
964 retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#jx");
965 retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%jd");
966 retval += resource_list_print_type(rl, "drq", SYS_RES_DRQ, "%jd");
967 if (device_get_flags(child))
968 retval += printf(" flags %#x", device_get_flags(child));
969 retval += bus_print_child_domain(bus, child);
970 retval += bus_print_child_footer(bus, child);
971
972 return (retval);
973 }
974
975 /*
976 * If this device is an ACPI child but no one claimed it, attempt
977 * to power it off. We'll power it back up when a driver is added.
978 *
979 * XXX Disabled for now since many necessary devices (like fdc and
980 * ATA) don't claim the devices we created for them but still expect
981 * them to be powered up.
982 */
983 static void
acpi_probe_nomatch(device_t bus,device_t child)984 acpi_probe_nomatch(device_t bus, device_t child)
985 {
986 #ifdef ACPI_ENABLE_POWERDOWN_NODRIVER
987 acpi_set_powerstate(child, ACPI_STATE_D3);
988 #endif
989 }
990
991 /*
992 * If a new driver has a chance to probe a child, first power it up.
993 *
994 * XXX Disabled for now (see acpi_probe_nomatch for details).
995 */
996 static void
acpi_driver_added(device_t dev,driver_t * driver)997 acpi_driver_added(device_t dev, driver_t *driver)
998 {
999 device_t child, *devlist;
1000 int i, numdevs;
1001
1002 DEVICE_IDENTIFY(driver, dev);
1003 if (device_get_children(dev, &devlist, &numdevs))
1004 return;
1005 for (i = 0; i < numdevs; i++) {
1006 child = devlist[i];
1007 if (device_get_state(child) == DS_NOTPRESENT) {
1008 #ifdef ACPI_ENABLE_POWERDOWN_NODRIVER
1009 acpi_set_powerstate(child, ACPI_STATE_D0);
1010 if (device_probe_and_attach(child) != 0)
1011 acpi_set_powerstate(child, ACPI_STATE_D3);
1012 #else
1013 device_probe_and_attach(child);
1014 #endif
1015 }
1016 }
1017 free(devlist, M_TEMP);
1018 }
1019
1020 /* Location hint for devctl(8) */
1021 static int
acpi_child_location_method(device_t cbdev,device_t child,struct sbuf * sb)1022 acpi_child_location_method(device_t cbdev, device_t child, struct sbuf *sb)
1023 {
1024 struct acpi_device *dinfo = device_get_ivars(child);
1025 int pxm;
1026
1027 if (dinfo->ad_handle) {
1028 sbuf_printf(sb, "handle=%s", acpi_name(dinfo->ad_handle));
1029 if (ACPI_SUCCESS(acpi_GetInteger(dinfo->ad_handle, "_PXM", &pxm))) {
1030 sbuf_printf(sb, " _PXM=%d", pxm);
1031 }
1032 }
1033 return (0);
1034 }
1035
1036 /* PnP information for devctl(8) */
1037 int
acpi_pnpinfo(ACPI_HANDLE handle,struct sbuf * sb)1038 acpi_pnpinfo(ACPI_HANDLE handle, struct sbuf *sb)
1039 {
1040 ACPI_DEVICE_INFO *adinfo;
1041
1042 if (ACPI_FAILURE(AcpiGetObjectInfo(handle, &adinfo))) {
1043 sbuf_printf(sb, "unknown");
1044 return (0);
1045 }
1046
1047 sbuf_printf(sb, "_HID=%s _UID=%lu _CID=%s",
1048 (adinfo->Valid & ACPI_VALID_HID) ?
1049 adinfo->HardwareId.String : "none",
1050 (adinfo->Valid & ACPI_VALID_UID) ?
1051 strtoul(adinfo->UniqueId.String, NULL, 10) : 0UL,
1052 ((adinfo->Valid & ACPI_VALID_CID) &&
1053 adinfo->CompatibleIdList.Count > 0) ?
1054 adinfo->CompatibleIdList.Ids[0].String : "none");
1055 AcpiOsFree(adinfo);
1056
1057 return (0);
1058 }
1059
1060 static int
acpi_child_pnpinfo_method(device_t cbdev,device_t child,struct sbuf * sb)1061 acpi_child_pnpinfo_method(device_t cbdev, device_t child, struct sbuf *sb)
1062 {
1063 struct acpi_device *dinfo = device_get_ivars(child);
1064
1065 return (acpi_pnpinfo(dinfo->ad_handle, sb));
1066 }
1067
1068 /*
1069 * Note: the check for ACPI locator may be redundant. However, this routine is
1070 * suitable for both busses whose only locator is ACPI and as a building block
1071 * for busses that have multiple locators to cope with.
1072 */
1073 int
acpi_get_acpi_device_path(device_t bus,device_t child,const char * locator,struct sbuf * sb)1074 acpi_get_acpi_device_path(device_t bus, device_t child, const char *locator, struct sbuf *sb)
1075 {
1076 if (strcmp(locator, BUS_LOCATOR_ACPI) == 0) {
1077 ACPI_HANDLE *handle = acpi_get_handle(child);
1078
1079 if (handle != NULL)
1080 sbuf_printf(sb, "%s", acpi_name(handle));
1081 return (0);
1082 }
1083
1084 return (bus_generic_get_device_path(bus, child, locator, sb));
1085 }
1086
1087 static int
acpi_get_device_path(device_t bus,device_t child,const char * locator,struct sbuf * sb)1088 acpi_get_device_path(device_t bus, device_t child, const char *locator, struct sbuf *sb)
1089 {
1090 struct acpi_device *dinfo = device_get_ivars(child);
1091
1092 if (strcmp(locator, BUS_LOCATOR_ACPI) == 0)
1093 return (acpi_get_acpi_device_path(bus, child, locator, sb));
1094
1095 if (strcmp(locator, BUS_LOCATOR_UEFI) == 0) {
1096 ACPI_DEVICE_INFO *adinfo;
1097 if (!ACPI_FAILURE(AcpiGetObjectInfo(dinfo->ad_handle, &adinfo)) &&
1098 dinfo->ad_handle != 0 && (adinfo->Valid & ACPI_VALID_HID)) {
1099 const char *hid = adinfo->HardwareId.String;
1100 u_long uid = (adinfo->Valid & ACPI_VALID_UID) ?
1101 strtoul(adinfo->UniqueId.String, NULL, 10) : 0UL;
1102 u_long hidval;
1103
1104 /*
1105 * In UEFI Stanard Version 2.6, Section 9.6.1.6 Text
1106 * Device Node Reference, there's an insanely long table
1107 * 98. This implements the relevant bits from that
1108 * table. Newer versions appear to have not required
1109 * anything new. The EDK2 firmware presents both PciRoot
1110 * and PcieRoot as PciRoot. Follow the EDK2 standard.
1111 */
1112 if (strncmp("PNP", hid, 3) != 0)
1113 goto nomatch;
1114 hidval = strtoul(hid + 3, NULL, 16);
1115 switch (hidval) {
1116 case 0x0301:
1117 sbuf_printf(sb, "Keyboard(0x%lx)", uid);
1118 break;
1119 case 0x0401:
1120 sbuf_printf(sb, "ParallelPort(0x%lx)", uid);
1121 break;
1122 case 0x0501:
1123 sbuf_printf(sb, "Serial(0x%lx)", uid);
1124 break;
1125 case 0x0604:
1126 sbuf_printf(sb, "Floppy(0x%lx)", uid);
1127 break;
1128 case 0x0a03:
1129 case 0x0a08:
1130 sbuf_printf(sb, "PciRoot(0x%lx)", uid);
1131 break;
1132 default: /* Everything else gets a generic encode */
1133 nomatch:
1134 sbuf_printf(sb, "Acpi(%s,0x%lx)", hid, uid);
1135 break;
1136 }
1137 }
1138 /* Not handled: AcpiAdr... unsure how to know it's one */
1139 }
1140
1141 /* For the rest, punt to the default handler */
1142 return (bus_generic_get_device_path(bus, child, locator, sb));
1143 }
1144
1145 /*
1146 * Handle device deletion.
1147 */
1148 static void
acpi_child_deleted(device_t dev,device_t child)1149 acpi_child_deleted(device_t dev, device_t child)
1150 {
1151 struct acpi_device *dinfo = device_get_ivars(child);
1152
1153 if (acpi_get_device(dinfo->ad_handle) == child)
1154 AcpiDetachData(dinfo->ad_handle, acpi_fake_objhandler);
1155 free(dinfo, M_ACPIDEV);
1156 }
1157
1158 _Static_assert(ACPI_IVAR_PRIVATE >= ISA_IVAR_LAST,
1159 "ACPI private IVARs overlap with ISA IVARs");
1160
1161 /*
1162 * Handle per-device ivars
1163 */
1164 static int
acpi_read_ivar(device_t dev,device_t child,int index,uintptr_t * result)1165 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
1166 {
1167 struct acpi_device *ad;
1168
1169 if ((ad = device_get_ivars(child)) == NULL) {
1170 device_printf(child, "device has no ivars\n");
1171 return (ENOENT);
1172 }
1173
1174 /* ACPI and ISA compatibility ivars */
1175 switch(index) {
1176 case ACPI_IVAR_HANDLE:
1177 *(ACPI_HANDLE *)result = ad->ad_handle;
1178 break;
1179 case ACPI_IVAR_PRIVATE:
1180 *(void **)result = ad->ad_private;
1181 break;
1182 case ACPI_IVAR_FLAGS:
1183 *(int *)result = ad->ad_flags;
1184 break;
1185 case ACPI_IVAR_DOMAIN:
1186 *(int *)result = ad->ad_domain;
1187 break;
1188 case ISA_IVAR_VENDORID:
1189 case ISA_IVAR_SERIAL:
1190 case ISA_IVAR_COMPATID:
1191 *(int *)result = -1;
1192 break;
1193 case ISA_IVAR_LOGICALID:
1194 *(int *)result = acpi_isa_get_logicalid(child);
1195 break;
1196 case PCI_IVAR_CLASS:
1197 *(uint8_t*)result = (ad->ad_cls_class >> 16) & 0xff;
1198 break;
1199 case PCI_IVAR_SUBCLASS:
1200 *(uint8_t*)result = (ad->ad_cls_class >> 8) & 0xff;
1201 break;
1202 case PCI_IVAR_PROGIF:
1203 *(uint8_t*)result = (ad->ad_cls_class >> 0) & 0xff;
1204 break;
1205 default:
1206 return (ENOENT);
1207 }
1208
1209 return (0);
1210 }
1211
1212 static int
acpi_write_ivar(device_t dev,device_t child,int index,uintptr_t value)1213 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
1214 {
1215 struct acpi_device *ad;
1216
1217 if ((ad = device_get_ivars(child)) == NULL) {
1218 device_printf(child, "device has no ivars\n");
1219 return (ENOENT);
1220 }
1221
1222 switch(index) {
1223 case ACPI_IVAR_HANDLE:
1224 ad->ad_handle = (ACPI_HANDLE)value;
1225 break;
1226 case ACPI_IVAR_PRIVATE:
1227 ad->ad_private = (void *)value;
1228 break;
1229 case ACPI_IVAR_FLAGS:
1230 ad->ad_flags = (int)value;
1231 break;
1232 case ACPI_IVAR_DOMAIN:
1233 ad->ad_domain = (int)value;
1234 break;
1235 default:
1236 panic("bad ivar write request (%d)", index);
1237 return (ENOENT);
1238 }
1239
1240 return (0);
1241 }
1242
1243 /*
1244 * Handle child resource allocation/removal
1245 */
1246 static struct resource_list *
acpi_get_rlist(device_t dev,device_t child)1247 acpi_get_rlist(device_t dev, device_t child)
1248 {
1249 struct acpi_device *ad;
1250
1251 ad = device_get_ivars(child);
1252 return (&ad->ad_rl);
1253 }
1254
1255 static int
acpi_match_resource_hint(device_t dev,int type,long value)1256 acpi_match_resource_hint(device_t dev, int type, long value)
1257 {
1258 struct acpi_device *ad = device_get_ivars(dev);
1259 struct resource_list *rl = &ad->ad_rl;
1260 struct resource_list_entry *rle;
1261
1262 STAILQ_FOREACH(rle, rl, link) {
1263 if (rle->type != type)
1264 continue;
1265 if (rle->start <= value && rle->end >= value)
1266 return (1);
1267 }
1268 return (0);
1269 }
1270
1271 /*
1272 * Does this device match because the resources match?
1273 */
1274 static bool
acpi_hint_device_matches_resources(device_t child,const char * name,int unit)1275 acpi_hint_device_matches_resources(device_t child, const char *name,
1276 int unit)
1277 {
1278 long value;
1279 bool matches;
1280
1281 /*
1282 * Check for matching resources. We must have at least one match.
1283 * Since I/O and memory resources cannot be shared, if we get a
1284 * match on either of those, ignore any mismatches in IRQs or DRQs.
1285 *
1286 * XXX: We may want to revisit this to be more lenient and wire
1287 * as long as it gets one match.
1288 */
1289 matches = false;
1290 if (resource_long_value(name, unit, "port", &value) == 0) {
1291 /*
1292 * Floppy drive controllers are notorious for having a
1293 * wide variety of resources not all of which include the
1294 * first port that is specified by the hint (typically
1295 * 0x3f0) (see the comment above fdc_isa_alloc_resources()
1296 * in fdc_isa.c). However, they do all seem to include
1297 * port + 2 (e.g. 0x3f2) so for a floppy device, look for
1298 * 'value + 2' in the port resources instead of the hint
1299 * value.
1300 */
1301 if (strcmp(name, "fdc") == 0)
1302 value += 2;
1303 if (acpi_match_resource_hint(child, SYS_RES_IOPORT, value))
1304 matches = true;
1305 else
1306 return false;
1307 }
1308 if (resource_long_value(name, unit, "maddr", &value) == 0) {
1309 if (acpi_match_resource_hint(child, SYS_RES_MEMORY, value))
1310 matches = true;
1311 else
1312 return false;
1313 }
1314
1315 /*
1316 * If either the I/O address and/or the memory address matched, then
1317 * assumed this devices matches and that any mismatch in other resources
1318 * will be resolved by siltently ignoring those other resources. Otherwise
1319 * all further resources must match.
1320 */
1321 if (matches) {
1322 return (true);
1323 }
1324 if (resource_long_value(name, unit, "irq", &value) == 0) {
1325 if (acpi_match_resource_hint(child, SYS_RES_IRQ, value))
1326 matches = true;
1327 else
1328 return false;
1329 }
1330 if (resource_long_value(name, unit, "drq", &value) == 0) {
1331 if (acpi_match_resource_hint(child, SYS_RES_DRQ, value))
1332 matches = true;
1333 else
1334 return false;
1335 }
1336 return matches;
1337 }
1338
1339
1340 /*
1341 * Wire device unit numbers based on resource matches in hints.
1342 */
1343 static void
acpi_hint_device_unit(device_t acdev,device_t child,const char * name,int * unitp)1344 acpi_hint_device_unit(device_t acdev, device_t child, const char *name,
1345 int *unitp)
1346 {
1347 device_location_cache_t *cache;
1348 const char *s;
1349 int line, unit;
1350 bool matches;
1351
1352 /*
1353 * Iterate over all the hints for the devices with the specified
1354 * name to see if one's resources are a subset of this device.
1355 */
1356 line = 0;
1357 cache = dev_wired_cache_init();
1358 while (resource_find_dev(&line, name, &unit, "at", NULL) == 0) {
1359 /* Must have an "at" for acpi or isa. */
1360 resource_string_value(name, unit, "at", &s);
1361 matches = false;
1362 if (strcmp(s, "acpi0") == 0 || strcmp(s, "acpi") == 0 ||
1363 strcmp(s, "isa0") == 0 || strcmp(s, "isa") == 0)
1364 matches = acpi_hint_device_matches_resources(child, name, unit);
1365 else
1366 matches = dev_wired_cache_match(cache, child, s);
1367
1368 if (matches) {
1369 /* We have a winner! */
1370 *unitp = unit;
1371 break;
1372 }
1373 }
1374 dev_wired_cache_fini(cache);
1375 }
1376
1377 /*
1378 * Fetch the NUMA domain for a device by mapping the value returned by
1379 * _PXM to a NUMA domain. If the device does not have a _PXM method,
1380 * -2 is returned. If any other error occurs, -1 is returned.
1381 */
1382 int
acpi_pxm_parse(device_t dev)1383 acpi_pxm_parse(device_t dev)
1384 {
1385 #ifdef NUMA
1386 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1387 ACPI_HANDLE handle;
1388 ACPI_STATUS status;
1389 int pxm;
1390
1391 handle = acpi_get_handle(dev);
1392 if (handle == NULL)
1393 return (-2);
1394 status = acpi_GetInteger(handle, "_PXM", &pxm);
1395 if (ACPI_SUCCESS(status))
1396 return (acpi_map_pxm_to_vm_domainid(pxm));
1397 if (status == AE_NOT_FOUND)
1398 return (-2);
1399 #endif
1400 #endif
1401 return (-1);
1402 }
1403
1404 int
acpi_get_cpus(device_t dev,device_t child,enum cpu_sets op,size_t setsize,cpuset_t * cpuset)1405 acpi_get_cpus(device_t dev, device_t child, enum cpu_sets op, size_t setsize,
1406 cpuset_t *cpuset)
1407 {
1408 int d, error;
1409
1410 d = acpi_pxm_parse(child);
1411 if (d < 0)
1412 return (bus_generic_get_cpus(dev, child, op, setsize, cpuset));
1413
1414 switch (op) {
1415 case LOCAL_CPUS:
1416 if (setsize != sizeof(cpuset_t))
1417 return (EINVAL);
1418 *cpuset = cpuset_domain[d];
1419 return (0);
1420 case INTR_CPUS:
1421 error = bus_generic_get_cpus(dev, child, op, setsize, cpuset);
1422 if (error != 0)
1423 return (error);
1424 if (setsize != sizeof(cpuset_t))
1425 return (EINVAL);
1426 CPU_AND(cpuset, cpuset, &cpuset_domain[d]);
1427 return (0);
1428 default:
1429 return (bus_generic_get_cpus(dev, child, op, setsize, cpuset));
1430 }
1431 }
1432
1433 static int
acpi_get_domain_method(device_t dev,device_t child,int * domain)1434 acpi_get_domain_method(device_t dev, device_t child, int *domain)
1435 {
1436 int error;
1437
1438 error = acpi_read_ivar(dev, child, ACPI_IVAR_DOMAIN,
1439 (uintptr_t *)domain);
1440 if (error == 0 && *domain != ACPI_DEV_DOMAIN_UNKNOWN)
1441 return (0);
1442 return (ENOENT);
1443 }
1444
1445 static struct rman *
acpi_get_rman(device_t bus,int type,u_int flags)1446 acpi_get_rman(device_t bus, int type, u_int flags)
1447 {
1448 /* Only memory and IO resources are managed. */
1449 switch (type) {
1450 case SYS_RES_IOPORT:
1451 return (&acpi_rman_io);
1452 case SYS_RES_MEMORY:
1453 return (&acpi_rman_mem);
1454 default:
1455 return (NULL);
1456 }
1457 }
1458
1459 /*
1460 * Pre-allocate/manage all memory and IO resources. Since rman can't handle
1461 * duplicates, we merge any in the sysresource attach routine.
1462 */
1463 static int
acpi_sysres_alloc(device_t dev)1464 acpi_sysres_alloc(device_t dev)
1465 {
1466 struct acpi_softc *sc = device_get_softc(dev);
1467 struct resource *res;
1468 struct resource_list_entry *rle;
1469 struct rman *rm;
1470 device_t *children;
1471 int child_count, i;
1472
1473 /*
1474 * Probe/attach any sysresource devices. This would be unnecessary if we
1475 * had multi-pass probe/attach.
1476 */
1477 if (device_get_children(dev, &children, &child_count) != 0)
1478 return (ENXIO);
1479 for (i = 0; i < child_count; i++) {
1480 if (ACPI_ID_PROBE(dev, children[i], sysres_ids, NULL) <= 0)
1481 device_probe_and_attach(children[i]);
1482 }
1483 free(children, M_TEMP);
1484
1485 STAILQ_FOREACH(rle, &sc->sysres_rl, link) {
1486 if (rle->res != NULL) {
1487 device_printf(dev, "duplicate resource for %jx\n", rle->start);
1488 continue;
1489 }
1490
1491 /* Only memory and IO resources are valid here. */
1492 rm = acpi_get_rman(dev, rle->type, 0);
1493 if (rm == NULL)
1494 continue;
1495
1496 /* Pre-allocate resource and add to our rman pool. */
1497 res = bus_alloc_resource(dev, rle->type,
1498 &rle->rid, rle->start, rle->start + rle->count - 1, rle->count,
1499 RF_ACTIVE | RF_UNMAPPED);
1500 if (res != NULL) {
1501 rman_manage_region(rm, rman_get_start(res), rman_get_end(res));
1502 rle->res = res;
1503 } else if (bootverbose)
1504 device_printf(dev, "reservation of %jx, %jx (%d) failed\n",
1505 rle->start, rle->count, rle->type);
1506 }
1507 return (0);
1508 }
1509
1510 /*
1511 * Reserve declared resources for active devices found during the
1512 * namespace scan once the boot-time attach of devices has completed.
1513 *
1514 * Ideally reserving firmware-assigned resources would work in a
1515 * depth-first traversal of the device namespace, but this is
1516 * complicated. In particular, not all resources are enumerated by
1517 * ACPI (e.g. PCI bridges and devices enumerate their resources via
1518 * other means). Some systems also enumerate devices via ACPI behind
1519 * PCI bridges but without a matching a PCI device_t enumerated via
1520 * PCI bus scanning, the device_t's end up as direct children of
1521 * acpi0. Doing this scan late is not ideal, but works for now.
1522 */
1523 static void
acpi_reserve_resources(device_t dev)1524 acpi_reserve_resources(device_t dev)
1525 {
1526 struct resource_list_entry *rle;
1527 struct resource_list *rl;
1528 struct acpi_device *ad;
1529 device_t *children;
1530 int child_count, i;
1531
1532 if (device_get_children(dev, &children, &child_count) != 0)
1533 return;
1534 for (i = 0; i < child_count; i++) {
1535 ad = device_get_ivars(children[i]);
1536 rl = &ad->ad_rl;
1537
1538 /* Don't reserve system resources. */
1539 if (ACPI_ID_PROBE(dev, children[i], sysres_ids, NULL) <= 0)
1540 continue;
1541
1542 STAILQ_FOREACH(rle, rl, link) {
1543 /*
1544 * Don't reserve IRQ resources. There are many sticky things
1545 * to get right otherwise (e.g. IRQs for psm, atkbd, and HPET
1546 * when using legacy routing).
1547 */
1548 if (rle->type == SYS_RES_IRQ)
1549 continue;
1550
1551 /*
1552 * Don't reserve the resource if it is already allocated.
1553 * The acpi_ec(4) driver can allocate its resources early
1554 * if ECDT is present.
1555 */
1556 if (rle->res != NULL)
1557 continue;
1558
1559 /*
1560 * Try to reserve the resource from our parent. If this
1561 * fails because the resource is a system resource, just
1562 * let it be. The resource range is already reserved so
1563 * that other devices will not use it. If the driver
1564 * needs to allocate the resource, then
1565 * acpi_alloc_resource() will sub-alloc from the system
1566 * resource.
1567 */
1568 resource_list_reserve(rl, dev, children[i], rle->type, rle->rid,
1569 rle->start, rle->end, rle->count, 0);
1570 }
1571 }
1572 free(children, M_TEMP);
1573 }
1574
1575 static int
acpi_set_resource(device_t dev,device_t child,int type,int rid,rman_res_t start,rman_res_t count)1576 acpi_set_resource(device_t dev, device_t child, int type, int rid,
1577 rman_res_t start, rman_res_t count)
1578 {
1579 struct acpi_device *ad = device_get_ivars(child);
1580 struct resource_list *rl = &ad->ad_rl;
1581 rman_res_t end;
1582
1583 #ifdef INTRNG
1584 /* map with default for now */
1585 if (type == SYS_RES_IRQ)
1586 start = (rman_res_t)acpi_map_intr(child, (u_int)start,
1587 acpi_get_handle(child));
1588 #endif
1589
1590 /* If the resource is already allocated, fail. */
1591 if (resource_list_busy(rl, type, rid))
1592 return (EBUSY);
1593
1594 /* If the resource is already reserved, release it. */
1595 if (resource_list_reserved(rl, type, rid))
1596 resource_list_unreserve(rl, dev, child, type, rid);
1597
1598 /* Add the resource. */
1599 end = (start + count - 1);
1600 resource_list_add(rl, type, rid, start, end, count);
1601 return (0);
1602 }
1603
1604 static struct resource *
acpi_alloc_resource(device_t bus,device_t child,int type,int rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)1605 acpi_alloc_resource(device_t bus, device_t child, int type, int rid,
1606 rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1607 {
1608 #ifndef INTRNG
1609 ACPI_RESOURCE ares;
1610 #endif
1611 struct acpi_device *ad;
1612 struct resource_list_entry *rle;
1613 struct resource_list *rl;
1614 struct resource *res;
1615 int isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
1616
1617 /*
1618 * First attempt at allocating the resource. For direct children,
1619 * use resource_list_alloc() to handle reserved resources. For
1620 * other devices, pass the request up to our parent.
1621 */
1622 if (bus == device_get_parent(child)) {
1623 ad = device_get_ivars(child);
1624 rl = &ad->ad_rl;
1625
1626 /*
1627 * Simulate the behavior of the ISA bus for direct children
1628 * devices. That is, if a non-default range is specified for
1629 * a resource that doesn't exist, use bus_set_resource() to
1630 * add the resource before allocating it. Note that these
1631 * resources will not be reserved.
1632 */
1633 if (!isdefault && resource_list_find(rl, type, rid) == NULL)
1634 resource_list_add(rl, type, rid, start, end, count);
1635 res = resource_list_alloc(rl, bus, child, type, rid, start, end, count,
1636 flags);
1637 #ifndef INTRNG
1638 if (res != NULL && type == SYS_RES_IRQ) {
1639 /*
1640 * Since bus_config_intr() takes immediate effect, we cannot
1641 * configure the interrupt associated with a device when we
1642 * parse the resources but have to defer it until a driver
1643 * actually allocates the interrupt via bus_alloc_resource().
1644 *
1645 * XXX: Should we handle the lookup failing?
1646 */
1647 if (ACPI_SUCCESS(acpi_lookup_irq_resource(child, rid, res, &ares)))
1648 acpi_config_intr(child, &ares);
1649 }
1650 #endif
1651
1652 /*
1653 * If this is an allocation of the "default" range for a given
1654 * RID, fetch the exact bounds for this resource from the
1655 * resource list entry to try to allocate the range from the
1656 * system resource regions.
1657 */
1658 if (res == NULL && isdefault) {
1659 rle = resource_list_find(rl, type, rid);
1660 if (rle != NULL) {
1661 start = rle->start;
1662 end = rle->end;
1663 count = rle->count;
1664 }
1665 }
1666 } else
1667 res = bus_generic_alloc_resource(bus, child, type, rid,
1668 start, end, count, flags);
1669
1670 /*
1671 * If the first attempt failed and this is an allocation of a
1672 * specific range, try to satisfy the request via a suballocation
1673 * from our system resource regions.
1674 */
1675 if (res == NULL && start + count - 1 == end)
1676 res = bus_generic_rman_alloc_resource(bus, child, type, rid, start, end,
1677 count, flags);
1678 return (res);
1679 }
1680
1681 static bool
acpi_is_resource_managed(device_t bus,struct resource * r)1682 acpi_is_resource_managed(device_t bus, struct resource *r)
1683 {
1684 struct rman *rm;
1685
1686 rm = acpi_get_rman(bus, rman_get_type(r), rman_get_flags(r));
1687 if (rm == NULL)
1688 return (false);
1689 return (rman_is_region_manager(r, rm));
1690 }
1691
1692 static struct resource *
acpi_managed_resource(device_t bus,struct resource * r)1693 acpi_managed_resource(device_t bus, struct resource *r)
1694 {
1695 struct acpi_softc *sc = device_get_softc(bus);
1696 struct resource_list_entry *rle;
1697
1698 KASSERT(acpi_is_resource_managed(bus, r),
1699 ("resource %p is not suballocated", r));
1700
1701 STAILQ_FOREACH(rle, &sc->sysres_rl, link) {
1702 if (rle->type != rman_get_type(r) || rle->res == NULL)
1703 continue;
1704 if (rman_get_start(r) >= rman_get_start(rle->res) &&
1705 rman_get_end(r) <= rman_get_end(rle->res))
1706 return (rle->res);
1707 }
1708 return (NULL);
1709 }
1710
1711 static int
acpi_adjust_resource(device_t bus,device_t child,struct resource * r,rman_res_t start,rman_res_t end)1712 acpi_adjust_resource(device_t bus, device_t child, struct resource *r,
1713 rman_res_t start, rman_res_t end)
1714 {
1715
1716 if (acpi_is_resource_managed(bus, r))
1717 return (rman_adjust_resource(r, start, end));
1718 return (bus_generic_adjust_resource(bus, child, r, start, end));
1719 }
1720
1721 static int
acpi_release_resource(device_t bus,device_t child,struct resource * r)1722 acpi_release_resource(device_t bus, device_t child, struct resource *r)
1723 {
1724 /*
1725 * If this resource belongs to one of our internal managers,
1726 * deactivate it and release it to the local pool.
1727 */
1728 if (acpi_is_resource_managed(bus, r))
1729 return (bus_generic_rman_release_resource(bus, child, r));
1730
1731 return (bus_generic_rl_release_resource(bus, child, r));
1732 }
1733
1734 static void
acpi_delete_resource(device_t bus,device_t child,int type,int rid)1735 acpi_delete_resource(device_t bus, device_t child, int type, int rid)
1736 {
1737 struct resource_list *rl;
1738
1739 rl = acpi_get_rlist(bus, child);
1740 if (resource_list_busy(rl, type, rid)) {
1741 device_printf(bus, "delete_resource: Resource still owned by child"
1742 " (type=%d, rid=%d)\n", type, rid);
1743 return;
1744 }
1745 if (resource_list_reserved(rl, type, rid))
1746 resource_list_unreserve(rl, bus, child, type, rid);
1747 resource_list_delete(rl, type, rid);
1748 }
1749
1750 static int
acpi_activate_resource(device_t bus,device_t child,struct resource * r)1751 acpi_activate_resource(device_t bus, device_t child, struct resource *r)
1752 {
1753 if (acpi_is_resource_managed(bus, r))
1754 return (bus_generic_rman_activate_resource(bus, child, r));
1755 return (bus_generic_activate_resource(bus, child, r));
1756 }
1757
1758 static int
acpi_deactivate_resource(device_t bus,device_t child,struct resource * r)1759 acpi_deactivate_resource(device_t bus, device_t child, struct resource *r)
1760 {
1761 if (acpi_is_resource_managed(bus, r))
1762 return (bus_generic_rman_deactivate_resource(bus, child, r));
1763 return (bus_generic_deactivate_resource(bus, child, r));
1764 }
1765
1766 static int
acpi_map_resource(device_t bus,device_t child,struct resource * r,struct resource_map_request * argsp,struct resource_map * map)1767 acpi_map_resource(device_t bus, device_t child, struct resource *r,
1768 struct resource_map_request *argsp, struct resource_map *map)
1769 {
1770 struct resource_map_request args;
1771 struct resource *sysres;
1772 rman_res_t length, start;
1773 int error;
1774
1775 if (!acpi_is_resource_managed(bus, r))
1776 return (bus_generic_map_resource(bus, child, r, argsp, map));
1777
1778 /* Resources must be active to be mapped. */
1779 if (!(rman_get_flags(r) & RF_ACTIVE))
1780 return (ENXIO);
1781
1782 resource_init_map_request(&args);
1783 error = resource_validate_map_request(r, argsp, &args, &start, &length);
1784 if (error)
1785 return (error);
1786
1787 sysres = acpi_managed_resource(bus, r);
1788 if (sysres == NULL)
1789 return (ENOENT);
1790
1791 args.offset = start - rman_get_start(sysres);
1792 args.length = length;
1793 return (bus_map_resource(bus, sysres, &args, map));
1794 }
1795
1796 static int
acpi_unmap_resource(device_t bus,device_t child,struct resource * r,struct resource_map * map)1797 acpi_unmap_resource(device_t bus, device_t child, struct resource *r,
1798 struct resource_map *map)
1799 {
1800 struct resource *sysres;
1801
1802 if (!acpi_is_resource_managed(bus, r))
1803 return (bus_generic_unmap_resource(bus, child, r, map));
1804
1805 sysres = acpi_managed_resource(bus, r);
1806 if (sysres == NULL)
1807 return (ENOENT);
1808 return (bus_unmap_resource(bus, sysres, map));
1809 }
1810
1811 /* Allocate an IO port or memory resource, given its GAS. */
1812 int
acpi_bus_alloc_gas(device_t dev,int * type,int rid,ACPI_GENERIC_ADDRESS * gas,struct resource ** res,u_int flags)1813 acpi_bus_alloc_gas(device_t dev, int *type, int rid, ACPI_GENERIC_ADDRESS *gas,
1814 struct resource **res, u_int flags)
1815 {
1816 int error, res_type;
1817
1818 error = ENOMEM;
1819 if (type == NULL || gas == NULL || res == NULL)
1820 return (EINVAL);
1821
1822 /* We only support memory and IO spaces. */
1823 switch (gas->SpaceId) {
1824 case ACPI_ADR_SPACE_SYSTEM_MEMORY:
1825 res_type = SYS_RES_MEMORY;
1826 break;
1827 case ACPI_ADR_SPACE_SYSTEM_IO:
1828 res_type = SYS_RES_IOPORT;
1829 break;
1830 default:
1831 return (EOPNOTSUPP);
1832 }
1833
1834 /*
1835 * If the register width is less than 8, assume the BIOS author means
1836 * it is a bit field and just allocate a byte.
1837 */
1838 if (gas->BitWidth && gas->BitWidth < 8)
1839 gas->BitWidth = 8;
1840
1841 /* Validate the address after we're sure we support the space. */
1842 if (gas->Address == 0 || gas->BitWidth == 0)
1843 return (EINVAL);
1844
1845 bus_set_resource(dev, res_type, rid, gas->Address,
1846 gas->BitWidth / 8);
1847 *res = bus_alloc_resource_any(dev, res_type, rid, RF_ACTIVE | flags);
1848 if (*res != NULL) {
1849 *type = res_type;
1850 error = 0;
1851 } else
1852 bus_delete_resource(dev, res_type, rid);
1853
1854 return (error);
1855 }
1856
1857 /* Probe _HID and _CID for compatible ISA PNP ids. */
1858 static uint32_t
acpi_isa_get_logicalid(device_t dev)1859 acpi_isa_get_logicalid(device_t dev)
1860 {
1861 ACPI_DEVICE_INFO *devinfo;
1862 ACPI_HANDLE h;
1863 uint32_t pnpid;
1864
1865 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1866
1867 /* Fetch and validate the HID. */
1868 if ((h = acpi_get_handle(dev)) == NULL ||
1869 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1870 return_VALUE (0);
1871
1872 pnpid = (devinfo->Valid & ACPI_VALID_HID) != 0 &&
1873 devinfo->HardwareId.Length >= ACPI_EISAID_STRING_SIZE ?
1874 PNP_EISAID(devinfo->HardwareId.String) : 0;
1875 AcpiOsFree(devinfo);
1876
1877 return_VALUE (pnpid);
1878 }
1879
1880 static int
acpi_isa_get_compatid(device_t dev,uint32_t * cids,int count)1881 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
1882 {
1883 ACPI_DEVICE_INFO *devinfo;
1884 ACPI_PNP_DEVICE_ID *ids;
1885 ACPI_HANDLE h;
1886 uint32_t *pnpid;
1887 int i, valid;
1888
1889 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1890
1891 pnpid = cids;
1892
1893 /* Fetch and validate the CID */
1894 if ((h = acpi_get_handle(dev)) == NULL ||
1895 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1896 return_VALUE (0);
1897
1898 if ((devinfo->Valid & ACPI_VALID_CID) == 0) {
1899 AcpiOsFree(devinfo);
1900 return_VALUE (0);
1901 }
1902
1903 if (devinfo->CompatibleIdList.Count < count)
1904 count = devinfo->CompatibleIdList.Count;
1905 ids = devinfo->CompatibleIdList.Ids;
1906 for (i = 0, valid = 0; i < count; i++)
1907 if (ids[i].Length >= ACPI_EISAID_STRING_SIZE &&
1908 strncmp(ids[i].String, "PNP", 3) == 0) {
1909 *pnpid++ = PNP_EISAID(ids[i].String);
1910 valid++;
1911 }
1912 AcpiOsFree(devinfo);
1913
1914 return_VALUE (valid);
1915 }
1916
1917 static int
acpi_device_id_probe(device_t bus,device_t dev,char ** ids,char ** match)1918 acpi_device_id_probe(device_t bus, device_t dev, char **ids, char **match)
1919 {
1920 ACPI_HANDLE h;
1921 ACPI_OBJECT_TYPE t;
1922 int rv;
1923 int i;
1924
1925 h = acpi_get_handle(dev);
1926 if (ids == NULL || h == NULL)
1927 return (ENXIO);
1928 t = acpi_get_type(dev);
1929 if (t != ACPI_TYPE_DEVICE && t != ACPI_TYPE_PROCESSOR)
1930 return (ENXIO);
1931
1932 /* Try to match one of the array of IDs with a HID or CID. */
1933 for (i = 0; ids[i] != NULL; i++) {
1934 rv = acpi_MatchHid(h, ids[i]);
1935 if (rv == ACPI_MATCHHID_NOMATCH)
1936 continue;
1937
1938 if (match != NULL) {
1939 *match = ids[i];
1940 }
1941 return ((rv == ACPI_MATCHHID_HID)?
1942 BUS_PROBE_DEFAULT : BUS_PROBE_LOW_PRIORITY);
1943 }
1944 return (ENXIO);
1945 }
1946
1947 static ACPI_STATUS
acpi_device_eval_obj(device_t bus,device_t dev,ACPI_STRING pathname,ACPI_OBJECT_LIST * parameters,ACPI_BUFFER * ret)1948 acpi_device_eval_obj(device_t bus, device_t dev, ACPI_STRING pathname,
1949 ACPI_OBJECT_LIST *parameters, ACPI_BUFFER *ret)
1950 {
1951 ACPI_HANDLE h;
1952
1953 if (dev == NULL)
1954 h = ACPI_ROOT_OBJECT;
1955 else if ((h = acpi_get_handle(dev)) == NULL)
1956 return (AE_BAD_PARAMETER);
1957 return (AcpiEvaluateObject(h, pathname, parameters, ret));
1958 }
1959
1960 static ACPI_STATUS
acpi_device_get_prop(device_t bus,device_t dev,ACPI_STRING propname,const ACPI_OBJECT ** value)1961 acpi_device_get_prop(device_t bus, device_t dev, ACPI_STRING propname,
1962 const ACPI_OBJECT **value)
1963 {
1964 const ACPI_OBJECT *pkg, *name, *val;
1965 struct acpi_device *ad;
1966 ACPI_STATUS status;
1967 int i;
1968
1969 ad = device_get_ivars(dev);
1970
1971 if (ad == NULL || propname == NULL)
1972 return (AE_BAD_PARAMETER);
1973 if (ad->dsd_pkg == NULL) {
1974 if (ad->dsd.Pointer == NULL) {
1975 status = acpi_find_dsd(ad);
1976 if (ACPI_FAILURE(status))
1977 return (status);
1978 } else {
1979 return (AE_NOT_FOUND);
1980 }
1981 }
1982
1983 for (i = 0; i < ad->dsd_pkg->Package.Count; i ++) {
1984 pkg = &ad->dsd_pkg->Package.Elements[i];
1985 if (pkg->Type != ACPI_TYPE_PACKAGE || pkg->Package.Count != 2)
1986 continue;
1987
1988 name = &pkg->Package.Elements[0];
1989 val = &pkg->Package.Elements[1];
1990 if (name->Type != ACPI_TYPE_STRING)
1991 continue;
1992 if (strncmp(propname, name->String.Pointer, name->String.Length) == 0) {
1993 if (value != NULL)
1994 *value = val;
1995
1996 return (AE_OK);
1997 }
1998 }
1999
2000 return (AE_NOT_FOUND);
2001 }
2002
2003 static ACPI_STATUS
acpi_find_dsd(struct acpi_device * ad)2004 acpi_find_dsd(struct acpi_device *ad)
2005 {
2006 const ACPI_OBJECT *dsd, *guid, *pkg;
2007 ACPI_STATUS status;
2008
2009 ad->dsd.Length = ACPI_ALLOCATE_BUFFER;
2010 ad->dsd.Pointer = NULL;
2011 ad->dsd_pkg = NULL;
2012
2013 status = AcpiEvaluateObject(ad->ad_handle, "_DSD", NULL, &ad->dsd);
2014 if (ACPI_FAILURE(status))
2015 return (status);
2016
2017 dsd = ad->dsd.Pointer;
2018 guid = &dsd->Package.Elements[0];
2019 pkg = &dsd->Package.Elements[1];
2020
2021 if (guid->Type != ACPI_TYPE_BUFFER || pkg->Type != ACPI_TYPE_PACKAGE ||
2022 guid->Buffer.Length != sizeof(acpi_dsd_uuid))
2023 return (AE_NOT_FOUND);
2024 if (memcmp(guid->Buffer.Pointer, &acpi_dsd_uuid,
2025 sizeof(acpi_dsd_uuid)) == 0) {
2026
2027 ad->dsd_pkg = pkg;
2028 return (AE_OK);
2029 }
2030
2031 return (AE_NOT_FOUND);
2032 }
2033
2034 static ssize_t
acpi_bus_get_prop_handle(const ACPI_OBJECT * hobj,void * propvalue,size_t size)2035 acpi_bus_get_prop_handle(const ACPI_OBJECT *hobj, void *propvalue, size_t size)
2036 {
2037 ACPI_OBJECT *pobj;
2038 ACPI_HANDLE h;
2039
2040 if (hobj->Type != ACPI_TYPE_PACKAGE)
2041 goto err;
2042 if (hobj->Package.Count != 1)
2043 goto err;
2044
2045 pobj = &hobj->Package.Elements[0];
2046 if (pobj == NULL)
2047 goto err;
2048 if (pobj->Type != ACPI_TYPE_LOCAL_REFERENCE)
2049 goto err;
2050
2051 h = acpi_GetReference(NULL, pobj);
2052 if (h == NULL)
2053 goto err;
2054
2055 if (propvalue != NULL && size >= sizeof(ACPI_HANDLE))
2056 *(ACPI_HANDLE *)propvalue = h;
2057 return (sizeof(ACPI_HANDLE));
2058
2059 err:
2060 return (-1);
2061 }
2062
2063 static ssize_t
acpi_bus_get_prop(device_t bus,device_t child,const char * propname,void * propvalue,size_t size,device_property_type_t type)2064 acpi_bus_get_prop(device_t bus, device_t child, const char *propname,
2065 void *propvalue, size_t size, device_property_type_t type)
2066 {
2067 ACPI_STATUS status;
2068 const ACPI_OBJECT *obj;
2069
2070 status = acpi_device_get_prop(bus, child, __DECONST(char *, propname),
2071 &obj);
2072 if (ACPI_FAILURE(status))
2073 return (-1);
2074
2075 switch (type) {
2076 case DEVICE_PROP_ANY:
2077 case DEVICE_PROP_BUFFER:
2078 case DEVICE_PROP_UINT32:
2079 case DEVICE_PROP_UINT64:
2080 break;
2081 case DEVICE_PROP_HANDLE:
2082 return (acpi_bus_get_prop_handle(obj, propvalue, size));
2083 default:
2084 return (-1);
2085 }
2086
2087 switch (obj->Type) {
2088 case ACPI_TYPE_INTEGER:
2089 if (type == DEVICE_PROP_UINT32) {
2090 if (propvalue != NULL && size >= sizeof(uint32_t))
2091 *((uint32_t *)propvalue) = obj->Integer.Value;
2092 return (sizeof(uint32_t));
2093 }
2094 if (propvalue != NULL && size >= sizeof(uint64_t))
2095 *((uint64_t *) propvalue) = obj->Integer.Value;
2096 return (sizeof(uint64_t));
2097
2098 case ACPI_TYPE_STRING:
2099 if (type != DEVICE_PROP_ANY &&
2100 type != DEVICE_PROP_BUFFER)
2101 return (-1);
2102
2103 if (propvalue != NULL && size > 0)
2104 memcpy(propvalue, obj->String.Pointer,
2105 MIN(size, obj->String.Length));
2106 return (obj->String.Length);
2107
2108 case ACPI_TYPE_BUFFER:
2109 if (propvalue != NULL && size > 0)
2110 memcpy(propvalue, obj->Buffer.Pointer,
2111 MIN(size, obj->Buffer.Length));
2112 return (obj->Buffer.Length);
2113
2114 case ACPI_TYPE_PACKAGE:
2115 if (propvalue != NULL && size >= sizeof(ACPI_OBJECT *)) {
2116 *((ACPI_OBJECT **) propvalue) =
2117 __DECONST(ACPI_OBJECT *, obj);
2118 }
2119 return (sizeof(ACPI_OBJECT *));
2120
2121 case ACPI_TYPE_LOCAL_REFERENCE:
2122 if (propvalue != NULL && size >= sizeof(ACPI_HANDLE)) {
2123 ACPI_HANDLE h;
2124
2125 h = acpi_GetReference(NULL,
2126 __DECONST(ACPI_OBJECT *, obj));
2127 memcpy(propvalue, h, sizeof(ACPI_HANDLE));
2128 }
2129 return (sizeof(ACPI_HANDLE));
2130 default:
2131 return (0);
2132 }
2133 }
2134
2135 static int
acpi_device_pwr_for_sleep_sxd(device_t dev,ACPI_HANDLE handle,int state,int * dstate)2136 acpi_device_pwr_for_sleep_sxd(device_t dev, ACPI_HANDLE handle, int state,
2137 int *dstate)
2138 {
2139 ACPI_STATUS status;
2140 char sxd[8];
2141
2142 /* Note illegal _S0D is evaluated because some systems expect this. */
2143 snprintf(sxd, sizeof(sxd), "_S%dD", state);
2144 status = acpi_GetInteger(handle, sxd, dstate);
2145 if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
2146 device_printf(dev, "failed to get %s on %s: %s\n", sxd,
2147 acpi_name(handle), AcpiFormatException(status));
2148 return (ENXIO);
2149 }
2150 return (0);
2151 }
2152
2153 /*
2154 * Get the D-state we need to set the device to for entry into the sleep type
2155 * we are currently entering (sc->acpi_stype is set in acpi_EnterSleepState
2156 * before the ACPI bus gets suspended, and thus before this function is called).
2157 *
2158 * If entering suspend_to_idle, we will try to enter whichever D-state we
2159 * would've been transitioning to in S3. If we are entering an ACPI S-state, we
2160 * evaluate the relevant _SxD state instead (ACPI 7.3.16 - 7.3.19).
2161 */
2162 int
acpi_device_pwr_for_sleep(device_t bus,device_t dev,int * dstate)2163 acpi_device_pwr_for_sleep(device_t bus, device_t dev, int *dstate)
2164 {
2165 struct acpi_softc *sc = device_get_softc(bus);
2166 ACPI_HANDLE handle = acpi_get_handle(dev);
2167 int state;
2168
2169 if (dstate == NULL)
2170 return (EINVAL);
2171
2172 /*
2173 * XXX If we find these devices, don't try to power them down.
2174 * The serial and IRDA ports on my T23 hang the system when
2175 * set to D3 and it appears that such legacy devices may
2176 * need special handling in their drivers.
2177 */
2178 if (handle == NULL ||
2179 acpi_MatchHid(handle, "PNP0500") ||
2180 acpi_MatchHid(handle, "PNP0501") ||
2181 acpi_MatchHid(handle, "PNP0502") ||
2182 acpi_MatchHid(handle, "PNP0510") ||
2183 acpi_MatchHid(handle, "PNP0511"))
2184 return (ENXIO);
2185
2186 if (sc->acpi_stype == POWER_STYPE_SUSPEND_TO_IDLE)
2187 state = ACPI_STATE_S3;
2188 else
2189 state = acpi_stype_to_sstate(sc, sc->acpi_stype);
2190 if (state == ACPI_STATE_UNKNOWN)
2191 return (ENOENT);
2192 return (acpi_device_pwr_for_sleep_sxd(bus, handle, state, dstate));
2193 }
2194
2195 /* Callback arg for our implementation of walking the namespace. */
2196 struct acpi_device_scan_ctx {
2197 acpi_scan_cb_t user_fn;
2198 void *arg;
2199 ACPI_HANDLE parent;
2200 };
2201
2202 static ACPI_STATUS
acpi_device_scan_cb(ACPI_HANDLE h,UINT32 level,void * arg,void ** retval)2203 acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level, void *arg, void **retval)
2204 {
2205 struct acpi_device_scan_ctx *ctx;
2206 device_t dev, old_dev;
2207 ACPI_STATUS status;
2208 ACPI_OBJECT_TYPE type;
2209
2210 /*
2211 * Skip this device if we think we'll have trouble with it or it is
2212 * the parent where the scan began.
2213 */
2214 ctx = (struct acpi_device_scan_ctx *)arg;
2215 if (acpi_avoid(h) || h == ctx->parent)
2216 return (AE_OK);
2217
2218 /* If this is not a valid device type (e.g., a method), skip it. */
2219 if (ACPI_FAILURE(AcpiGetType(h, &type)))
2220 return (AE_OK);
2221 if (type != ACPI_TYPE_DEVICE && type != ACPI_TYPE_PROCESSOR &&
2222 type != ACPI_TYPE_THERMAL && type != ACPI_TYPE_POWER)
2223 return (AE_OK);
2224
2225 /*
2226 * Call the user function with the current device. If it is unchanged
2227 * afterwards, return. Otherwise, we update the handle to the new dev.
2228 */
2229 old_dev = acpi_get_device(h);
2230 dev = old_dev;
2231 status = ctx->user_fn(h, &dev, level, ctx->arg);
2232 if (ACPI_FAILURE(status) || old_dev == dev)
2233 return (status);
2234
2235 /* Remove the old child and its connection to the handle. */
2236 if (old_dev != NULL)
2237 device_delete_child(device_get_parent(old_dev), old_dev);
2238
2239 /* Recreate the handle association if the user created a device. */
2240 if (dev != NULL)
2241 AcpiAttachData(h, acpi_fake_objhandler, dev);
2242
2243 return (AE_OK);
2244 }
2245
2246 static ACPI_STATUS
acpi_device_scan_children(device_t bus,device_t dev,int max_depth,acpi_scan_cb_t user_fn,void * arg)2247 acpi_device_scan_children(device_t bus, device_t dev, int max_depth,
2248 acpi_scan_cb_t user_fn, void *arg)
2249 {
2250 ACPI_HANDLE h;
2251 struct acpi_device_scan_ctx ctx;
2252
2253 if (acpi_disabled("children"))
2254 return (AE_OK);
2255
2256 if (dev == NULL)
2257 h = ACPI_ROOT_OBJECT;
2258 else if ((h = acpi_get_handle(dev)) == NULL)
2259 return (AE_BAD_PARAMETER);
2260 ctx.user_fn = user_fn;
2261 ctx.arg = arg;
2262 ctx.parent = h;
2263 return (AcpiWalkNamespace(ACPI_TYPE_ANY, h, max_depth,
2264 acpi_device_scan_cb, NULL, &ctx, NULL));
2265 }
2266
2267 /*
2268 * Even though ACPI devices are not PCI, we use the PCI approach for setting
2269 * device power states since it's close enough to ACPI.
2270 */
2271 int
acpi_set_powerstate(device_t child,int state)2272 acpi_set_powerstate(device_t child, int state)
2273 {
2274 ACPI_HANDLE h;
2275 ACPI_STATUS status;
2276
2277 h = acpi_get_handle(child);
2278 if (state < ACPI_STATE_D0 || state > ACPI_D_STATES_MAX)
2279 return (EINVAL);
2280 if (h == NULL)
2281 return (0);
2282
2283 /* Ignore errors if the power methods aren't present. */
2284 status = acpi_pwr_switch_consumer(h, state);
2285 if (ACPI_SUCCESS(status)) {
2286 if (bootverbose)
2287 device_printf(child, "set ACPI power state %s on %s\n",
2288 acpi_d_state_to_str(state), acpi_name(h));
2289 } else if (status != AE_NOT_FOUND)
2290 device_printf(child,
2291 "failed to set ACPI power state %s on %s: %s\n",
2292 acpi_d_state_to_str(state), acpi_name(h),
2293 AcpiFormatException(status));
2294
2295 return (0);
2296 }
2297
2298 static int
acpi_isa_pnp_probe(device_t bus,device_t child,struct isa_pnp_id * ids)2299 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
2300 {
2301 int result, cid_count, i;
2302 uint32_t lid, cids[8];
2303
2304 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2305
2306 /*
2307 * ISA-style drivers attached to ACPI may persist and
2308 * probe manually if we return ENOENT. We never want
2309 * that to happen, so don't ever return it.
2310 */
2311 result = ENXIO;
2312
2313 /* Scan the supplied IDs for a match */
2314 lid = acpi_isa_get_logicalid(child);
2315 cid_count = acpi_isa_get_compatid(child, cids, 8);
2316 while (ids && ids->ip_id) {
2317 if (lid == ids->ip_id) {
2318 result = 0;
2319 goto out;
2320 }
2321 for (i = 0; i < cid_count; i++) {
2322 if (cids[i] == ids->ip_id) {
2323 result = 0;
2324 goto out;
2325 }
2326 }
2327 ids++;
2328 }
2329
2330 out:
2331 if (result == 0 && ids->ip_desc)
2332 device_set_desc(child, ids->ip_desc);
2333
2334 return_VALUE (result);
2335 }
2336
2337 /*
2338 * Look for a MCFG table. If it is present, use the settings for
2339 * domain (segment) 0 to setup PCI config space access via the memory
2340 * map.
2341 *
2342 * On non-x86 architectures (arm64 for now), this will be done from the
2343 * PCI host bridge driver.
2344 */
2345 static void
acpi_enable_pcie(void)2346 acpi_enable_pcie(void)
2347 {
2348 #if defined(__i386__) || defined(__amd64__)
2349 ACPI_TABLE_HEADER *hdr;
2350 ACPI_MCFG_ALLOCATION *alloc, *end;
2351 ACPI_STATUS status;
2352
2353 status = AcpiGetTable(ACPI_SIG_MCFG, 1, &hdr);
2354 if (ACPI_FAILURE(status))
2355 return;
2356
2357 end = (ACPI_MCFG_ALLOCATION *)((char *)hdr + hdr->Length);
2358 alloc = (ACPI_MCFG_ALLOCATION *)((ACPI_TABLE_MCFG *)hdr + 1);
2359 while (alloc < end) {
2360 pcie_cfgregopen(alloc->Address, alloc->PciSegment,
2361 alloc->StartBusNumber, alloc->EndBusNumber);
2362 alloc++;
2363 }
2364 #endif
2365 }
2366
2367 static void
acpi_platform_osc(device_t dev)2368 acpi_platform_osc(device_t dev)
2369 {
2370 ACPI_HANDLE sb_handle;
2371 ACPI_STATUS status;
2372 uint32_t cap_set[2];
2373
2374 /* 0811B06E-4A27-44F9-8D60-3CBBC22E7B48 */
2375 static uint8_t acpi_platform_uuid[ACPI_UUID_LENGTH] = {
2376 0x6e, 0xb0, 0x11, 0x08, 0x27, 0x4a, 0xf9, 0x44,
2377 0x8d, 0x60, 0x3c, 0xbb, 0xc2, 0x2e, 0x7b, 0x48
2378 };
2379
2380 if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2381 return;
2382
2383 cap_set[1] = 0x10; /* APEI Support */
2384 status = acpi_EvaluateOSC(sb_handle, acpi_platform_uuid, 1,
2385 nitems(cap_set), cap_set, cap_set, false);
2386 if (ACPI_FAILURE(status)) {
2387 if (status == AE_NOT_FOUND)
2388 return;
2389 device_printf(dev, "_OSC failed: %s\n",
2390 AcpiFormatException(status));
2391 return;
2392 }
2393 }
2394
2395 /*
2396 * Scan all of the ACPI namespace and attach child devices.
2397 *
2398 * We should only expect to find devices in the \_PR, \_TZ, \_SI, and
2399 * \_SB scopes, and \_PR and \_TZ became obsolete in the ACPI 2.0 spec.
2400 * However, in violation of the spec, some systems place their PCI link
2401 * devices in \, so we have to walk the whole namespace. We check the
2402 * type of namespace nodes, so this should be ok.
2403 */
2404 static void
acpi_probe_children(device_t bus)2405 acpi_probe_children(device_t bus)
2406 {
2407
2408 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2409
2410 /*
2411 * Scan the namespace and insert placeholders for all the devices that
2412 * we find. We also probe/attach any early devices.
2413 *
2414 * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
2415 * we want to create nodes for all devices, not just those that are
2416 * currently present. (This assumes that we don't want to create/remove
2417 * devices as they appear, which might be smarter.)
2418 */
2419 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
2420 AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, 100, acpi_probe_child,
2421 NULL, bus, NULL);
2422
2423 /* Pre-allocate resources for our rman from any sysresource devices. */
2424 acpi_sysres_alloc(bus);
2425
2426 /* Create any static children by calling device identify methods. */
2427 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
2428 bus_identify_children(bus);
2429
2430 /* Probe/attach all children, created statically and from the namespace. */
2431 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "acpi bus_attach_children\n"));
2432 bus_attach_children(bus);
2433
2434 /*
2435 * Reserve resources allocated to children but not yet allocated
2436 * by a driver.
2437 */
2438 acpi_reserve_resources(bus);
2439
2440 /* Attach wake sysctls. */
2441 acpi_wake_sysctl_walk(bus);
2442
2443 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
2444 return_VOID;
2445 }
2446
2447 /*
2448 * Determine the probe order for a given device.
2449 */
2450 static void
acpi_probe_order(ACPI_HANDLE handle,int * order)2451 acpi_probe_order(ACPI_HANDLE handle, int *order)
2452 {
2453 ACPI_OBJECT_TYPE type;
2454
2455 /*
2456 * 0. CPUs
2457 * 1. I/O port and memory system resource holders
2458 * 2. Clocks and timers (to handle early accesses)
2459 * 3. Embedded controllers (to handle early accesses)
2460 * 4. PCI Link Devices
2461 */
2462 AcpiGetType(handle, &type);
2463 if (type == ACPI_TYPE_PROCESSOR)
2464 *order = 0;
2465 else if (acpi_MatchHid(handle, "PNP0C01") ||
2466 acpi_MatchHid(handle, "PNP0C02"))
2467 *order = 1;
2468 else if (acpi_MatchHid(handle, "PNP0100") ||
2469 acpi_MatchHid(handle, "PNP0103") ||
2470 acpi_MatchHid(handle, "PNP0B00"))
2471 *order = 2;
2472 else if (acpi_MatchHid(handle, "PNP0C09"))
2473 *order = 3;
2474 else if (acpi_MatchHid(handle, "PNP0C0F"))
2475 *order = 4;
2476 }
2477
2478 /*
2479 * Evaluate a child device and determine whether we might attach a device to
2480 * it.
2481 */
2482 static ACPI_STATUS
acpi_probe_child(ACPI_HANDLE handle,UINT32 level,void * context,void ** status)2483 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2484 {
2485 ACPI_DEVICE_INFO *devinfo;
2486 struct acpi_device *ad;
2487 struct acpi_prw_data prw;
2488 ACPI_OBJECT_TYPE type;
2489 ACPI_HANDLE h;
2490 device_t bus, child;
2491 char *handle_str;
2492 int d, order;
2493
2494 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2495
2496 if (acpi_disabled("children"))
2497 return_ACPI_STATUS (AE_OK);
2498
2499 /* Skip this device if we think we'll have trouble with it. */
2500 if (acpi_avoid(handle))
2501 return_ACPI_STATUS (AE_OK);
2502
2503 bus = (device_t)context;
2504 if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
2505 handle_str = acpi_name(handle);
2506 switch (type) {
2507 case ACPI_TYPE_DEVICE:
2508 /*
2509 * Since we scan from \, be sure to skip system scope objects.
2510 * \_SB_ and \_TZ_ are defined in ACPICA as devices to work around
2511 * BIOS bugs. For example, \_SB_ is to allow \_SB_._INI to be run
2512 * during the initialization and \_TZ_ is to support Notify() on it.
2513 */
2514 if (strcmp(handle_str, "\\_SB_") == 0 ||
2515 strcmp(handle_str, "\\_TZ_") == 0)
2516 break;
2517 if (acpi_parse_prw(handle, &prw) == 0)
2518 AcpiSetupGpeForWake(handle, prw.gpe_handle, prw.gpe_bit);
2519
2520 /*
2521 * Ignore devices that do not have a _HID or _CID. They should
2522 * be discovered by other buses (e.g. the PCI bus driver).
2523 */
2524 if (!acpi_has_hid(handle))
2525 break;
2526 /* FALLTHROUGH */
2527 case ACPI_TYPE_PROCESSOR:
2528 case ACPI_TYPE_THERMAL:
2529 case ACPI_TYPE_POWER:
2530 /*
2531 * Create a placeholder device for this node. Sort the
2532 * placeholder so that the probe/attach passes will run
2533 * breadth-first. Orders less than ACPI_DEV_BASE_ORDER
2534 * are reserved for special objects (i.e., system
2535 * resources).
2536 */
2537 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
2538 order = level * 10 + ACPI_DEV_BASE_ORDER;
2539 acpi_probe_order(handle, &order);
2540 child = BUS_ADD_CHILD(bus, order, NULL, DEVICE_UNIT_ANY);
2541 if (child == NULL)
2542 break;
2543
2544 /* Associate the handle with the device_t and vice versa. */
2545 acpi_set_handle(child, handle);
2546 AcpiAttachData(handle, acpi_fake_objhandler, child);
2547
2548 /*
2549 * Check that the device is present. If it's not present,
2550 * leave it disabled (so that we have a device_t attached to
2551 * the handle, but we don't probe it).
2552 *
2553 * XXX PCI link devices sometimes report "present" but not
2554 * "functional" (i.e. if disabled). Go ahead and probe them
2555 * anyway since we may enable them later.
2556 */
2557 if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
2558 /* Never disable PCI link devices. */
2559 if (acpi_MatchHid(handle, "PNP0C0F"))
2560 break;
2561
2562 /*
2563 * RTC Device should be enabled for CMOS register space
2564 * unless FADT indicate it is not present.
2565 * (checked in RTC probe routine.)
2566 */
2567 if (acpi_MatchHid(handle, "PNP0B00"))
2568 break;
2569
2570 /*
2571 * Docking stations should remain enabled since the system
2572 * may be undocked at boot.
2573 */
2574 if (ACPI_SUCCESS(AcpiGetHandle(handle, "_DCK", &h)))
2575 break;
2576
2577 device_disable(child);
2578 break;
2579 }
2580
2581 /*
2582 * Get the device's resource settings and attach them.
2583 * Note that if the device has _PRS but no _CRS, we need
2584 * to decide when it's appropriate to try to configure the
2585 * device. Ignore the return value here; it's OK for the
2586 * device not to have any resources.
2587 */
2588 acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
2589
2590 ad = device_get_ivars(child);
2591 ad->ad_cls_class = 0xffffff;
2592 if (ACPI_SUCCESS(AcpiGetObjectInfo(handle, &devinfo))) {
2593 if ((devinfo->Valid & ACPI_VALID_CLS) != 0 &&
2594 devinfo->ClassCode.Length >= ACPI_PCICLS_STRING_SIZE) {
2595 ad->ad_cls_class = strtoul(devinfo->ClassCode.String,
2596 NULL, 16);
2597 }
2598 AcpiOsFree(devinfo);
2599 }
2600
2601 d = acpi_pxm_parse(child);
2602 if (d >= 0)
2603 ad->ad_domain = d;
2604 break;
2605 }
2606 }
2607
2608 return_ACPI_STATUS (AE_OK);
2609 }
2610
2611 /*
2612 * AcpiAttachData() requires an object handler but never uses it. This is a
2613 * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
2614 */
2615 void
acpi_fake_objhandler(ACPI_HANDLE h,void * data)2616 acpi_fake_objhandler(ACPI_HANDLE h, void *data)
2617 {
2618 }
2619
2620 /*
2621 * Simple wrapper around AcpiEnterSleepStatePrep() printing diagnostic on error.
2622 */
2623 static ACPI_STATUS
acpi_EnterSleepStatePrep(device_t acpi_dev,UINT8 SleepState)2624 acpi_EnterSleepStatePrep(device_t acpi_dev, UINT8 SleepState)
2625 {
2626 ACPI_STATUS status;
2627
2628 status = AcpiEnterSleepStatePrep(SleepState);
2629 if (ACPI_FAILURE(status))
2630 device_printf(acpi_dev,
2631 "AcpiEnterSleepStatePrep(%u) failed - %s\n",
2632 SleepState,
2633 AcpiFormatException(status));
2634 return (status);
2635 }
2636
2637 /* Return from this function indicates failure. */
2638 static void
acpi_poweroff(device_t acpi_dev)2639 acpi_poweroff(device_t acpi_dev)
2640 {
2641 register_t intr;
2642 ACPI_STATUS status;
2643
2644 device_printf(acpi_dev, "Powering system off...\n");
2645 status = acpi_EnterSleepStatePrep(acpi_dev, ACPI_STATE_S5);
2646 if (ACPI_FAILURE(status)) {
2647 device_printf(acpi_dev, "Power-off preparation failed! - %s\n",
2648 AcpiFormatException(status));
2649 return;
2650 }
2651 intr = intr_disable();
2652 status = AcpiEnterSleepState(ACPI_STATE_S5);
2653 if (ACPI_FAILURE(status)) {
2654 intr_restore(intr);
2655 device_printf(acpi_dev, "Power-off failed! - %s\n",
2656 AcpiFormatException(status));
2657 } else {
2658 DELAY(1000000);
2659 intr_restore(intr);
2660 device_printf(acpi_dev, "Power-off failed! - timeout\n");
2661 }
2662 }
2663
2664 static void
acpi_shutdown_final(void * arg,int howto)2665 acpi_shutdown_final(void *arg, int howto)
2666 {
2667 struct acpi_softc *sc = (struct acpi_softc *)arg;
2668 ACPI_STATUS status;
2669
2670 /*
2671 * XXX Shutdown code should only run on the BSP (cpuid 0).
2672 * Some chipsets do not power off the system correctly if called from
2673 * an AP.
2674 */
2675 if ((howto & RB_POWEROFF) != 0) {
2676 acpi_poweroff(sc->acpi_dev);
2677 } else if ((howto & RB_HALT) == 0 && sc->acpi_handle_reboot) {
2678 /* Reboot using the reset register. */
2679 status = AcpiReset();
2680 if (ACPI_SUCCESS(status)) {
2681 DELAY(1000000);
2682 device_printf(sc->acpi_dev, "reset failed - timeout\n");
2683 } else if (status != AE_NOT_EXIST)
2684 device_printf(sc->acpi_dev, "reset failed - %s\n",
2685 AcpiFormatException(status));
2686 } else if (sc->acpi_do_disable && !KERNEL_PANICKED()) {
2687 /*
2688 * Only disable ACPI if the user requested. On some systems, writing
2689 * the disable value to SMI_CMD hangs the system.
2690 */
2691 device_printf(sc->acpi_dev, "Shutting down\n");
2692 AcpiTerminate();
2693 }
2694 }
2695
2696 static void
acpi_enable_fixed_events(struct acpi_softc * sc)2697 acpi_enable_fixed_events(struct acpi_softc *sc)
2698 {
2699 static int first_time = 1;
2700
2701 /* Enable and clear fixed events and install handlers. */
2702 if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
2703 AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
2704 AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
2705 acpi_event_power_button_sleep, sc);
2706 if (first_time)
2707 device_printf(sc->acpi_dev, "Power Button (fixed)\n");
2708 }
2709 if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
2710 AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
2711 AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
2712 acpi_event_sleep_button_sleep, sc);
2713 if (first_time)
2714 device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
2715 }
2716
2717 first_time = 0;
2718 }
2719
2720 /*
2721 * Returns true if the device is actually present and should
2722 * be attached to. This requires the present, enabled, UI-visible
2723 * and diagnostics-passed bits to be set.
2724 */
2725 BOOLEAN
acpi_DeviceIsPresent(device_t dev)2726 acpi_DeviceIsPresent(device_t dev)
2727 {
2728 ACPI_HANDLE h;
2729 UINT32 s;
2730 ACPI_STATUS status;
2731
2732 h = acpi_get_handle(dev);
2733 if (h == NULL)
2734 return (FALSE);
2735
2736 #ifdef ACPI_EARLY_EPYC_WAR
2737 /*
2738 * Certain Treadripper boards always returns 0 for FreeBSD because it
2739 * only returns non-zero for the OS string "Windows 2015". Otherwise it
2740 * will return zero. Force them to always be treated as present.
2741 * Beata versions were worse: they always returned 0.
2742 */
2743 if (acpi_MatchHid(h, "AMDI0020") || acpi_MatchHid(h, "AMDI0010"))
2744 return (TRUE);
2745 #endif
2746
2747 status = acpi_GetInteger(h, "_STA", &s);
2748
2749 /*
2750 * If no _STA method or if it failed, then assume that
2751 * the device is present.
2752 */
2753 if (ACPI_FAILURE(status))
2754 return (TRUE);
2755
2756 return (ACPI_DEVICE_PRESENT(s) ? TRUE : FALSE);
2757 }
2758
2759 /*
2760 * Returns true if the battery is actually present and inserted.
2761 */
2762 BOOLEAN
acpi_BatteryIsPresent(device_t dev)2763 acpi_BatteryIsPresent(device_t dev)
2764 {
2765 ACPI_HANDLE h;
2766 UINT32 s;
2767 ACPI_STATUS status;
2768
2769 h = acpi_get_handle(dev);
2770 if (h == NULL)
2771 return (FALSE);
2772 status = acpi_GetInteger(h, "_STA", &s);
2773
2774 /*
2775 * If no _STA method or if it failed, then assume that
2776 * the device is present.
2777 */
2778 if (ACPI_FAILURE(status))
2779 return (TRUE);
2780
2781 return (ACPI_BATTERY_PRESENT(s) ? TRUE : FALSE);
2782 }
2783
2784 /*
2785 * Returns true if a device has at least one valid device ID.
2786 */
2787 BOOLEAN
acpi_has_hid(ACPI_HANDLE h)2788 acpi_has_hid(ACPI_HANDLE h)
2789 {
2790 ACPI_DEVICE_INFO *devinfo;
2791 BOOLEAN ret;
2792
2793 if (h == NULL ||
2794 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2795 return (FALSE);
2796
2797 ret = FALSE;
2798 if ((devinfo->Valid & ACPI_VALID_HID) != 0)
2799 ret = TRUE;
2800 else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2801 if (devinfo->CompatibleIdList.Count > 0)
2802 ret = TRUE;
2803
2804 AcpiOsFree(devinfo);
2805 return (ret);
2806 }
2807
2808 /*
2809 * Match a HID string against a handle
2810 * returns ACPI_MATCHHID_HID if _HID match
2811 * ACPI_MATCHHID_CID if _CID match and not _HID match.
2812 * ACPI_MATCHHID_NOMATCH=0 if no match.
2813 */
2814 int
acpi_MatchHid(ACPI_HANDLE h,const char * hid)2815 acpi_MatchHid(ACPI_HANDLE h, const char *hid)
2816 {
2817 ACPI_DEVICE_INFO *devinfo;
2818 BOOLEAN ret;
2819 int i;
2820
2821 if (hid == NULL || h == NULL ||
2822 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2823 return (ACPI_MATCHHID_NOMATCH);
2824
2825 ret = ACPI_MATCHHID_NOMATCH;
2826 if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
2827 strcmp(hid, devinfo->HardwareId.String) == 0)
2828 ret = ACPI_MATCHHID_HID;
2829 else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2830 for (i = 0; i < devinfo->CompatibleIdList.Count; i++) {
2831 if (strcmp(hid, devinfo->CompatibleIdList.Ids[i].String) == 0) {
2832 ret = ACPI_MATCHHID_CID;
2833 break;
2834 }
2835 }
2836
2837 AcpiOsFree(devinfo);
2838 return (ret);
2839 }
2840
2841 /*
2842 * Return the handle of a named object within our scope, ie. that of (parent)
2843 * or one if its parents.
2844 */
2845 ACPI_STATUS
acpi_GetHandleInScope(ACPI_HANDLE parent,char * path,ACPI_HANDLE * result)2846 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
2847 {
2848 ACPI_HANDLE r;
2849 ACPI_STATUS status;
2850
2851 /* Walk back up the tree to the root */
2852 for (;;) {
2853 status = AcpiGetHandle(parent, path, &r);
2854 if (ACPI_SUCCESS(status)) {
2855 *result = r;
2856 return (AE_OK);
2857 }
2858 /* XXX Return error here? */
2859 if (status != AE_NOT_FOUND)
2860 return (AE_OK);
2861 if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
2862 return (AE_NOT_FOUND);
2863 parent = r;
2864 }
2865 }
2866
2867 ACPI_STATUS
acpi_GetProperty(device_t dev,ACPI_STRING propname,const ACPI_OBJECT ** value)2868 acpi_GetProperty(device_t dev, ACPI_STRING propname,
2869 const ACPI_OBJECT **value)
2870 {
2871 device_t bus = device_get_parent(dev);
2872
2873 return (ACPI_GET_PROPERTY(bus, dev, propname, value));
2874 }
2875
2876 /*
2877 * Allocate a buffer with a preset data size.
2878 */
2879 ACPI_BUFFER *
acpi_AllocBuffer(int size)2880 acpi_AllocBuffer(int size)
2881 {
2882 ACPI_BUFFER *buf;
2883
2884 if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
2885 return (NULL);
2886 buf->Length = size;
2887 buf->Pointer = (void *)(buf + 1);
2888 return (buf);
2889 }
2890
2891 ACPI_STATUS
acpi_SetInteger(ACPI_HANDLE handle,char * path,UINT32 number)2892 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
2893 {
2894 ACPI_OBJECT arg1;
2895 ACPI_OBJECT_LIST args;
2896
2897 arg1.Type = ACPI_TYPE_INTEGER;
2898 arg1.Integer.Value = number;
2899 args.Count = 1;
2900 args.Pointer = &arg1;
2901
2902 return (AcpiEvaluateObject(handle, path, &args, NULL));
2903 }
2904
2905 /*
2906 * Evaluate a path that should return an integer.
2907 */
2908 ACPI_STATUS
acpi_GetInteger(ACPI_HANDLE handle,char * path,UINT32 * number)2909 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
2910 {
2911 ACPI_STATUS status;
2912 ACPI_BUFFER buf;
2913 ACPI_OBJECT param;
2914
2915 if (handle == NULL)
2916 handle = ACPI_ROOT_OBJECT;
2917
2918 /*
2919 * Assume that what we've been pointed at is an Integer object, or
2920 * a method that will return an Integer.
2921 */
2922 buf.Pointer = ¶m;
2923 buf.Length = sizeof(param);
2924 status = AcpiEvaluateObject(handle, path, NULL, &buf);
2925 if (ACPI_SUCCESS(status)) {
2926 if (param.Type == ACPI_TYPE_INTEGER)
2927 *number = param.Integer.Value;
2928 else
2929 status = AE_TYPE;
2930 }
2931
2932 /*
2933 * In some applications, a method that's expected to return an Integer
2934 * may instead return a Buffer (probably to simplify some internal
2935 * arithmetic). We'll try to fetch whatever it is, and if it's a Buffer,
2936 * convert it into an Integer as best we can.
2937 *
2938 * This is a hack.
2939 */
2940 if (status == AE_BUFFER_OVERFLOW) {
2941 if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
2942 status = AE_NO_MEMORY;
2943 } else {
2944 status = AcpiEvaluateObject(handle, path, NULL, &buf);
2945 if (ACPI_SUCCESS(status))
2946 status = acpi_ConvertBufferToInteger(&buf, number);
2947 AcpiOsFree(buf.Pointer);
2948 }
2949 }
2950 return (status);
2951 }
2952
2953 ACPI_STATUS
acpi_ConvertBufferToInteger(ACPI_BUFFER * bufp,UINT32 * number)2954 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
2955 {
2956 ACPI_OBJECT *p;
2957 UINT8 *val;
2958 int i;
2959
2960 p = (ACPI_OBJECT *)bufp->Pointer;
2961 if (p->Type == ACPI_TYPE_INTEGER) {
2962 *number = p->Integer.Value;
2963 return (AE_OK);
2964 }
2965 if (p->Type != ACPI_TYPE_BUFFER)
2966 return (AE_TYPE);
2967 if (p->Buffer.Length > sizeof(int))
2968 return (AE_BAD_DATA);
2969
2970 *number = 0;
2971 val = p->Buffer.Pointer;
2972 for (i = 0; i < p->Buffer.Length; i++)
2973 *number += val[i] << (i * 8);
2974 return (AE_OK);
2975 }
2976
2977 /*
2978 * Iterate over the elements of an a package object, calling the supplied
2979 * function for each element.
2980 *
2981 * XXX possible enhancement might be to abort traversal on error.
2982 */
2983 ACPI_STATUS
acpi_ForeachPackageObject(ACPI_OBJECT * pkg,void (* func)(ACPI_OBJECT * comp,void * arg),void * arg)2984 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
2985 void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
2986 {
2987 ACPI_OBJECT *comp;
2988 int i;
2989
2990 if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
2991 return (AE_BAD_PARAMETER);
2992
2993 /* Iterate over components */
2994 i = 0;
2995 comp = pkg->Package.Elements;
2996 for (; i < pkg->Package.Count; i++, comp++)
2997 func(comp, arg);
2998
2999 return (AE_OK);
3000 }
3001
3002 /*
3003 * Find the (index)th resource object in a set.
3004 */
3005 ACPI_STATUS
acpi_FindIndexedResource(ACPI_BUFFER * buf,int index,ACPI_RESOURCE ** resp)3006 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
3007 {
3008 ACPI_RESOURCE *rp;
3009 int i;
3010
3011 rp = (ACPI_RESOURCE *)buf->Pointer;
3012 i = index;
3013 while (i-- > 0) {
3014 /* Range check */
3015 if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
3016 return (AE_BAD_PARAMETER);
3017
3018 /* Check for terminator */
3019 if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
3020 return (AE_NOT_FOUND);
3021 rp = ACPI_NEXT_RESOURCE(rp);
3022 }
3023 if (resp != NULL)
3024 *resp = rp;
3025
3026 return (AE_OK);
3027 }
3028
3029 /*
3030 * Append an ACPI_RESOURCE to an ACPI_BUFFER.
3031 *
3032 * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
3033 * provided to contain it. If the ACPI_BUFFER is empty, allocate a sensible
3034 * backing block. If the ACPI_RESOURCE is NULL, return an empty set of
3035 * resources.
3036 */
3037 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE 512
3038
3039 ACPI_STATUS
acpi_AppendBufferResource(ACPI_BUFFER * buf,ACPI_RESOURCE * res)3040 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
3041 {
3042 ACPI_RESOURCE *rp;
3043 void *newp;
3044
3045 /* Initialise the buffer if necessary. */
3046 if (buf->Pointer == NULL) {
3047 buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
3048 if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
3049 return (AE_NO_MEMORY);
3050 rp = (ACPI_RESOURCE *)buf->Pointer;
3051 rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
3052 rp->Length = ACPI_RS_SIZE_MIN;
3053 }
3054 if (res == NULL)
3055 return (AE_OK);
3056
3057 /*
3058 * Scan the current buffer looking for the terminator.
3059 * This will either find the terminator or hit the end
3060 * of the buffer and return an error.
3061 */
3062 rp = (ACPI_RESOURCE *)buf->Pointer;
3063 for (;;) {
3064 /* Range check, don't go outside the buffer */
3065 if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
3066 return (AE_BAD_PARAMETER);
3067 if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
3068 break;
3069 rp = ACPI_NEXT_RESOURCE(rp);
3070 }
3071
3072 /*
3073 * Check the size of the buffer and expand if required.
3074 *
3075 * Required size is:
3076 * size of existing resources before terminator +
3077 * size of new resource and header +
3078 * size of terminator.
3079 *
3080 * Note that this loop should really only run once, unless
3081 * for some reason we are stuffing a *really* huge resource.
3082 */
3083 while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
3084 res->Length + ACPI_RS_SIZE_NO_DATA +
3085 ACPI_RS_SIZE_MIN) >= buf->Length) {
3086 if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
3087 return (AE_NO_MEMORY);
3088 bcopy(buf->Pointer, newp, buf->Length);
3089 rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
3090 ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
3091 AcpiOsFree(buf->Pointer);
3092 buf->Pointer = newp;
3093 buf->Length += buf->Length;
3094 }
3095
3096 /* Insert the new resource. */
3097 bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
3098
3099 /* And add the terminator. */
3100 rp = ACPI_NEXT_RESOURCE(rp);
3101 rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
3102 rp->Length = ACPI_RS_SIZE_MIN;
3103
3104 return (AE_OK);
3105 }
3106
3107 UINT64
acpi_DSMQuery(ACPI_HANDLE h,const uint8_t * uuid,int revision)3108 acpi_DSMQuery(ACPI_HANDLE h, const uint8_t *uuid, int revision)
3109 {
3110 /*
3111 * ACPI spec 9.1.1 defines this.
3112 *
3113 * "Arg2: Function Index Represents a specific function whose meaning is
3114 * specific to the UUID and Revision ID. Function indices should start
3115 * with 1. Function number zero is a query function (see the special
3116 * return code defined below)."
3117 */
3118 ACPI_BUFFER buf;
3119 ACPI_OBJECT *obj;
3120 UINT64 ret = 0;
3121 int i;
3122
3123 if (!ACPI_SUCCESS(acpi_EvaluateDSM(h, uuid, revision, 0, NULL, &buf))) {
3124 ACPI_INFO(("Failed to enumerate DSM functions\n"));
3125 return (0);
3126 }
3127
3128 obj = (ACPI_OBJECT *)buf.Pointer;
3129 KASSERT(obj, ("Object not allowed to be NULL\n"));
3130
3131 /*
3132 * From ACPI 6.2 spec 9.1.1:
3133 * If Function Index = 0, a Buffer containing a function index bitfield.
3134 * Otherwise, the return value and type depends on the UUID and revision
3135 * ID (see below).
3136 */
3137 switch (obj->Type) {
3138 case ACPI_TYPE_BUFFER:
3139 for (i = 0; i < MIN(obj->Buffer.Length, sizeof(ret)); i++)
3140 ret |= (((uint64_t)obj->Buffer.Pointer[i]) << (i * 8));
3141 break;
3142 case ACPI_TYPE_INTEGER:
3143 ACPI_BIOS_WARNING((AE_INFO,
3144 "Possibly buggy BIOS with ACPI_TYPE_INTEGER for function enumeration\n"));
3145 ret = obj->Integer.Value;
3146 break;
3147 default:
3148 ACPI_WARNING((AE_INFO, "Unexpected return type %u\n", obj->Type));
3149 };
3150
3151 AcpiOsFree(obj);
3152 return ret;
3153 }
3154
3155 /*
3156 * DSM may return multiple types depending on the function. It is therefore
3157 * unsafe to use the typed evaluation. It is highly recommended that the caller
3158 * check the type of the returned object.
3159 */
3160 ACPI_STATUS
acpi_EvaluateDSM(ACPI_HANDLE handle,const uint8_t * uuid,int revision,UINT64 function,ACPI_OBJECT * package,ACPI_BUFFER * out_buf)3161 acpi_EvaluateDSM(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
3162 UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf)
3163 {
3164 return (acpi_EvaluateDSMTyped(handle, uuid, revision, function,
3165 package, out_buf, ACPI_TYPE_ANY));
3166 }
3167
3168 ACPI_STATUS
acpi_EvaluateDSMTyped(ACPI_HANDLE handle,const uint8_t * uuid,int revision,UINT64 function,ACPI_OBJECT * package,ACPI_BUFFER * out_buf,ACPI_OBJECT_TYPE type)3169 acpi_EvaluateDSMTyped(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
3170 UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf,
3171 ACPI_OBJECT_TYPE type)
3172 {
3173 ACPI_OBJECT arg[4];
3174 ACPI_OBJECT_LIST arglist;
3175 ACPI_BUFFER buf;
3176 ACPI_STATUS status;
3177
3178 if (out_buf == NULL)
3179 return (AE_NO_MEMORY);
3180
3181 arg[0].Type = ACPI_TYPE_BUFFER;
3182 arg[0].Buffer.Length = ACPI_UUID_LENGTH;
3183 arg[0].Buffer.Pointer = __DECONST(uint8_t *, uuid);
3184 arg[1].Type = ACPI_TYPE_INTEGER;
3185 arg[1].Integer.Value = revision;
3186 arg[2].Type = ACPI_TYPE_INTEGER;
3187 arg[2].Integer.Value = function;
3188 if (package) {
3189 arg[3] = *package;
3190 } else {
3191 arg[3].Type = ACPI_TYPE_PACKAGE;
3192 arg[3].Package.Count = 0;
3193 arg[3].Package.Elements = NULL;
3194 }
3195
3196 arglist.Pointer = arg;
3197 arglist.Count = 4;
3198 buf.Pointer = NULL;
3199 buf.Length = ACPI_ALLOCATE_BUFFER;
3200 status = AcpiEvaluateObjectTyped(handle, "_DSM", &arglist, &buf, type);
3201 if (ACPI_FAILURE(status))
3202 return (status);
3203
3204 KASSERT(ACPI_SUCCESS(status), ("Unexpected status"));
3205
3206 *out_buf = buf;
3207 return (status);
3208 }
3209
3210 ACPI_STATUS
acpi_EvaluateOSC(ACPI_HANDLE handle,uint8_t * uuid,int revision,int count,uint32_t * caps_in,uint32_t * caps_out,bool query)3211 acpi_EvaluateOSC(ACPI_HANDLE handle, uint8_t *uuid, int revision, int count,
3212 uint32_t *caps_in, uint32_t *caps_out, bool query)
3213 {
3214 ACPI_OBJECT arg[4], *ret;
3215 ACPI_OBJECT_LIST arglist;
3216 ACPI_BUFFER buf;
3217 ACPI_STATUS status;
3218
3219 arglist.Pointer = arg;
3220 arglist.Count = 4;
3221 arg[0].Type = ACPI_TYPE_BUFFER;
3222 arg[0].Buffer.Length = ACPI_UUID_LENGTH;
3223 arg[0].Buffer.Pointer = uuid;
3224 arg[1].Type = ACPI_TYPE_INTEGER;
3225 arg[1].Integer.Value = revision;
3226 arg[2].Type = ACPI_TYPE_INTEGER;
3227 arg[2].Integer.Value = count;
3228 arg[3].Type = ACPI_TYPE_BUFFER;
3229 arg[3].Buffer.Length = count * sizeof(*caps_in);
3230 arg[3].Buffer.Pointer = (uint8_t *)caps_in;
3231 caps_in[0] = query ? 1 : 0;
3232 buf.Pointer = NULL;
3233 buf.Length = ACPI_ALLOCATE_BUFFER;
3234 status = AcpiEvaluateObjectTyped(handle, "_OSC", &arglist, &buf,
3235 ACPI_TYPE_BUFFER);
3236 if (ACPI_FAILURE(status))
3237 return (status);
3238 if (caps_out != NULL) {
3239 ret = buf.Pointer;
3240 if (ret->Buffer.Length != count * sizeof(*caps_out)) {
3241 AcpiOsFree(buf.Pointer);
3242 return (AE_BUFFER_OVERFLOW);
3243 }
3244 bcopy(ret->Buffer.Pointer, caps_out, ret->Buffer.Length);
3245 }
3246 AcpiOsFree(buf.Pointer);
3247 return (status);
3248 }
3249
3250 /*
3251 * Set interrupt model.
3252 */
3253 ACPI_STATUS
acpi_SetIntrModel(int model)3254 acpi_SetIntrModel(int model)
3255 {
3256
3257 return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
3258 }
3259
3260 /*
3261 * Walk subtables of a table and call a callback routine for each
3262 * subtable. The caller should provide the first subtable and a
3263 * pointer to the end of the table. This can be used to walk tables
3264 * such as MADT and SRAT that use subtable entries.
3265 */
3266 void
acpi_walk_subtables(void * first,void * end,acpi_subtable_handler * handler,void * arg)3267 acpi_walk_subtables(void *first, void *end, acpi_subtable_handler *handler,
3268 void *arg)
3269 {
3270 ACPI_SUBTABLE_HEADER *entry;
3271
3272 for (entry = first; (void *)entry < end; ) {
3273 /* Avoid an infinite loop if we hit a bogus entry. */
3274 if (entry->Length < sizeof(ACPI_SUBTABLE_HEADER))
3275 return;
3276
3277 handler(entry, arg);
3278 entry = ACPI_ADD_PTR(ACPI_SUBTABLE_HEADER, entry, entry->Length);
3279 }
3280 }
3281
3282 /*
3283 * DEPRECATED. This interface has serious deficiencies and will be
3284 * removed.
3285 *
3286 * Immediately enter the sleep state. In the old model, acpiconf(8) ran
3287 * rc.suspend and rc.resume so we don't have to notify devd(8) to do this.
3288 */
3289 ACPI_STATUS
acpi_SetSleepState(struct acpi_softc * sc,int state)3290 acpi_SetSleepState(struct acpi_softc *sc, int state)
3291 {
3292 static int once;
3293
3294 if (!once) {
3295 device_printf(sc->acpi_dev,
3296 "warning: acpi_SetSleepState() deprecated, need to update your software\n");
3297 once = 1;
3298 }
3299 return (acpi_EnterSleepState(sc, state));
3300 }
3301
3302 #if defined(__amd64__) || defined(__i386__)
3303 static void
acpi_sleep_force_task(void * context)3304 acpi_sleep_force_task(void *context)
3305 {
3306 struct acpi_softc *sc = (struct acpi_softc *)context;
3307
3308 if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_stype)))
3309 device_printf(sc->acpi_dev, "force sleep state %s failed\n",
3310 power_stype_to_name(sc->acpi_next_stype));
3311 }
3312
3313 static void
acpi_sleep_force(void * arg)3314 acpi_sleep_force(void *arg)
3315 {
3316 struct acpi_softc *sc = (struct acpi_softc *)arg;
3317
3318 device_printf(sc->acpi_dev,
3319 "suspend request timed out, forcing sleep now\n");
3320 /*
3321 * XXX Suspending from callout causes freezes in DEVICE_SUSPEND().
3322 * Suspend from acpi_task thread instead.
3323 */
3324 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3325 acpi_sleep_force_task, sc)))
3326 device_printf(sc->acpi_dev, "AcpiOsExecute() for sleeping failed\n");
3327 }
3328 #endif
3329
3330 /*
3331 * Request that the system enter the given suspend state. All /dev/apm
3332 * devices and devd(8) will be notified. Userland then has a chance to
3333 * save state and acknowledge the request. The system sleeps once all
3334 * acks are in.
3335 */
3336 int
acpi_ReqSleepState(struct acpi_softc * sc,enum power_stype stype)3337 acpi_ReqSleepState(struct acpi_softc *sc, enum power_stype stype)
3338 {
3339 #if defined(__amd64__) || defined(__i386__)
3340 struct apm_clone_data *clone;
3341 ACPI_STATUS status;
3342
3343 if (stype < POWER_STYPE_AWAKE || stype >= POWER_STYPE_COUNT)
3344 return (EINVAL);
3345 if (!acpi_supported_stypes[stype])
3346 return (EOPNOTSUPP);
3347
3348 /*
3349 * If a reboot/shutdown/suspend request is already in progress or
3350 * suspend is blocked due to an upcoming shutdown, just return.
3351 */
3352 if (rebooting || sc->acpi_next_stype != POWER_STYPE_AWAKE ||
3353 suspend_blocked)
3354 return (0);
3355
3356 /* Wait until sleep is enabled. */
3357 while (sc->acpi_sleep_disabled) {
3358 AcpiOsSleep(1000);
3359 }
3360
3361 ACPI_LOCK(acpi);
3362
3363 sc->acpi_next_stype = stype;
3364
3365 /* S5 (soft-off) should be entered directly with no waiting. */
3366 if (stype == POWER_STYPE_POWEROFF) {
3367 ACPI_UNLOCK(acpi);
3368 status = acpi_EnterSleepState(sc, stype);
3369 return (ACPI_SUCCESS(status) ? 0 : ENXIO);
3370 }
3371
3372 /* Record the pending state and notify all apm devices. */
3373 STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
3374 clone->notify_status = APM_EV_NONE;
3375 if ((clone->flags & ACPI_EVF_DEVD) == 0) {
3376 selwakeuppri(&clone->sel_read, PZERO);
3377 KNOTE_LOCKED(&clone->sel_read.si_note, 0);
3378 }
3379 }
3380
3381 /* If devd(8) is not running, immediately enter the sleep state. */
3382 if (!devctl_process_running()) {
3383 ACPI_UNLOCK(acpi);
3384 status = acpi_EnterSleepState(sc, stype);
3385 return (ACPI_SUCCESS(status) ? 0 : ENXIO);
3386 }
3387
3388 /*
3389 * Set a timeout to fire if userland doesn't ack the suspend request
3390 * in time. This way we still eventually go to sleep if we were
3391 * overheating or running low on battery, even if userland is hung.
3392 * We cancel this timeout once all userland acks are in or the
3393 * suspend request is aborted.
3394 */
3395 callout_reset(&sc->susp_force_to, 10 * hz, acpi_sleep_force, sc);
3396 ACPI_UNLOCK(acpi);
3397
3398 /* Now notify devd(8) also. */
3399 acpi_UserNotify("Suspend", ACPI_ROOT_OBJECT, stype);
3400
3401 return (0);
3402 #else
3403 device_printf(sc->acpi_dev, "ACPI suspend not supported on this platform "
3404 "(TODO suspend to idle should be, however)\n");
3405 return (EOPNOTSUPP);
3406 #endif
3407 }
3408
3409 /*
3410 * Acknowledge (or reject) a pending sleep state. The caller has
3411 * prepared for suspend and is now ready for it to proceed. If the
3412 * error argument is non-zero, it indicates suspend should be cancelled
3413 * and gives an errno value describing why. Once all votes are in,
3414 * we suspend the system.
3415 */
3416 int
acpi_AckSleepState(struct apm_clone_data * clone,int error)3417 acpi_AckSleepState(struct apm_clone_data *clone, int error)
3418 {
3419 struct acpi_softc *sc = clone->acpi_sc;
3420
3421 #if defined(__amd64__) || defined(__i386__)
3422 int ret, sleeping;
3423
3424 /* If no pending sleep type, return an error. */
3425 ACPI_LOCK(acpi);
3426 if (sc->acpi_next_stype == POWER_STYPE_AWAKE) {
3427 ACPI_UNLOCK(acpi);
3428 return (ENXIO);
3429 }
3430
3431 /* Caller wants to abort suspend process. */
3432 if (error) {
3433 sc->acpi_next_stype = POWER_STYPE_AWAKE;
3434 callout_stop(&sc->susp_force_to);
3435 device_printf(sc->acpi_dev,
3436 "listener on %s cancelled the pending suspend\n",
3437 devtoname(clone->cdev));
3438 ACPI_UNLOCK(acpi);
3439 return (0);
3440 }
3441
3442 /*
3443 * Mark this device as acking the suspend request. Then, walk through
3444 * all devices, seeing if they agree yet. We only count devices that
3445 * are writable since read-only devices couldn't ack the request.
3446 */
3447 sleeping = TRUE;
3448 clone->notify_status = APM_EV_ACKED;
3449 STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
3450 if ((clone->flags & ACPI_EVF_WRITE) != 0 &&
3451 clone->notify_status != APM_EV_ACKED) {
3452 sleeping = FALSE;
3453 break;
3454 }
3455 }
3456
3457 /* If all devices have voted "yes", we will suspend now. */
3458 if (sleeping)
3459 callout_stop(&sc->susp_force_to);
3460 ACPI_UNLOCK(acpi);
3461 ret = 0;
3462 if (sleeping) {
3463 if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_stype)))
3464 ret = ENODEV;
3465 }
3466 return (ret);
3467 #else
3468 device_printf(sc->acpi_dev, "ACPI suspend not supported on this platform "
3469 "(TODO suspend to idle should be, however)\n");
3470 return (EOPNOTSUPP);
3471 #endif
3472 }
3473
3474 static void
acpi_sleep_enable(void * arg)3475 acpi_sleep_enable(void *arg)
3476 {
3477 struct acpi_softc *sc = (struct acpi_softc *)arg;
3478
3479 ACPI_LOCK_ASSERT(acpi);
3480
3481 /* Reschedule if the system is not fully up and running. */
3482 if (!AcpiGbl_SystemAwakeAndRunning) {
3483 callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3484 return;
3485 }
3486
3487 sc->acpi_sleep_disabled = FALSE;
3488 }
3489
3490 static ACPI_STATUS
acpi_sleep_disable(struct acpi_softc * sc)3491 acpi_sleep_disable(struct acpi_softc *sc)
3492 {
3493 ACPI_STATUS status;
3494
3495 /* Fail if the system is not fully up and running. */
3496 if (!AcpiGbl_SystemAwakeAndRunning)
3497 return (AE_ERROR);
3498
3499 ACPI_LOCK(acpi);
3500 status = sc->acpi_sleep_disabled ? AE_ERROR : AE_OK;
3501 sc->acpi_sleep_disabled = TRUE;
3502 ACPI_UNLOCK(acpi);
3503
3504 return (status);
3505 }
3506
3507 enum acpi_sleep_state {
3508 ACPI_SS_NONE = 0,
3509 ACPI_SS_GPE_SET = 1 << 0,
3510 ACPI_SS_DEV_SUSPEND = 1 << 1,
3511 ACPI_SS_SLP_PREP = 1 << 2,
3512 ACPI_SS_SLEPT = 1 << 3,
3513 };
3514
3515 static void
do_standby(struct acpi_softc * sc,enum acpi_sleep_state * slp_state,register_t rflags)3516 do_standby(struct acpi_softc *sc, enum acpi_sleep_state *slp_state,
3517 register_t rflags)
3518 {
3519 ACPI_STATUS status;
3520
3521 status = AcpiEnterSleepState(sc->acpi_standby_sx);
3522 intr_restore(rflags);
3523 AcpiLeaveSleepStatePrep(sc->acpi_standby_sx);
3524 if (ACPI_FAILURE(status)) {
3525 device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
3526 AcpiFormatException(status));
3527 return;
3528 }
3529 *slp_state |= ACPI_SS_SLEPT;
3530 }
3531
3532 static void
do_sleep(struct acpi_softc * sc,enum acpi_sleep_state * slp_state,register_t rflags,int state)3533 do_sleep(struct acpi_softc *sc, enum acpi_sleep_state *slp_state,
3534 register_t rflags, int state)
3535 {
3536 int sleep_result;
3537 ACPI_EVENT_STATUS power_button_status;
3538
3539 MPASS(state == ACPI_STATE_S3 || state == ACPI_STATE_S4);
3540
3541 sleep_result = acpi_sleep_machdep(sc, state);
3542 acpi_wakeup_machdep(sc, state, sleep_result, 0);
3543
3544 if (sleep_result == 1 && state == ACPI_STATE_S3) {
3545 /*
3546 * XXX According to ACPI specification SCI_EN bit should be restored
3547 * by ACPI platform (BIOS, firmware) to its pre-sleep state.
3548 * Unfortunately some BIOSes fail to do that and that leads to
3549 * unexpected and serious consequences during wake up like a system
3550 * getting stuck in SMI handlers.
3551 * This hack is picked up from Linux, which claims that it follows
3552 * Windows behavior.
3553 */
3554 AcpiWriteBitRegister(ACPI_BITREG_SCI_ENABLE, ACPI_ENABLE_EVENT);
3555
3556 /*
3557 * Prevent misinterpretation of the wakeup by power button
3558 * as a request for power off.
3559 * Ideally we should post an appropriate wakeup event,
3560 * perhaps using acpi_event_power_button_wake or alike.
3561 *
3562 * Clearing of power button status after wakeup is mandated
3563 * by ACPI specification in section "Fixed Power Button".
3564 *
3565 * XXX As of ACPICA 20121114 AcpiGetEventStatus provides
3566 * status as 0/1 corresponding to inactive/active despite
3567 * its type being ACPI_EVENT_STATUS. In other words,
3568 * we should not test for ACPI_EVENT_FLAG_SET for time being.
3569 */
3570 if (ACPI_SUCCESS(AcpiGetEventStatus(ACPI_EVENT_POWER_BUTTON,
3571 &power_button_status)) && power_button_status != 0) {
3572 AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
3573 device_printf(sc->acpi_dev, "cleared fixed power button status\n");
3574 }
3575 }
3576
3577 intr_restore(rflags);
3578
3579 /* call acpi_wakeup_machdep() again with interrupt enabled */
3580 acpi_wakeup_machdep(sc, state, sleep_result, 1);
3581
3582 AcpiLeaveSleepStatePrep(state);
3583
3584 if (sleep_result == -1)
3585 return;
3586
3587 /* Re-enable ACPI hardware on wakeup from sleep state 4. */
3588 if (state == ACPI_STATE_S4)
3589 AcpiEnable();
3590 *slp_state |= ACPI_SS_SLEPT;
3591 }
3592
3593 #if defined(__i386__) || defined(__amd64__)
3594 static void
do_idle(struct acpi_softc * sc,enum acpi_sleep_state * slp_state,register_t rflags)3595 do_idle(struct acpi_softc *sc, enum acpi_sleep_state *slp_state,
3596 register_t rflags)
3597 {
3598
3599 intr_suspend();
3600
3601 /*
3602 * The CPU will exit idle when interrupted, so we want to minimize the
3603 * number of interrupts it can receive while idle. We do this by only
3604 * allowing SCI (system control interrupt) interrupts, which are used by
3605 * the ACPI firmware to send wake GPEs to the OS.
3606 *
3607 * XXX We might still receive other spurious non-wake GPEs from noisy
3608 * devices that can't be disabled, so this will need to end up being a
3609 * suspend-to-idle loop which, when breaking out of idle, will check the
3610 * reason for the wakeup and immediately idle the CPU again if it was not a
3611 * proper wake event.
3612 */
3613 intr_enable_src(AcpiGbl_FADT.SciInterrupt);
3614
3615 cpu_idle(0);
3616
3617 intr_resume(false);
3618 intr_restore(rflags);
3619 *slp_state |= ACPI_SS_SLEPT;
3620 }
3621 #endif
3622
3623 /*
3624 * Enter the desired system sleep state.
3625 *
3626 * Currently we support S1-S5 and suspend-to-idle, but S4 is only S4BIOS.
3627 */
3628 static ACPI_STATUS
acpi_EnterSleepState(struct acpi_softc * sc,enum power_stype stype)3629 acpi_EnterSleepState(struct acpi_softc *sc, enum power_stype stype)
3630 {
3631 register_t intr;
3632 ACPI_STATUS status;
3633 enum acpi_sleep_state slp_state;
3634 int acpi_sstate;
3635
3636 ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, stype);
3637
3638 if (stype <= POWER_STYPE_AWAKE || stype >= POWER_STYPE_COUNT)
3639 return_ACPI_STATUS (AE_BAD_PARAMETER);
3640 if (!acpi_supported_stypes[stype]) {
3641 device_printf(sc->acpi_dev, "Sleep type %s not supported on this "
3642 "platform\n", power_stype_to_name(stype));
3643 return (AE_SUPPORT);
3644 }
3645
3646 acpi_sstate = acpi_stype_to_sstate(sc, stype);
3647
3648 /* Re-entry once we're suspending is not allowed. */
3649 status = acpi_sleep_disable(sc);
3650 if (ACPI_FAILURE(status)) {
3651 device_printf(sc->acpi_dev,
3652 "suspend request ignored (not ready yet)\n");
3653 return (status);
3654 }
3655
3656 if (stype == POWER_STYPE_POWEROFF) {
3657 /*
3658 * Shut down cleanly and power off. This will call us back through the
3659 * shutdown handlers.
3660 */
3661 shutdown_nice(RB_POWEROFF);
3662 return_ACPI_STATUS (AE_OK);
3663 }
3664
3665 EVENTHANDLER_INVOKE(power_suspend_early, stype);
3666 stop_all_proc();
3667 suspend_all_fs();
3668 EVENTHANDLER_INVOKE(power_suspend, stype);
3669
3670 #ifdef EARLY_AP_STARTUP
3671 MPASS(mp_ncpus == 1 || smp_started);
3672 thread_lock(curthread);
3673 sched_bind(curthread, 0);
3674 thread_unlock(curthread);
3675 #else
3676 if (smp_started) {
3677 thread_lock(curthread);
3678 sched_bind(curthread, 0);
3679 thread_unlock(curthread);
3680 }
3681 #endif
3682
3683 /*
3684 * Be sure to hold bus topology lock across DEVICE_SUSPEND/RESUME.
3685 */
3686 bus_topo_lock();
3687
3688 slp_state = ACPI_SS_NONE;
3689
3690 sc->acpi_stype = stype;
3691
3692 /* Enable any GPEs as appropriate and requested by the user. */
3693 acpi_wake_prep_walk(sc, stype);
3694 slp_state |= ACPI_SS_GPE_SET;
3695
3696 /*
3697 * Inform all devices that we are going to sleep. If at least one
3698 * device fails, DEVICE_SUSPEND() automatically resumes the tree.
3699 *
3700 * XXX Note that a better two-pass approach with a 'veto' pass
3701 * followed by a "real thing" pass would be better, but the current
3702 * bus interface does not provide for this.
3703 */
3704 if (DEVICE_SUSPEND(root_bus) != 0) {
3705 device_printf(sc->acpi_dev, "device_suspend failed\n");
3706 goto backout;
3707 }
3708 EVENTHANDLER_INVOKE(acpi_post_dev_suspend, stype);
3709 slp_state |= ACPI_SS_DEV_SUSPEND;
3710
3711 if (stype != POWER_STYPE_SUSPEND_TO_IDLE) {
3712 status = acpi_EnterSleepStatePrep(sc->acpi_dev, acpi_sstate);
3713 if (ACPI_FAILURE(status))
3714 goto backout;
3715 slp_state |= ACPI_SS_SLP_PREP;
3716 }
3717
3718 if (sc->acpi_sleep_delay > 0)
3719 DELAY(sc->acpi_sleep_delay * 1000000);
3720
3721 suspendclock();
3722 intr = intr_disable();
3723 switch (stype) {
3724 case POWER_STYPE_STANDBY:
3725 do_standby(sc, &slp_state, intr);
3726 break;
3727 case POWER_STYPE_FW_SUSPEND:
3728 case POWER_STYPE_FW_HIBERNATE:
3729 do_sleep(sc, &slp_state, intr, acpi_sstate);
3730 break;
3731 case POWER_STYPE_SUSPEND_TO_IDLE:
3732 #if defined(__i386__) || defined(__amd64__)
3733 do_idle(sc, &slp_state, intr);
3734 break;
3735 #endif
3736 case POWER_STYPE_AWAKE:
3737 case POWER_STYPE_POWEROFF:
3738 case POWER_STYPE_COUNT:
3739 case POWER_STYPE_UNKNOWN:
3740 __unreachable();
3741 }
3742 resumeclock();
3743
3744 /*
3745 * Back out state according to how far along we got in the suspend
3746 * process. This handles both the error and success cases.
3747 */
3748 backout:
3749 if ((slp_state & ACPI_SS_GPE_SET) != 0) {
3750 acpi_wake_prep_walk(sc, stype);
3751 sc->acpi_stype = POWER_STYPE_AWAKE;
3752 slp_state &= ~ACPI_SS_GPE_SET;
3753 }
3754 if ((slp_state & ACPI_SS_DEV_SUSPEND) != 0) {
3755 EVENTHANDLER_INVOKE(acpi_pre_dev_resume, stype);
3756 DEVICE_RESUME(root_bus);
3757 slp_state &= ~ACPI_SS_DEV_SUSPEND;
3758 }
3759 if ((slp_state & ACPI_SS_SLP_PREP) != 0) {
3760 AcpiLeaveSleepState(acpi_sstate);
3761 slp_state &= ~ACPI_SS_SLP_PREP;
3762 }
3763 if ((slp_state & ACPI_SS_SLEPT) != 0) {
3764 #if defined(__i386__) || defined(__amd64__)
3765 /* NB: we are still using ACPI timecounter at this point. */
3766 resume_TSC();
3767 #endif
3768 acpi_resync_clock(sc);
3769 acpi_enable_fixed_events(sc);
3770 slp_state &= ~ACPI_SS_SLEPT;
3771 }
3772 sc->acpi_next_stype = POWER_STYPE_AWAKE;
3773
3774 MPASS(slp_state == ACPI_SS_NONE);
3775
3776 bus_topo_unlock();
3777
3778 #ifdef EARLY_AP_STARTUP
3779 thread_lock(curthread);
3780 sched_unbind(curthread);
3781 thread_unlock(curthread);
3782 #else
3783 if (smp_started) {
3784 thread_lock(curthread);
3785 sched_unbind(curthread);
3786 thread_unlock(curthread);
3787 }
3788 #endif
3789
3790 resume_all_fs();
3791 resume_all_proc();
3792
3793 EVENTHANDLER_INVOKE(power_resume, stype);
3794
3795 /* Allow another sleep request after a while. */
3796 callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3797
3798 /* Run /etc/rc.resume after we are back. */
3799 if (devctl_process_running())
3800 acpi_UserNotify("Resume", ACPI_ROOT_OBJECT, stype);
3801
3802 return_ACPI_STATUS (status);
3803 }
3804
3805 static void
acpi_resync_clock(struct acpi_softc * sc)3806 acpi_resync_clock(struct acpi_softc *sc)
3807 {
3808
3809 /*
3810 * Warm up timecounter again and reset system clock.
3811 */
3812 (void)timecounter->tc_get_timecount(timecounter);
3813 inittodr(time_second + sc->acpi_sleep_delay);
3814 }
3815
3816 /* Enable or disable the device's wake GPE. */
3817 int
acpi_wake_set_enable(device_t dev,int enable)3818 acpi_wake_set_enable(device_t dev, int enable)
3819 {
3820 struct acpi_prw_data prw;
3821 ACPI_STATUS status;
3822 int flags;
3823
3824 /* Make sure the device supports waking the system and get the GPE. */
3825 if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
3826 return (ENXIO);
3827
3828 flags = acpi_get_flags(dev);
3829 if (enable) {
3830 status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3831 ACPI_GPE_ENABLE);
3832 if (ACPI_FAILURE(status)) {
3833 device_printf(dev, "enable wake failed\n");
3834 return (ENXIO);
3835 }
3836 acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
3837 } else {
3838 status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3839 ACPI_GPE_DISABLE);
3840 if (ACPI_FAILURE(status)) {
3841 device_printf(dev, "disable wake failed\n");
3842 return (ENXIO);
3843 }
3844 acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
3845 }
3846
3847 return (0);
3848 }
3849
3850 static int
acpi_wake_sleep_prep(struct acpi_softc * sc,ACPI_HANDLE handle,enum power_stype stype)3851 acpi_wake_sleep_prep(struct acpi_softc *sc, ACPI_HANDLE handle,
3852 enum power_stype stype)
3853 {
3854 int sstate;
3855 struct acpi_prw_data prw;
3856 device_t dev;
3857
3858 /* Check that this is a wake-capable device and get its GPE. */
3859 if (acpi_parse_prw(handle, &prw) != 0)
3860 return (ENXIO);
3861 dev = acpi_get_device(handle);
3862
3863 sstate = acpi_stype_to_sstate(sc, stype);
3864
3865 /*
3866 * The destination sleep state must be less than (i.e., higher power)
3867 * or equal to the value specified by _PRW. If this GPE cannot be
3868 * enabled for the next sleep state, then disable it. If it can and
3869 * the user requested it be enabled, turn on any required power resources
3870 * and set _PSW.
3871 */
3872 if (sstate > prw.lowest_wake) {
3873 AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_DISABLE);
3874 if (bootverbose)
3875 device_printf(dev, "wake_prep disabled wake for %s (%s)\n",
3876 acpi_name(handle), power_stype_to_name(stype));
3877 } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
3878 acpi_pwr_wake_enable(handle, 1);
3879 acpi_SetInteger(handle, "_PSW", 1);
3880 if (bootverbose)
3881 device_printf(dev, "wake_prep enabled for %s (%s)\n",
3882 acpi_name(handle), power_stype_to_name(stype));
3883 }
3884
3885 return (0);
3886 }
3887
3888 static int
acpi_wake_run_prep(struct acpi_softc * sc,ACPI_HANDLE handle,enum power_stype stype)3889 acpi_wake_run_prep(struct acpi_softc *sc, ACPI_HANDLE handle,
3890 enum power_stype stype)
3891 {
3892 int sstate;
3893 struct acpi_prw_data prw;
3894 device_t dev;
3895
3896 /*
3897 * Check that this is a wake-capable device and get its GPE. Return
3898 * now if the user didn't enable this device for wake.
3899 */
3900 if (acpi_parse_prw(handle, &prw) != 0)
3901 return (ENXIO);
3902 dev = acpi_get_device(handle);
3903 if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
3904 return (0);
3905
3906 sstate = acpi_stype_to_sstate(sc, stype);
3907
3908 /*
3909 * If this GPE couldn't be enabled for the previous sleep state, it was
3910 * disabled before going to sleep so re-enable it. If it was enabled,
3911 * clear _PSW and turn off any power resources it used.
3912 */
3913 if (sstate > prw.lowest_wake) {
3914 AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_ENABLE);
3915 if (bootverbose)
3916 device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
3917 } else {
3918 acpi_SetInteger(handle, "_PSW", 0);
3919 acpi_pwr_wake_enable(handle, 0);
3920 if (bootverbose)
3921 device_printf(dev, "run_prep cleaned up for %s\n",
3922 acpi_name(handle));
3923 }
3924
3925 return (0);
3926 }
3927
3928 static ACPI_STATUS
acpi_wake_prep(ACPI_HANDLE handle,UINT32 level,void * context,void ** status)3929 acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
3930 {
3931 struct acpi_wake_prep_context *ctx = context;
3932
3933 /* If suspending, run the sleep prep function, otherwise wake. */
3934 if (AcpiGbl_SystemAwakeAndRunning)
3935 acpi_wake_sleep_prep(ctx->sc, handle, ctx->stype);
3936 else
3937 acpi_wake_run_prep(ctx->sc, handle, ctx->stype);
3938 return (AE_OK);
3939 }
3940
3941 /* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
3942 static int
acpi_wake_prep_walk(struct acpi_softc * sc,enum power_stype stype)3943 acpi_wake_prep_walk(struct acpi_softc *sc, enum power_stype stype)
3944 {
3945 ACPI_HANDLE sb_handle;
3946 struct acpi_wake_prep_context ctx = {
3947 .sc = sc,
3948 .stype = stype,
3949 };
3950
3951 if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
3952 AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
3953 acpi_wake_prep, NULL, &ctx, NULL);
3954 return (0);
3955 }
3956
3957 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
3958 static int
acpi_wake_sysctl_walk(device_t dev)3959 acpi_wake_sysctl_walk(device_t dev)
3960 {
3961 int error, i, numdevs;
3962 device_t *devlist;
3963 device_t child;
3964 ACPI_STATUS status;
3965
3966 error = device_get_children(dev, &devlist, &numdevs);
3967 if (error != 0 || numdevs == 0) {
3968 if (numdevs == 0)
3969 free(devlist, M_TEMP);
3970 return (error);
3971 }
3972 for (i = 0; i < numdevs; i++) {
3973 child = devlist[i];
3974 acpi_wake_sysctl_walk(child);
3975 if (!device_is_attached(child) || !acpi_has_flags(child))
3976 continue;
3977 status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
3978 if (ACPI_SUCCESS(status)) {
3979 SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
3980 SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
3981 "wake", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, child, 0,
3982 acpi_wake_set_sysctl, "I", "Device set to wake the system");
3983 }
3984 }
3985 free(devlist, M_TEMP);
3986
3987 return (0);
3988 }
3989
3990 /* Enable or disable wake from userland. */
3991 static int
acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)3992 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
3993 {
3994 int enable, error;
3995 device_t dev;
3996
3997 dev = (device_t)arg1;
3998 enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
3999
4000 error = sysctl_handle_int(oidp, &enable, 0, req);
4001 if (error != 0 || req->newptr == NULL)
4002 return (error);
4003 if (enable != 0 && enable != 1)
4004 return (EINVAL);
4005
4006 return (acpi_wake_set_enable(dev, enable));
4007 }
4008
4009 /* Parse a device's _PRW into a structure. */
4010 int
acpi_parse_prw(ACPI_HANDLE h,struct acpi_prw_data * prw)4011 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
4012 {
4013 ACPI_STATUS status;
4014 ACPI_BUFFER prw_buffer;
4015 ACPI_OBJECT *res, *res2;
4016 int error, i, power_count;
4017
4018 if (h == NULL || prw == NULL)
4019 return (EINVAL);
4020
4021 /*
4022 * The _PRW object (7.2.9) is only required for devices that have the
4023 * ability to wake the system from a sleeping state.
4024 */
4025 error = EINVAL;
4026 prw_buffer.Pointer = NULL;
4027 prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
4028 status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
4029 if (ACPI_FAILURE(status))
4030 return (ENOENT);
4031 res = (ACPI_OBJECT *)prw_buffer.Pointer;
4032 if (res == NULL)
4033 return (ENOENT);
4034 if (!ACPI_PKG_VALID(res, 2))
4035 goto out;
4036
4037 /*
4038 * Element 1 of the _PRW object:
4039 * The lowest power system sleeping state that can be entered while still
4040 * providing wake functionality. The sleeping state being entered must
4041 * be less than (i.e., higher power) or equal to this value.
4042 */
4043 if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
4044 goto out;
4045
4046 /*
4047 * Element 0 of the _PRW object:
4048 */
4049 switch (res->Package.Elements[0].Type) {
4050 case ACPI_TYPE_INTEGER:
4051 /*
4052 * If the data type of this package element is numeric, then this
4053 * _PRW package element is the bit index in the GPEx_EN, in the
4054 * GPE blocks described in the FADT, of the enable bit that is
4055 * enabled for the wake event.
4056 */
4057 prw->gpe_handle = NULL;
4058 prw->gpe_bit = res->Package.Elements[0].Integer.Value;
4059 error = 0;
4060 break;
4061 case ACPI_TYPE_PACKAGE:
4062 /*
4063 * If the data type of this package element is a package, then this
4064 * _PRW package element is itself a package containing two
4065 * elements. The first is an object reference to the GPE Block
4066 * device that contains the GPE that will be triggered by the wake
4067 * event. The second element is numeric and it contains the bit
4068 * index in the GPEx_EN, in the GPE Block referenced by the
4069 * first element in the package, of the enable bit that is enabled for
4070 * the wake event.
4071 *
4072 * For example, if this field is a package then it is of the form:
4073 * Package() {\_SB.PCI0.ISA.GPE, 2}
4074 */
4075 res2 = &res->Package.Elements[0];
4076 if (!ACPI_PKG_VALID(res2, 2))
4077 goto out;
4078 prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
4079 if (prw->gpe_handle == NULL)
4080 goto out;
4081 if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
4082 goto out;
4083 error = 0;
4084 break;
4085 default:
4086 goto out;
4087 }
4088
4089 /* Elements 2 to N of the _PRW object are power resources. */
4090 power_count = res->Package.Count - 2;
4091 if (power_count > ACPI_PRW_MAX_POWERRES) {
4092 printf("ACPI device %s has too many power resources\n", acpi_name(h));
4093 power_count = 0;
4094 }
4095 prw->power_res_count = power_count;
4096 for (i = 0; i < power_count; i++)
4097 prw->power_res[i] = res->Package.Elements[i];
4098
4099 out:
4100 if (prw_buffer.Pointer != NULL)
4101 AcpiOsFree(prw_buffer.Pointer);
4102 return (error);
4103 }
4104
4105 /*
4106 * ACPI Event Handlers
4107 */
4108
4109 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
4110
4111 static void
acpi_system_eventhandler_sleep(void * arg,enum power_stype stype)4112 acpi_system_eventhandler_sleep(void *arg, enum power_stype stype)
4113 {
4114 struct acpi_softc *sc = (struct acpi_softc *)arg;
4115 int ret;
4116
4117 ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, stype);
4118
4119 /* Check if button action is disabled or unknown. */
4120 if (stype == POWER_STYPE_UNKNOWN)
4121 return;
4122
4123 /*
4124 * Request that the system prepare to enter the given suspend state. We can
4125 * totally pass an ACPI S-state to an enum power_stype.
4126 */
4127 ret = acpi_ReqSleepState(sc, stype);
4128 if (ret != 0)
4129 device_printf(sc->acpi_dev,
4130 "request to enter state %s failed (err %d)\n",
4131 power_stype_to_name(stype), ret);
4132
4133 return_VOID;
4134 }
4135
4136 static void
acpi_system_eventhandler_wakeup(void * arg,enum power_stype stype)4137 acpi_system_eventhandler_wakeup(void *arg, enum power_stype stype)
4138 {
4139
4140 ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, stype);
4141
4142 /* Currently, nothing to do for wakeup. */
4143
4144 return_VOID;
4145 }
4146
4147 /*
4148 * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
4149 */
4150 static void
acpi_invoke_sleep_eventhandler(void * context)4151 acpi_invoke_sleep_eventhandler(void *context)
4152 {
4153
4154 EVENTHANDLER_INVOKE(acpi_sleep_event, *(enum power_stype *)context);
4155 }
4156
4157 static void
acpi_invoke_wake_eventhandler(void * context)4158 acpi_invoke_wake_eventhandler(void *context)
4159 {
4160
4161 EVENTHANDLER_INVOKE(acpi_wakeup_event, *(enum power_stype *)context);
4162 }
4163
4164 UINT32
acpi_event_power_button_sleep(void * context)4165 acpi_event_power_button_sleep(void *context)
4166 {
4167 #if defined(__amd64__) || defined(__i386__)
4168 struct acpi_softc *sc = (struct acpi_softc *)context;
4169 #else
4170 (void)context;
4171 #endif
4172
4173 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
4174
4175 #if defined(__amd64__) || defined(__i386__)
4176 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
4177 acpi_invoke_sleep_eventhandler, &sc->acpi_power_button_stype)))
4178 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
4179 #else
4180 shutdown_nice(RB_POWEROFF);
4181 #endif
4182
4183 return_VALUE (ACPI_INTERRUPT_HANDLED);
4184 }
4185
4186 UINT32
acpi_event_power_button_wake(void * context)4187 acpi_event_power_button_wake(void *context)
4188 {
4189 struct acpi_softc *sc = (struct acpi_softc *)context;
4190
4191 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
4192
4193 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
4194 acpi_invoke_wake_eventhandler, &sc->acpi_power_button_stype)))
4195 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
4196 return_VALUE (ACPI_INTERRUPT_HANDLED);
4197 }
4198
4199 UINT32
acpi_event_sleep_button_sleep(void * context)4200 acpi_event_sleep_button_sleep(void *context)
4201 {
4202 struct acpi_softc *sc = (struct acpi_softc *)context;
4203
4204 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
4205
4206 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
4207 acpi_invoke_sleep_eventhandler, &sc->acpi_sleep_button_stype)))
4208 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
4209 return_VALUE (ACPI_INTERRUPT_HANDLED);
4210 }
4211
4212 UINT32
acpi_event_sleep_button_wake(void * context)4213 acpi_event_sleep_button_wake(void *context)
4214 {
4215 struct acpi_softc *sc = (struct acpi_softc *)context;
4216
4217 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
4218
4219 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
4220 acpi_invoke_wake_eventhandler, &sc->acpi_sleep_button_stype)))
4221 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
4222 return_VALUE (ACPI_INTERRUPT_HANDLED);
4223 }
4224
4225 /*
4226 * XXX This static buffer is suboptimal. There is no locking so only
4227 * use this for single-threaded callers.
4228 */
4229 char *
acpi_name(ACPI_HANDLE handle)4230 acpi_name(ACPI_HANDLE handle)
4231 {
4232 ACPI_BUFFER buf;
4233 static char data[256];
4234
4235 buf.Length = sizeof(data);
4236 buf.Pointer = data;
4237
4238 if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
4239 return (data);
4240 return ("(unknown)");
4241 }
4242
4243 /*
4244 * Debugging/bug-avoidance. Avoid trying to fetch info on various
4245 * parts of the namespace.
4246 */
4247 int
acpi_avoid(ACPI_HANDLE handle)4248 acpi_avoid(ACPI_HANDLE handle)
4249 {
4250 char *cp, *env, *np;
4251 int len;
4252
4253 np = acpi_name(handle);
4254 if (*np == '\\')
4255 np++;
4256 if ((env = kern_getenv("debug.acpi.avoid")) == NULL)
4257 return (0);
4258
4259 /* Scan the avoid list checking for a match */
4260 cp = env;
4261 for (;;) {
4262 while (*cp != 0 && isspace(*cp))
4263 cp++;
4264 if (*cp == 0)
4265 break;
4266 len = 0;
4267 while (cp[len] != 0 && !isspace(cp[len]))
4268 len++;
4269 if (!strncmp(cp, np, len)) {
4270 freeenv(env);
4271 return(1);
4272 }
4273 cp += len;
4274 }
4275 freeenv(env);
4276
4277 return (0);
4278 }
4279
4280 /*
4281 * Debugging/bug-avoidance. Disable ACPI subsystem components.
4282 */
4283 int
acpi_disabled(char * subsys)4284 acpi_disabled(char *subsys)
4285 {
4286 char *cp, *env;
4287 int len;
4288
4289 if ((env = kern_getenv("debug.acpi.disabled")) == NULL)
4290 return (0);
4291 if (strcmp(env, "all") == 0) {
4292 freeenv(env);
4293 return (1);
4294 }
4295
4296 /* Scan the disable list, checking for a match. */
4297 cp = env;
4298 for (;;) {
4299 while (*cp != '\0' && isspace(*cp))
4300 cp++;
4301 if (*cp == '\0')
4302 break;
4303 len = 0;
4304 while (cp[len] != '\0' && !isspace(cp[len]))
4305 len++;
4306 if (strncmp(cp, subsys, len) == 0) {
4307 freeenv(env);
4308 return (1);
4309 }
4310 cp += len;
4311 }
4312 freeenv(env);
4313
4314 return (0);
4315 }
4316
4317 static void
acpi_lookup(void * arg,const char * name,device_t * dev)4318 acpi_lookup(void *arg, const char *name, device_t *dev)
4319 {
4320 ACPI_HANDLE handle;
4321
4322 if (*dev != NULL)
4323 return;
4324
4325 /*
4326 * Allow any handle name that is specified as an absolute path and
4327 * starts with '\'. We could restrict this to \_SB and friends,
4328 * but see acpi_probe_children() for notes on why we scan the entire
4329 * namespace for devices.
4330 *
4331 * XXX: The pathname argument to AcpiGetHandle() should be fixed to
4332 * be const.
4333 */
4334 if (name[0] != '\\')
4335 return;
4336 if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, __DECONST(char *, name),
4337 &handle)))
4338 return;
4339 *dev = acpi_get_device(handle);
4340 }
4341
4342 /*
4343 * Control interface.
4344 *
4345 * We multiplex ioctls for all participating ACPI devices here. Individual
4346 * drivers wanting to be accessible via /dev/acpi should use the
4347 * register/deregister interface to make their handlers visible.
4348 */
4349 struct acpi_ioctl_hook
4350 {
4351 TAILQ_ENTRY(acpi_ioctl_hook) link;
4352 u_long cmd;
4353 acpi_ioctl_fn fn;
4354 void *arg;
4355 };
4356
4357 static TAILQ_HEAD(,acpi_ioctl_hook) acpi_ioctl_hooks =
4358 TAILQ_HEAD_INITIALIZER(acpi_ioctl_hooks);
4359
4360 int
acpi_register_ioctl(u_long cmd,acpi_ioctl_fn fn,void * arg)4361 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
4362 {
4363 struct acpi_ioctl_hook *hp, *thp;
4364
4365 hp = malloc(sizeof(*hp), M_ACPIDEV, M_WAITOK);
4366 hp->cmd = cmd;
4367 hp->fn = fn;
4368 hp->arg = arg;
4369
4370 ACPI_LOCK(acpi);
4371 TAILQ_FOREACH(thp, &acpi_ioctl_hooks, link) {
4372 if (thp->cmd == cmd) {
4373 ACPI_UNLOCK(acpi);
4374 free(hp, M_ACPIDEV);
4375 return (EBUSY);
4376 }
4377 }
4378
4379 TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
4380 ACPI_UNLOCK(acpi);
4381
4382 return (0);
4383 }
4384
4385 void
acpi_deregister_ioctl(u_long cmd,acpi_ioctl_fn fn)4386 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
4387 {
4388 struct acpi_ioctl_hook *hp;
4389
4390 ACPI_LOCK(acpi);
4391 TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
4392 if (hp->cmd == cmd && hp->fn == fn)
4393 break;
4394
4395 if (hp != NULL) {
4396 TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
4397 free(hp, M_ACPIDEV);
4398 }
4399 ACPI_UNLOCK(acpi);
4400 }
4401
4402 void
acpi_deregister_ioctls(acpi_ioctl_fn fn)4403 acpi_deregister_ioctls(acpi_ioctl_fn fn)
4404 {
4405 struct acpi_ioctl_hook *hp, *thp;
4406
4407 ACPI_LOCK(acpi);
4408 TAILQ_FOREACH_SAFE(hp, &acpi_ioctl_hooks, link, thp) {
4409 if (hp->fn == fn) {
4410 TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
4411 free(hp, M_ACPIDEV);
4412 }
4413 }
4414 ACPI_UNLOCK(acpi);
4415 }
4416
4417 static int
acpiopen(struct cdev * dev,int flag,int fmt,struct thread * td)4418 acpiopen(struct cdev *dev, int flag, int fmt, struct thread *td)
4419 {
4420 return (0);
4421 }
4422
4423 static int
acpiclose(struct cdev * dev,int flag,int fmt,struct thread * td)4424 acpiclose(struct cdev *dev, int flag, int fmt, struct thread *td)
4425 {
4426 return (0);
4427 }
4428
4429 static int
acpiioctl(struct cdev * dev,u_long cmd,caddr_t addr,int flag,struct thread * td)4430 acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
4431 {
4432 struct acpi_softc *sc;
4433 struct acpi_ioctl_hook *hp;
4434 int error;
4435 int sstate;
4436
4437 error = 0;
4438 hp = NULL;
4439 sc = dev->si_drv1;
4440
4441 /*
4442 * Scan the list of registered ioctls, looking for handlers.
4443 */
4444 ACPI_LOCK(acpi);
4445 TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
4446 if (hp->cmd == cmd)
4447 break;
4448 }
4449 ACPI_UNLOCK(acpi);
4450 if (hp)
4451 return (hp->fn(cmd, addr, hp->arg));
4452
4453 /*
4454 * Core ioctls are not permitted for non-writable user.
4455 * Currently, other ioctls just fetch information.
4456 * Not changing system behavior.
4457 */
4458 if ((flag & FWRITE) == 0)
4459 return (EPERM);
4460
4461 /* Core system ioctls. */
4462 switch (cmd) {
4463 case ACPIIO_REQSLPSTATE:
4464 sstate = *(int *)addr;
4465 if (sstate != ACPI_STATE_S5)
4466 return (acpi_ReqSleepState(sc, acpi_sstate_to_stype(sstate)));
4467 device_printf(sc->acpi_dev, "power off via acpi ioctl not supported\n");
4468 error = EOPNOTSUPP;
4469 break;
4470 case ACPIIO_ACKSLPSTATE:
4471 error = *(int *)addr;
4472 error = acpi_AckSleepState(sc->acpi_clone, error);
4473 break;
4474 case ACPIIO_SETSLPSTATE: /* DEPRECATED */
4475 sstate = *(int *)addr;
4476 if (sstate < ACPI_STATE_S0 || sstate > ACPI_STATE_S5)
4477 return (EINVAL);
4478 if (!acpi_supported_sstates[sstate])
4479 return (EOPNOTSUPP);
4480 if (ACPI_FAILURE(acpi_SetSleepState(sc, acpi_sstate_to_stype(sstate))))
4481 error = ENXIO;
4482 break;
4483 default:
4484 error = ENXIO;
4485 break;
4486 }
4487
4488 return (error);
4489 }
4490
4491 static int
acpi_s4bios_sysctl(SYSCTL_HANDLER_ARGS)4492 acpi_s4bios_sysctl(SYSCTL_HANDLER_ARGS)
4493 {
4494 struct acpi_softc *const sc = arg1;
4495 bool val;
4496 int error;
4497
4498 val = sc->acpi_s4bios;
4499 error = sysctl_handle_bool(oidp, &val, 0, req);
4500 if (error != 0 || req->newptr == NULL)
4501 return (error);
4502
4503 if (val && !sc->acpi_s4bios_supported)
4504 return (EOPNOTSUPP);
4505 sc->acpi_s4bios = val;
4506
4507 return (0);
4508 }
4509
4510 static int
acpi_sname_to_sstate(const char * sname)4511 acpi_sname_to_sstate(const char *sname)
4512 {
4513 int sstate;
4514
4515 if (strcasecmp(sname, "NONE") == 0)
4516 return (ACPI_STATE_UNKNOWN);
4517
4518 if (toupper(sname[0]) == 'S') {
4519 sstate = sname[1] - '0';
4520 if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5 &&
4521 sname[2] == '\0')
4522 return (sstate);
4523 }
4524 return (-1);
4525 }
4526
4527 static const char *
acpi_sstate_to_sname(int state)4528 acpi_sstate_to_sname(int state)
4529 {
4530 static const char *snames[ACPI_S_STATE_COUNT] = {"S0", "S1", "S2", "S3",
4531 "S4", "S5"};
4532
4533 if (state == ACPI_STATE_UNKNOWN)
4534 return ("NONE");
4535 if (state >= ACPI_STATE_S0 && state < ACPI_S_STATE_COUNT)
4536 return (snames[state]);
4537 return (NULL);
4538 }
4539
4540 static int
acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)4541 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
4542 {
4543 int error;
4544 struct sbuf sb;
4545 UINT8 state;
4546
4547 sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
4548 for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
4549 if (acpi_supported_sstates[state])
4550 sbuf_printf(&sb, "%s ", acpi_sstate_to_sname(state));
4551 sbuf_trim(&sb);
4552 sbuf_finish(&sb);
4553 error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
4554 sbuf_delete(&sb);
4555 return (error);
4556 }
4557
4558 static int
acpi_suspend_state_sysctl(SYSCTL_HANDLER_ARGS)4559 acpi_suspend_state_sysctl(SYSCTL_HANDLER_ARGS)
4560 {
4561 char name[10];
4562 int err;
4563 struct acpi_softc *sc = oidp->oid_arg1;
4564 enum power_stype new_stype;
4565 enum power_stype old_stype = power_suspend_stype;
4566 int old_sstate = acpi_stype_to_sstate(sc, old_stype);
4567 int new_sstate;
4568
4569 strlcpy(name, acpi_sstate_to_sname(old_sstate), sizeof(name));
4570 err = sysctl_handle_string(oidp, name, sizeof(name), req);
4571 if (err != 0 || req->newptr == NULL)
4572 return (err);
4573
4574 new_sstate = acpi_sname_to_sstate(name);
4575 if (new_sstate < 0)
4576 return (EINVAL);
4577 new_stype = acpi_sstate_to_stype(new_sstate);
4578 if (new_sstate != ACPI_STATE_UNKNOWN &&
4579 acpi_supported_stypes[new_stype] == false)
4580 return (EOPNOTSUPP);
4581
4582 if (new_stype != old_stype)
4583 power_suspend_stype = new_stype;
4584 return (err);
4585 }
4586
4587 static int
acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)4588 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
4589 {
4590 char sleep_state[10];
4591 int error;
4592 int new_sstate, old_sstate;
4593
4594 old_sstate = *(int *)oidp->oid_arg1;
4595 strlcpy(sleep_state, acpi_sstate_to_sname(old_sstate), sizeof(sleep_state));
4596 error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
4597 if (error == 0 && req->newptr != NULL) {
4598 new_sstate = acpi_sname_to_sstate(sleep_state);
4599 if (new_sstate < 0)
4600 return (EINVAL);
4601 if (new_sstate < ACPI_S_STATE_COUNT &&
4602 !acpi_supported_sstates[new_sstate])
4603 return (EOPNOTSUPP);
4604 if (new_sstate != old_sstate)
4605 *(int *)oidp->oid_arg1 = new_sstate;
4606 }
4607 return (error);
4608 }
4609
4610 static int
acpi_stype_sysctl(SYSCTL_HANDLER_ARGS)4611 acpi_stype_sysctl(SYSCTL_HANDLER_ARGS)
4612 {
4613 char name[POWER_STYPE_NAME_LEN];
4614 int err;
4615 int sstate;
4616 enum power_stype new_stype, old_stype;
4617
4618 old_stype = *(enum power_stype *)oidp->oid_arg1;
4619 strlcpy(name, power_stype_to_name(old_stype), sizeof(name));
4620 err = sysctl_handle_string(oidp, name, sizeof(name), req);
4621 if (err != 0 || req->newptr == NULL)
4622 return (err);
4623
4624 if (strcasecmp(name, "NONE") == 0) {
4625 new_stype = POWER_STYPE_UNKNOWN;
4626 } else {
4627 new_stype = power_name_to_stype(name);
4628 if (new_stype == POWER_STYPE_UNKNOWN) {
4629 sstate = acpi_sname_to_sstate(name);
4630 if (sstate < 0)
4631 return (EINVAL);
4632 printf("warning: the 'hw.acpi.%s' sysctl expects a sleep type, but "
4633 "an ACPI S-state has been passed to it. This functionality "
4634 "is deprecated; see acpi(4).\n", oidp->oid_name);
4635 MPASS(sstate < ACPI_S_STATE_COUNT);
4636 if (acpi_supported_sstates[sstate] == false)
4637 return (EOPNOTSUPP);
4638 new_stype = acpi_sstate_to_stype(sstate);
4639 }
4640 if (acpi_supported_stypes[new_stype] == false)
4641 return (EOPNOTSUPP);
4642 }
4643
4644 if (new_stype != old_stype)
4645 *(enum power_stype *)oidp->oid_arg1 = new_stype;
4646 return (0);
4647 }
4648
4649 /* Inform devctl(4) when we receive a Notify. */
4650 void
acpi_UserNotify(const char * subsystem,ACPI_HANDLE h,uint8_t notify)4651 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
4652 {
4653 char notify_buf[16];
4654 ACPI_BUFFER handle_buf;
4655 ACPI_STATUS status;
4656
4657 if (subsystem == NULL)
4658 return;
4659
4660 handle_buf.Pointer = NULL;
4661 handle_buf.Length = ACPI_ALLOCATE_BUFFER;
4662 status = AcpiNsHandleToPathname(h, &handle_buf, FALSE);
4663 if (ACPI_FAILURE(status))
4664 return;
4665 snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
4666 devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
4667 AcpiOsFree(handle_buf.Pointer);
4668 }
4669
4670 #ifdef ACPI_DEBUG
4671 /*
4672 * Support for parsing debug options from the kernel environment.
4673 *
4674 * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
4675 * by specifying the names of the bits in the debug.acpi.layer and
4676 * debug.acpi.level environment variables. Bits may be unset by
4677 * prefixing the bit name with !.
4678 */
4679 struct debugtag
4680 {
4681 char *name;
4682 UINT32 value;
4683 };
4684
4685 static struct debugtag dbg_layer[] = {
4686 {"ACPI_UTILITIES", ACPI_UTILITIES},
4687 {"ACPI_HARDWARE", ACPI_HARDWARE},
4688 {"ACPI_EVENTS", ACPI_EVENTS},
4689 {"ACPI_TABLES", ACPI_TABLES},
4690 {"ACPI_NAMESPACE", ACPI_NAMESPACE},
4691 {"ACPI_PARSER", ACPI_PARSER},
4692 {"ACPI_DISPATCHER", ACPI_DISPATCHER},
4693 {"ACPI_EXECUTER", ACPI_EXECUTER},
4694 {"ACPI_RESOURCES", ACPI_RESOURCES},
4695 {"ACPI_CA_DEBUGGER", ACPI_CA_DEBUGGER},
4696 {"ACPI_OS_SERVICES", ACPI_OS_SERVICES},
4697 {"ACPI_CA_DISASSEMBLER", ACPI_CA_DISASSEMBLER},
4698 {"ACPI_ALL_COMPONENTS", ACPI_ALL_COMPONENTS},
4699
4700 {"ACPI_AC_ADAPTER", ACPI_AC_ADAPTER},
4701 {"ACPI_BATTERY", ACPI_BATTERY},
4702 {"ACPI_BUS", ACPI_BUS},
4703 {"ACPI_BUTTON", ACPI_BUTTON},
4704 {"ACPI_EC", ACPI_EC},
4705 {"ACPI_FAN", ACPI_FAN},
4706 {"ACPI_POWERRES", ACPI_POWERRES},
4707 {"ACPI_PROCESSOR", ACPI_PROCESSOR},
4708 {"ACPI_SPMC", ACPI_SPMC},
4709 {"ACPI_THERMAL", ACPI_THERMAL},
4710 {"ACPI_TIMER", ACPI_TIMER},
4711 {"ACPI_ALL_DRIVERS", ACPI_ALL_DRIVERS},
4712 {NULL, 0}
4713 };
4714
4715 static struct debugtag dbg_level[] = {
4716 {"ACPI_LV_INIT", ACPI_LV_INIT},
4717 {"ACPI_LV_DEBUG_OBJECT", ACPI_LV_DEBUG_OBJECT},
4718 {"ACPI_LV_INFO", ACPI_LV_INFO},
4719 {"ACPI_LV_REPAIR", ACPI_LV_REPAIR},
4720 {"ACPI_LV_ALL_EXCEPTIONS", ACPI_LV_ALL_EXCEPTIONS},
4721
4722 /* Trace verbosity level 1 [Standard Trace Level] */
4723 {"ACPI_LV_INIT_NAMES", ACPI_LV_INIT_NAMES},
4724 {"ACPI_LV_PARSE", ACPI_LV_PARSE},
4725 {"ACPI_LV_LOAD", ACPI_LV_LOAD},
4726 {"ACPI_LV_DISPATCH", ACPI_LV_DISPATCH},
4727 {"ACPI_LV_EXEC", ACPI_LV_EXEC},
4728 {"ACPI_LV_NAMES", ACPI_LV_NAMES},
4729 {"ACPI_LV_OPREGION", ACPI_LV_OPREGION},
4730 {"ACPI_LV_BFIELD", ACPI_LV_BFIELD},
4731 {"ACPI_LV_TABLES", ACPI_LV_TABLES},
4732 {"ACPI_LV_VALUES", ACPI_LV_VALUES},
4733 {"ACPI_LV_OBJECTS", ACPI_LV_OBJECTS},
4734 {"ACPI_LV_RESOURCES", ACPI_LV_RESOURCES},
4735 {"ACPI_LV_USER_REQUESTS", ACPI_LV_USER_REQUESTS},
4736 {"ACPI_LV_PACKAGE", ACPI_LV_PACKAGE},
4737 {"ACPI_LV_VERBOSITY1", ACPI_LV_VERBOSITY1},
4738
4739 /* Trace verbosity level 2 [Function tracing and memory allocation] */
4740 {"ACPI_LV_ALLOCATIONS", ACPI_LV_ALLOCATIONS},
4741 {"ACPI_LV_FUNCTIONS", ACPI_LV_FUNCTIONS},
4742 {"ACPI_LV_OPTIMIZATIONS", ACPI_LV_OPTIMIZATIONS},
4743 {"ACPI_LV_VERBOSITY2", ACPI_LV_VERBOSITY2},
4744 {"ACPI_LV_ALL", ACPI_LV_ALL},
4745
4746 /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
4747 {"ACPI_LV_MUTEX", ACPI_LV_MUTEX},
4748 {"ACPI_LV_THREADS", ACPI_LV_THREADS},
4749 {"ACPI_LV_IO", ACPI_LV_IO},
4750 {"ACPI_LV_INTERRUPTS", ACPI_LV_INTERRUPTS},
4751 {"ACPI_LV_VERBOSITY3", ACPI_LV_VERBOSITY3},
4752
4753 /* Exceptionally verbose output -- also used in the global "DebugLevel" */
4754 {"ACPI_LV_AML_DISASSEMBLE", ACPI_LV_AML_DISASSEMBLE},
4755 {"ACPI_LV_VERBOSE_INFO", ACPI_LV_VERBOSE_INFO},
4756 {"ACPI_LV_FULL_TABLES", ACPI_LV_FULL_TABLES},
4757 {"ACPI_LV_EVENTS", ACPI_LV_EVENTS},
4758 {"ACPI_LV_VERBOSE", ACPI_LV_VERBOSE},
4759 {NULL, 0}
4760 };
4761
4762 static void
acpi_parse_debug(char * cp,struct debugtag * tag,UINT32 * flag)4763 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
4764 {
4765 char *ep;
4766 int i, l;
4767 int set;
4768
4769 while (*cp) {
4770 if (isspace(*cp)) {
4771 cp++;
4772 continue;
4773 }
4774 ep = cp;
4775 while (*ep && !isspace(*ep))
4776 ep++;
4777 if (*cp == '!') {
4778 set = 0;
4779 cp++;
4780 if (cp == ep)
4781 continue;
4782 } else {
4783 set = 1;
4784 }
4785 l = ep - cp;
4786 for (i = 0; tag[i].name != NULL; i++) {
4787 if (!strncmp(cp, tag[i].name, l)) {
4788 if (set)
4789 *flag |= tag[i].value;
4790 else
4791 *flag &= ~tag[i].value;
4792 }
4793 }
4794 cp = ep;
4795 }
4796 }
4797
4798 static void
acpi_set_debugging(void * junk)4799 acpi_set_debugging(void *junk)
4800 {
4801 char *layer, *level;
4802
4803 if (cold) {
4804 AcpiDbgLayer = 0;
4805 AcpiDbgLevel = 0;
4806 }
4807
4808 layer = kern_getenv("debug.acpi.layer");
4809 level = kern_getenv("debug.acpi.level");
4810 if (layer == NULL && level == NULL)
4811 return;
4812
4813 printf("ACPI set debug");
4814 if (layer != NULL) {
4815 if (strcmp("NONE", layer) != 0)
4816 printf(" layer '%s'", layer);
4817 acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
4818 freeenv(layer);
4819 }
4820 if (level != NULL) {
4821 if (strcmp("NONE", level) != 0)
4822 printf(" level '%s'", level);
4823 acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
4824 freeenv(level);
4825 }
4826 printf("\n");
4827 }
4828
4829 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
4830 NULL);
4831
4832 static int
acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)4833 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
4834 {
4835 int error, *dbg;
4836 struct debugtag *tag;
4837 struct sbuf sb;
4838 char temp[128];
4839
4840 if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
4841 return (ENOMEM);
4842 if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
4843 tag = &dbg_layer[0];
4844 dbg = &AcpiDbgLayer;
4845 } else {
4846 tag = &dbg_level[0];
4847 dbg = &AcpiDbgLevel;
4848 }
4849
4850 /* Get old values if this is a get request. */
4851 ACPI_SERIAL_BEGIN(acpi);
4852 if (*dbg == 0) {
4853 sbuf_cpy(&sb, "NONE");
4854 } else if (req->newptr == NULL) {
4855 for (; tag->name != NULL; tag++) {
4856 if ((*dbg & tag->value) == tag->value)
4857 sbuf_printf(&sb, "%s ", tag->name);
4858 }
4859 }
4860 sbuf_trim(&sb);
4861 sbuf_finish(&sb);
4862 strlcpy(temp, sbuf_data(&sb), sizeof(temp));
4863 sbuf_delete(&sb);
4864
4865 error = sysctl_handle_string(oidp, temp, sizeof(temp), req);
4866
4867 /* Check for error or no change */
4868 if (error == 0 && req->newptr != NULL) {
4869 *dbg = 0;
4870 kern_setenv((char *)oidp->oid_arg1, temp);
4871 acpi_set_debugging(NULL);
4872 }
4873 ACPI_SERIAL_END(acpi);
4874
4875 return (error);
4876 }
4877
4878 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer,
4879 CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, "debug.acpi.layer", 0,
4880 acpi_debug_sysctl, "A",
4881 "");
4882 SYSCTL_PROC(_debug_acpi, OID_AUTO, level,
4883 CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, "debug.acpi.level", 0,
4884 acpi_debug_sysctl, "A",
4885 "");
4886 #endif /* ACPI_DEBUG */
4887
4888 static int
acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)4889 acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)
4890 {
4891 int error;
4892 int old;
4893
4894 old = acpi_debug_objects;
4895 error = sysctl_handle_int(oidp, &acpi_debug_objects, 0, req);
4896 if (error != 0 || req->newptr == NULL)
4897 return (error);
4898 if (old == acpi_debug_objects || (old && acpi_debug_objects))
4899 return (0);
4900
4901 ACPI_SERIAL_BEGIN(acpi);
4902 AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
4903 ACPI_SERIAL_END(acpi);
4904
4905 return (0);
4906 }
4907
4908 static int
acpi_parse_interfaces(char * str,struct acpi_interface * iface)4909 acpi_parse_interfaces(char *str, struct acpi_interface *iface)
4910 {
4911 char *p;
4912 size_t len;
4913 int i, j;
4914
4915 p = str;
4916 while (isspace(*p) || *p == ',')
4917 p++;
4918 len = strlen(p);
4919 if (len == 0)
4920 return (0);
4921 p = strdup(p, M_TEMP);
4922 for (i = 0; i < len; i++)
4923 if (p[i] == ',')
4924 p[i] = '\0';
4925 i = j = 0;
4926 while (i < len)
4927 if (isspace(p[i]) || p[i] == '\0')
4928 i++;
4929 else {
4930 i += strlen(p + i) + 1;
4931 j++;
4932 }
4933 if (j == 0) {
4934 free(p, M_TEMP);
4935 return (0);
4936 }
4937 iface->data = malloc(sizeof(*iface->data) * j, M_TEMP, M_WAITOK);
4938 iface->num = j;
4939 i = j = 0;
4940 while (i < len)
4941 if (isspace(p[i]) || p[i] == '\0')
4942 i++;
4943 else {
4944 iface->data[j] = p + i;
4945 i += strlen(p + i) + 1;
4946 j++;
4947 }
4948
4949 return (j);
4950 }
4951
4952 static void
acpi_free_interfaces(struct acpi_interface * iface)4953 acpi_free_interfaces(struct acpi_interface *iface)
4954 {
4955
4956 free(iface->data[0], M_TEMP);
4957 free(iface->data, M_TEMP);
4958 }
4959
4960 static void
acpi_reset_interfaces(device_t dev)4961 acpi_reset_interfaces(device_t dev)
4962 {
4963 struct acpi_interface list;
4964 ACPI_STATUS status;
4965 int i;
4966
4967 if (acpi_parse_interfaces(acpi_install_interface, &list) > 0) {
4968 for (i = 0; i < list.num; i++) {
4969 status = AcpiInstallInterface(list.data[i]);
4970 if (ACPI_FAILURE(status))
4971 device_printf(dev,
4972 "failed to install _OSI(\"%s\"): %s\n",
4973 list.data[i], AcpiFormatException(status));
4974 else if (bootverbose)
4975 device_printf(dev, "installed _OSI(\"%s\")\n",
4976 list.data[i]);
4977 }
4978 acpi_free_interfaces(&list);
4979 }
4980 if (acpi_parse_interfaces(acpi_remove_interface, &list) > 0) {
4981 for (i = 0; i < list.num; i++) {
4982 status = AcpiRemoveInterface(list.data[i]);
4983 if (ACPI_FAILURE(status))
4984 device_printf(dev,
4985 "failed to remove _OSI(\"%s\"): %s\n",
4986 list.data[i], AcpiFormatException(status));
4987 else if (bootverbose)
4988 device_printf(dev, "removed _OSI(\"%s\")\n",
4989 list.data[i]);
4990 }
4991 acpi_free_interfaces(&list);
4992 }
4993
4994 /*
4995 * Apple Mac hardware quirk: install Darwin OSI.
4996 *
4997 * On Apple hardware, install the Darwin OSI and remove the Windows OSI
4998 * to match Linux behavior.
4999 *
5000 * This is required for dual-GPU MacBook Pro systems
5001 * (Intel iGPU + AMD/NVIDIA dGPU) where the iGPU is hidden when the
5002 * firmware doesn't see Darwin OSI, but it also unlocks additional ACPI
5003 * support on non-MacBook Pro Apple platforms.
5004 *
5005 * Apple's ACPI firmware checks _OSI("Darwin") and sets OSYS=10000
5006 * for macOS. Many device methods use OSDW() which checks OSYS==10000
5007 * for macOS-specific behavior including GPU visibility and power
5008 * management.
5009 *
5010 * Linux enables Darwin OSI by default on Apple hardware and disables
5011 * all Windows OSI strings (drivers/acpi/osi.c). Users can override
5012 * this behavior with acpi_osi=!Darwin to get Windows-like behavior,
5013 * in general, but this logic makes that process unnecessary.
5014 *
5015 * Detect Apple via SMBIOS and enable Darwin while disabling Windows
5016 * vendor strings. This makes both GPUs visible on dual-GPU MacBook Pro
5017 * systems (Intel iGPU + AMD dGPU) and unlocks full platform
5018 * ACPI support.
5019 */
5020 if (acpi_apple_darwin_osi) {
5021 char *vendor = kern_getenv("smbios.system.maker");
5022 if (vendor != NULL) {
5023 if (strcmp(vendor, "Apple Inc.") == 0 ||
5024 strcmp(vendor, "Apple Computer, Inc.") == 0) {
5025 /* Disable all other OSI vendor strings. */
5026 status = AcpiUpdateInterfaces(
5027 ACPI_DISABLE_ALL_VENDOR_STRINGS);
5028 if (ACPI_SUCCESS(status)) {
5029 /* Install Darwin OSI */
5030 status = AcpiInstallInterface("Darwin");
5031 }
5032 if (bootverbose) {
5033 if (ACPI_SUCCESS(status)) {
5034 device_printf(dev,
5035 "disabled non-Darwin OSI & "
5036 "installed Darwin OSI\n");
5037 } else {
5038 device_printf(dev,
5039 "could not install "
5040 "Darwin OSI: %s\n",
5041 AcpiFormatException(status));
5042 }
5043 }
5044 } else if (bootverbose) {
5045 device_printf(dev,
5046 "Not installing Darwin OSI on unsupported platform: %s\n",
5047 vendor);
5048 }
5049 freeenv(vendor);
5050 }
5051 }
5052 }
5053
5054 static int
acpi_pm_func(u_long cmd,void * arg,enum power_stype stype)5055 acpi_pm_func(u_long cmd, void *arg, enum power_stype stype)
5056 {
5057 int error;
5058 struct acpi_softc *sc;
5059
5060 error = 0;
5061 switch (cmd) {
5062 case POWER_CMD_SUSPEND:
5063 sc = (struct acpi_softc *)arg;
5064 if (sc == NULL) {
5065 error = EINVAL;
5066 goto out;
5067 }
5068 if (ACPI_FAILURE(acpi_ReqSleepState(sc, stype)))
5069 error = ENXIO;
5070 break;
5071 default:
5072 error = EINVAL;
5073 goto out;
5074 }
5075
5076 out:
5077 return (error);
5078 }
5079
5080 static void
acpi_pm_register(void * arg)5081 acpi_pm_register(void *arg)
5082 {
5083 if (!cold || resource_disabled("acpi", 0))
5084 return;
5085
5086 power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL,
5087 acpi_supported_stypes);
5088 }
5089
5090 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, NULL);
5091