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