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