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