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,int type,struct resource * r)1568 acpi_managed_resource(device_t bus, int type, 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 != type || 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,int type,struct resource * r,rman_res_t start,rman_res_t end)1587 acpi_adjust_resource(device_t bus, device_t child, int type, 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, type, r, start, end));
1594 }
1595
1596 static int
acpi_release_resource(device_t bus,device_t child,int type,int rid,struct resource * r)1597 acpi_release_resource(device_t bus, device_t child, int type, int rid,
1598 struct resource *r)
1599 {
1600 /*
1601 * If this resource belongs to one of our internal managers,
1602 * deactivate it and release it to the local pool.
1603 */
1604 if (acpi_is_resource_managed(bus, r))
1605 return (bus_generic_rman_release_resource(bus, child, type, rid, r));
1606
1607 return (bus_generic_rl_release_resource(bus, child, type, rid, r));
1608 }
1609
1610 static void
acpi_delete_resource(device_t bus,device_t child,int type,int rid)1611 acpi_delete_resource(device_t bus, device_t child, int type, int rid)
1612 {
1613 struct resource_list *rl;
1614
1615 rl = acpi_get_rlist(bus, child);
1616 if (resource_list_busy(rl, type, rid)) {
1617 device_printf(bus, "delete_resource: Resource still owned by child"
1618 " (type=%d, rid=%d)\n", type, rid);
1619 return;
1620 }
1621 if (resource_list_reserved(rl, type, rid))
1622 resource_list_unreserve(rl, bus, child, type, rid);
1623 resource_list_delete(rl, type, rid);
1624 }
1625
1626 static int
acpi_activate_resource(device_t bus,device_t child,int type,int rid,struct resource * r)1627 acpi_activate_resource(device_t bus, device_t child, int type, int rid,
1628 struct resource *r)
1629 {
1630 if (acpi_is_resource_managed(bus, r))
1631 return (bus_generic_rman_activate_resource(bus, child, type,
1632 rid, r));
1633 return (bus_generic_activate_resource(bus, child, type, rid, r));
1634 }
1635
1636 static int
acpi_deactivate_resource(device_t bus,device_t child,int type,int rid,struct resource * r)1637 acpi_deactivate_resource(device_t bus, device_t child, int type, int rid,
1638 struct resource *r)
1639 {
1640 if (acpi_is_resource_managed(bus, r))
1641 return (bus_generic_rman_deactivate_resource(bus, child, type,
1642 rid, r));
1643 return (bus_generic_deactivate_resource(bus, child, type, rid, r));
1644 }
1645
1646 static int
acpi_map_resource(device_t bus,device_t child,int type,struct resource * r,struct resource_map_request * argsp,struct resource_map * map)1647 acpi_map_resource(device_t bus, device_t child, int type, struct resource *r,
1648 struct resource_map_request *argsp, struct resource_map *map)
1649 {
1650 struct resource_map_request args;
1651 struct resource *sysres;
1652 rman_res_t length, start;
1653 int error;
1654
1655 if (!acpi_is_resource_managed(bus, r))
1656 return (bus_generic_map_resource(bus, child, type, r, argsp,
1657 map));
1658
1659 /* Resources must be active to be mapped. */
1660 if (!(rman_get_flags(r) & RF_ACTIVE))
1661 return (ENXIO);
1662
1663 resource_init_map_request(&args);
1664 error = resource_validate_map_request(r, argsp, &args, &start, &length);
1665 if (error)
1666 return (error);
1667
1668 sysres = acpi_managed_resource(bus, type, r);
1669 if (sysres == NULL)
1670 return (ENOENT);
1671
1672 args.offset = start - rman_get_start(sysres);
1673 args.length = length;
1674 return (bus_map_resource(bus, sysres, &args, map));
1675 }
1676
1677 static int
acpi_unmap_resource(device_t bus,device_t child,int type,struct resource * r,struct resource_map * map)1678 acpi_unmap_resource(device_t bus, device_t child, int type, struct resource *r,
1679 struct resource_map *map)
1680 {
1681 struct resource *sysres;
1682
1683 if (!acpi_is_resource_managed(bus, r))
1684 return (bus_generic_unmap_resource(bus, child, type, r, map));
1685
1686 sysres = acpi_managed_resource(bus, type, r);
1687 if (sysres == NULL)
1688 return (ENOENT);
1689 return (bus_unmap_resource(bus, sysres, map));
1690 }
1691
1692 /* Allocate an IO port or memory resource, given its GAS. */
1693 int
acpi_bus_alloc_gas(device_t dev,int * type,int * rid,ACPI_GENERIC_ADDRESS * gas,struct resource ** res,u_int flags)1694 acpi_bus_alloc_gas(device_t dev, int *type, int *rid, ACPI_GENERIC_ADDRESS *gas,
1695 struct resource **res, u_int flags)
1696 {
1697 int error, res_type;
1698
1699 error = ENOMEM;
1700 if (type == NULL || rid == NULL || gas == NULL || res == NULL)
1701 return (EINVAL);
1702
1703 /* We only support memory and IO spaces. */
1704 switch (gas->SpaceId) {
1705 case ACPI_ADR_SPACE_SYSTEM_MEMORY:
1706 res_type = SYS_RES_MEMORY;
1707 break;
1708 case ACPI_ADR_SPACE_SYSTEM_IO:
1709 res_type = SYS_RES_IOPORT;
1710 break;
1711 default:
1712 return (EOPNOTSUPP);
1713 }
1714
1715 /*
1716 * If the register width is less than 8, assume the BIOS author means
1717 * it is a bit field and just allocate a byte.
1718 */
1719 if (gas->BitWidth && gas->BitWidth < 8)
1720 gas->BitWidth = 8;
1721
1722 /* Validate the address after we're sure we support the space. */
1723 if (gas->Address == 0 || gas->BitWidth == 0)
1724 return (EINVAL);
1725
1726 bus_set_resource(dev, res_type, *rid, gas->Address,
1727 gas->BitWidth / 8);
1728 *res = bus_alloc_resource_any(dev, res_type, rid, RF_ACTIVE | flags);
1729 if (*res != NULL) {
1730 *type = res_type;
1731 error = 0;
1732 } else
1733 bus_delete_resource(dev, res_type, *rid);
1734
1735 return (error);
1736 }
1737
1738 /* Probe _HID and _CID for compatible ISA PNP ids. */
1739 static uint32_t
acpi_isa_get_logicalid(device_t dev)1740 acpi_isa_get_logicalid(device_t dev)
1741 {
1742 ACPI_DEVICE_INFO *devinfo;
1743 ACPI_HANDLE h;
1744 uint32_t pnpid;
1745
1746 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1747
1748 /* Fetch and validate the HID. */
1749 if ((h = acpi_get_handle(dev)) == NULL ||
1750 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1751 return_VALUE (0);
1752
1753 pnpid = (devinfo->Valid & ACPI_VALID_HID) != 0 &&
1754 devinfo->HardwareId.Length >= ACPI_EISAID_STRING_SIZE ?
1755 PNP_EISAID(devinfo->HardwareId.String) : 0;
1756 AcpiOsFree(devinfo);
1757
1758 return_VALUE (pnpid);
1759 }
1760
1761 static int
acpi_isa_get_compatid(device_t dev,uint32_t * cids,int count)1762 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
1763 {
1764 ACPI_DEVICE_INFO *devinfo;
1765 ACPI_PNP_DEVICE_ID *ids;
1766 ACPI_HANDLE h;
1767 uint32_t *pnpid;
1768 int i, valid;
1769
1770 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1771
1772 pnpid = cids;
1773
1774 /* Fetch and validate the CID */
1775 if ((h = acpi_get_handle(dev)) == NULL ||
1776 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1777 return_VALUE (0);
1778
1779 if ((devinfo->Valid & ACPI_VALID_CID) == 0) {
1780 AcpiOsFree(devinfo);
1781 return_VALUE (0);
1782 }
1783
1784 if (devinfo->CompatibleIdList.Count < count)
1785 count = devinfo->CompatibleIdList.Count;
1786 ids = devinfo->CompatibleIdList.Ids;
1787 for (i = 0, valid = 0; i < count; i++)
1788 if (ids[i].Length >= ACPI_EISAID_STRING_SIZE &&
1789 strncmp(ids[i].String, "PNP", 3) == 0) {
1790 *pnpid++ = PNP_EISAID(ids[i].String);
1791 valid++;
1792 }
1793 AcpiOsFree(devinfo);
1794
1795 return_VALUE (valid);
1796 }
1797
1798 static int
acpi_device_id_probe(device_t bus,device_t dev,char ** ids,char ** match)1799 acpi_device_id_probe(device_t bus, device_t dev, char **ids, char **match)
1800 {
1801 ACPI_HANDLE h;
1802 ACPI_OBJECT_TYPE t;
1803 int rv;
1804 int i;
1805
1806 h = acpi_get_handle(dev);
1807 if (ids == NULL || h == NULL)
1808 return (ENXIO);
1809 t = acpi_get_type(dev);
1810 if (t != ACPI_TYPE_DEVICE && t != ACPI_TYPE_PROCESSOR)
1811 return (ENXIO);
1812
1813 /* Try to match one of the array of IDs with a HID or CID. */
1814 for (i = 0; ids[i] != NULL; i++) {
1815 rv = acpi_MatchHid(h, ids[i]);
1816 if (rv == ACPI_MATCHHID_NOMATCH)
1817 continue;
1818
1819 if (match != NULL) {
1820 *match = ids[i];
1821 }
1822 return ((rv == ACPI_MATCHHID_HID)?
1823 BUS_PROBE_DEFAULT : BUS_PROBE_LOW_PRIORITY);
1824 }
1825 return (ENXIO);
1826 }
1827
1828 static ACPI_STATUS
acpi_device_eval_obj(device_t bus,device_t dev,ACPI_STRING pathname,ACPI_OBJECT_LIST * parameters,ACPI_BUFFER * ret)1829 acpi_device_eval_obj(device_t bus, device_t dev, ACPI_STRING pathname,
1830 ACPI_OBJECT_LIST *parameters, ACPI_BUFFER *ret)
1831 {
1832 ACPI_HANDLE h;
1833
1834 if (dev == NULL)
1835 h = ACPI_ROOT_OBJECT;
1836 else if ((h = acpi_get_handle(dev)) == NULL)
1837 return (AE_BAD_PARAMETER);
1838 return (AcpiEvaluateObject(h, pathname, parameters, ret));
1839 }
1840
1841 static ACPI_STATUS
acpi_device_get_prop(device_t bus,device_t dev,ACPI_STRING propname,const ACPI_OBJECT ** value)1842 acpi_device_get_prop(device_t bus, device_t dev, ACPI_STRING propname,
1843 const ACPI_OBJECT **value)
1844 {
1845 const ACPI_OBJECT *pkg, *name, *val;
1846 struct acpi_device *ad;
1847 ACPI_STATUS status;
1848 int i;
1849
1850 ad = device_get_ivars(dev);
1851
1852 if (ad == NULL || propname == NULL)
1853 return (AE_BAD_PARAMETER);
1854 if (ad->dsd_pkg == NULL) {
1855 if (ad->dsd.Pointer == NULL) {
1856 status = acpi_find_dsd(ad);
1857 if (ACPI_FAILURE(status))
1858 return (status);
1859 } else {
1860 return (AE_NOT_FOUND);
1861 }
1862 }
1863
1864 for (i = 0; i < ad->dsd_pkg->Package.Count; i ++) {
1865 pkg = &ad->dsd_pkg->Package.Elements[i];
1866 if (pkg->Type != ACPI_TYPE_PACKAGE || pkg->Package.Count != 2)
1867 continue;
1868
1869 name = &pkg->Package.Elements[0];
1870 val = &pkg->Package.Elements[1];
1871 if (name->Type != ACPI_TYPE_STRING)
1872 continue;
1873 if (strncmp(propname, name->String.Pointer, name->String.Length) == 0) {
1874 if (value != NULL)
1875 *value = val;
1876
1877 return (AE_OK);
1878 }
1879 }
1880
1881 return (AE_NOT_FOUND);
1882 }
1883
1884 static ACPI_STATUS
acpi_find_dsd(struct acpi_device * ad)1885 acpi_find_dsd(struct acpi_device *ad)
1886 {
1887 const ACPI_OBJECT *dsd, *guid, *pkg;
1888 ACPI_STATUS status;
1889
1890 ad->dsd.Length = ACPI_ALLOCATE_BUFFER;
1891 ad->dsd.Pointer = NULL;
1892 ad->dsd_pkg = NULL;
1893
1894 status = AcpiEvaluateObject(ad->ad_handle, "_DSD", NULL, &ad->dsd);
1895 if (ACPI_FAILURE(status))
1896 return (status);
1897
1898 dsd = ad->dsd.Pointer;
1899 guid = &dsd->Package.Elements[0];
1900 pkg = &dsd->Package.Elements[1];
1901
1902 if (guid->Type != ACPI_TYPE_BUFFER || pkg->Type != ACPI_TYPE_PACKAGE ||
1903 guid->Buffer.Length != sizeof(acpi_dsd_uuid))
1904 return (AE_NOT_FOUND);
1905 if (memcmp(guid->Buffer.Pointer, &acpi_dsd_uuid,
1906 sizeof(acpi_dsd_uuid)) == 0) {
1907
1908 ad->dsd_pkg = pkg;
1909 return (AE_OK);
1910 }
1911
1912 return (AE_NOT_FOUND);
1913 }
1914
1915 static ssize_t
acpi_bus_get_prop_handle(const ACPI_OBJECT * hobj,void * propvalue,size_t size)1916 acpi_bus_get_prop_handle(const ACPI_OBJECT *hobj, void *propvalue, size_t size)
1917 {
1918 ACPI_OBJECT *pobj;
1919 ACPI_HANDLE h;
1920
1921 if (hobj->Type != ACPI_TYPE_PACKAGE)
1922 goto err;
1923 if (hobj->Package.Count != 1)
1924 goto err;
1925
1926 pobj = &hobj->Package.Elements[0];
1927 if (pobj == NULL)
1928 goto err;
1929 if (pobj->Type != ACPI_TYPE_LOCAL_REFERENCE)
1930 goto err;
1931
1932 h = acpi_GetReference(NULL, pobj);
1933 if (h == NULL)
1934 goto err;
1935
1936 if (propvalue != NULL && size >= sizeof(ACPI_HANDLE))
1937 *(ACPI_HANDLE *)propvalue = h;
1938 return (sizeof(ACPI_HANDLE));
1939
1940 err:
1941 return (-1);
1942 }
1943
1944 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)1945 acpi_bus_get_prop(device_t bus, device_t child, const char *propname,
1946 void *propvalue, size_t size, device_property_type_t type)
1947 {
1948 ACPI_STATUS status;
1949 const ACPI_OBJECT *obj;
1950
1951 status = acpi_device_get_prop(bus, child, __DECONST(char *, propname),
1952 &obj);
1953 if (ACPI_FAILURE(status))
1954 return (-1);
1955
1956 switch (type) {
1957 case DEVICE_PROP_ANY:
1958 case DEVICE_PROP_BUFFER:
1959 case DEVICE_PROP_UINT32:
1960 case DEVICE_PROP_UINT64:
1961 break;
1962 case DEVICE_PROP_HANDLE:
1963 return (acpi_bus_get_prop_handle(obj, propvalue, size));
1964 default:
1965 return (-1);
1966 }
1967
1968 switch (obj->Type) {
1969 case ACPI_TYPE_INTEGER:
1970 if (type == DEVICE_PROP_UINT32) {
1971 if (propvalue != NULL && size >= sizeof(uint32_t))
1972 *((uint32_t *)propvalue) = obj->Integer.Value;
1973 return (sizeof(uint32_t));
1974 }
1975 if (propvalue != NULL && size >= sizeof(uint64_t))
1976 *((uint64_t *) propvalue) = obj->Integer.Value;
1977 return (sizeof(uint64_t));
1978
1979 case ACPI_TYPE_STRING:
1980 if (type != DEVICE_PROP_ANY &&
1981 type != DEVICE_PROP_BUFFER)
1982 return (-1);
1983
1984 if (propvalue != NULL && size > 0)
1985 memcpy(propvalue, obj->String.Pointer,
1986 MIN(size, obj->String.Length));
1987 return (obj->String.Length);
1988
1989 case ACPI_TYPE_BUFFER:
1990 if (propvalue != NULL && size > 0)
1991 memcpy(propvalue, obj->Buffer.Pointer,
1992 MIN(size, obj->Buffer.Length));
1993 return (obj->Buffer.Length);
1994
1995 case ACPI_TYPE_PACKAGE:
1996 if (propvalue != NULL && size >= sizeof(ACPI_OBJECT *)) {
1997 *((ACPI_OBJECT **) propvalue) =
1998 __DECONST(ACPI_OBJECT *, obj);
1999 }
2000 return (sizeof(ACPI_OBJECT *));
2001
2002 case ACPI_TYPE_LOCAL_REFERENCE:
2003 if (propvalue != NULL && size >= sizeof(ACPI_HANDLE)) {
2004 ACPI_HANDLE h;
2005
2006 h = acpi_GetReference(NULL,
2007 __DECONST(ACPI_OBJECT *, obj));
2008 memcpy(propvalue, h, sizeof(ACPI_HANDLE));
2009 }
2010 return (sizeof(ACPI_HANDLE));
2011 default:
2012 return (0);
2013 }
2014 }
2015
2016 int
acpi_device_pwr_for_sleep(device_t bus,device_t dev,int * dstate)2017 acpi_device_pwr_for_sleep(device_t bus, device_t dev, int *dstate)
2018 {
2019 struct acpi_softc *sc;
2020 ACPI_HANDLE handle;
2021 ACPI_STATUS status;
2022 char sxd[8];
2023
2024 handle = acpi_get_handle(dev);
2025
2026 /*
2027 * XXX If we find these devices, don't try to power them down.
2028 * The serial and IRDA ports on my T23 hang the system when
2029 * set to D3 and it appears that such legacy devices may
2030 * need special handling in their drivers.
2031 */
2032 if (dstate == NULL || handle == NULL ||
2033 acpi_MatchHid(handle, "PNP0500") ||
2034 acpi_MatchHid(handle, "PNP0501") ||
2035 acpi_MatchHid(handle, "PNP0502") ||
2036 acpi_MatchHid(handle, "PNP0510") ||
2037 acpi_MatchHid(handle, "PNP0511"))
2038 return (ENXIO);
2039
2040 /*
2041 * Override next state with the value from _SxD, if present.
2042 * Note illegal _S0D is evaluated because some systems expect this.
2043 */
2044 sc = device_get_softc(bus);
2045 snprintf(sxd, sizeof(sxd), "_S%dD", sc->acpi_sstate);
2046 status = acpi_GetInteger(handle, sxd, dstate);
2047 if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
2048 device_printf(dev, "failed to get %s on %s: %s\n", sxd,
2049 acpi_name(handle), AcpiFormatException(status));
2050 return (ENXIO);
2051 }
2052
2053 return (0);
2054 }
2055
2056 /* Callback arg for our implementation of walking the namespace. */
2057 struct acpi_device_scan_ctx {
2058 acpi_scan_cb_t user_fn;
2059 void *arg;
2060 ACPI_HANDLE parent;
2061 };
2062
2063 static ACPI_STATUS
acpi_device_scan_cb(ACPI_HANDLE h,UINT32 level,void * arg,void ** retval)2064 acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level, void *arg, void **retval)
2065 {
2066 struct acpi_device_scan_ctx *ctx;
2067 device_t dev, old_dev;
2068 ACPI_STATUS status;
2069 ACPI_OBJECT_TYPE type;
2070
2071 /*
2072 * Skip this device if we think we'll have trouble with it or it is
2073 * the parent where the scan began.
2074 */
2075 ctx = (struct acpi_device_scan_ctx *)arg;
2076 if (acpi_avoid(h) || h == ctx->parent)
2077 return (AE_OK);
2078
2079 /* If this is not a valid device type (e.g., a method), skip it. */
2080 if (ACPI_FAILURE(AcpiGetType(h, &type)))
2081 return (AE_OK);
2082 if (type != ACPI_TYPE_DEVICE && type != ACPI_TYPE_PROCESSOR &&
2083 type != ACPI_TYPE_THERMAL && type != ACPI_TYPE_POWER)
2084 return (AE_OK);
2085
2086 /*
2087 * Call the user function with the current device. If it is unchanged
2088 * afterwards, return. Otherwise, we update the handle to the new dev.
2089 */
2090 old_dev = acpi_get_device(h);
2091 dev = old_dev;
2092 status = ctx->user_fn(h, &dev, level, ctx->arg);
2093 if (ACPI_FAILURE(status) || old_dev == dev)
2094 return (status);
2095
2096 /* Remove the old child and its connection to the handle. */
2097 if (old_dev != NULL)
2098 device_delete_child(device_get_parent(old_dev), old_dev);
2099
2100 /* Recreate the handle association if the user created a device. */
2101 if (dev != NULL)
2102 AcpiAttachData(h, acpi_fake_objhandler, dev);
2103
2104 return (AE_OK);
2105 }
2106
2107 static ACPI_STATUS
acpi_device_scan_children(device_t bus,device_t dev,int max_depth,acpi_scan_cb_t user_fn,void * arg)2108 acpi_device_scan_children(device_t bus, device_t dev, int max_depth,
2109 acpi_scan_cb_t user_fn, void *arg)
2110 {
2111 ACPI_HANDLE h;
2112 struct acpi_device_scan_ctx ctx;
2113
2114 if (acpi_disabled("children"))
2115 return (AE_OK);
2116
2117 if (dev == NULL)
2118 h = ACPI_ROOT_OBJECT;
2119 else if ((h = acpi_get_handle(dev)) == NULL)
2120 return (AE_BAD_PARAMETER);
2121 ctx.user_fn = user_fn;
2122 ctx.arg = arg;
2123 ctx.parent = h;
2124 return (AcpiWalkNamespace(ACPI_TYPE_ANY, h, max_depth,
2125 acpi_device_scan_cb, NULL, &ctx, NULL));
2126 }
2127
2128 /*
2129 * Even though ACPI devices are not PCI, we use the PCI approach for setting
2130 * device power states since it's close enough to ACPI.
2131 */
2132 int
acpi_set_powerstate(device_t child,int state)2133 acpi_set_powerstate(device_t child, int state)
2134 {
2135 ACPI_HANDLE h;
2136 ACPI_STATUS status;
2137
2138 h = acpi_get_handle(child);
2139 if (state < ACPI_STATE_D0 || state > ACPI_D_STATES_MAX)
2140 return (EINVAL);
2141 if (h == NULL)
2142 return (0);
2143
2144 /* Ignore errors if the power methods aren't present. */
2145 status = acpi_pwr_switch_consumer(h, state);
2146 if (ACPI_SUCCESS(status)) {
2147 if (bootverbose)
2148 device_printf(child, "set ACPI power state D%d on %s\n",
2149 state, acpi_name(h));
2150 } else if (status != AE_NOT_FOUND)
2151 device_printf(child,
2152 "failed to set ACPI power state D%d on %s: %s\n", state,
2153 acpi_name(h), AcpiFormatException(status));
2154
2155 return (0);
2156 }
2157
2158 static int
acpi_isa_pnp_probe(device_t bus,device_t child,struct isa_pnp_id * ids)2159 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
2160 {
2161 int result, cid_count, i;
2162 uint32_t lid, cids[8];
2163
2164 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2165
2166 /*
2167 * ISA-style drivers attached to ACPI may persist and
2168 * probe manually if we return ENOENT. We never want
2169 * that to happen, so don't ever return it.
2170 */
2171 result = ENXIO;
2172
2173 /* Scan the supplied IDs for a match */
2174 lid = acpi_isa_get_logicalid(child);
2175 cid_count = acpi_isa_get_compatid(child, cids, 8);
2176 while (ids && ids->ip_id) {
2177 if (lid == ids->ip_id) {
2178 result = 0;
2179 goto out;
2180 }
2181 for (i = 0; i < cid_count; i++) {
2182 if (cids[i] == ids->ip_id) {
2183 result = 0;
2184 goto out;
2185 }
2186 }
2187 ids++;
2188 }
2189
2190 out:
2191 if (result == 0 && ids->ip_desc)
2192 device_set_desc(child, ids->ip_desc);
2193
2194 return_VALUE (result);
2195 }
2196
2197 /*
2198 * Look for a MCFG table. If it is present, use the settings for
2199 * domain (segment) 0 to setup PCI config space access via the memory
2200 * map.
2201 *
2202 * On non-x86 architectures (arm64 for now), this will be done from the
2203 * PCI host bridge driver.
2204 */
2205 static void
acpi_enable_pcie(void)2206 acpi_enable_pcie(void)
2207 {
2208 #if defined(__i386__) || defined(__amd64__)
2209 ACPI_TABLE_HEADER *hdr;
2210 ACPI_MCFG_ALLOCATION *alloc, *end;
2211 ACPI_STATUS status;
2212
2213 status = AcpiGetTable(ACPI_SIG_MCFG, 1, &hdr);
2214 if (ACPI_FAILURE(status))
2215 return;
2216
2217 end = (ACPI_MCFG_ALLOCATION *)((char *)hdr + hdr->Length);
2218 alloc = (ACPI_MCFG_ALLOCATION *)((ACPI_TABLE_MCFG *)hdr + 1);
2219 while (alloc < end) {
2220 pcie_cfgregopen(alloc->Address, alloc->PciSegment,
2221 alloc->StartBusNumber, alloc->EndBusNumber);
2222 alloc++;
2223 }
2224 #endif
2225 }
2226
2227 static void
acpi_platform_osc(device_t dev)2228 acpi_platform_osc(device_t dev)
2229 {
2230 ACPI_HANDLE sb_handle;
2231 ACPI_STATUS status;
2232 uint32_t cap_set[2];
2233
2234 /* 0811B06E-4A27-44F9-8D60-3CBBC22E7B48 */
2235 static uint8_t acpi_platform_uuid[ACPI_UUID_LENGTH] = {
2236 0x6e, 0xb0, 0x11, 0x08, 0x27, 0x4a, 0xf9, 0x44,
2237 0x8d, 0x60, 0x3c, 0xbb, 0xc2, 0x2e, 0x7b, 0x48
2238 };
2239
2240 if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2241 return;
2242
2243 cap_set[1] = 0x10; /* APEI Support */
2244 status = acpi_EvaluateOSC(sb_handle, acpi_platform_uuid, 1,
2245 nitems(cap_set), cap_set, cap_set, false);
2246 if (ACPI_FAILURE(status)) {
2247 if (status == AE_NOT_FOUND)
2248 return;
2249 device_printf(dev, "_OSC failed: %s\n",
2250 AcpiFormatException(status));
2251 return;
2252 }
2253 }
2254
2255 /*
2256 * Scan all of the ACPI namespace and attach child devices.
2257 *
2258 * We should only expect to find devices in the \_PR, \_TZ, \_SI, and
2259 * \_SB scopes, and \_PR and \_TZ became obsolete in the ACPI 2.0 spec.
2260 * However, in violation of the spec, some systems place their PCI link
2261 * devices in \, so we have to walk the whole namespace. We check the
2262 * type of namespace nodes, so this should be ok.
2263 */
2264 static void
acpi_probe_children(device_t bus)2265 acpi_probe_children(device_t bus)
2266 {
2267
2268 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2269
2270 /*
2271 * Scan the namespace and insert placeholders for all the devices that
2272 * we find. We also probe/attach any early devices.
2273 *
2274 * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
2275 * we want to create nodes for all devices, not just those that are
2276 * currently present. (This assumes that we don't want to create/remove
2277 * devices as they appear, which might be smarter.)
2278 */
2279 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
2280 AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, 100, acpi_probe_child,
2281 NULL, bus, NULL);
2282
2283 /* Pre-allocate resources for our rman from any sysresource devices. */
2284 acpi_sysres_alloc(bus);
2285
2286 /* Create any static children by calling device identify methods. */
2287 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
2288 bus_generic_probe(bus);
2289
2290 /* Probe/attach all children, created statically and from the namespace. */
2291 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "acpi bus_generic_attach\n"));
2292 bus_generic_attach(bus);
2293
2294 /*
2295 * Reserve resources allocated to children but not yet allocated
2296 * by a driver.
2297 */
2298 acpi_reserve_resources(bus);
2299
2300 /* Attach wake sysctls. */
2301 acpi_wake_sysctl_walk(bus);
2302
2303 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
2304 return_VOID;
2305 }
2306
2307 /*
2308 * Determine the probe order for a given device.
2309 */
2310 static void
acpi_probe_order(ACPI_HANDLE handle,int * order)2311 acpi_probe_order(ACPI_HANDLE handle, int *order)
2312 {
2313 ACPI_OBJECT_TYPE type;
2314
2315 /*
2316 * 0. CPUs
2317 * 1. I/O port and memory system resource holders
2318 * 2. Clocks and timers (to handle early accesses)
2319 * 3. Embedded controllers (to handle early accesses)
2320 * 4. PCI Link Devices
2321 */
2322 AcpiGetType(handle, &type);
2323 if (type == ACPI_TYPE_PROCESSOR)
2324 *order = 0;
2325 else if (acpi_MatchHid(handle, "PNP0C01") ||
2326 acpi_MatchHid(handle, "PNP0C02"))
2327 *order = 1;
2328 else if (acpi_MatchHid(handle, "PNP0100") ||
2329 acpi_MatchHid(handle, "PNP0103") ||
2330 acpi_MatchHid(handle, "PNP0B00"))
2331 *order = 2;
2332 else if (acpi_MatchHid(handle, "PNP0C09"))
2333 *order = 3;
2334 else if (acpi_MatchHid(handle, "PNP0C0F"))
2335 *order = 4;
2336 }
2337
2338 /*
2339 * Evaluate a child device and determine whether we might attach a device to
2340 * it.
2341 */
2342 static ACPI_STATUS
acpi_probe_child(ACPI_HANDLE handle,UINT32 level,void * context,void ** status)2343 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2344 {
2345 ACPI_DEVICE_INFO *devinfo;
2346 struct acpi_device *ad;
2347 struct acpi_prw_data prw;
2348 ACPI_OBJECT_TYPE type;
2349 ACPI_HANDLE h;
2350 device_t bus, child;
2351 char *handle_str;
2352 int d, order;
2353
2354 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2355
2356 if (acpi_disabled("children"))
2357 return_ACPI_STATUS (AE_OK);
2358
2359 /* Skip this device if we think we'll have trouble with it. */
2360 if (acpi_avoid(handle))
2361 return_ACPI_STATUS (AE_OK);
2362
2363 bus = (device_t)context;
2364 if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
2365 handle_str = acpi_name(handle);
2366 switch (type) {
2367 case ACPI_TYPE_DEVICE:
2368 /*
2369 * Since we scan from \, be sure to skip system scope objects.
2370 * \_SB_ and \_TZ_ are defined in ACPICA as devices to work around
2371 * BIOS bugs. For example, \_SB_ is to allow \_SB_._INI to be run
2372 * during the initialization and \_TZ_ is to support Notify() on it.
2373 */
2374 if (strcmp(handle_str, "\\_SB_") == 0 ||
2375 strcmp(handle_str, "\\_TZ_") == 0)
2376 break;
2377 if (acpi_parse_prw(handle, &prw) == 0)
2378 AcpiSetupGpeForWake(handle, prw.gpe_handle, prw.gpe_bit);
2379
2380 /*
2381 * Ignore devices that do not have a _HID or _CID. They should
2382 * be discovered by other buses (e.g. the PCI bus driver).
2383 */
2384 if (!acpi_has_hid(handle))
2385 break;
2386 /* FALLTHROUGH */
2387 case ACPI_TYPE_PROCESSOR:
2388 case ACPI_TYPE_THERMAL:
2389 case ACPI_TYPE_POWER:
2390 /*
2391 * Create a placeholder device for this node. Sort the
2392 * placeholder so that the probe/attach passes will run
2393 * breadth-first. Orders less than ACPI_DEV_BASE_ORDER
2394 * are reserved for special objects (i.e., system
2395 * resources).
2396 */
2397 ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
2398 order = level * 10 + ACPI_DEV_BASE_ORDER;
2399 acpi_probe_order(handle, &order);
2400 child = BUS_ADD_CHILD(bus, order, NULL, -1);
2401 if (child == NULL)
2402 break;
2403
2404 /* Associate the handle with the device_t and vice versa. */
2405 acpi_set_handle(child, handle);
2406 AcpiAttachData(handle, acpi_fake_objhandler, child);
2407
2408 /*
2409 * Check that the device is present. If it's not present,
2410 * leave it disabled (so that we have a device_t attached to
2411 * the handle, but we don't probe it).
2412 *
2413 * XXX PCI link devices sometimes report "present" but not
2414 * "functional" (i.e. if disabled). Go ahead and probe them
2415 * anyway since we may enable them later.
2416 */
2417 if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
2418 /* Never disable PCI link devices. */
2419 if (acpi_MatchHid(handle, "PNP0C0F"))
2420 break;
2421
2422 /*
2423 * RTC Device should be enabled for CMOS register space
2424 * unless FADT indicate it is not present.
2425 * (checked in RTC probe routine.)
2426 */
2427 if (acpi_MatchHid(handle, "PNP0B00"))
2428 break;
2429
2430 /*
2431 * Docking stations should remain enabled since the system
2432 * may be undocked at boot.
2433 */
2434 if (ACPI_SUCCESS(AcpiGetHandle(handle, "_DCK", &h)))
2435 break;
2436
2437 device_disable(child);
2438 break;
2439 }
2440
2441 /*
2442 * Get the device's resource settings and attach them.
2443 * Note that if the device has _PRS but no _CRS, we need
2444 * to decide when it's appropriate to try to configure the
2445 * device. Ignore the return value here; it's OK for the
2446 * device not to have any resources.
2447 */
2448 acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
2449
2450 ad = device_get_ivars(child);
2451 ad->ad_cls_class = 0xffffff;
2452 if (ACPI_SUCCESS(AcpiGetObjectInfo(handle, &devinfo))) {
2453 if ((devinfo->Valid & ACPI_VALID_CLS) != 0 &&
2454 devinfo->ClassCode.Length >= ACPI_PCICLS_STRING_SIZE) {
2455 ad->ad_cls_class = strtoul(devinfo->ClassCode.String,
2456 NULL, 16);
2457 }
2458 AcpiOsFree(devinfo);
2459 }
2460
2461 d = acpi_pxm_parse(child);
2462 if (d >= 0)
2463 ad->ad_domain = d;
2464 break;
2465 }
2466 }
2467
2468 return_ACPI_STATUS (AE_OK);
2469 }
2470
2471 /*
2472 * AcpiAttachData() requires an object handler but never uses it. This is a
2473 * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
2474 */
2475 void
acpi_fake_objhandler(ACPI_HANDLE h,void * data)2476 acpi_fake_objhandler(ACPI_HANDLE h, void *data)
2477 {
2478 }
2479
2480 static void
acpi_shutdown_final(void * arg,int howto)2481 acpi_shutdown_final(void *arg, int howto)
2482 {
2483 struct acpi_softc *sc = (struct acpi_softc *)arg;
2484 register_t intr;
2485 ACPI_STATUS status;
2486
2487 /*
2488 * XXX Shutdown code should only run on the BSP (cpuid 0).
2489 * Some chipsets do not power off the system correctly if called from
2490 * an AP.
2491 */
2492 if ((howto & RB_POWEROFF) != 0) {
2493 status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
2494 if (ACPI_FAILURE(status)) {
2495 device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
2496 AcpiFormatException(status));
2497 return;
2498 }
2499 device_printf(sc->acpi_dev, "Powering system off\n");
2500 intr = intr_disable();
2501 status = AcpiEnterSleepState(ACPI_STATE_S5);
2502 if (ACPI_FAILURE(status)) {
2503 intr_restore(intr);
2504 device_printf(sc->acpi_dev, "power-off failed - %s\n",
2505 AcpiFormatException(status));
2506 } else {
2507 DELAY(1000000);
2508 intr_restore(intr);
2509 device_printf(sc->acpi_dev, "power-off failed - timeout\n");
2510 }
2511 } else if ((howto & RB_HALT) == 0 && sc->acpi_handle_reboot) {
2512 /* Reboot using the reset register. */
2513 status = AcpiReset();
2514 if (ACPI_SUCCESS(status)) {
2515 DELAY(1000000);
2516 device_printf(sc->acpi_dev, "reset failed - timeout\n");
2517 } else if (status != AE_NOT_EXIST)
2518 device_printf(sc->acpi_dev, "reset failed - %s\n",
2519 AcpiFormatException(status));
2520 } else if (sc->acpi_do_disable && !KERNEL_PANICKED()) {
2521 /*
2522 * Only disable ACPI if the user requested. On some systems, writing
2523 * the disable value to SMI_CMD hangs the system.
2524 */
2525 device_printf(sc->acpi_dev, "Shutting down\n");
2526 AcpiTerminate();
2527 }
2528 }
2529
2530 static void
acpi_enable_fixed_events(struct acpi_softc * sc)2531 acpi_enable_fixed_events(struct acpi_softc *sc)
2532 {
2533 static int first_time = 1;
2534
2535 /* Enable and clear fixed events and install handlers. */
2536 if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
2537 AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
2538 AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
2539 acpi_event_power_button_sleep, sc);
2540 if (first_time)
2541 device_printf(sc->acpi_dev, "Power Button (fixed)\n");
2542 }
2543 if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
2544 AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
2545 AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
2546 acpi_event_sleep_button_sleep, sc);
2547 if (first_time)
2548 device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
2549 }
2550
2551 first_time = 0;
2552 }
2553
2554 /*
2555 * Returns true if the device is actually present and should
2556 * be attached to. This requires the present, enabled, UI-visible
2557 * and diagnostics-passed bits to be set.
2558 */
2559 BOOLEAN
acpi_DeviceIsPresent(device_t dev)2560 acpi_DeviceIsPresent(device_t dev)
2561 {
2562 ACPI_HANDLE h;
2563 UINT32 s;
2564 ACPI_STATUS status;
2565
2566 h = acpi_get_handle(dev);
2567 if (h == NULL)
2568 return (FALSE);
2569
2570 #ifdef ACPI_EARLY_EPYC_WAR
2571 /*
2572 * Certain Treadripper boards always returns 0 for FreeBSD because it
2573 * only returns non-zero for the OS string "Windows 2015". Otherwise it
2574 * will return zero. Force them to always be treated as present.
2575 * Beata versions were worse: they always returned 0.
2576 */
2577 if (acpi_MatchHid(h, "AMDI0020") || acpi_MatchHid(h, "AMDI0010"))
2578 return (TRUE);
2579 #endif
2580
2581 status = acpi_GetInteger(h, "_STA", &s);
2582
2583 /*
2584 * If no _STA method or if it failed, then assume that
2585 * the device is present.
2586 */
2587 if (ACPI_FAILURE(status))
2588 return (TRUE);
2589
2590 return (ACPI_DEVICE_PRESENT(s) ? TRUE : FALSE);
2591 }
2592
2593 /*
2594 * Returns true if the battery is actually present and inserted.
2595 */
2596 BOOLEAN
acpi_BatteryIsPresent(device_t dev)2597 acpi_BatteryIsPresent(device_t dev)
2598 {
2599 ACPI_HANDLE h;
2600 UINT32 s;
2601 ACPI_STATUS status;
2602
2603 h = acpi_get_handle(dev);
2604 if (h == NULL)
2605 return (FALSE);
2606 status = acpi_GetInteger(h, "_STA", &s);
2607
2608 /*
2609 * If no _STA method or if it failed, then assume that
2610 * the device is present.
2611 */
2612 if (ACPI_FAILURE(status))
2613 return (TRUE);
2614
2615 return (ACPI_BATTERY_PRESENT(s) ? TRUE : FALSE);
2616 }
2617
2618 /*
2619 * Returns true if a device has at least one valid device ID.
2620 */
2621 BOOLEAN
acpi_has_hid(ACPI_HANDLE h)2622 acpi_has_hid(ACPI_HANDLE h)
2623 {
2624 ACPI_DEVICE_INFO *devinfo;
2625 BOOLEAN ret;
2626
2627 if (h == NULL ||
2628 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2629 return (FALSE);
2630
2631 ret = FALSE;
2632 if ((devinfo->Valid & ACPI_VALID_HID) != 0)
2633 ret = TRUE;
2634 else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2635 if (devinfo->CompatibleIdList.Count > 0)
2636 ret = TRUE;
2637
2638 AcpiOsFree(devinfo);
2639 return (ret);
2640 }
2641
2642 /*
2643 * Match a HID string against a handle
2644 * returns ACPI_MATCHHID_HID if _HID match
2645 * ACPI_MATCHHID_CID if _CID match and not _HID match.
2646 * ACPI_MATCHHID_NOMATCH=0 if no match.
2647 */
2648 int
acpi_MatchHid(ACPI_HANDLE h,const char * hid)2649 acpi_MatchHid(ACPI_HANDLE h, const char *hid)
2650 {
2651 ACPI_DEVICE_INFO *devinfo;
2652 BOOLEAN ret;
2653 int i;
2654
2655 if (hid == NULL || h == NULL ||
2656 ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2657 return (ACPI_MATCHHID_NOMATCH);
2658
2659 ret = ACPI_MATCHHID_NOMATCH;
2660 if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
2661 strcmp(hid, devinfo->HardwareId.String) == 0)
2662 ret = ACPI_MATCHHID_HID;
2663 else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2664 for (i = 0; i < devinfo->CompatibleIdList.Count; i++) {
2665 if (strcmp(hid, devinfo->CompatibleIdList.Ids[i].String) == 0) {
2666 ret = ACPI_MATCHHID_CID;
2667 break;
2668 }
2669 }
2670
2671 AcpiOsFree(devinfo);
2672 return (ret);
2673 }
2674
2675 /*
2676 * Return the handle of a named object within our scope, ie. that of (parent)
2677 * or one if its parents.
2678 */
2679 ACPI_STATUS
acpi_GetHandleInScope(ACPI_HANDLE parent,char * path,ACPI_HANDLE * result)2680 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
2681 {
2682 ACPI_HANDLE r;
2683 ACPI_STATUS status;
2684
2685 /* Walk back up the tree to the root */
2686 for (;;) {
2687 status = AcpiGetHandle(parent, path, &r);
2688 if (ACPI_SUCCESS(status)) {
2689 *result = r;
2690 return (AE_OK);
2691 }
2692 /* XXX Return error here? */
2693 if (status != AE_NOT_FOUND)
2694 return (AE_OK);
2695 if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
2696 return (AE_NOT_FOUND);
2697 parent = r;
2698 }
2699 }
2700
2701 ACPI_STATUS
acpi_GetProperty(device_t dev,ACPI_STRING propname,const ACPI_OBJECT ** value)2702 acpi_GetProperty(device_t dev, ACPI_STRING propname,
2703 const ACPI_OBJECT **value)
2704 {
2705 device_t bus = device_get_parent(dev);
2706
2707 return (ACPI_GET_PROPERTY(bus, dev, propname, value));
2708 }
2709
2710 /*
2711 * Allocate a buffer with a preset data size.
2712 */
2713 ACPI_BUFFER *
acpi_AllocBuffer(int size)2714 acpi_AllocBuffer(int size)
2715 {
2716 ACPI_BUFFER *buf;
2717
2718 if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
2719 return (NULL);
2720 buf->Length = size;
2721 buf->Pointer = (void *)(buf + 1);
2722 return (buf);
2723 }
2724
2725 ACPI_STATUS
acpi_SetInteger(ACPI_HANDLE handle,char * path,UINT32 number)2726 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
2727 {
2728 ACPI_OBJECT arg1;
2729 ACPI_OBJECT_LIST args;
2730
2731 arg1.Type = ACPI_TYPE_INTEGER;
2732 arg1.Integer.Value = number;
2733 args.Count = 1;
2734 args.Pointer = &arg1;
2735
2736 return (AcpiEvaluateObject(handle, path, &args, NULL));
2737 }
2738
2739 /*
2740 * Evaluate a path that should return an integer.
2741 */
2742 ACPI_STATUS
acpi_GetInteger(ACPI_HANDLE handle,char * path,UINT32 * number)2743 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
2744 {
2745 ACPI_STATUS status;
2746 ACPI_BUFFER buf;
2747 ACPI_OBJECT param;
2748
2749 if (handle == NULL)
2750 handle = ACPI_ROOT_OBJECT;
2751
2752 /*
2753 * Assume that what we've been pointed at is an Integer object, or
2754 * a method that will return an Integer.
2755 */
2756 buf.Pointer = ¶m;
2757 buf.Length = sizeof(param);
2758 status = AcpiEvaluateObject(handle, path, NULL, &buf);
2759 if (ACPI_SUCCESS(status)) {
2760 if (param.Type == ACPI_TYPE_INTEGER)
2761 *number = param.Integer.Value;
2762 else
2763 status = AE_TYPE;
2764 }
2765
2766 /*
2767 * In some applications, a method that's expected to return an Integer
2768 * may instead return a Buffer (probably to simplify some internal
2769 * arithmetic). We'll try to fetch whatever it is, and if it's a Buffer,
2770 * convert it into an Integer as best we can.
2771 *
2772 * This is a hack.
2773 */
2774 if (status == AE_BUFFER_OVERFLOW) {
2775 if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
2776 status = AE_NO_MEMORY;
2777 } else {
2778 status = AcpiEvaluateObject(handle, path, NULL, &buf);
2779 if (ACPI_SUCCESS(status))
2780 status = acpi_ConvertBufferToInteger(&buf, number);
2781 AcpiOsFree(buf.Pointer);
2782 }
2783 }
2784 return (status);
2785 }
2786
2787 ACPI_STATUS
acpi_ConvertBufferToInteger(ACPI_BUFFER * bufp,UINT32 * number)2788 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
2789 {
2790 ACPI_OBJECT *p;
2791 UINT8 *val;
2792 int i;
2793
2794 p = (ACPI_OBJECT *)bufp->Pointer;
2795 if (p->Type == ACPI_TYPE_INTEGER) {
2796 *number = p->Integer.Value;
2797 return (AE_OK);
2798 }
2799 if (p->Type != ACPI_TYPE_BUFFER)
2800 return (AE_TYPE);
2801 if (p->Buffer.Length > sizeof(int))
2802 return (AE_BAD_DATA);
2803
2804 *number = 0;
2805 val = p->Buffer.Pointer;
2806 for (i = 0; i < p->Buffer.Length; i++)
2807 *number += val[i] << (i * 8);
2808 return (AE_OK);
2809 }
2810
2811 /*
2812 * Iterate over the elements of an a package object, calling the supplied
2813 * function for each element.
2814 *
2815 * XXX possible enhancement might be to abort traversal on error.
2816 */
2817 ACPI_STATUS
acpi_ForeachPackageObject(ACPI_OBJECT * pkg,void (* func)(ACPI_OBJECT * comp,void * arg),void * arg)2818 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
2819 void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
2820 {
2821 ACPI_OBJECT *comp;
2822 int i;
2823
2824 if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
2825 return (AE_BAD_PARAMETER);
2826
2827 /* Iterate over components */
2828 i = 0;
2829 comp = pkg->Package.Elements;
2830 for (; i < pkg->Package.Count; i++, comp++)
2831 func(comp, arg);
2832
2833 return (AE_OK);
2834 }
2835
2836 /*
2837 * Find the (index)th resource object in a set.
2838 */
2839 ACPI_STATUS
acpi_FindIndexedResource(ACPI_BUFFER * buf,int index,ACPI_RESOURCE ** resp)2840 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
2841 {
2842 ACPI_RESOURCE *rp;
2843 int i;
2844
2845 rp = (ACPI_RESOURCE *)buf->Pointer;
2846 i = index;
2847 while (i-- > 0) {
2848 /* Range check */
2849 if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2850 return (AE_BAD_PARAMETER);
2851
2852 /* Check for terminator */
2853 if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2854 return (AE_NOT_FOUND);
2855 rp = ACPI_NEXT_RESOURCE(rp);
2856 }
2857 if (resp != NULL)
2858 *resp = rp;
2859
2860 return (AE_OK);
2861 }
2862
2863 /*
2864 * Append an ACPI_RESOURCE to an ACPI_BUFFER.
2865 *
2866 * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
2867 * provided to contain it. If the ACPI_BUFFER is empty, allocate a sensible
2868 * backing block. If the ACPI_RESOURCE is NULL, return an empty set of
2869 * resources.
2870 */
2871 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE 512
2872
2873 ACPI_STATUS
acpi_AppendBufferResource(ACPI_BUFFER * buf,ACPI_RESOURCE * res)2874 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
2875 {
2876 ACPI_RESOURCE *rp;
2877 void *newp;
2878
2879 /* Initialise the buffer if necessary. */
2880 if (buf->Pointer == NULL) {
2881 buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
2882 if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
2883 return (AE_NO_MEMORY);
2884 rp = (ACPI_RESOURCE *)buf->Pointer;
2885 rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2886 rp->Length = ACPI_RS_SIZE_MIN;
2887 }
2888 if (res == NULL)
2889 return (AE_OK);
2890
2891 /*
2892 * Scan the current buffer looking for the terminator.
2893 * This will either find the terminator or hit the end
2894 * of the buffer and return an error.
2895 */
2896 rp = (ACPI_RESOURCE *)buf->Pointer;
2897 for (;;) {
2898 /* Range check, don't go outside the buffer */
2899 if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2900 return (AE_BAD_PARAMETER);
2901 if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2902 break;
2903 rp = ACPI_NEXT_RESOURCE(rp);
2904 }
2905
2906 /*
2907 * Check the size of the buffer and expand if required.
2908 *
2909 * Required size is:
2910 * size of existing resources before terminator +
2911 * size of new resource and header +
2912 * size of terminator.
2913 *
2914 * Note that this loop should really only run once, unless
2915 * for some reason we are stuffing a *really* huge resource.
2916 */
2917 while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
2918 res->Length + ACPI_RS_SIZE_NO_DATA +
2919 ACPI_RS_SIZE_MIN) >= buf->Length) {
2920 if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
2921 return (AE_NO_MEMORY);
2922 bcopy(buf->Pointer, newp, buf->Length);
2923 rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
2924 ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
2925 AcpiOsFree(buf->Pointer);
2926 buf->Pointer = newp;
2927 buf->Length += buf->Length;
2928 }
2929
2930 /* Insert the new resource. */
2931 bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
2932
2933 /* And add the terminator. */
2934 rp = ACPI_NEXT_RESOURCE(rp);
2935 rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2936 rp->Length = ACPI_RS_SIZE_MIN;
2937
2938 return (AE_OK);
2939 }
2940
2941 UINT64
acpi_DSMQuery(ACPI_HANDLE h,const uint8_t * uuid,int revision)2942 acpi_DSMQuery(ACPI_HANDLE h, const uint8_t *uuid, int revision)
2943 {
2944 /*
2945 * ACPI spec 9.1.1 defines this.
2946 *
2947 * "Arg2: Function Index Represents a specific function whose meaning is
2948 * specific to the UUID and Revision ID. Function indices should start
2949 * with 1. Function number zero is a query function (see the special
2950 * return code defined below)."
2951 */
2952 ACPI_BUFFER buf;
2953 ACPI_OBJECT *obj;
2954 UINT64 ret = 0;
2955 int i;
2956
2957 if (!ACPI_SUCCESS(acpi_EvaluateDSM(h, uuid, revision, 0, NULL, &buf))) {
2958 ACPI_INFO(("Failed to enumerate DSM functions\n"));
2959 return (0);
2960 }
2961
2962 obj = (ACPI_OBJECT *)buf.Pointer;
2963 KASSERT(obj, ("Object not allowed to be NULL\n"));
2964
2965 /*
2966 * From ACPI 6.2 spec 9.1.1:
2967 * If Function Index = 0, a Buffer containing a function index bitfield.
2968 * Otherwise, the return value and type depends on the UUID and revision
2969 * ID (see below).
2970 */
2971 switch (obj->Type) {
2972 case ACPI_TYPE_BUFFER:
2973 for (i = 0; i < MIN(obj->Buffer.Length, sizeof(ret)); i++)
2974 ret |= (((uint64_t)obj->Buffer.Pointer[i]) << (i * 8));
2975 break;
2976 case ACPI_TYPE_INTEGER:
2977 ACPI_BIOS_WARNING((AE_INFO,
2978 "Possibly buggy BIOS with ACPI_TYPE_INTEGER for function enumeration\n"));
2979 ret = obj->Integer.Value;
2980 break;
2981 default:
2982 ACPI_WARNING((AE_INFO, "Unexpected return type %u\n", obj->Type));
2983 };
2984
2985 AcpiOsFree(obj);
2986 return ret;
2987 }
2988
2989 /*
2990 * DSM may return multiple types depending on the function. It is therefore
2991 * unsafe to use the typed evaluation. It is highly recommended that the caller
2992 * check the type of the returned object.
2993 */
2994 ACPI_STATUS
acpi_EvaluateDSM(ACPI_HANDLE handle,const uint8_t * uuid,int revision,UINT64 function,ACPI_OBJECT * package,ACPI_BUFFER * out_buf)2995 acpi_EvaluateDSM(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
2996 UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf)
2997 {
2998 return (acpi_EvaluateDSMTyped(handle, uuid, revision, function,
2999 package, out_buf, ACPI_TYPE_ANY));
3000 }
3001
3002 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)3003 acpi_EvaluateDSMTyped(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
3004 UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf,
3005 ACPI_OBJECT_TYPE type)
3006 {
3007 ACPI_OBJECT arg[4];
3008 ACPI_OBJECT_LIST arglist;
3009 ACPI_BUFFER buf;
3010 ACPI_STATUS status;
3011
3012 if (out_buf == NULL)
3013 return (AE_NO_MEMORY);
3014
3015 arg[0].Type = ACPI_TYPE_BUFFER;
3016 arg[0].Buffer.Length = ACPI_UUID_LENGTH;
3017 arg[0].Buffer.Pointer = __DECONST(uint8_t *, uuid);
3018 arg[1].Type = ACPI_TYPE_INTEGER;
3019 arg[1].Integer.Value = revision;
3020 arg[2].Type = ACPI_TYPE_INTEGER;
3021 arg[2].Integer.Value = function;
3022 if (package) {
3023 arg[3] = *package;
3024 } else {
3025 arg[3].Type = ACPI_TYPE_PACKAGE;
3026 arg[3].Package.Count = 0;
3027 arg[3].Package.Elements = NULL;
3028 }
3029
3030 arglist.Pointer = arg;
3031 arglist.Count = 4;
3032 buf.Pointer = NULL;
3033 buf.Length = ACPI_ALLOCATE_BUFFER;
3034 status = AcpiEvaluateObjectTyped(handle, "_DSM", &arglist, &buf, type);
3035 if (ACPI_FAILURE(status))
3036 return (status);
3037
3038 KASSERT(ACPI_SUCCESS(status), ("Unexpected status"));
3039
3040 *out_buf = buf;
3041 return (status);
3042 }
3043
3044 ACPI_STATUS
acpi_EvaluateOSC(ACPI_HANDLE handle,uint8_t * uuid,int revision,int count,uint32_t * caps_in,uint32_t * caps_out,bool query)3045 acpi_EvaluateOSC(ACPI_HANDLE handle, uint8_t *uuid, int revision, int count,
3046 uint32_t *caps_in, uint32_t *caps_out, bool query)
3047 {
3048 ACPI_OBJECT arg[4], *ret;
3049 ACPI_OBJECT_LIST arglist;
3050 ACPI_BUFFER buf;
3051 ACPI_STATUS status;
3052
3053 arglist.Pointer = arg;
3054 arglist.Count = 4;
3055 arg[0].Type = ACPI_TYPE_BUFFER;
3056 arg[0].Buffer.Length = ACPI_UUID_LENGTH;
3057 arg[0].Buffer.Pointer = uuid;
3058 arg[1].Type = ACPI_TYPE_INTEGER;
3059 arg[1].Integer.Value = revision;
3060 arg[2].Type = ACPI_TYPE_INTEGER;
3061 arg[2].Integer.Value = count;
3062 arg[3].Type = ACPI_TYPE_BUFFER;
3063 arg[3].Buffer.Length = count * sizeof(*caps_in);
3064 arg[3].Buffer.Pointer = (uint8_t *)caps_in;
3065 caps_in[0] = query ? 1 : 0;
3066 buf.Pointer = NULL;
3067 buf.Length = ACPI_ALLOCATE_BUFFER;
3068 status = AcpiEvaluateObjectTyped(handle, "_OSC", &arglist, &buf,
3069 ACPI_TYPE_BUFFER);
3070 if (ACPI_FAILURE(status))
3071 return (status);
3072 if (caps_out != NULL) {
3073 ret = buf.Pointer;
3074 if (ret->Buffer.Length != count * sizeof(*caps_out)) {
3075 AcpiOsFree(buf.Pointer);
3076 return (AE_BUFFER_OVERFLOW);
3077 }
3078 bcopy(ret->Buffer.Pointer, caps_out, ret->Buffer.Length);
3079 }
3080 AcpiOsFree(buf.Pointer);
3081 return (status);
3082 }
3083
3084 /*
3085 * Set interrupt model.
3086 */
3087 ACPI_STATUS
acpi_SetIntrModel(int model)3088 acpi_SetIntrModel(int model)
3089 {
3090
3091 return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
3092 }
3093
3094 /*
3095 * Walk subtables of a table and call a callback routine for each
3096 * subtable. The caller should provide the first subtable and a
3097 * pointer to the end of the table. This can be used to walk tables
3098 * such as MADT and SRAT that use subtable entries.
3099 */
3100 void
acpi_walk_subtables(void * first,void * end,acpi_subtable_handler * handler,void * arg)3101 acpi_walk_subtables(void *first, void *end, acpi_subtable_handler *handler,
3102 void *arg)
3103 {
3104 ACPI_SUBTABLE_HEADER *entry;
3105
3106 for (entry = first; (void *)entry < end; ) {
3107 /* Avoid an infinite loop if we hit a bogus entry. */
3108 if (entry->Length < sizeof(ACPI_SUBTABLE_HEADER))
3109 return;
3110
3111 handler(entry, arg);
3112 entry = ACPI_ADD_PTR(ACPI_SUBTABLE_HEADER, entry, entry->Length);
3113 }
3114 }
3115
3116 /*
3117 * DEPRECATED. This interface has serious deficiencies and will be
3118 * removed.
3119 *
3120 * Immediately enter the sleep state. In the old model, acpiconf(8) ran
3121 * rc.suspend and rc.resume so we don't have to notify devd(8) to do this.
3122 */
3123 ACPI_STATUS
acpi_SetSleepState(struct acpi_softc * sc,int state)3124 acpi_SetSleepState(struct acpi_softc *sc, int state)
3125 {
3126 static int once;
3127
3128 if (!once) {
3129 device_printf(sc->acpi_dev,
3130 "warning: acpi_SetSleepState() deprecated, need to update your software\n");
3131 once = 1;
3132 }
3133 return (acpi_EnterSleepState(sc, state));
3134 }
3135
3136 #if defined(__amd64__) || defined(__i386__)
3137 static void
acpi_sleep_force_task(void * context)3138 acpi_sleep_force_task(void *context)
3139 {
3140 struct acpi_softc *sc = (struct acpi_softc *)context;
3141
3142 if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
3143 device_printf(sc->acpi_dev, "force sleep state S%d failed\n",
3144 sc->acpi_next_sstate);
3145 }
3146
3147 static void
acpi_sleep_force(void * arg)3148 acpi_sleep_force(void *arg)
3149 {
3150 struct acpi_softc *sc = (struct acpi_softc *)arg;
3151
3152 device_printf(sc->acpi_dev,
3153 "suspend request timed out, forcing sleep now\n");
3154 /*
3155 * XXX Suspending from callout causes freezes in DEVICE_SUSPEND().
3156 * Suspend from acpi_task thread instead.
3157 */
3158 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3159 acpi_sleep_force_task, sc)))
3160 device_printf(sc->acpi_dev, "AcpiOsExecute() for sleeping failed\n");
3161 }
3162 #endif
3163
3164 /*
3165 * Request that the system enter the given suspend state. All /dev/apm
3166 * devices and devd(8) will be notified. Userland then has a chance to
3167 * save state and acknowledge the request. The system sleeps once all
3168 * acks are in.
3169 */
3170 int
acpi_ReqSleepState(struct acpi_softc * sc,int state)3171 acpi_ReqSleepState(struct acpi_softc *sc, int state)
3172 {
3173 #if defined(__amd64__) || defined(__i386__)
3174 struct apm_clone_data *clone;
3175 ACPI_STATUS status;
3176
3177 if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
3178 return (EINVAL);
3179 if (!acpi_sleep_states[state])
3180 return (EOPNOTSUPP);
3181
3182 /*
3183 * If a reboot/shutdown/suspend request is already in progress or
3184 * suspend is blocked due to an upcoming shutdown, just return.
3185 */
3186 if (rebooting || sc->acpi_next_sstate != 0 || suspend_blocked) {
3187 return (0);
3188 }
3189
3190 /* Wait until sleep is enabled. */
3191 while (sc->acpi_sleep_disabled) {
3192 AcpiOsSleep(1000);
3193 }
3194
3195 ACPI_LOCK(acpi);
3196
3197 sc->acpi_next_sstate = state;
3198
3199 /* S5 (soft-off) should be entered directly with no waiting. */
3200 if (state == ACPI_STATE_S5) {
3201 ACPI_UNLOCK(acpi);
3202 status = acpi_EnterSleepState(sc, state);
3203 return (ACPI_SUCCESS(status) ? 0 : ENXIO);
3204 }
3205
3206 /* Record the pending state and notify all apm devices. */
3207 STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
3208 clone->notify_status = APM_EV_NONE;
3209 if ((clone->flags & ACPI_EVF_DEVD) == 0) {
3210 selwakeuppri(&clone->sel_read, PZERO);
3211 KNOTE_LOCKED(&clone->sel_read.si_note, 0);
3212 }
3213 }
3214
3215 /* If devd(8) is not running, immediately enter the sleep state. */
3216 if (!devctl_process_running()) {
3217 ACPI_UNLOCK(acpi);
3218 status = acpi_EnterSleepState(sc, state);
3219 return (ACPI_SUCCESS(status) ? 0 : ENXIO);
3220 }
3221
3222 /*
3223 * Set a timeout to fire if userland doesn't ack the suspend request
3224 * in time. This way we still eventually go to sleep if we were
3225 * overheating or running low on battery, even if userland is hung.
3226 * We cancel this timeout once all userland acks are in or the
3227 * suspend request is aborted.
3228 */
3229 callout_reset(&sc->susp_force_to, 10 * hz, acpi_sleep_force, sc);
3230 ACPI_UNLOCK(acpi);
3231
3232 /* Now notify devd(8) also. */
3233 acpi_UserNotify("Suspend", ACPI_ROOT_OBJECT, state);
3234
3235 return (0);
3236 #else
3237 /* This platform does not support acpi suspend/resume. */
3238 return (EOPNOTSUPP);
3239 #endif
3240 }
3241
3242 /*
3243 * Acknowledge (or reject) a pending sleep state. The caller has
3244 * prepared for suspend and is now ready for it to proceed. If the
3245 * error argument is non-zero, it indicates suspend should be cancelled
3246 * and gives an errno value describing why. Once all votes are in,
3247 * we suspend the system.
3248 */
3249 int
acpi_AckSleepState(struct apm_clone_data * clone,int error)3250 acpi_AckSleepState(struct apm_clone_data *clone, int error)
3251 {
3252 #if defined(__amd64__) || defined(__i386__)
3253 struct acpi_softc *sc;
3254 int ret, sleeping;
3255
3256 /* If no pending sleep state, return an error. */
3257 ACPI_LOCK(acpi);
3258 sc = clone->acpi_sc;
3259 if (sc->acpi_next_sstate == 0) {
3260 ACPI_UNLOCK(acpi);
3261 return (ENXIO);
3262 }
3263
3264 /* Caller wants to abort suspend process. */
3265 if (error) {
3266 sc->acpi_next_sstate = 0;
3267 callout_stop(&sc->susp_force_to);
3268 device_printf(sc->acpi_dev,
3269 "listener on %s cancelled the pending suspend\n",
3270 devtoname(clone->cdev));
3271 ACPI_UNLOCK(acpi);
3272 return (0);
3273 }
3274
3275 /*
3276 * Mark this device as acking the suspend request. Then, walk through
3277 * all devices, seeing if they agree yet. We only count devices that
3278 * are writable since read-only devices couldn't ack the request.
3279 */
3280 sleeping = TRUE;
3281 clone->notify_status = APM_EV_ACKED;
3282 STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
3283 if ((clone->flags & ACPI_EVF_WRITE) != 0 &&
3284 clone->notify_status != APM_EV_ACKED) {
3285 sleeping = FALSE;
3286 break;
3287 }
3288 }
3289
3290 /* If all devices have voted "yes", we will suspend now. */
3291 if (sleeping)
3292 callout_stop(&sc->susp_force_to);
3293 ACPI_UNLOCK(acpi);
3294 ret = 0;
3295 if (sleeping) {
3296 if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
3297 ret = ENODEV;
3298 }
3299 return (ret);
3300 #else
3301 /* This platform does not support acpi suspend/resume. */
3302 return (EOPNOTSUPP);
3303 #endif
3304 }
3305
3306 static void
acpi_sleep_enable(void * arg)3307 acpi_sleep_enable(void *arg)
3308 {
3309 struct acpi_softc *sc = (struct acpi_softc *)arg;
3310
3311 ACPI_LOCK_ASSERT(acpi);
3312
3313 /* Reschedule if the system is not fully up and running. */
3314 if (!AcpiGbl_SystemAwakeAndRunning) {
3315 callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3316 return;
3317 }
3318
3319 sc->acpi_sleep_disabled = FALSE;
3320 }
3321
3322 static ACPI_STATUS
acpi_sleep_disable(struct acpi_softc * sc)3323 acpi_sleep_disable(struct acpi_softc *sc)
3324 {
3325 ACPI_STATUS status;
3326
3327 /* Fail if the system is not fully up and running. */
3328 if (!AcpiGbl_SystemAwakeAndRunning)
3329 return (AE_ERROR);
3330
3331 ACPI_LOCK(acpi);
3332 status = sc->acpi_sleep_disabled ? AE_ERROR : AE_OK;
3333 sc->acpi_sleep_disabled = TRUE;
3334 ACPI_UNLOCK(acpi);
3335
3336 return (status);
3337 }
3338
3339 enum acpi_sleep_state {
3340 ACPI_SS_NONE,
3341 ACPI_SS_GPE_SET,
3342 ACPI_SS_DEV_SUSPEND,
3343 ACPI_SS_SLP_PREP,
3344 ACPI_SS_SLEPT,
3345 };
3346
3347 /*
3348 * Enter the desired system sleep state.
3349 *
3350 * Currently we support S1-S5 but S4 is only S4BIOS
3351 */
3352 static ACPI_STATUS
acpi_EnterSleepState(struct acpi_softc * sc,int state)3353 acpi_EnterSleepState(struct acpi_softc *sc, int state)
3354 {
3355 register_t intr;
3356 ACPI_STATUS status;
3357 ACPI_EVENT_STATUS power_button_status;
3358 enum acpi_sleep_state slp_state;
3359 int sleep_result;
3360
3361 ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3362
3363 if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
3364 return_ACPI_STATUS (AE_BAD_PARAMETER);
3365 if (!acpi_sleep_states[state]) {
3366 device_printf(sc->acpi_dev, "Sleep state S%d not supported by BIOS\n",
3367 state);
3368 return (AE_SUPPORT);
3369 }
3370
3371 /* Re-entry once we're suspending is not allowed. */
3372 status = acpi_sleep_disable(sc);
3373 if (ACPI_FAILURE(status)) {
3374 device_printf(sc->acpi_dev,
3375 "suspend request ignored (not ready yet)\n");
3376 return (status);
3377 }
3378
3379 if (state == ACPI_STATE_S5) {
3380 /*
3381 * Shut down cleanly and power off. This will call us back through the
3382 * shutdown handlers.
3383 */
3384 shutdown_nice(RB_POWEROFF);
3385 return_ACPI_STATUS (AE_OK);
3386 }
3387
3388 EVENTHANDLER_INVOKE(power_suspend_early);
3389 stop_all_proc();
3390 suspend_all_fs();
3391 EVENTHANDLER_INVOKE(power_suspend);
3392
3393 #ifdef EARLY_AP_STARTUP
3394 MPASS(mp_ncpus == 1 || smp_started);
3395 thread_lock(curthread);
3396 sched_bind(curthread, 0);
3397 thread_unlock(curthread);
3398 #else
3399 if (smp_started) {
3400 thread_lock(curthread);
3401 sched_bind(curthread, 0);
3402 thread_unlock(curthread);
3403 }
3404 #endif
3405
3406 /*
3407 * Be sure to hold Giant across DEVICE_SUSPEND/RESUME
3408 */
3409 bus_topo_lock();
3410
3411 slp_state = ACPI_SS_NONE;
3412
3413 sc->acpi_sstate = state;
3414
3415 /* Enable any GPEs as appropriate and requested by the user. */
3416 acpi_wake_prep_walk(state);
3417 slp_state = ACPI_SS_GPE_SET;
3418
3419 /*
3420 * Inform all devices that we are going to sleep. If at least one
3421 * device fails, DEVICE_SUSPEND() automatically resumes the tree.
3422 *
3423 * XXX Note that a better two-pass approach with a 'veto' pass
3424 * followed by a "real thing" pass would be better, but the current
3425 * bus interface does not provide for this.
3426 */
3427 if (DEVICE_SUSPEND(root_bus) != 0) {
3428 device_printf(sc->acpi_dev, "device_suspend failed\n");
3429 goto backout;
3430 }
3431 slp_state = ACPI_SS_DEV_SUSPEND;
3432
3433 status = AcpiEnterSleepStatePrep(state);
3434 if (ACPI_FAILURE(status)) {
3435 device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
3436 AcpiFormatException(status));
3437 goto backout;
3438 }
3439 slp_state = ACPI_SS_SLP_PREP;
3440
3441 if (sc->acpi_sleep_delay > 0)
3442 DELAY(sc->acpi_sleep_delay * 1000000);
3443
3444 suspendclock();
3445 intr = intr_disable();
3446 if (state != ACPI_STATE_S1) {
3447 sleep_result = acpi_sleep_machdep(sc, state);
3448 acpi_wakeup_machdep(sc, state, sleep_result, 0);
3449
3450 /*
3451 * XXX According to ACPI specification SCI_EN bit should be restored
3452 * by ACPI platform (BIOS, firmware) to its pre-sleep state.
3453 * Unfortunately some BIOSes fail to do that and that leads to
3454 * unexpected and serious consequences during wake up like a system
3455 * getting stuck in SMI handlers.
3456 * This hack is picked up from Linux, which claims that it follows
3457 * Windows behavior.
3458 */
3459 if (sleep_result == 1 && state != ACPI_STATE_S4)
3460 AcpiWriteBitRegister(ACPI_BITREG_SCI_ENABLE, ACPI_ENABLE_EVENT);
3461
3462 if (sleep_result == 1 && state == ACPI_STATE_S3) {
3463 /*
3464 * Prevent mis-interpretation of the wakeup by power button
3465 * as a request for power off.
3466 * Ideally we should post an appropriate wakeup event,
3467 * perhaps using acpi_event_power_button_wake or alike.
3468 *
3469 * Clearing of power button status after wakeup is mandated
3470 * by ACPI specification in section "Fixed Power Button".
3471 *
3472 * XXX As of ACPICA 20121114 AcpiGetEventStatus provides
3473 * status as 0/1 corressponding to inactive/active despite
3474 * its type being ACPI_EVENT_STATUS. In other words,
3475 * we should not test for ACPI_EVENT_FLAG_SET for time being.
3476 */
3477 if (ACPI_SUCCESS(AcpiGetEventStatus(ACPI_EVENT_POWER_BUTTON,
3478 &power_button_status)) && power_button_status != 0) {
3479 AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
3480 device_printf(sc->acpi_dev,
3481 "cleared fixed power button status\n");
3482 }
3483 }
3484
3485 intr_restore(intr);
3486
3487 /* call acpi_wakeup_machdep() again with interrupt enabled */
3488 acpi_wakeup_machdep(sc, state, sleep_result, 1);
3489
3490 AcpiLeaveSleepStatePrep(state);
3491
3492 if (sleep_result == -1)
3493 goto backout;
3494
3495 /* Re-enable ACPI hardware on wakeup from sleep state 4. */
3496 if (state == ACPI_STATE_S4)
3497 AcpiEnable();
3498 } else {
3499 status = AcpiEnterSleepState(state);
3500 intr_restore(intr);
3501 AcpiLeaveSleepStatePrep(state);
3502 if (ACPI_FAILURE(status)) {
3503 device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
3504 AcpiFormatException(status));
3505 goto backout;
3506 }
3507 }
3508 slp_state = ACPI_SS_SLEPT;
3509
3510 /*
3511 * Back out state according to how far along we got in the suspend
3512 * process. This handles both the error and success cases.
3513 */
3514 backout:
3515 if (slp_state >= ACPI_SS_SLP_PREP)
3516 resumeclock();
3517 if (slp_state >= ACPI_SS_GPE_SET) {
3518 acpi_wake_prep_walk(state);
3519 sc->acpi_sstate = ACPI_STATE_S0;
3520 }
3521 if (slp_state >= ACPI_SS_DEV_SUSPEND)
3522 DEVICE_RESUME(root_bus);
3523 if (slp_state >= ACPI_SS_SLP_PREP)
3524 AcpiLeaveSleepState(state);
3525 if (slp_state >= ACPI_SS_SLEPT) {
3526 #if defined(__i386__) || defined(__amd64__)
3527 /* NB: we are still using ACPI timecounter at this point. */
3528 resume_TSC();
3529 #endif
3530 acpi_resync_clock(sc);
3531 acpi_enable_fixed_events(sc);
3532 }
3533 sc->acpi_next_sstate = 0;
3534
3535 bus_topo_unlock();
3536
3537 #ifdef EARLY_AP_STARTUP
3538 thread_lock(curthread);
3539 sched_unbind(curthread);
3540 thread_unlock(curthread);
3541 #else
3542 if (smp_started) {
3543 thread_lock(curthread);
3544 sched_unbind(curthread);
3545 thread_unlock(curthread);
3546 }
3547 #endif
3548
3549 resume_all_fs();
3550 resume_all_proc();
3551
3552 EVENTHANDLER_INVOKE(power_resume);
3553
3554 /* Allow another sleep request after a while. */
3555 callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3556
3557 /* Run /etc/rc.resume after we are back. */
3558 if (devctl_process_running())
3559 acpi_UserNotify("Resume", ACPI_ROOT_OBJECT, state);
3560
3561 return_ACPI_STATUS (status);
3562 }
3563
3564 static void
acpi_resync_clock(struct acpi_softc * sc)3565 acpi_resync_clock(struct acpi_softc *sc)
3566 {
3567
3568 /*
3569 * Warm up timecounter again and reset system clock.
3570 */
3571 (void)timecounter->tc_get_timecount(timecounter);
3572 inittodr(time_second + sc->acpi_sleep_delay);
3573 }
3574
3575 /* Enable or disable the device's wake GPE. */
3576 int
acpi_wake_set_enable(device_t dev,int enable)3577 acpi_wake_set_enable(device_t dev, int enable)
3578 {
3579 struct acpi_prw_data prw;
3580 ACPI_STATUS status;
3581 int flags;
3582
3583 /* Make sure the device supports waking the system and get the GPE. */
3584 if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
3585 return (ENXIO);
3586
3587 flags = acpi_get_flags(dev);
3588 if (enable) {
3589 status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3590 ACPI_GPE_ENABLE);
3591 if (ACPI_FAILURE(status)) {
3592 device_printf(dev, "enable wake failed\n");
3593 return (ENXIO);
3594 }
3595 acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
3596 } else {
3597 status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3598 ACPI_GPE_DISABLE);
3599 if (ACPI_FAILURE(status)) {
3600 device_printf(dev, "disable wake failed\n");
3601 return (ENXIO);
3602 }
3603 acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
3604 }
3605
3606 return (0);
3607 }
3608
3609 static int
acpi_wake_sleep_prep(ACPI_HANDLE handle,int sstate)3610 acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate)
3611 {
3612 struct acpi_prw_data prw;
3613 device_t dev;
3614
3615 /* Check that this is a wake-capable device and get its GPE. */
3616 if (acpi_parse_prw(handle, &prw) != 0)
3617 return (ENXIO);
3618 dev = acpi_get_device(handle);
3619
3620 /*
3621 * The destination sleep state must be less than (i.e., higher power)
3622 * or equal to the value specified by _PRW. If this GPE cannot be
3623 * enabled for the next sleep state, then disable it. If it can and
3624 * the user requested it be enabled, turn on any required power resources
3625 * and set _PSW.
3626 */
3627 if (sstate > prw.lowest_wake) {
3628 AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_DISABLE);
3629 if (bootverbose)
3630 device_printf(dev, "wake_prep disabled wake for %s (S%d)\n",
3631 acpi_name(handle), sstate);
3632 } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
3633 acpi_pwr_wake_enable(handle, 1);
3634 acpi_SetInteger(handle, "_PSW", 1);
3635 if (bootverbose)
3636 device_printf(dev, "wake_prep enabled for %s (S%d)\n",
3637 acpi_name(handle), sstate);
3638 }
3639
3640 return (0);
3641 }
3642
3643 static int
acpi_wake_run_prep(ACPI_HANDLE handle,int sstate)3644 acpi_wake_run_prep(ACPI_HANDLE handle, int sstate)
3645 {
3646 struct acpi_prw_data prw;
3647 device_t dev;
3648
3649 /*
3650 * Check that this is a wake-capable device and get its GPE. Return
3651 * now if the user didn't enable this device for wake.
3652 */
3653 if (acpi_parse_prw(handle, &prw) != 0)
3654 return (ENXIO);
3655 dev = acpi_get_device(handle);
3656 if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
3657 return (0);
3658
3659 /*
3660 * If this GPE couldn't be enabled for the previous sleep state, it was
3661 * disabled before going to sleep so re-enable it. If it was enabled,
3662 * clear _PSW and turn off any power resources it used.
3663 */
3664 if (sstate > prw.lowest_wake) {
3665 AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_ENABLE);
3666 if (bootverbose)
3667 device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
3668 } else {
3669 acpi_SetInteger(handle, "_PSW", 0);
3670 acpi_pwr_wake_enable(handle, 0);
3671 if (bootverbose)
3672 device_printf(dev, "run_prep cleaned up for %s\n",
3673 acpi_name(handle));
3674 }
3675
3676 return (0);
3677 }
3678
3679 static ACPI_STATUS
acpi_wake_prep(ACPI_HANDLE handle,UINT32 level,void * context,void ** status)3680 acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
3681 {
3682 int sstate;
3683
3684 /* If suspending, run the sleep prep function, otherwise wake. */
3685 sstate = *(int *)context;
3686 if (AcpiGbl_SystemAwakeAndRunning)
3687 acpi_wake_sleep_prep(handle, sstate);
3688 else
3689 acpi_wake_run_prep(handle, sstate);
3690 return (AE_OK);
3691 }
3692
3693 /* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
3694 static int
acpi_wake_prep_walk(int sstate)3695 acpi_wake_prep_walk(int sstate)
3696 {
3697 ACPI_HANDLE sb_handle;
3698
3699 if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
3700 AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
3701 acpi_wake_prep, NULL, &sstate, NULL);
3702 return (0);
3703 }
3704
3705 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
3706 static int
acpi_wake_sysctl_walk(device_t dev)3707 acpi_wake_sysctl_walk(device_t dev)
3708 {
3709 int error, i, numdevs;
3710 device_t *devlist;
3711 device_t child;
3712 ACPI_STATUS status;
3713
3714 error = device_get_children(dev, &devlist, &numdevs);
3715 if (error != 0 || numdevs == 0) {
3716 if (numdevs == 0)
3717 free(devlist, M_TEMP);
3718 return (error);
3719 }
3720 for (i = 0; i < numdevs; i++) {
3721 child = devlist[i];
3722 acpi_wake_sysctl_walk(child);
3723 if (!device_is_attached(child))
3724 continue;
3725 status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
3726 if (ACPI_SUCCESS(status)) {
3727 SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
3728 SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
3729 "wake", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, child, 0,
3730 acpi_wake_set_sysctl, "I", "Device set to wake the system");
3731 }
3732 }
3733 free(devlist, M_TEMP);
3734
3735 return (0);
3736 }
3737
3738 /* Enable or disable wake from userland. */
3739 static int
acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)3740 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
3741 {
3742 int enable, error;
3743 device_t dev;
3744
3745 dev = (device_t)arg1;
3746 enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
3747
3748 error = sysctl_handle_int(oidp, &enable, 0, req);
3749 if (error != 0 || req->newptr == NULL)
3750 return (error);
3751 if (enable != 0 && enable != 1)
3752 return (EINVAL);
3753
3754 return (acpi_wake_set_enable(dev, enable));
3755 }
3756
3757 /* Parse a device's _PRW into a structure. */
3758 int
acpi_parse_prw(ACPI_HANDLE h,struct acpi_prw_data * prw)3759 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
3760 {
3761 ACPI_STATUS status;
3762 ACPI_BUFFER prw_buffer;
3763 ACPI_OBJECT *res, *res2;
3764 int error, i, power_count;
3765
3766 if (h == NULL || prw == NULL)
3767 return (EINVAL);
3768
3769 /*
3770 * The _PRW object (7.2.9) is only required for devices that have the
3771 * ability to wake the system from a sleeping state.
3772 */
3773 error = EINVAL;
3774 prw_buffer.Pointer = NULL;
3775 prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
3776 status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
3777 if (ACPI_FAILURE(status))
3778 return (ENOENT);
3779 res = (ACPI_OBJECT *)prw_buffer.Pointer;
3780 if (res == NULL)
3781 return (ENOENT);
3782 if (!ACPI_PKG_VALID(res, 2))
3783 goto out;
3784
3785 /*
3786 * Element 1 of the _PRW object:
3787 * The lowest power system sleeping state that can be entered while still
3788 * providing wake functionality. The sleeping state being entered must
3789 * be less than (i.e., higher power) or equal to this value.
3790 */
3791 if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
3792 goto out;
3793
3794 /*
3795 * Element 0 of the _PRW object:
3796 */
3797 switch (res->Package.Elements[0].Type) {
3798 case ACPI_TYPE_INTEGER:
3799 /*
3800 * If the data type of this package element is numeric, then this
3801 * _PRW package element is the bit index in the GPEx_EN, in the
3802 * GPE blocks described in the FADT, of the enable bit that is
3803 * enabled for the wake event.
3804 */
3805 prw->gpe_handle = NULL;
3806 prw->gpe_bit = res->Package.Elements[0].Integer.Value;
3807 error = 0;
3808 break;
3809 case ACPI_TYPE_PACKAGE:
3810 /*
3811 * If the data type of this package element is a package, then this
3812 * _PRW package element is itself a package containing two
3813 * elements. The first is an object reference to the GPE Block
3814 * device that contains the GPE that will be triggered by the wake
3815 * event. The second element is numeric and it contains the bit
3816 * index in the GPEx_EN, in the GPE Block referenced by the
3817 * first element in the package, of the enable bit that is enabled for
3818 * the wake event.
3819 *
3820 * For example, if this field is a package then it is of the form:
3821 * Package() {\_SB.PCI0.ISA.GPE, 2}
3822 */
3823 res2 = &res->Package.Elements[0];
3824 if (!ACPI_PKG_VALID(res2, 2))
3825 goto out;
3826 prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
3827 if (prw->gpe_handle == NULL)
3828 goto out;
3829 if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
3830 goto out;
3831 error = 0;
3832 break;
3833 default:
3834 goto out;
3835 }
3836
3837 /* Elements 2 to N of the _PRW object are power resources. */
3838 power_count = res->Package.Count - 2;
3839 if (power_count > ACPI_PRW_MAX_POWERRES) {
3840 printf("ACPI device %s has too many power resources\n", acpi_name(h));
3841 power_count = 0;
3842 }
3843 prw->power_res_count = power_count;
3844 for (i = 0; i < power_count; i++)
3845 prw->power_res[i] = res->Package.Elements[i];
3846
3847 out:
3848 if (prw_buffer.Pointer != NULL)
3849 AcpiOsFree(prw_buffer.Pointer);
3850 return (error);
3851 }
3852
3853 /*
3854 * ACPI Event Handlers
3855 */
3856
3857 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
3858
3859 static void
acpi_system_eventhandler_sleep(void * arg,int state)3860 acpi_system_eventhandler_sleep(void *arg, int state)
3861 {
3862 struct acpi_softc *sc = (struct acpi_softc *)arg;
3863 int ret;
3864
3865 ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3866
3867 /* Check if button action is disabled or unknown. */
3868 if (state == ACPI_STATE_UNKNOWN)
3869 return;
3870
3871 /* Request that the system prepare to enter the given suspend state. */
3872 ret = acpi_ReqSleepState(sc, state);
3873 if (ret != 0)
3874 device_printf(sc->acpi_dev,
3875 "request to enter state S%d failed (err %d)\n", state, ret);
3876
3877 return_VOID;
3878 }
3879
3880 static void
acpi_system_eventhandler_wakeup(void * arg,int state)3881 acpi_system_eventhandler_wakeup(void *arg, int state)
3882 {
3883
3884 ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3885
3886 /* Currently, nothing to do for wakeup. */
3887
3888 return_VOID;
3889 }
3890
3891 /*
3892 * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
3893 */
3894 static void
acpi_invoke_sleep_eventhandler(void * context)3895 acpi_invoke_sleep_eventhandler(void *context)
3896 {
3897
3898 EVENTHANDLER_INVOKE(acpi_sleep_event, *(int *)context);
3899 }
3900
3901 static void
acpi_invoke_wake_eventhandler(void * context)3902 acpi_invoke_wake_eventhandler(void *context)
3903 {
3904
3905 EVENTHANDLER_INVOKE(acpi_wakeup_event, *(int *)context);
3906 }
3907
3908 UINT32
acpi_event_power_button_sleep(void * context)3909 acpi_event_power_button_sleep(void *context)
3910 {
3911 #if defined(__amd64__) || defined(__i386__)
3912 struct acpi_softc *sc = (struct acpi_softc *)context;
3913 #else
3914 (void)context;
3915 #endif
3916
3917 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3918
3919 #if defined(__amd64__) || defined(__i386__)
3920 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3921 acpi_invoke_sleep_eventhandler, &sc->acpi_power_button_sx)))
3922 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3923 #else
3924 shutdown_nice(RB_POWEROFF);
3925 #endif
3926
3927 return_VALUE (ACPI_INTERRUPT_HANDLED);
3928 }
3929
3930 UINT32
acpi_event_power_button_wake(void * context)3931 acpi_event_power_button_wake(void *context)
3932 {
3933 struct acpi_softc *sc = (struct acpi_softc *)context;
3934
3935 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3936
3937 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3938 acpi_invoke_wake_eventhandler, &sc->acpi_power_button_sx)))
3939 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3940 return_VALUE (ACPI_INTERRUPT_HANDLED);
3941 }
3942
3943 UINT32
acpi_event_sleep_button_sleep(void * context)3944 acpi_event_sleep_button_sleep(void *context)
3945 {
3946 struct acpi_softc *sc = (struct acpi_softc *)context;
3947
3948 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3949
3950 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3951 acpi_invoke_sleep_eventhandler, &sc->acpi_sleep_button_sx)))
3952 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3953 return_VALUE (ACPI_INTERRUPT_HANDLED);
3954 }
3955
3956 UINT32
acpi_event_sleep_button_wake(void * context)3957 acpi_event_sleep_button_wake(void *context)
3958 {
3959 struct acpi_softc *sc = (struct acpi_softc *)context;
3960
3961 ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3962
3963 if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3964 acpi_invoke_wake_eventhandler, &sc->acpi_sleep_button_sx)))
3965 return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3966 return_VALUE (ACPI_INTERRUPT_HANDLED);
3967 }
3968
3969 /*
3970 * XXX This static buffer is suboptimal. There is no locking so only
3971 * use this for single-threaded callers.
3972 */
3973 char *
acpi_name(ACPI_HANDLE handle)3974 acpi_name(ACPI_HANDLE handle)
3975 {
3976 ACPI_BUFFER buf;
3977 static char data[256];
3978
3979 buf.Length = sizeof(data);
3980 buf.Pointer = data;
3981
3982 if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
3983 return (data);
3984 return ("(unknown)");
3985 }
3986
3987 /*
3988 * Debugging/bug-avoidance. Avoid trying to fetch info on various
3989 * parts of the namespace.
3990 */
3991 int
acpi_avoid(ACPI_HANDLE handle)3992 acpi_avoid(ACPI_HANDLE handle)
3993 {
3994 char *cp, *env, *np;
3995 int len;
3996
3997 np = acpi_name(handle);
3998 if (*np == '\\')
3999 np++;
4000 if ((env = kern_getenv("debug.acpi.avoid")) == NULL)
4001 return (0);
4002
4003 /* Scan the avoid list checking for a match */
4004 cp = env;
4005 for (;;) {
4006 while (*cp != 0 && isspace(*cp))
4007 cp++;
4008 if (*cp == 0)
4009 break;
4010 len = 0;
4011 while (cp[len] != 0 && !isspace(cp[len]))
4012 len++;
4013 if (!strncmp(cp, np, len)) {
4014 freeenv(env);
4015 return(1);
4016 }
4017 cp += len;
4018 }
4019 freeenv(env);
4020
4021 return (0);
4022 }
4023
4024 /*
4025 * Debugging/bug-avoidance. Disable ACPI subsystem components.
4026 */
4027 int
acpi_disabled(char * subsys)4028 acpi_disabled(char *subsys)
4029 {
4030 char *cp, *env;
4031 int len;
4032
4033 if ((env = kern_getenv("debug.acpi.disabled")) == NULL)
4034 return (0);
4035 if (strcmp(env, "all") == 0) {
4036 freeenv(env);
4037 return (1);
4038 }
4039
4040 /* Scan the disable list, checking for a match. */
4041 cp = env;
4042 for (;;) {
4043 while (*cp != '\0' && isspace(*cp))
4044 cp++;
4045 if (*cp == '\0')
4046 break;
4047 len = 0;
4048 while (cp[len] != '\0' && !isspace(cp[len]))
4049 len++;
4050 if (strncmp(cp, subsys, len) == 0) {
4051 freeenv(env);
4052 return (1);
4053 }
4054 cp += len;
4055 }
4056 freeenv(env);
4057
4058 return (0);
4059 }
4060
4061 static void
acpi_lookup(void * arg,const char * name,device_t * dev)4062 acpi_lookup(void *arg, const char *name, device_t *dev)
4063 {
4064 ACPI_HANDLE handle;
4065
4066 if (*dev != NULL)
4067 return;
4068
4069 /*
4070 * Allow any handle name that is specified as an absolute path and
4071 * starts with '\'. We could restrict this to \_SB and friends,
4072 * but see acpi_probe_children() for notes on why we scan the entire
4073 * namespace for devices.
4074 *
4075 * XXX: The pathname argument to AcpiGetHandle() should be fixed to
4076 * be const.
4077 */
4078 if (name[0] != '\\')
4079 return;
4080 if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, __DECONST(char *, name),
4081 &handle)))
4082 return;
4083 *dev = acpi_get_device(handle);
4084 }
4085
4086 /*
4087 * Control interface.
4088 *
4089 * We multiplex ioctls for all participating ACPI devices here. Individual
4090 * drivers wanting to be accessible via /dev/acpi should use the
4091 * register/deregister interface to make their handlers visible.
4092 */
4093 struct acpi_ioctl_hook
4094 {
4095 TAILQ_ENTRY(acpi_ioctl_hook) link;
4096 u_long cmd;
4097 acpi_ioctl_fn fn;
4098 void *arg;
4099 };
4100
4101 static TAILQ_HEAD(,acpi_ioctl_hook) acpi_ioctl_hooks;
4102 static int acpi_ioctl_hooks_initted;
4103
4104 int
acpi_register_ioctl(u_long cmd,acpi_ioctl_fn fn,void * arg)4105 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
4106 {
4107 struct acpi_ioctl_hook *hp;
4108
4109 if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
4110 return (ENOMEM);
4111 hp->cmd = cmd;
4112 hp->fn = fn;
4113 hp->arg = arg;
4114
4115 ACPI_LOCK(acpi);
4116 if (acpi_ioctl_hooks_initted == 0) {
4117 TAILQ_INIT(&acpi_ioctl_hooks);
4118 acpi_ioctl_hooks_initted = 1;
4119 }
4120 TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
4121 ACPI_UNLOCK(acpi);
4122
4123 return (0);
4124 }
4125
4126 void
acpi_deregister_ioctl(u_long cmd,acpi_ioctl_fn fn)4127 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
4128 {
4129 struct acpi_ioctl_hook *hp;
4130
4131 ACPI_LOCK(acpi);
4132 TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
4133 if (hp->cmd == cmd && hp->fn == fn)
4134 break;
4135
4136 if (hp != NULL) {
4137 TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
4138 free(hp, M_ACPIDEV);
4139 }
4140 ACPI_UNLOCK(acpi);
4141 }
4142
4143 static int
acpiopen(struct cdev * dev,int flag,int fmt,struct thread * td)4144 acpiopen(struct cdev *dev, int flag, int fmt, struct thread *td)
4145 {
4146 return (0);
4147 }
4148
4149 static int
acpiclose(struct cdev * dev,int flag,int fmt,struct thread * td)4150 acpiclose(struct cdev *dev, int flag, int fmt, struct thread *td)
4151 {
4152 return (0);
4153 }
4154
4155 static int
acpiioctl(struct cdev * dev,u_long cmd,caddr_t addr,int flag,struct thread * td)4156 acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
4157 {
4158 struct acpi_softc *sc;
4159 struct acpi_ioctl_hook *hp;
4160 int error, state;
4161
4162 error = 0;
4163 hp = NULL;
4164 sc = dev->si_drv1;
4165
4166 /*
4167 * Scan the list of registered ioctls, looking for handlers.
4168 */
4169 ACPI_LOCK(acpi);
4170 if (acpi_ioctl_hooks_initted)
4171 TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
4172 if (hp->cmd == cmd)
4173 break;
4174 }
4175 ACPI_UNLOCK(acpi);
4176 if (hp)
4177 return (hp->fn(cmd, addr, hp->arg));
4178
4179 /*
4180 * Core ioctls are not permitted for non-writable user.
4181 * Currently, other ioctls just fetch information.
4182 * Not changing system behavior.
4183 */
4184 if ((flag & FWRITE) == 0)
4185 return (EPERM);
4186
4187 /* Core system ioctls. */
4188 switch (cmd) {
4189 case ACPIIO_REQSLPSTATE:
4190 state = *(int *)addr;
4191 if (state != ACPI_STATE_S5)
4192 return (acpi_ReqSleepState(sc, state));
4193 device_printf(sc->acpi_dev, "power off via acpi ioctl not supported\n");
4194 error = EOPNOTSUPP;
4195 break;
4196 case ACPIIO_ACKSLPSTATE:
4197 error = *(int *)addr;
4198 error = acpi_AckSleepState(sc->acpi_clone, error);
4199 break;
4200 case ACPIIO_SETSLPSTATE: /* DEPRECATED */
4201 state = *(int *)addr;
4202 if (state < ACPI_STATE_S0 || state > ACPI_S_STATES_MAX)
4203 return (EINVAL);
4204 if (!acpi_sleep_states[state])
4205 return (EOPNOTSUPP);
4206 if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
4207 error = ENXIO;
4208 break;
4209 default:
4210 error = ENXIO;
4211 break;
4212 }
4213
4214 return (error);
4215 }
4216
4217 static int
acpi_sname2sstate(const char * sname)4218 acpi_sname2sstate(const char *sname)
4219 {
4220 int sstate;
4221
4222 if (toupper(sname[0]) == 'S') {
4223 sstate = sname[1] - '0';
4224 if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5 &&
4225 sname[2] == '\0')
4226 return (sstate);
4227 } else if (strcasecmp(sname, "NONE") == 0)
4228 return (ACPI_STATE_UNKNOWN);
4229 return (-1);
4230 }
4231
4232 static const char *
acpi_sstate2sname(int sstate)4233 acpi_sstate2sname(int sstate)
4234 {
4235 static const char *snames[] = { "S0", "S1", "S2", "S3", "S4", "S5" };
4236
4237 if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5)
4238 return (snames[sstate]);
4239 else if (sstate == ACPI_STATE_UNKNOWN)
4240 return ("NONE");
4241 return (NULL);
4242 }
4243
4244 static int
acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)4245 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
4246 {
4247 int error;
4248 struct sbuf sb;
4249 UINT8 state;
4250
4251 sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
4252 for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
4253 if (acpi_sleep_states[state])
4254 sbuf_printf(&sb, "%s ", acpi_sstate2sname(state));
4255 sbuf_trim(&sb);
4256 sbuf_finish(&sb);
4257 error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
4258 sbuf_delete(&sb);
4259 return (error);
4260 }
4261
4262 static int
acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)4263 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
4264 {
4265 char sleep_state[10];
4266 int error, new_state, old_state;
4267
4268 old_state = *(int *)oidp->oid_arg1;
4269 strlcpy(sleep_state, acpi_sstate2sname(old_state), sizeof(sleep_state));
4270 error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
4271 if (error == 0 && req->newptr != NULL) {
4272 new_state = acpi_sname2sstate(sleep_state);
4273 if (new_state < ACPI_STATE_S1)
4274 return (EINVAL);
4275 if (new_state < ACPI_S_STATE_COUNT && !acpi_sleep_states[new_state])
4276 return (EOPNOTSUPP);
4277 if (new_state != old_state)
4278 *(int *)oidp->oid_arg1 = new_state;
4279 }
4280 return (error);
4281 }
4282
4283 /* Inform devctl(4) when we receive a Notify. */
4284 void
acpi_UserNotify(const char * subsystem,ACPI_HANDLE h,uint8_t notify)4285 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
4286 {
4287 char notify_buf[16];
4288 ACPI_BUFFER handle_buf;
4289 ACPI_STATUS status;
4290
4291 if (subsystem == NULL)
4292 return;
4293
4294 handle_buf.Pointer = NULL;
4295 handle_buf.Length = ACPI_ALLOCATE_BUFFER;
4296 status = AcpiNsHandleToPathname(h, &handle_buf, FALSE);
4297 if (ACPI_FAILURE(status))
4298 return;
4299 snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
4300 devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
4301 AcpiOsFree(handle_buf.Pointer);
4302 }
4303
4304 #ifdef ACPI_DEBUG
4305 /*
4306 * Support for parsing debug options from the kernel environment.
4307 *
4308 * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
4309 * by specifying the names of the bits in the debug.acpi.layer and
4310 * debug.acpi.level environment variables. Bits may be unset by
4311 * prefixing the bit name with !.
4312 */
4313 struct debugtag
4314 {
4315 char *name;
4316 UINT32 value;
4317 };
4318
4319 static struct debugtag dbg_layer[] = {
4320 {"ACPI_UTILITIES", ACPI_UTILITIES},
4321 {"ACPI_HARDWARE", ACPI_HARDWARE},
4322 {"ACPI_EVENTS", ACPI_EVENTS},
4323 {"ACPI_TABLES", ACPI_TABLES},
4324 {"ACPI_NAMESPACE", ACPI_NAMESPACE},
4325 {"ACPI_PARSER", ACPI_PARSER},
4326 {"ACPI_DISPATCHER", ACPI_DISPATCHER},
4327 {"ACPI_EXECUTER", ACPI_EXECUTER},
4328 {"ACPI_RESOURCES", ACPI_RESOURCES},
4329 {"ACPI_CA_DEBUGGER", ACPI_CA_DEBUGGER},
4330 {"ACPI_OS_SERVICES", ACPI_OS_SERVICES},
4331 {"ACPI_CA_DISASSEMBLER", ACPI_CA_DISASSEMBLER},
4332 {"ACPI_ALL_COMPONENTS", ACPI_ALL_COMPONENTS},
4333
4334 {"ACPI_AC_ADAPTER", ACPI_AC_ADAPTER},
4335 {"ACPI_BATTERY", ACPI_BATTERY},
4336 {"ACPI_BUS", ACPI_BUS},
4337 {"ACPI_BUTTON", ACPI_BUTTON},
4338 {"ACPI_EC", ACPI_EC},
4339 {"ACPI_FAN", ACPI_FAN},
4340 {"ACPI_POWERRES", ACPI_POWERRES},
4341 {"ACPI_PROCESSOR", ACPI_PROCESSOR},
4342 {"ACPI_THERMAL", ACPI_THERMAL},
4343 {"ACPI_TIMER", ACPI_TIMER},
4344 {"ACPI_ALL_DRIVERS", ACPI_ALL_DRIVERS},
4345 {NULL, 0}
4346 };
4347
4348 static struct debugtag dbg_level[] = {
4349 {"ACPI_LV_INIT", ACPI_LV_INIT},
4350 {"ACPI_LV_DEBUG_OBJECT", ACPI_LV_DEBUG_OBJECT},
4351 {"ACPI_LV_INFO", ACPI_LV_INFO},
4352 {"ACPI_LV_REPAIR", ACPI_LV_REPAIR},
4353 {"ACPI_LV_ALL_EXCEPTIONS", ACPI_LV_ALL_EXCEPTIONS},
4354
4355 /* Trace verbosity level 1 [Standard Trace Level] */
4356 {"ACPI_LV_INIT_NAMES", ACPI_LV_INIT_NAMES},
4357 {"ACPI_LV_PARSE", ACPI_LV_PARSE},
4358 {"ACPI_LV_LOAD", ACPI_LV_LOAD},
4359 {"ACPI_LV_DISPATCH", ACPI_LV_DISPATCH},
4360 {"ACPI_LV_EXEC", ACPI_LV_EXEC},
4361 {"ACPI_LV_NAMES", ACPI_LV_NAMES},
4362 {"ACPI_LV_OPREGION", ACPI_LV_OPREGION},
4363 {"ACPI_LV_BFIELD", ACPI_LV_BFIELD},
4364 {"ACPI_LV_TABLES", ACPI_LV_TABLES},
4365 {"ACPI_LV_VALUES", ACPI_LV_VALUES},
4366 {"ACPI_LV_OBJECTS", ACPI_LV_OBJECTS},
4367 {"ACPI_LV_RESOURCES", ACPI_LV_RESOURCES},
4368 {"ACPI_LV_USER_REQUESTS", ACPI_LV_USER_REQUESTS},
4369 {"ACPI_LV_PACKAGE", ACPI_LV_PACKAGE},
4370 {"ACPI_LV_VERBOSITY1", ACPI_LV_VERBOSITY1},
4371
4372 /* Trace verbosity level 2 [Function tracing and memory allocation] */
4373 {"ACPI_LV_ALLOCATIONS", ACPI_LV_ALLOCATIONS},
4374 {"ACPI_LV_FUNCTIONS", ACPI_LV_FUNCTIONS},
4375 {"ACPI_LV_OPTIMIZATIONS", ACPI_LV_OPTIMIZATIONS},
4376 {"ACPI_LV_VERBOSITY2", ACPI_LV_VERBOSITY2},
4377 {"ACPI_LV_ALL", ACPI_LV_ALL},
4378
4379 /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
4380 {"ACPI_LV_MUTEX", ACPI_LV_MUTEX},
4381 {"ACPI_LV_THREADS", ACPI_LV_THREADS},
4382 {"ACPI_LV_IO", ACPI_LV_IO},
4383 {"ACPI_LV_INTERRUPTS", ACPI_LV_INTERRUPTS},
4384 {"ACPI_LV_VERBOSITY3", ACPI_LV_VERBOSITY3},
4385
4386 /* Exceptionally verbose output -- also used in the global "DebugLevel" */
4387 {"ACPI_LV_AML_DISASSEMBLE", ACPI_LV_AML_DISASSEMBLE},
4388 {"ACPI_LV_VERBOSE_INFO", ACPI_LV_VERBOSE_INFO},
4389 {"ACPI_LV_FULL_TABLES", ACPI_LV_FULL_TABLES},
4390 {"ACPI_LV_EVENTS", ACPI_LV_EVENTS},
4391 {"ACPI_LV_VERBOSE", ACPI_LV_VERBOSE},
4392 {NULL, 0}
4393 };
4394
4395 static void
acpi_parse_debug(char * cp,struct debugtag * tag,UINT32 * flag)4396 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
4397 {
4398 char *ep;
4399 int i, l;
4400 int set;
4401
4402 while (*cp) {
4403 if (isspace(*cp)) {
4404 cp++;
4405 continue;
4406 }
4407 ep = cp;
4408 while (*ep && !isspace(*ep))
4409 ep++;
4410 if (*cp == '!') {
4411 set = 0;
4412 cp++;
4413 if (cp == ep)
4414 continue;
4415 } else {
4416 set = 1;
4417 }
4418 l = ep - cp;
4419 for (i = 0; tag[i].name != NULL; i++) {
4420 if (!strncmp(cp, tag[i].name, l)) {
4421 if (set)
4422 *flag |= tag[i].value;
4423 else
4424 *flag &= ~tag[i].value;
4425 }
4426 }
4427 cp = ep;
4428 }
4429 }
4430
4431 static void
acpi_set_debugging(void * junk)4432 acpi_set_debugging(void *junk)
4433 {
4434 char *layer, *level;
4435
4436 if (cold) {
4437 AcpiDbgLayer = 0;
4438 AcpiDbgLevel = 0;
4439 }
4440
4441 layer = kern_getenv("debug.acpi.layer");
4442 level = kern_getenv("debug.acpi.level");
4443 if (layer == NULL && level == NULL)
4444 return;
4445
4446 printf("ACPI set debug");
4447 if (layer != NULL) {
4448 if (strcmp("NONE", layer) != 0)
4449 printf(" layer '%s'", layer);
4450 acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
4451 freeenv(layer);
4452 }
4453 if (level != NULL) {
4454 if (strcmp("NONE", level) != 0)
4455 printf(" level '%s'", level);
4456 acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
4457 freeenv(level);
4458 }
4459 printf("\n");
4460 }
4461
4462 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
4463 NULL);
4464
4465 static int
acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)4466 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
4467 {
4468 int error, *dbg;
4469 struct debugtag *tag;
4470 struct sbuf sb;
4471 char temp[128];
4472
4473 if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
4474 return (ENOMEM);
4475 if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
4476 tag = &dbg_layer[0];
4477 dbg = &AcpiDbgLayer;
4478 } else {
4479 tag = &dbg_level[0];
4480 dbg = &AcpiDbgLevel;
4481 }
4482
4483 /* Get old values if this is a get request. */
4484 ACPI_SERIAL_BEGIN(acpi);
4485 if (*dbg == 0) {
4486 sbuf_cpy(&sb, "NONE");
4487 } else if (req->newptr == NULL) {
4488 for (; tag->name != NULL; tag++) {
4489 if ((*dbg & tag->value) == tag->value)
4490 sbuf_printf(&sb, "%s ", tag->name);
4491 }
4492 }
4493 sbuf_trim(&sb);
4494 sbuf_finish(&sb);
4495 strlcpy(temp, sbuf_data(&sb), sizeof(temp));
4496 sbuf_delete(&sb);
4497
4498 error = sysctl_handle_string(oidp, temp, sizeof(temp), req);
4499
4500 /* Check for error or no change */
4501 if (error == 0 && req->newptr != NULL) {
4502 *dbg = 0;
4503 kern_setenv((char *)oidp->oid_arg1, temp);
4504 acpi_set_debugging(NULL);
4505 }
4506 ACPI_SERIAL_END(acpi);
4507
4508 return (error);
4509 }
4510
4511 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer,
4512 CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, "debug.acpi.layer", 0,
4513 acpi_debug_sysctl, "A",
4514 "");
4515 SYSCTL_PROC(_debug_acpi, OID_AUTO, level,
4516 CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, "debug.acpi.level", 0,
4517 acpi_debug_sysctl, "A",
4518 "");
4519 #endif /* ACPI_DEBUG */
4520
4521 static int
acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)4522 acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)
4523 {
4524 int error;
4525 int old;
4526
4527 old = acpi_debug_objects;
4528 error = sysctl_handle_int(oidp, &acpi_debug_objects, 0, req);
4529 if (error != 0 || req->newptr == NULL)
4530 return (error);
4531 if (old == acpi_debug_objects || (old && acpi_debug_objects))
4532 return (0);
4533
4534 ACPI_SERIAL_BEGIN(acpi);
4535 AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
4536 ACPI_SERIAL_END(acpi);
4537
4538 return (0);
4539 }
4540
4541 static int
acpi_parse_interfaces(char * str,struct acpi_interface * iface)4542 acpi_parse_interfaces(char *str, struct acpi_interface *iface)
4543 {
4544 char *p;
4545 size_t len;
4546 int i, j;
4547
4548 p = str;
4549 while (isspace(*p) || *p == ',')
4550 p++;
4551 len = strlen(p);
4552 if (len == 0)
4553 return (0);
4554 p = strdup(p, M_TEMP);
4555 for (i = 0; i < len; i++)
4556 if (p[i] == ',')
4557 p[i] = '\0';
4558 i = j = 0;
4559 while (i < len)
4560 if (isspace(p[i]) || p[i] == '\0')
4561 i++;
4562 else {
4563 i += strlen(p + i) + 1;
4564 j++;
4565 }
4566 if (j == 0) {
4567 free(p, M_TEMP);
4568 return (0);
4569 }
4570 iface->data = malloc(sizeof(*iface->data) * j, M_TEMP, M_WAITOK);
4571 iface->num = j;
4572 i = j = 0;
4573 while (i < len)
4574 if (isspace(p[i]) || p[i] == '\0')
4575 i++;
4576 else {
4577 iface->data[j] = p + i;
4578 i += strlen(p + i) + 1;
4579 j++;
4580 }
4581
4582 return (j);
4583 }
4584
4585 static void
acpi_free_interfaces(struct acpi_interface * iface)4586 acpi_free_interfaces(struct acpi_interface *iface)
4587 {
4588
4589 free(iface->data[0], M_TEMP);
4590 free(iface->data, M_TEMP);
4591 }
4592
4593 static void
acpi_reset_interfaces(device_t dev)4594 acpi_reset_interfaces(device_t dev)
4595 {
4596 struct acpi_interface list;
4597 ACPI_STATUS status;
4598 int i;
4599
4600 if (acpi_parse_interfaces(acpi_install_interface, &list) > 0) {
4601 for (i = 0; i < list.num; i++) {
4602 status = AcpiInstallInterface(list.data[i]);
4603 if (ACPI_FAILURE(status))
4604 device_printf(dev,
4605 "failed to install _OSI(\"%s\"): %s\n",
4606 list.data[i], AcpiFormatException(status));
4607 else if (bootverbose)
4608 device_printf(dev, "installed _OSI(\"%s\")\n",
4609 list.data[i]);
4610 }
4611 acpi_free_interfaces(&list);
4612 }
4613 if (acpi_parse_interfaces(acpi_remove_interface, &list) > 0) {
4614 for (i = 0; i < list.num; i++) {
4615 status = AcpiRemoveInterface(list.data[i]);
4616 if (ACPI_FAILURE(status))
4617 device_printf(dev,
4618 "failed to remove _OSI(\"%s\"): %s\n",
4619 list.data[i], AcpiFormatException(status));
4620 else if (bootverbose)
4621 device_printf(dev, "removed _OSI(\"%s\")\n",
4622 list.data[i]);
4623 }
4624 acpi_free_interfaces(&list);
4625 }
4626 }
4627
4628 static int
acpi_pm_func(u_long cmd,void * arg,...)4629 acpi_pm_func(u_long cmd, void *arg, ...)
4630 {
4631 int state, acpi_state;
4632 int error;
4633 struct acpi_softc *sc;
4634 va_list ap;
4635
4636 error = 0;
4637 switch (cmd) {
4638 case POWER_CMD_SUSPEND:
4639 sc = (struct acpi_softc *)arg;
4640 if (sc == NULL) {
4641 error = EINVAL;
4642 goto out;
4643 }
4644
4645 va_start(ap, arg);
4646 state = va_arg(ap, int);
4647 va_end(ap);
4648
4649 switch (state) {
4650 case POWER_SLEEP_STATE_STANDBY:
4651 acpi_state = sc->acpi_standby_sx;
4652 break;
4653 case POWER_SLEEP_STATE_SUSPEND:
4654 acpi_state = sc->acpi_suspend_sx;
4655 break;
4656 case POWER_SLEEP_STATE_HIBERNATE:
4657 acpi_state = ACPI_STATE_S4;
4658 break;
4659 default:
4660 error = EINVAL;
4661 goto out;
4662 }
4663
4664 if (ACPI_FAILURE(acpi_EnterSleepState(sc, acpi_state)))
4665 error = ENXIO;
4666 break;
4667 default:
4668 error = EINVAL;
4669 goto out;
4670 }
4671
4672 out:
4673 return (error);
4674 }
4675
4676 static void
acpi_pm_register(void * arg)4677 acpi_pm_register(void *arg)
4678 {
4679 if (!cold || resource_disabled("acpi", 0))
4680 return;
4681
4682 power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
4683 }
4684
4685 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, NULL);
4686