xref: /freebsd/sys/dev/acpica/acpi.c (revision 95b4436e989df29f6368f13832cb13d7cbc52eac)
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_FW_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_FW_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_FW_SUSPEND:
820 		return (ACPI_STATE_S3);
821 	case POWER_STYPE_FW_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_FW_SUSPEND);
855 	case ACPI_STATE_S4:
856 		return (POWER_STYPE_FW_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 _Static_assert(ACPI_IVAR_PRIVATE >= ISA_IVAR_LAST,
1158     "ACPI private IVARs overlap with ISA IVARs");
1159 
1160 /*
1161  * Handle per-device ivars
1162  */
1163 static int
acpi_read_ivar(device_t dev,device_t child,int index,uintptr_t * result)1164 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
1165 {
1166     struct acpi_device	*ad;
1167 
1168     if ((ad = device_get_ivars(child)) == NULL) {
1169 	device_printf(child, "device has no ivars\n");
1170 	return (ENOENT);
1171     }
1172 
1173     /* ACPI and ISA compatibility ivars */
1174     switch(index) {
1175     case ACPI_IVAR_HANDLE:
1176 	*(ACPI_HANDLE *)result = ad->ad_handle;
1177 	break;
1178     case ACPI_IVAR_PRIVATE:
1179 	*(void **)result = ad->ad_private;
1180 	break;
1181     case ACPI_IVAR_FLAGS:
1182 	*(int *)result = ad->ad_flags;
1183 	break;
1184     case ACPI_IVAR_DOMAIN:
1185 	*(int *)result = ad->ad_domain;
1186 	break;
1187     case ISA_IVAR_VENDORID:
1188     case ISA_IVAR_SERIAL:
1189     case ISA_IVAR_COMPATID:
1190 	*(int *)result = -1;
1191 	break;
1192     case ISA_IVAR_LOGICALID:
1193 	*(int *)result = acpi_isa_get_logicalid(child);
1194 	break;
1195     case PCI_IVAR_CLASS:
1196 	*(uint8_t*)result = (ad->ad_cls_class >> 16) & 0xff;
1197 	break;
1198     case PCI_IVAR_SUBCLASS:
1199 	*(uint8_t*)result = (ad->ad_cls_class >> 8) & 0xff;
1200 	break;
1201     case PCI_IVAR_PROGIF:
1202 	*(uint8_t*)result = (ad->ad_cls_class >> 0) & 0xff;
1203 	break;
1204     default:
1205 	return (ENOENT);
1206     }
1207 
1208     return (0);
1209 }
1210 
1211 static int
acpi_write_ivar(device_t dev,device_t child,int index,uintptr_t value)1212 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
1213 {
1214     struct acpi_device	*ad;
1215 
1216     if ((ad = device_get_ivars(child)) == NULL) {
1217 	device_printf(child, "device has no ivars\n");
1218 	return (ENOENT);
1219     }
1220 
1221     switch(index) {
1222     case ACPI_IVAR_HANDLE:
1223 	ad->ad_handle = (ACPI_HANDLE)value;
1224 	break;
1225     case ACPI_IVAR_PRIVATE:
1226 	ad->ad_private = (void *)value;
1227 	break;
1228     case ACPI_IVAR_FLAGS:
1229 	ad->ad_flags = (int)value;
1230 	break;
1231     case ACPI_IVAR_DOMAIN:
1232 	ad->ad_domain = (int)value;
1233 	break;
1234     default:
1235 	panic("bad ivar write request (%d)", index);
1236 	return (ENOENT);
1237     }
1238 
1239     return (0);
1240 }
1241 
1242 /*
1243  * Handle child resource allocation/removal
1244  */
1245 static struct resource_list *
acpi_get_rlist(device_t dev,device_t child)1246 acpi_get_rlist(device_t dev, device_t child)
1247 {
1248     struct acpi_device		*ad;
1249 
1250     ad = device_get_ivars(child);
1251     return (&ad->ad_rl);
1252 }
1253 
1254 static int
acpi_match_resource_hint(device_t dev,int type,long value)1255 acpi_match_resource_hint(device_t dev, int type, long value)
1256 {
1257     struct acpi_device *ad = device_get_ivars(dev);
1258     struct resource_list *rl = &ad->ad_rl;
1259     struct resource_list_entry *rle;
1260 
1261     STAILQ_FOREACH(rle, rl, link) {
1262 	if (rle->type != type)
1263 	    continue;
1264 	if (rle->start <= value && rle->end >= value)
1265 	    return (1);
1266     }
1267     return (0);
1268 }
1269 
1270 /*
1271  * Does this device match because the resources match?
1272  */
1273 static bool
acpi_hint_device_matches_resources(device_t child,const char * name,int unit)1274 acpi_hint_device_matches_resources(device_t child, const char *name,
1275     int unit)
1276 {
1277 	long value;
1278 	bool matches;
1279 
1280 	/*
1281 	 * Check for matching resources.  We must have at least one match.
1282 	 * Since I/O and memory resources cannot be shared, if we get a
1283 	 * match on either of those, ignore any mismatches in IRQs or DRQs.
1284 	 *
1285 	 * XXX: We may want to revisit this to be more lenient and wire
1286 	 * as long as it gets one match.
1287 	 */
1288 	matches = false;
1289 	if (resource_long_value(name, unit, "port", &value) == 0) {
1290 		/*
1291 		 * Floppy drive controllers are notorious for having a
1292 		 * wide variety of resources not all of which include the
1293 		 * first port that is specified by the hint (typically
1294 		 * 0x3f0) (see the comment above fdc_isa_alloc_resources()
1295 		 * in fdc_isa.c).  However, they do all seem to include
1296 		 * port + 2 (e.g. 0x3f2) so for a floppy device, look for
1297 		 * 'value + 2' in the port resources instead of the hint
1298 		 * value.
1299 		 */
1300 		if (strcmp(name, "fdc") == 0)
1301 			value += 2;
1302 		if (acpi_match_resource_hint(child, SYS_RES_IOPORT, value))
1303 			matches = true;
1304 		else
1305 			return false;
1306 	}
1307 	if (resource_long_value(name, unit, "maddr", &value) == 0) {
1308 		if (acpi_match_resource_hint(child, SYS_RES_MEMORY, value))
1309 			matches = true;
1310 		else
1311 			return false;
1312 	}
1313 
1314 	/*
1315 	 * If either the I/O address and/or the memory address matched, then
1316 	 * assumed this devices matches and that any mismatch in other resources
1317 	 * will be resolved by siltently ignoring those other resources. Otherwise
1318 	 * all further resources must match.
1319 	 */
1320 	if (matches) {
1321 		return (true);
1322 	}
1323 	if (resource_long_value(name, unit, "irq", &value) == 0) {
1324 		if (acpi_match_resource_hint(child, SYS_RES_IRQ, value))
1325 			matches = true;
1326 		else
1327 			return false;
1328 	}
1329 	if (resource_long_value(name, unit, "drq", &value) == 0) {
1330 		if (acpi_match_resource_hint(child, SYS_RES_DRQ, value))
1331 			matches = true;
1332 		else
1333 			return false;
1334 	}
1335 	return matches;
1336 }
1337 
1338 
1339 /*
1340  * Wire device unit numbers based on resource matches in hints.
1341  */
1342 static void
acpi_hint_device_unit(device_t acdev,device_t child,const char * name,int * unitp)1343 acpi_hint_device_unit(device_t acdev, device_t child, const char *name,
1344     int *unitp)
1345 {
1346     device_location_cache_t *cache;
1347     const char *s;
1348     int line, unit;
1349     bool matches;
1350 
1351     /*
1352      * Iterate over all the hints for the devices with the specified
1353      * name to see if one's resources are a subset of this device.
1354      */
1355     line = 0;
1356     cache = dev_wired_cache_init();
1357     while (resource_find_dev(&line, name, &unit, "at", NULL) == 0) {
1358 	/* Must have an "at" for acpi or isa. */
1359 	resource_string_value(name, unit, "at", &s);
1360 	matches = false;
1361 	if (strcmp(s, "acpi0") == 0 || strcmp(s, "acpi") == 0 ||
1362 	    strcmp(s, "isa0") == 0 || strcmp(s, "isa") == 0)
1363 	    matches = acpi_hint_device_matches_resources(child, name, unit);
1364 	else
1365 	    matches = dev_wired_cache_match(cache, child, s);
1366 
1367 	if (matches) {
1368 	    /* We have a winner! */
1369 	    *unitp = unit;
1370 	    break;
1371 	}
1372     }
1373     dev_wired_cache_fini(cache);
1374 }
1375 
1376 /*
1377  * Fetch the NUMA domain for a device by mapping the value returned by
1378  * _PXM to a NUMA domain.  If the device does not have a _PXM method,
1379  * -2 is returned.  If any other error occurs, -1 is returned.
1380  */
1381 int
acpi_pxm_parse(device_t dev)1382 acpi_pxm_parse(device_t dev)
1383 {
1384 #ifdef NUMA
1385 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1386 	ACPI_HANDLE handle;
1387 	ACPI_STATUS status;
1388 	int pxm;
1389 
1390 	handle = acpi_get_handle(dev);
1391 	if (handle == NULL)
1392 		return (-2);
1393 	status = acpi_GetInteger(handle, "_PXM", &pxm);
1394 	if (ACPI_SUCCESS(status))
1395 		return (acpi_map_pxm_to_vm_domainid(pxm));
1396 	if (status == AE_NOT_FOUND)
1397 		return (-2);
1398 #endif
1399 #endif
1400 	return (-1);
1401 }
1402 
1403 int
acpi_get_cpus(device_t dev,device_t child,enum cpu_sets op,size_t setsize,cpuset_t * cpuset)1404 acpi_get_cpus(device_t dev, device_t child, enum cpu_sets op, size_t setsize,
1405     cpuset_t *cpuset)
1406 {
1407 	int d, error;
1408 
1409 	d = acpi_pxm_parse(child);
1410 	if (d < 0)
1411 		return (bus_generic_get_cpus(dev, child, op, setsize, cpuset));
1412 
1413 	switch (op) {
1414 	case LOCAL_CPUS:
1415 		if (setsize != sizeof(cpuset_t))
1416 			return (EINVAL);
1417 		*cpuset = cpuset_domain[d];
1418 		return (0);
1419 	case INTR_CPUS:
1420 		error = bus_generic_get_cpus(dev, child, op, setsize, cpuset);
1421 		if (error != 0)
1422 			return (error);
1423 		if (setsize != sizeof(cpuset_t))
1424 			return (EINVAL);
1425 		CPU_AND(cpuset, cpuset, &cpuset_domain[d]);
1426 		return (0);
1427 	default:
1428 		return (bus_generic_get_cpus(dev, child, op, setsize, cpuset));
1429 	}
1430 }
1431 
1432 static int
acpi_get_domain_method(device_t dev,device_t child,int * domain)1433 acpi_get_domain_method(device_t dev, device_t child, int *domain)
1434 {
1435 	int error;
1436 
1437 	error = acpi_read_ivar(dev, child, ACPI_IVAR_DOMAIN,
1438 	    (uintptr_t *)domain);
1439 	if (error == 0 && *domain != ACPI_DEV_DOMAIN_UNKNOWN)
1440 		return (0);
1441 	return (ENOENT);
1442 }
1443 
1444 static struct rman *
acpi_get_rman(device_t bus,int type,u_int flags)1445 acpi_get_rman(device_t bus, int type, u_int flags)
1446 {
1447 	/* Only memory and IO resources are managed. */
1448 	switch (type) {
1449 	case SYS_RES_IOPORT:
1450 		return (&acpi_rman_io);
1451 	case SYS_RES_MEMORY:
1452 		return (&acpi_rman_mem);
1453 	default:
1454 		return (NULL);
1455 	}
1456 }
1457 
1458 /*
1459  * Pre-allocate/manage all memory and IO resources.  Since rman can't handle
1460  * duplicates, we merge any in the sysresource attach routine.
1461  */
1462 static int
acpi_sysres_alloc(device_t dev)1463 acpi_sysres_alloc(device_t dev)
1464 {
1465     struct acpi_softc *sc = device_get_softc(dev);
1466     struct resource *res;
1467     struct resource_list_entry *rle;
1468     struct rman *rm;
1469     device_t *children;
1470     int child_count, i;
1471 
1472     /*
1473      * Probe/attach any sysresource devices.  This would be unnecessary if we
1474      * had multi-pass probe/attach.
1475      */
1476     if (device_get_children(dev, &children, &child_count) != 0)
1477 	return (ENXIO);
1478     for (i = 0; i < child_count; i++) {
1479 	if (ACPI_ID_PROBE(dev, children[i], sysres_ids, NULL) <= 0)
1480 	    device_probe_and_attach(children[i]);
1481     }
1482     free(children, M_TEMP);
1483 
1484     STAILQ_FOREACH(rle, &sc->sysres_rl, link) {
1485 	if (rle->res != NULL) {
1486 	    device_printf(dev, "duplicate resource for %jx\n", rle->start);
1487 	    continue;
1488 	}
1489 
1490 	/* Only memory and IO resources are valid here. */
1491 	rm = acpi_get_rman(dev, rle->type, 0);
1492 	if (rm == NULL)
1493 	    continue;
1494 
1495 	/* Pre-allocate resource and add to our rman pool. */
1496 	res = bus_alloc_resource(dev, rle->type,
1497 	    &rle->rid, rle->start, rle->start + rle->count - 1, rle->count,
1498 	    RF_ACTIVE | RF_UNMAPPED);
1499 	if (res != NULL) {
1500 	    rman_manage_region(rm, rman_get_start(res), rman_get_end(res));
1501 	    rle->res = res;
1502 	} else if (bootverbose)
1503 	    device_printf(dev, "reservation of %jx, %jx (%d) failed\n",
1504 		rle->start, rle->count, rle->type);
1505     }
1506     return (0);
1507 }
1508 
1509 /*
1510  * Reserve declared resources for active devices found during the
1511  * namespace scan once the boot-time attach of devices has completed.
1512  *
1513  * Ideally reserving firmware-assigned resources would work in a
1514  * depth-first traversal of the device namespace, but this is
1515  * complicated.  In particular, not all resources are enumerated by
1516  * ACPI (e.g. PCI bridges and devices enumerate their resources via
1517  * other means).  Some systems also enumerate devices via ACPI behind
1518  * PCI bridges but without a matching a PCI device_t enumerated via
1519  * PCI bus scanning, the device_t's end up as direct children of
1520  * acpi0.  Doing this scan late is not ideal, but works for now.
1521  */
1522 static void
acpi_reserve_resources(device_t dev)1523 acpi_reserve_resources(device_t dev)
1524 {
1525     struct resource_list_entry *rle;
1526     struct resource_list *rl;
1527     struct acpi_device *ad;
1528     device_t *children;
1529     int child_count, i;
1530 
1531     if (device_get_children(dev, &children, &child_count) != 0)
1532 	return;
1533     for (i = 0; i < child_count; i++) {
1534 	ad = device_get_ivars(children[i]);
1535 	rl = &ad->ad_rl;
1536 
1537 	/* Don't reserve system resources. */
1538 	if (ACPI_ID_PROBE(dev, children[i], sysres_ids, NULL) <= 0)
1539 	    continue;
1540 
1541 	STAILQ_FOREACH(rle, rl, link) {
1542 	    /*
1543 	     * Don't reserve IRQ resources.  There are many sticky things
1544 	     * to get right otherwise (e.g. IRQs for psm, atkbd, and HPET
1545 	     * when using legacy routing).
1546 	     */
1547 	    if (rle->type == SYS_RES_IRQ)
1548 		continue;
1549 
1550 	    /*
1551 	     * Don't reserve the resource if it is already allocated.
1552 	     * The acpi_ec(4) driver can allocate its resources early
1553 	     * if ECDT is present.
1554 	     */
1555 	    if (rle->res != NULL)
1556 		continue;
1557 
1558 	    /*
1559 	     * Try to reserve the resource from our parent.  If this
1560 	     * fails because the resource is a system resource, just
1561 	     * let it be.  The resource range is already reserved so
1562 	     * that other devices will not use it.  If the driver
1563 	     * needs to allocate the resource, then
1564 	     * acpi_alloc_resource() will sub-alloc from the system
1565 	     * resource.
1566 	     */
1567 	    resource_list_reserve(rl, dev, children[i], rle->type, rle->rid,
1568 		rle->start, rle->end, rle->count, 0);
1569 	}
1570     }
1571     free(children, M_TEMP);
1572 }
1573 
1574 static int
acpi_set_resource(device_t dev,device_t child,int type,int rid,rman_res_t start,rman_res_t count)1575 acpi_set_resource(device_t dev, device_t child, int type, int rid,
1576     rman_res_t start, rman_res_t count)
1577 {
1578     struct acpi_device *ad = device_get_ivars(child);
1579     struct resource_list *rl = &ad->ad_rl;
1580     rman_res_t end;
1581 
1582 #ifdef INTRNG
1583     /* map with default for now */
1584     if (type == SYS_RES_IRQ)
1585 	start = (rman_res_t)acpi_map_intr(child, (u_int)start,
1586 			acpi_get_handle(child));
1587 #endif
1588 
1589     /* If the resource is already allocated, fail. */
1590     if (resource_list_busy(rl, type, rid))
1591 	return (EBUSY);
1592 
1593     /* If the resource is already reserved, release it. */
1594     if (resource_list_reserved(rl, type, rid))
1595 	resource_list_unreserve(rl, dev, child, type, rid);
1596 
1597     /* Add the resource. */
1598     end = (start + count - 1);
1599     resource_list_add(rl, type, rid, start, end, count);
1600     return (0);
1601 }
1602 
1603 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)1604 acpi_alloc_resource(device_t bus, device_t child, int type, int rid,
1605     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1606 {
1607 #ifndef INTRNG
1608     ACPI_RESOURCE ares;
1609 #endif
1610     struct acpi_device *ad;
1611     struct resource_list_entry *rle;
1612     struct resource_list *rl;
1613     struct resource *res;
1614     int isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
1615 
1616     /*
1617      * First attempt at allocating the resource.  For direct children,
1618      * use resource_list_alloc() to handle reserved resources.  For
1619      * other devices, pass the request up to our parent.
1620      */
1621     if (bus == device_get_parent(child)) {
1622 	ad = device_get_ivars(child);
1623 	rl = &ad->ad_rl;
1624 
1625 	/*
1626 	 * Simulate the behavior of the ISA bus for direct children
1627 	 * devices.  That is, if a non-default range is specified for
1628 	 * a resource that doesn't exist, use bus_set_resource() to
1629 	 * add the resource before allocating it.  Note that these
1630 	 * resources will not be reserved.
1631 	 */
1632 	if (!isdefault && resource_list_find(rl, type, rid) == NULL)
1633 		resource_list_add(rl, type, rid, start, end, count);
1634 	res = resource_list_alloc(rl, bus, child, type, rid, start, end, count,
1635 	    flags);
1636 #ifndef INTRNG
1637 	if (res != NULL && type == SYS_RES_IRQ) {
1638 	    /*
1639 	     * Since bus_config_intr() takes immediate effect, we cannot
1640 	     * configure the interrupt associated with a device when we
1641 	     * parse the resources but have to defer it until a driver
1642 	     * actually allocates the interrupt via bus_alloc_resource().
1643 	     *
1644 	     * XXX: Should we handle the lookup failing?
1645 	     */
1646 	    if (ACPI_SUCCESS(acpi_lookup_irq_resource(child, rid, res, &ares)))
1647 		acpi_config_intr(child, &ares);
1648 	}
1649 #endif
1650 
1651 	/*
1652 	 * If this is an allocation of the "default" range for a given
1653 	 * RID, fetch the exact bounds for this resource from the
1654 	 * resource list entry to try to allocate the range from the
1655 	 * system resource regions.
1656 	 */
1657 	if (res == NULL && isdefault) {
1658 	    rle = resource_list_find(rl, type, rid);
1659 	    if (rle != NULL) {
1660 		start = rle->start;
1661 		end = rle->end;
1662 		count = rle->count;
1663 	    }
1664 	}
1665     } else
1666 	res = bus_generic_alloc_resource(bus, child, type, rid,
1667 	    start, end, count, flags);
1668 
1669     /*
1670      * If the first attempt failed and this is an allocation of a
1671      * specific range, try to satisfy the request via a suballocation
1672      * from our system resource regions.
1673      */
1674     if (res == NULL && start + count - 1 == end)
1675 	res = bus_generic_rman_alloc_resource(bus, child, type, rid, start, end,
1676 	    count, flags);
1677     return (res);
1678 }
1679 
1680 static bool
acpi_is_resource_managed(device_t bus,struct resource * r)1681 acpi_is_resource_managed(device_t bus, struct resource *r)
1682 {
1683 	struct rman *rm;
1684 
1685 	rm = acpi_get_rman(bus, rman_get_type(r), rman_get_flags(r));
1686 	if (rm == NULL)
1687 		return (false);
1688 	return (rman_is_region_manager(r, rm));
1689 }
1690 
1691 static struct resource *
acpi_managed_resource(device_t bus,struct resource * r)1692 acpi_managed_resource(device_t bus, struct resource *r)
1693 {
1694 	struct acpi_softc *sc = device_get_softc(bus);
1695 	struct resource_list_entry *rle;
1696 
1697 	KASSERT(acpi_is_resource_managed(bus, r),
1698 	    ("resource %p is not suballocated", r));
1699 
1700 	STAILQ_FOREACH(rle, &sc->sysres_rl, link) {
1701 		if (rle->type != rman_get_type(r) || rle->res == NULL)
1702 			continue;
1703 		if (rman_get_start(r) >= rman_get_start(rle->res) &&
1704 		    rman_get_end(r) <= rman_get_end(rle->res))
1705 			return (rle->res);
1706 	}
1707 	return (NULL);
1708 }
1709 
1710 static int
acpi_adjust_resource(device_t bus,device_t child,struct resource * r,rman_res_t start,rman_res_t end)1711 acpi_adjust_resource(device_t bus, device_t child, struct resource *r,
1712     rman_res_t start, rman_res_t end)
1713 {
1714 
1715     if (acpi_is_resource_managed(bus, r))
1716 	return (rman_adjust_resource(r, start, end));
1717     return (bus_generic_adjust_resource(bus, child, r, start, end));
1718 }
1719 
1720 static int
acpi_release_resource(device_t bus,device_t child,struct resource * r)1721 acpi_release_resource(device_t bus, device_t child, struct resource *r)
1722 {
1723     /*
1724      * If this resource belongs to one of our internal managers,
1725      * deactivate it and release it to the local pool.
1726      */
1727     if (acpi_is_resource_managed(bus, r))
1728 	return (bus_generic_rman_release_resource(bus, child, r));
1729 
1730     return (bus_generic_rl_release_resource(bus, child, r));
1731 }
1732 
1733 static void
acpi_delete_resource(device_t bus,device_t child,int type,int rid)1734 acpi_delete_resource(device_t bus, device_t child, int type, int rid)
1735 {
1736     struct resource_list *rl;
1737 
1738     rl = acpi_get_rlist(bus, child);
1739     if (resource_list_busy(rl, type, rid)) {
1740 	device_printf(bus, "delete_resource: Resource still owned by child"
1741 	    " (type=%d, rid=%d)\n", type, rid);
1742 	return;
1743     }
1744     if (resource_list_reserved(rl, type, rid))
1745 	resource_list_unreserve(rl, bus, child, type, rid);
1746     resource_list_delete(rl, type, rid);
1747 }
1748 
1749 static int
acpi_activate_resource(device_t bus,device_t child,struct resource * r)1750 acpi_activate_resource(device_t bus, device_t child, struct resource *r)
1751 {
1752 	if (acpi_is_resource_managed(bus, r))
1753 		return (bus_generic_rman_activate_resource(bus, child, r));
1754 	return (bus_generic_activate_resource(bus, child, r));
1755 }
1756 
1757 static int
acpi_deactivate_resource(device_t bus,device_t child,struct resource * r)1758 acpi_deactivate_resource(device_t bus, device_t child, struct resource *r)
1759 {
1760 	if (acpi_is_resource_managed(bus, r))
1761 		return (bus_generic_rman_deactivate_resource(bus, child, r));
1762 	return (bus_generic_deactivate_resource(bus, child, r));
1763 }
1764 
1765 static int
acpi_map_resource(device_t bus,device_t child,struct resource * r,struct resource_map_request * argsp,struct resource_map * map)1766 acpi_map_resource(device_t bus, device_t child, struct resource *r,
1767     struct resource_map_request *argsp, struct resource_map *map)
1768 {
1769 	struct resource_map_request args;
1770 	struct resource *sysres;
1771 	rman_res_t length, start;
1772 	int error;
1773 
1774 	if (!acpi_is_resource_managed(bus, r))
1775 		return (bus_generic_map_resource(bus, child, r, argsp, map));
1776 
1777 	/* Resources must be active to be mapped. */
1778 	if (!(rman_get_flags(r) & RF_ACTIVE))
1779 		return (ENXIO);
1780 
1781 	resource_init_map_request(&args);
1782 	error = resource_validate_map_request(r, argsp, &args, &start, &length);
1783 	if (error)
1784 		return (error);
1785 
1786 	sysres = acpi_managed_resource(bus, r);
1787 	if (sysres == NULL)
1788 		return (ENOENT);
1789 
1790 	args.offset = start - rman_get_start(sysres);
1791 	args.length = length;
1792 	return (bus_map_resource(bus, sysres, &args, map));
1793 }
1794 
1795 static int
acpi_unmap_resource(device_t bus,device_t child,struct resource * r,struct resource_map * map)1796 acpi_unmap_resource(device_t bus, device_t child, struct resource *r,
1797     struct resource_map *map)
1798 {
1799 	struct resource *sysres;
1800 
1801 	if (!acpi_is_resource_managed(bus, r))
1802 		return (bus_generic_unmap_resource(bus, child, r, map));
1803 
1804 	sysres = acpi_managed_resource(bus, r);
1805 	if (sysres == NULL)
1806 		return (ENOENT);
1807 	return (bus_unmap_resource(bus, sysres, map));
1808 }
1809 
1810 /* Allocate an IO port or memory resource, given its GAS. */
1811 int
acpi_bus_alloc_gas(device_t dev,int * type,int rid,ACPI_GENERIC_ADDRESS * gas,struct resource ** res,u_int flags)1812 acpi_bus_alloc_gas(device_t dev, int *type, int rid, ACPI_GENERIC_ADDRESS *gas,
1813     struct resource **res, u_int flags)
1814 {
1815     int error, res_type;
1816 
1817     error = ENOMEM;
1818     if (type == NULL || gas == NULL || res == NULL)
1819 	return (EINVAL);
1820 
1821     /* We only support memory and IO spaces. */
1822     switch (gas->SpaceId) {
1823     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
1824 	res_type = SYS_RES_MEMORY;
1825 	break;
1826     case ACPI_ADR_SPACE_SYSTEM_IO:
1827 	res_type = SYS_RES_IOPORT;
1828 	break;
1829     default:
1830 	return (EOPNOTSUPP);
1831     }
1832 
1833     /*
1834      * If the register width is less than 8, assume the BIOS author means
1835      * it is a bit field and just allocate a byte.
1836      */
1837     if (gas->BitWidth && gas->BitWidth < 8)
1838 	gas->BitWidth = 8;
1839 
1840     /* Validate the address after we're sure we support the space. */
1841     if (gas->Address == 0 || gas->BitWidth == 0)
1842 	return (EINVAL);
1843 
1844     bus_set_resource(dev, res_type, rid, gas->Address,
1845 	gas->BitWidth / 8);
1846     *res = bus_alloc_resource_any(dev, res_type, rid, RF_ACTIVE | flags);
1847     if (*res != NULL) {
1848 	*type = res_type;
1849 	error = 0;
1850     } else
1851 	bus_delete_resource(dev, res_type, rid);
1852 
1853     return (error);
1854 }
1855 
1856 /* Probe _HID and _CID for compatible ISA PNP ids. */
1857 static uint32_t
acpi_isa_get_logicalid(device_t dev)1858 acpi_isa_get_logicalid(device_t dev)
1859 {
1860     ACPI_DEVICE_INFO	*devinfo;
1861     ACPI_HANDLE		h;
1862     uint32_t		pnpid;
1863 
1864     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1865 
1866     /* Fetch and validate the HID. */
1867     if ((h = acpi_get_handle(dev)) == NULL ||
1868 	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1869 	return_VALUE (0);
1870 
1871     pnpid = (devinfo->Valid & ACPI_VALID_HID) != 0 &&
1872 	devinfo->HardwareId.Length >= ACPI_EISAID_STRING_SIZE ?
1873 	PNP_EISAID(devinfo->HardwareId.String) : 0;
1874     AcpiOsFree(devinfo);
1875 
1876     return_VALUE (pnpid);
1877 }
1878 
1879 static int
acpi_isa_get_compatid(device_t dev,uint32_t * cids,int count)1880 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
1881 {
1882     ACPI_DEVICE_INFO	*devinfo;
1883     ACPI_PNP_DEVICE_ID	*ids;
1884     ACPI_HANDLE		h;
1885     uint32_t		*pnpid;
1886     int			i, valid;
1887 
1888     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1889 
1890     pnpid = cids;
1891 
1892     /* Fetch and validate the CID */
1893     if ((h = acpi_get_handle(dev)) == NULL ||
1894 	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1895 	return_VALUE (0);
1896 
1897     if ((devinfo->Valid & ACPI_VALID_CID) == 0) {
1898 	AcpiOsFree(devinfo);
1899 	return_VALUE (0);
1900     }
1901 
1902     if (devinfo->CompatibleIdList.Count < count)
1903 	count = devinfo->CompatibleIdList.Count;
1904     ids = devinfo->CompatibleIdList.Ids;
1905     for (i = 0, valid = 0; i < count; i++)
1906 	if (ids[i].Length >= ACPI_EISAID_STRING_SIZE &&
1907 	    strncmp(ids[i].String, "PNP", 3) == 0) {
1908 	    *pnpid++ = PNP_EISAID(ids[i].String);
1909 	    valid++;
1910 	}
1911     AcpiOsFree(devinfo);
1912 
1913     return_VALUE (valid);
1914 }
1915 
1916 static int
acpi_device_id_probe(device_t bus,device_t dev,char ** ids,char ** match)1917 acpi_device_id_probe(device_t bus, device_t dev, char **ids, char **match)
1918 {
1919     ACPI_HANDLE h;
1920     ACPI_OBJECT_TYPE t;
1921     int rv;
1922     int i;
1923 
1924     h = acpi_get_handle(dev);
1925     if (ids == NULL || h == NULL)
1926 	return (ENXIO);
1927     t = acpi_get_type(dev);
1928     if (t != ACPI_TYPE_DEVICE && t != ACPI_TYPE_PROCESSOR)
1929 	return (ENXIO);
1930 
1931     /* Try to match one of the array of IDs with a HID or CID. */
1932     for (i = 0; ids[i] != NULL; i++) {
1933 	rv = acpi_MatchHid(h, ids[i]);
1934 	if (rv == ACPI_MATCHHID_NOMATCH)
1935 	    continue;
1936 
1937 	if (match != NULL) {
1938 	    *match = ids[i];
1939 	}
1940 	return ((rv == ACPI_MATCHHID_HID)?
1941 		    BUS_PROBE_DEFAULT : BUS_PROBE_LOW_PRIORITY);
1942     }
1943     return (ENXIO);
1944 }
1945 
1946 static ACPI_STATUS
acpi_device_eval_obj(device_t bus,device_t dev,ACPI_STRING pathname,ACPI_OBJECT_LIST * parameters,ACPI_BUFFER * ret)1947 acpi_device_eval_obj(device_t bus, device_t dev, ACPI_STRING pathname,
1948     ACPI_OBJECT_LIST *parameters, ACPI_BUFFER *ret)
1949 {
1950     ACPI_HANDLE h;
1951 
1952     if (dev == NULL)
1953 	h = ACPI_ROOT_OBJECT;
1954     else if ((h = acpi_get_handle(dev)) == NULL)
1955 	return (AE_BAD_PARAMETER);
1956     return (AcpiEvaluateObject(h, pathname, parameters, ret));
1957 }
1958 
1959 static ACPI_STATUS
acpi_device_get_prop(device_t bus,device_t dev,ACPI_STRING propname,const ACPI_OBJECT ** value)1960 acpi_device_get_prop(device_t bus, device_t dev, ACPI_STRING propname,
1961     const ACPI_OBJECT **value)
1962 {
1963 	const ACPI_OBJECT *pkg, *name, *val;
1964 	struct acpi_device *ad;
1965 	ACPI_STATUS status;
1966 	int i;
1967 
1968 	ad = device_get_ivars(dev);
1969 
1970 	if (ad == NULL || propname == NULL)
1971 		return (AE_BAD_PARAMETER);
1972 	if (ad->dsd_pkg == NULL) {
1973 		if (ad->dsd.Pointer == NULL) {
1974 			status = acpi_find_dsd(ad);
1975 			if (ACPI_FAILURE(status))
1976 				return (status);
1977 		} else {
1978 			return (AE_NOT_FOUND);
1979 		}
1980 	}
1981 
1982 	for (i = 0; i < ad->dsd_pkg->Package.Count; i ++) {
1983 		pkg = &ad->dsd_pkg->Package.Elements[i];
1984 		if (pkg->Type != ACPI_TYPE_PACKAGE || pkg->Package.Count != 2)
1985 			continue;
1986 
1987 		name = &pkg->Package.Elements[0];
1988 		val = &pkg->Package.Elements[1];
1989 		if (name->Type != ACPI_TYPE_STRING)
1990 			continue;
1991 		if (strncmp(propname, name->String.Pointer, name->String.Length) == 0) {
1992 			if (value != NULL)
1993 				*value = val;
1994 
1995 			return (AE_OK);
1996 		}
1997 	}
1998 
1999 	return (AE_NOT_FOUND);
2000 }
2001 
2002 static ACPI_STATUS
acpi_find_dsd(struct acpi_device * ad)2003 acpi_find_dsd(struct acpi_device *ad)
2004 {
2005 	const ACPI_OBJECT *dsd, *guid, *pkg;
2006 	ACPI_STATUS status;
2007 
2008 	ad->dsd.Length = ACPI_ALLOCATE_BUFFER;
2009 	ad->dsd.Pointer = NULL;
2010 	ad->dsd_pkg = NULL;
2011 
2012 	status = AcpiEvaluateObject(ad->ad_handle, "_DSD", NULL, &ad->dsd);
2013 	if (ACPI_FAILURE(status))
2014 		return (status);
2015 
2016 	dsd = ad->dsd.Pointer;
2017 	guid = &dsd->Package.Elements[0];
2018 	pkg = &dsd->Package.Elements[1];
2019 
2020 	if (guid->Type != ACPI_TYPE_BUFFER || pkg->Type != ACPI_TYPE_PACKAGE ||
2021 		guid->Buffer.Length != sizeof(acpi_dsd_uuid))
2022 		return (AE_NOT_FOUND);
2023 	if (memcmp(guid->Buffer.Pointer, &acpi_dsd_uuid,
2024 		sizeof(acpi_dsd_uuid)) == 0) {
2025 
2026 		ad->dsd_pkg = pkg;
2027 		return (AE_OK);
2028 	}
2029 
2030 	return (AE_NOT_FOUND);
2031 }
2032 
2033 static ssize_t
acpi_bus_get_prop_handle(const ACPI_OBJECT * hobj,void * propvalue,size_t size)2034 acpi_bus_get_prop_handle(const ACPI_OBJECT *hobj, void *propvalue, size_t size)
2035 {
2036 	ACPI_OBJECT *pobj;
2037 	ACPI_HANDLE h;
2038 
2039 	if (hobj->Type != ACPI_TYPE_PACKAGE)
2040 		goto err;
2041 	if (hobj->Package.Count != 1)
2042 		goto err;
2043 
2044 	pobj = &hobj->Package.Elements[0];
2045 	if (pobj == NULL)
2046 		goto err;
2047 	if (pobj->Type != ACPI_TYPE_LOCAL_REFERENCE)
2048 		goto err;
2049 
2050 	h = acpi_GetReference(NULL, pobj);
2051 	if (h == NULL)
2052 		goto err;
2053 
2054 	if (propvalue != NULL && size >= sizeof(ACPI_HANDLE))
2055 		*(ACPI_HANDLE *)propvalue = h;
2056 	return (sizeof(ACPI_HANDLE));
2057 
2058 err:
2059 	return (-1);
2060 }
2061 
2062 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)2063 acpi_bus_get_prop(device_t bus, device_t child, const char *propname,
2064     void *propvalue, size_t size, device_property_type_t type)
2065 {
2066 	ACPI_STATUS status;
2067 	const ACPI_OBJECT *obj;
2068 
2069 	status = acpi_device_get_prop(bus, child, __DECONST(char *, propname),
2070 		&obj);
2071 	if (ACPI_FAILURE(status))
2072 		return (-1);
2073 
2074 	switch (type) {
2075 	case DEVICE_PROP_ANY:
2076 	case DEVICE_PROP_BUFFER:
2077 	case DEVICE_PROP_UINT32:
2078 	case DEVICE_PROP_UINT64:
2079 		break;
2080 	case DEVICE_PROP_HANDLE:
2081 		return (acpi_bus_get_prop_handle(obj, propvalue, size));
2082 	default:
2083 		return (-1);
2084 	}
2085 
2086 	switch (obj->Type) {
2087 	case ACPI_TYPE_INTEGER:
2088 		if (type == DEVICE_PROP_UINT32) {
2089 			if (propvalue != NULL && size >= sizeof(uint32_t))
2090 				*((uint32_t *)propvalue) = obj->Integer.Value;
2091 			return (sizeof(uint32_t));
2092 		}
2093 		if (propvalue != NULL && size >= sizeof(uint64_t))
2094 			*((uint64_t *) propvalue) = obj->Integer.Value;
2095 		return (sizeof(uint64_t));
2096 
2097 	case ACPI_TYPE_STRING:
2098 		if (type != DEVICE_PROP_ANY &&
2099 		    type != DEVICE_PROP_BUFFER)
2100 			return (-1);
2101 
2102 		if (propvalue != NULL && size > 0)
2103 			memcpy(propvalue, obj->String.Pointer,
2104 			    MIN(size, obj->String.Length));
2105 		return (obj->String.Length);
2106 
2107 	case ACPI_TYPE_BUFFER:
2108 		if (propvalue != NULL && size > 0)
2109 			memcpy(propvalue, obj->Buffer.Pointer,
2110 			    MIN(size, obj->Buffer.Length));
2111 		return (obj->Buffer.Length);
2112 
2113 	case ACPI_TYPE_PACKAGE:
2114 		if (propvalue != NULL && size >= sizeof(ACPI_OBJECT *)) {
2115 			*((ACPI_OBJECT **) propvalue) =
2116 			    __DECONST(ACPI_OBJECT *, obj);
2117 		}
2118 		return (sizeof(ACPI_OBJECT *));
2119 
2120 	case ACPI_TYPE_LOCAL_REFERENCE:
2121 		if (propvalue != NULL && size >= sizeof(ACPI_HANDLE)) {
2122 			ACPI_HANDLE h;
2123 
2124 			h = acpi_GetReference(NULL,
2125 			    __DECONST(ACPI_OBJECT *, obj));
2126 			memcpy(propvalue, h, sizeof(ACPI_HANDLE));
2127 		}
2128 		return (sizeof(ACPI_HANDLE));
2129 	default:
2130 		return (0);
2131 	}
2132 }
2133 
2134 static int
acpi_device_pwr_for_sleep_sxd(device_t dev,ACPI_HANDLE handle,int state,int * dstate)2135 acpi_device_pwr_for_sleep_sxd(device_t dev, ACPI_HANDLE handle, int state,
2136     int *dstate)
2137 {
2138 	ACPI_STATUS status;
2139 	char sxd[8];
2140 
2141 	/* Note illegal _S0D is evaluated because some systems expect this. */
2142 	snprintf(sxd, sizeof(sxd), "_S%dD", state);
2143 	status = acpi_GetInteger(handle, sxd, dstate);
2144 	if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
2145 		device_printf(dev, "failed to get %s on %s: %s\n", sxd,
2146 		    acpi_name(handle), AcpiFormatException(status));
2147 		return (ENXIO);
2148 	}
2149 	return (0);
2150 }
2151 
2152 /*
2153  * Get the D-state we need to set the device to for entry into the sleep type
2154  * we are currently entering (sc->acpi_stype is set in acpi_EnterSleepState
2155  * before the ACPI bus gets suspended, and thus before this function is called).
2156  *
2157  * If entering s2idle, we will try to enter whichever D-state we would've been
2158  * transitioning to in S3. If we are entering an ACPI S-state, we evaluate the
2159  * relevant _SxD state instead (ACPI 7.3.16 - 7.3.19).
2160  */
2161 int
acpi_device_pwr_for_sleep(device_t bus,device_t dev,int * dstate)2162 acpi_device_pwr_for_sleep(device_t bus, device_t dev, int *dstate)
2163 {
2164 	struct acpi_softc *sc = device_get_softc(bus);
2165 	ACPI_HANDLE handle = acpi_get_handle(dev);
2166 	int state;
2167 
2168 	if (dstate == NULL)
2169 		return (EINVAL);
2170 
2171 	/*
2172 	 * XXX If we find these devices, don't try to power them down.
2173 	 * The serial and IRDA ports on my T23 hang the system when
2174 	 * set to D3 and it appears that such legacy devices may
2175 	 * need special handling in their drivers.
2176 	 */
2177 	if (handle == NULL ||
2178 	    acpi_MatchHid(handle, "PNP0500") ||
2179 	    acpi_MatchHid(handle, "PNP0501") ||
2180 	    acpi_MatchHid(handle, "PNP0502") ||
2181 	    acpi_MatchHid(handle, "PNP0510") ||
2182 	    acpi_MatchHid(handle, "PNP0511"))
2183 		return (ENXIO);
2184 
2185 	if (sc->acpi_stype == POWER_STYPE_SUSPEND_TO_IDLE)
2186 		state = ACPI_STATE_S3;
2187 	else
2188 		state = acpi_stype_to_sstate(sc, sc->acpi_stype);
2189 	if (state == ACPI_STATE_UNKNOWN)
2190 		return (ENOENT);
2191 	return (acpi_device_pwr_for_sleep_sxd(bus, handle, state, dstate));
2192 }
2193 
2194 /* Callback arg for our implementation of walking the namespace. */
2195 struct acpi_device_scan_ctx {
2196     acpi_scan_cb_t	user_fn;
2197     void		*arg;
2198     ACPI_HANDLE		parent;
2199 };
2200 
2201 static ACPI_STATUS
acpi_device_scan_cb(ACPI_HANDLE h,UINT32 level,void * arg,void ** retval)2202 acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level, void *arg, void **retval)
2203 {
2204     struct acpi_device_scan_ctx *ctx;
2205     device_t dev, old_dev;
2206     ACPI_STATUS status;
2207     ACPI_OBJECT_TYPE type;
2208 
2209     /*
2210      * Skip this device if we think we'll have trouble with it or it is
2211      * the parent where the scan began.
2212      */
2213     ctx = (struct acpi_device_scan_ctx *)arg;
2214     if (acpi_avoid(h) || h == ctx->parent)
2215 	return (AE_OK);
2216 
2217     /* If this is not a valid device type (e.g., a method), skip it. */
2218     if (ACPI_FAILURE(AcpiGetType(h, &type)))
2219 	return (AE_OK);
2220     if (type != ACPI_TYPE_DEVICE && type != ACPI_TYPE_PROCESSOR &&
2221 	type != ACPI_TYPE_THERMAL && type != ACPI_TYPE_POWER)
2222 	return (AE_OK);
2223 
2224     /*
2225      * Call the user function with the current device.  If it is unchanged
2226      * afterwards, return.  Otherwise, we update the handle to the new dev.
2227      */
2228     old_dev = acpi_get_device(h);
2229     dev = old_dev;
2230     status = ctx->user_fn(h, &dev, level, ctx->arg);
2231     if (ACPI_FAILURE(status) || old_dev == dev)
2232 	return (status);
2233 
2234     /* Remove the old child and its connection to the handle. */
2235     if (old_dev != NULL)
2236 	device_delete_child(device_get_parent(old_dev), old_dev);
2237 
2238     /* Recreate the handle association if the user created a device. */
2239     if (dev != NULL)
2240 	AcpiAttachData(h, acpi_fake_objhandler, dev);
2241 
2242     return (AE_OK);
2243 }
2244 
2245 static ACPI_STATUS
acpi_device_scan_children(device_t bus,device_t dev,int max_depth,acpi_scan_cb_t user_fn,void * arg)2246 acpi_device_scan_children(device_t bus, device_t dev, int max_depth,
2247     acpi_scan_cb_t user_fn, void *arg)
2248 {
2249     ACPI_HANDLE h;
2250     struct acpi_device_scan_ctx ctx;
2251 
2252     if (acpi_disabled("children"))
2253 	return (AE_OK);
2254 
2255     if (dev == NULL)
2256 	h = ACPI_ROOT_OBJECT;
2257     else if ((h = acpi_get_handle(dev)) == NULL)
2258 	return (AE_BAD_PARAMETER);
2259     ctx.user_fn = user_fn;
2260     ctx.arg = arg;
2261     ctx.parent = h;
2262     return (AcpiWalkNamespace(ACPI_TYPE_ANY, h, max_depth,
2263 	acpi_device_scan_cb, NULL, &ctx, NULL));
2264 }
2265 
2266 /*
2267  * Even though ACPI devices are not PCI, we use the PCI approach for setting
2268  * device power states since it's close enough to ACPI.
2269  */
2270 int
acpi_set_powerstate(device_t child,int state)2271 acpi_set_powerstate(device_t child, int state)
2272 {
2273     ACPI_HANDLE h;
2274     ACPI_STATUS status;
2275 
2276     h = acpi_get_handle(child);
2277     if (state < ACPI_STATE_D0 || state > ACPI_D_STATES_MAX)
2278 	return (EINVAL);
2279     if (h == NULL)
2280 	return (0);
2281 
2282     /* Ignore errors if the power methods aren't present. */
2283     status = acpi_pwr_switch_consumer(h, state);
2284     if (ACPI_SUCCESS(status)) {
2285 	if (bootverbose)
2286 	    device_printf(child, "set ACPI power state %s on %s\n",
2287 		acpi_d_state_to_str(state), acpi_name(h));
2288     } else if (status != AE_NOT_FOUND)
2289 	device_printf(child,
2290 	    "failed to set ACPI power state %s on %s: %s\n",
2291 	    acpi_d_state_to_str(state), acpi_name(h),
2292 	    AcpiFormatException(status));
2293 
2294     return (0);
2295 }
2296 
2297 static int
acpi_isa_pnp_probe(device_t bus,device_t child,struct isa_pnp_id * ids)2298 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
2299 {
2300     int			result, cid_count, i;
2301     uint32_t		lid, cids[8];
2302 
2303     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2304 
2305     /*
2306      * ISA-style drivers attached to ACPI may persist and
2307      * probe manually if we return ENOENT.  We never want
2308      * that to happen, so don't ever return it.
2309      */
2310     result = ENXIO;
2311 
2312     /* Scan the supplied IDs for a match */
2313     lid = acpi_isa_get_logicalid(child);
2314     cid_count = acpi_isa_get_compatid(child, cids, 8);
2315     while (ids && ids->ip_id) {
2316 	if (lid == ids->ip_id) {
2317 	    result = 0;
2318 	    goto out;
2319 	}
2320 	for (i = 0; i < cid_count; i++) {
2321 	    if (cids[i] == ids->ip_id) {
2322 		result = 0;
2323 		goto out;
2324 	    }
2325 	}
2326 	ids++;
2327     }
2328 
2329  out:
2330     if (result == 0 && ids->ip_desc)
2331 	device_set_desc(child, ids->ip_desc);
2332 
2333     return_VALUE (result);
2334 }
2335 
2336 /*
2337  * Look for a MCFG table.  If it is present, use the settings for
2338  * domain (segment) 0 to setup PCI config space access via the memory
2339  * map.
2340  *
2341  * On non-x86 architectures (arm64 for now), this will be done from the
2342  * PCI host bridge driver.
2343  */
2344 static void
acpi_enable_pcie(void)2345 acpi_enable_pcie(void)
2346 {
2347 #if defined(__i386__) || defined(__amd64__)
2348 	ACPI_TABLE_HEADER *hdr;
2349 	ACPI_MCFG_ALLOCATION *alloc, *end;
2350 	ACPI_STATUS status;
2351 
2352 	status = AcpiGetTable(ACPI_SIG_MCFG, 1, &hdr);
2353 	if (ACPI_FAILURE(status))
2354 		return;
2355 
2356 	end = (ACPI_MCFG_ALLOCATION *)((char *)hdr + hdr->Length);
2357 	alloc = (ACPI_MCFG_ALLOCATION *)((ACPI_TABLE_MCFG *)hdr + 1);
2358 	while (alloc < end) {
2359 		pcie_cfgregopen(alloc->Address, alloc->PciSegment,
2360 		    alloc->StartBusNumber, alloc->EndBusNumber);
2361 		alloc++;
2362 	}
2363 #endif
2364 }
2365 
2366 static void
acpi_platform_osc(device_t dev)2367 acpi_platform_osc(device_t dev)
2368 {
2369 	ACPI_HANDLE sb_handle;
2370 	ACPI_STATUS status;
2371 	uint32_t cap_set[2];
2372 
2373 	/* 0811B06E-4A27-44F9-8D60-3CBBC22E7B48 */
2374 	static uint8_t acpi_platform_uuid[ACPI_UUID_LENGTH] = {
2375 		0x6e, 0xb0, 0x11, 0x08, 0x27, 0x4a, 0xf9, 0x44,
2376 		0x8d, 0x60, 0x3c, 0xbb, 0xc2, 0x2e, 0x7b, 0x48
2377 	};
2378 
2379 	if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2380 		return;
2381 
2382 	cap_set[1] = 0x10;	/* APEI Support */
2383 	status = acpi_EvaluateOSC(sb_handle, acpi_platform_uuid, 1,
2384 	    nitems(cap_set), cap_set, cap_set, false);
2385 	if (ACPI_FAILURE(status)) {
2386 		if (status == AE_NOT_FOUND)
2387 			return;
2388 		device_printf(dev, "_OSC failed: %s\n",
2389 		    AcpiFormatException(status));
2390 		return;
2391 	}
2392 }
2393 
2394 /*
2395  * Scan all of the ACPI namespace and attach child devices.
2396  *
2397  * We should only expect to find devices in the \_PR, \_TZ, \_SI, and
2398  * \_SB scopes, and \_PR and \_TZ became obsolete in the ACPI 2.0 spec.
2399  * However, in violation of the spec, some systems place their PCI link
2400  * devices in \, so we have to walk the whole namespace.  We check the
2401  * type of namespace nodes, so this should be ok.
2402  */
2403 static void
acpi_probe_children(device_t bus)2404 acpi_probe_children(device_t bus)
2405 {
2406 
2407     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2408 
2409     /*
2410      * Scan the namespace and insert placeholders for all the devices that
2411      * we find.  We also probe/attach any early devices.
2412      *
2413      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
2414      * we want to create nodes for all devices, not just those that are
2415      * currently present. (This assumes that we don't want to create/remove
2416      * devices as they appear, which might be smarter.)
2417      */
2418     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
2419     AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, 100, acpi_probe_child,
2420 	NULL, bus, NULL);
2421 
2422     /* Pre-allocate resources for our rman from any sysresource devices. */
2423     acpi_sysres_alloc(bus);
2424 
2425     /* Create any static children by calling device identify methods. */
2426     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
2427     bus_identify_children(bus);
2428 
2429     /* Probe/attach all children, created statically and from the namespace. */
2430     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "acpi bus_attach_children\n"));
2431     bus_attach_children(bus);
2432 
2433     /*
2434      * Reserve resources allocated to children but not yet allocated
2435      * by a driver.
2436      */
2437     acpi_reserve_resources(bus);
2438 
2439     /* Attach wake sysctls. */
2440     acpi_wake_sysctl_walk(bus);
2441 
2442     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
2443     return_VOID;
2444 }
2445 
2446 /*
2447  * Determine the probe order for a given device.
2448  */
2449 static void
acpi_probe_order(ACPI_HANDLE handle,int * order)2450 acpi_probe_order(ACPI_HANDLE handle, int *order)
2451 {
2452 	ACPI_OBJECT_TYPE type;
2453 
2454 	/*
2455 	 * 0. CPUs
2456 	 * 1. I/O port and memory system resource holders
2457 	 * 2. Clocks and timers (to handle early accesses)
2458 	 * 3. Embedded controllers (to handle early accesses)
2459 	 * 4. PCI Link Devices
2460 	 */
2461 	AcpiGetType(handle, &type);
2462 	if (type == ACPI_TYPE_PROCESSOR)
2463 		*order = 0;
2464 	else if (acpi_MatchHid(handle, "PNP0C01") ||
2465 	    acpi_MatchHid(handle, "PNP0C02"))
2466 		*order = 1;
2467 	else if (acpi_MatchHid(handle, "PNP0100") ||
2468 	    acpi_MatchHid(handle, "PNP0103") ||
2469 	    acpi_MatchHid(handle, "PNP0B00"))
2470 		*order = 2;
2471 	else if (acpi_MatchHid(handle, "PNP0C09"))
2472 		*order = 3;
2473 	else if (acpi_MatchHid(handle, "PNP0C0F"))
2474 		*order = 4;
2475 }
2476 
2477 /*
2478  * Evaluate a child device and determine whether we might attach a device to
2479  * it.
2480  */
2481 static ACPI_STATUS
acpi_probe_child(ACPI_HANDLE handle,UINT32 level,void * context,void ** status)2482 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2483 {
2484     ACPI_DEVICE_INFO *devinfo;
2485     struct acpi_device	*ad;
2486     struct acpi_prw_data prw;
2487     ACPI_OBJECT_TYPE type;
2488     ACPI_HANDLE h;
2489     device_t bus, child;
2490     char *handle_str;
2491     int d, order;
2492 
2493     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2494 
2495     if (acpi_disabled("children"))
2496 	return_ACPI_STATUS (AE_OK);
2497 
2498     /* Skip this device if we think we'll have trouble with it. */
2499     if (acpi_avoid(handle))
2500 	return_ACPI_STATUS (AE_OK);
2501 
2502     bus = (device_t)context;
2503     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
2504 	handle_str = acpi_name(handle);
2505 	switch (type) {
2506 	case ACPI_TYPE_DEVICE:
2507 	    /*
2508 	     * Since we scan from \, be sure to skip system scope objects.
2509 	     * \_SB_ and \_TZ_ are defined in ACPICA as devices to work around
2510 	     * BIOS bugs.  For example, \_SB_ is to allow \_SB_._INI to be run
2511 	     * during the initialization and \_TZ_ is to support Notify() on it.
2512 	     */
2513 	    if (strcmp(handle_str, "\\_SB_") == 0 ||
2514 		strcmp(handle_str, "\\_TZ_") == 0)
2515 		break;
2516 	    if (acpi_parse_prw(handle, &prw) == 0)
2517 		AcpiSetupGpeForWake(handle, prw.gpe_handle, prw.gpe_bit);
2518 
2519 	    /*
2520 	     * Ignore devices that do not have a _HID or _CID.  They should
2521 	     * be discovered by other buses (e.g. the PCI bus driver).
2522 	     */
2523 	    if (!acpi_has_hid(handle))
2524 		break;
2525 	    /* FALLTHROUGH */
2526 	case ACPI_TYPE_PROCESSOR:
2527 	case ACPI_TYPE_THERMAL:
2528 	case ACPI_TYPE_POWER:
2529 	    /*
2530 	     * Create a placeholder device for this node.  Sort the
2531 	     * placeholder so that the probe/attach passes will run
2532 	     * breadth-first.  Orders less than ACPI_DEV_BASE_ORDER
2533 	     * are reserved for special objects (i.e., system
2534 	     * resources).
2535 	     */
2536 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
2537 	    order = level * 10 + ACPI_DEV_BASE_ORDER;
2538 	    acpi_probe_order(handle, &order);
2539 	    child = BUS_ADD_CHILD(bus, order, NULL, DEVICE_UNIT_ANY);
2540 	    if (child == NULL)
2541 		break;
2542 
2543 	    /* Associate the handle with the device_t and vice versa. */
2544 	    acpi_set_handle(child, handle);
2545 	    AcpiAttachData(handle, acpi_fake_objhandler, child);
2546 
2547 	    /*
2548 	     * Check that the device is present.  If it's not present,
2549 	     * leave it disabled (so that we have a device_t attached to
2550 	     * the handle, but we don't probe it).
2551 	     *
2552 	     * XXX PCI link devices sometimes report "present" but not
2553 	     * "functional" (i.e. if disabled).  Go ahead and probe them
2554 	     * anyway since we may enable them later.
2555 	     */
2556 	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
2557 		/* Never disable PCI link devices. */
2558 		if (acpi_MatchHid(handle, "PNP0C0F"))
2559 		    break;
2560 
2561 		/*
2562 		 * RTC Device should be enabled for CMOS register space
2563 		 * unless FADT indicate it is not present.
2564 		 * (checked in RTC probe routine.)
2565 		 */
2566 		if (acpi_MatchHid(handle, "PNP0B00"))
2567 		    break;
2568 
2569 		/*
2570 		 * Docking stations should remain enabled since the system
2571 		 * may be undocked at boot.
2572 		 */
2573 		if (ACPI_SUCCESS(AcpiGetHandle(handle, "_DCK", &h)))
2574 		    break;
2575 
2576 		device_disable(child);
2577 		break;
2578 	    }
2579 
2580 	    /*
2581 	     * Get the device's resource settings and attach them.
2582 	     * Note that if the device has _PRS but no _CRS, we need
2583 	     * to decide when it's appropriate to try to configure the
2584 	     * device.  Ignore the return value here; it's OK for the
2585 	     * device not to have any resources.
2586 	     */
2587 	    acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
2588 
2589 	    ad = device_get_ivars(child);
2590 	    ad->ad_cls_class = 0xffffff;
2591 	    if (ACPI_SUCCESS(AcpiGetObjectInfo(handle, &devinfo))) {
2592 		if ((devinfo->Valid & ACPI_VALID_CLS) != 0 &&
2593 		    devinfo->ClassCode.Length >= ACPI_PCICLS_STRING_SIZE) {
2594 		    ad->ad_cls_class = strtoul(devinfo->ClassCode.String,
2595 			NULL, 16);
2596 		}
2597 		AcpiOsFree(devinfo);
2598 	    }
2599 
2600 	    d = acpi_pxm_parse(child);
2601 	    if (d >= 0)
2602 		ad->ad_domain = d;
2603 	    break;
2604 	}
2605     }
2606 
2607     return_ACPI_STATUS (AE_OK);
2608 }
2609 
2610 /*
2611  * AcpiAttachData() requires an object handler but never uses it.  This is a
2612  * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
2613  */
2614 void
acpi_fake_objhandler(ACPI_HANDLE h,void * data)2615 acpi_fake_objhandler(ACPI_HANDLE h, void *data)
2616 {
2617 }
2618 
2619 /*
2620  * Simple wrapper around AcpiEnterSleepStatePrep() printing diagnostic on error.
2621  */
2622 static ACPI_STATUS
acpi_EnterSleepStatePrep(device_t acpi_dev,UINT8 SleepState)2623 acpi_EnterSleepStatePrep(device_t acpi_dev, UINT8 SleepState)
2624 {
2625 	ACPI_STATUS status;
2626 
2627 	status = AcpiEnterSleepStatePrep(SleepState);
2628 	if (ACPI_FAILURE(status))
2629 		device_printf(acpi_dev,
2630 		    "AcpiEnterSleepStatePrep(%u) failed - %s\n",
2631 		    SleepState,
2632 		    AcpiFormatException(status));
2633 	return (status);
2634 }
2635 
2636 /* Return from this function indicates failure. */
2637 static void
acpi_poweroff(device_t acpi_dev)2638 acpi_poweroff(device_t acpi_dev)
2639 {
2640 	register_t intr;
2641 	ACPI_STATUS status;
2642 
2643 	device_printf(acpi_dev, "Powering system off...\n");
2644 	status = acpi_EnterSleepStatePrep(acpi_dev, ACPI_STATE_S5);
2645 	if (ACPI_FAILURE(status)) {
2646 		device_printf(acpi_dev, "Power-off preparation failed! - %s\n",
2647 		    AcpiFormatException(status));
2648 		return;
2649 	}
2650 	intr = intr_disable();
2651 	status = AcpiEnterSleepState(ACPI_STATE_S5);
2652 	if (ACPI_FAILURE(status)) {
2653 		intr_restore(intr);
2654 		device_printf(acpi_dev, "Power-off failed! - %s\n",
2655 		    AcpiFormatException(status));
2656 	} else {
2657 		DELAY(1000000);
2658 		intr_restore(intr);
2659 		device_printf(acpi_dev, "Power-off failed! - timeout\n");
2660 	}
2661 }
2662 
2663 static void
acpi_shutdown_final(void * arg,int howto)2664 acpi_shutdown_final(void *arg, int howto)
2665 {
2666     struct acpi_softc *sc = (struct acpi_softc *)arg;
2667     ACPI_STATUS status;
2668 
2669     /*
2670      * XXX Shutdown code should only run on the BSP (cpuid 0).
2671      * Some chipsets do not power off the system correctly if called from
2672      * an AP.
2673      */
2674     if ((howto & RB_POWEROFF) != 0) {
2675 	acpi_poweroff(sc->acpi_dev);
2676     } else if ((howto & RB_HALT) == 0 && sc->acpi_handle_reboot) {
2677 	/* Reboot using the reset register. */
2678 	status = AcpiReset();
2679 	if (ACPI_SUCCESS(status)) {
2680 	    DELAY(1000000);
2681 	    device_printf(sc->acpi_dev, "reset failed - timeout\n");
2682 	} else if (status != AE_NOT_EXIST)
2683 	    device_printf(sc->acpi_dev, "reset failed - %s\n",
2684 		AcpiFormatException(status));
2685     } else if (sc->acpi_do_disable && !KERNEL_PANICKED()) {
2686 	/*
2687 	 * Only disable ACPI if the user requested.  On some systems, writing
2688 	 * the disable value to SMI_CMD hangs the system.
2689 	 */
2690 	device_printf(sc->acpi_dev, "Shutting down\n");
2691 	AcpiTerminate();
2692     }
2693 }
2694 
2695 static void
acpi_enable_fixed_events(struct acpi_softc * sc)2696 acpi_enable_fixed_events(struct acpi_softc *sc)
2697 {
2698     static int	first_time = 1;
2699 
2700     /* Enable and clear fixed events and install handlers. */
2701     if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
2702 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
2703 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
2704 				     acpi_event_power_button_sleep, sc);
2705 	if (first_time)
2706 	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
2707     }
2708     if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
2709 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
2710 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
2711 				     acpi_event_sleep_button_sleep, sc);
2712 	if (first_time)
2713 	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
2714     }
2715 
2716     first_time = 0;
2717 }
2718 
2719 /*
2720  * Returns true if the device is actually present and should
2721  * be attached to.  This requires the present, enabled, UI-visible
2722  * and diagnostics-passed bits to be set.
2723  */
2724 BOOLEAN
acpi_DeviceIsPresent(device_t dev)2725 acpi_DeviceIsPresent(device_t dev)
2726 {
2727 	ACPI_HANDLE h;
2728 	UINT32 s;
2729 	ACPI_STATUS status;
2730 
2731 	h = acpi_get_handle(dev);
2732 	if (h == NULL)
2733 		return (FALSE);
2734 
2735 #ifdef ACPI_EARLY_EPYC_WAR
2736 	/*
2737 	 * Certain Treadripper boards always returns 0 for FreeBSD because it
2738 	 * only returns non-zero for the OS string "Windows 2015". Otherwise it
2739 	 * will return zero. Force them to always be treated as present.
2740 	 * Beata versions were worse: they always returned 0.
2741 	 */
2742 	if (acpi_MatchHid(h, "AMDI0020") || acpi_MatchHid(h, "AMDI0010"))
2743 		return (TRUE);
2744 #endif
2745 
2746 	status = acpi_GetInteger(h, "_STA", &s);
2747 
2748 	/*
2749 	 * If no _STA method or if it failed, then assume that
2750 	 * the device is present.
2751 	 */
2752 	if (ACPI_FAILURE(status))
2753 		return (TRUE);
2754 
2755 	return (ACPI_DEVICE_PRESENT(s) ? TRUE : FALSE);
2756 }
2757 
2758 /*
2759  * Returns true if the battery is actually present and inserted.
2760  */
2761 BOOLEAN
acpi_BatteryIsPresent(device_t dev)2762 acpi_BatteryIsPresent(device_t dev)
2763 {
2764 	ACPI_HANDLE h;
2765 	UINT32 s;
2766 	ACPI_STATUS status;
2767 
2768 	h = acpi_get_handle(dev);
2769 	if (h == NULL)
2770 		return (FALSE);
2771 	status = acpi_GetInteger(h, "_STA", &s);
2772 
2773 	/*
2774 	 * If no _STA method or if it failed, then assume that
2775 	 * the device is present.
2776 	 */
2777 	if (ACPI_FAILURE(status))
2778 		return (TRUE);
2779 
2780 	return (ACPI_BATTERY_PRESENT(s) ? TRUE : FALSE);
2781 }
2782 
2783 /*
2784  * Returns true if a device has at least one valid device ID.
2785  */
2786 BOOLEAN
acpi_has_hid(ACPI_HANDLE h)2787 acpi_has_hid(ACPI_HANDLE h)
2788 {
2789     ACPI_DEVICE_INFO	*devinfo;
2790     BOOLEAN		ret;
2791 
2792     if (h == NULL ||
2793 	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2794 	return (FALSE);
2795 
2796     ret = FALSE;
2797     if ((devinfo->Valid & ACPI_VALID_HID) != 0)
2798 	ret = TRUE;
2799     else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2800 	if (devinfo->CompatibleIdList.Count > 0)
2801 	    ret = TRUE;
2802 
2803     AcpiOsFree(devinfo);
2804     return (ret);
2805 }
2806 
2807 /*
2808  * Match a HID string against a handle
2809  * returns ACPI_MATCHHID_HID if _HID match
2810  *         ACPI_MATCHHID_CID if _CID match and not _HID match.
2811  *         ACPI_MATCHHID_NOMATCH=0 if no match.
2812  */
2813 int
acpi_MatchHid(ACPI_HANDLE h,const char * hid)2814 acpi_MatchHid(ACPI_HANDLE h, const char *hid)
2815 {
2816     ACPI_DEVICE_INFO	*devinfo;
2817     BOOLEAN		ret;
2818     int			i;
2819 
2820     if (hid == NULL || h == NULL ||
2821 	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2822 	return (ACPI_MATCHHID_NOMATCH);
2823 
2824     ret = ACPI_MATCHHID_NOMATCH;
2825     if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
2826 	strcmp(hid, devinfo->HardwareId.String) == 0)
2827 	    ret = ACPI_MATCHHID_HID;
2828     else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2829 	for (i = 0; i < devinfo->CompatibleIdList.Count; i++) {
2830 	    if (strcmp(hid, devinfo->CompatibleIdList.Ids[i].String) == 0) {
2831 		ret = ACPI_MATCHHID_CID;
2832 		break;
2833 	    }
2834 	}
2835 
2836     AcpiOsFree(devinfo);
2837     return (ret);
2838 }
2839 
2840 /*
2841  * Return the handle of a named object within our scope, ie. that of (parent)
2842  * or one if its parents.
2843  */
2844 ACPI_STATUS
acpi_GetHandleInScope(ACPI_HANDLE parent,char * path,ACPI_HANDLE * result)2845 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
2846 {
2847     ACPI_HANDLE		r;
2848     ACPI_STATUS		status;
2849 
2850     /* Walk back up the tree to the root */
2851     for (;;) {
2852 	status = AcpiGetHandle(parent, path, &r);
2853 	if (ACPI_SUCCESS(status)) {
2854 	    *result = r;
2855 	    return (AE_OK);
2856 	}
2857 	/* XXX Return error here? */
2858 	if (status != AE_NOT_FOUND)
2859 	    return (AE_OK);
2860 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
2861 	    return (AE_NOT_FOUND);
2862 	parent = r;
2863     }
2864 }
2865 
2866 ACPI_STATUS
acpi_GetProperty(device_t dev,ACPI_STRING propname,const ACPI_OBJECT ** value)2867 acpi_GetProperty(device_t dev, ACPI_STRING propname,
2868     const ACPI_OBJECT **value)
2869 {
2870 	device_t bus = device_get_parent(dev);
2871 
2872 	return (ACPI_GET_PROPERTY(bus, dev, propname, value));
2873 }
2874 
2875 /*
2876  * Allocate a buffer with a preset data size.
2877  */
2878 ACPI_BUFFER *
acpi_AllocBuffer(int size)2879 acpi_AllocBuffer(int size)
2880 {
2881     ACPI_BUFFER	*buf;
2882 
2883     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
2884 	return (NULL);
2885     buf->Length = size;
2886     buf->Pointer = (void *)(buf + 1);
2887     return (buf);
2888 }
2889 
2890 ACPI_STATUS
acpi_SetInteger(ACPI_HANDLE handle,char * path,UINT32 number)2891 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
2892 {
2893     ACPI_OBJECT arg1;
2894     ACPI_OBJECT_LIST args;
2895 
2896     arg1.Type = ACPI_TYPE_INTEGER;
2897     arg1.Integer.Value = number;
2898     args.Count = 1;
2899     args.Pointer = &arg1;
2900 
2901     return (AcpiEvaluateObject(handle, path, &args, NULL));
2902 }
2903 
2904 /*
2905  * Evaluate a path that should return an integer.
2906  */
2907 ACPI_STATUS
acpi_GetInteger(ACPI_HANDLE handle,char * path,UINT32 * number)2908 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
2909 {
2910     ACPI_STATUS	status;
2911     ACPI_BUFFER	buf;
2912     ACPI_OBJECT	param;
2913 
2914     if (handle == NULL)
2915 	handle = ACPI_ROOT_OBJECT;
2916 
2917     /*
2918      * Assume that what we've been pointed at is an Integer object, or
2919      * a method that will return an Integer.
2920      */
2921     buf.Pointer = &param;
2922     buf.Length = sizeof(param);
2923     status = AcpiEvaluateObject(handle, path, NULL, &buf);
2924     if (ACPI_SUCCESS(status)) {
2925 	if (param.Type == ACPI_TYPE_INTEGER)
2926 	    *number = param.Integer.Value;
2927 	else
2928 	    status = AE_TYPE;
2929     }
2930 
2931     /*
2932      * In some applications, a method that's expected to return an Integer
2933      * may instead return a Buffer (probably to simplify some internal
2934      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
2935      * convert it into an Integer as best we can.
2936      *
2937      * This is a hack.
2938      */
2939     if (status == AE_BUFFER_OVERFLOW) {
2940 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
2941 	    status = AE_NO_MEMORY;
2942 	} else {
2943 	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
2944 	    if (ACPI_SUCCESS(status))
2945 		status = acpi_ConvertBufferToInteger(&buf, number);
2946 	    AcpiOsFree(buf.Pointer);
2947 	}
2948     }
2949     return (status);
2950 }
2951 
2952 ACPI_STATUS
acpi_ConvertBufferToInteger(ACPI_BUFFER * bufp,UINT32 * number)2953 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
2954 {
2955     ACPI_OBJECT	*p;
2956     UINT8	*val;
2957     int		i;
2958 
2959     p = (ACPI_OBJECT *)bufp->Pointer;
2960     if (p->Type == ACPI_TYPE_INTEGER) {
2961 	*number = p->Integer.Value;
2962 	return (AE_OK);
2963     }
2964     if (p->Type != ACPI_TYPE_BUFFER)
2965 	return (AE_TYPE);
2966     if (p->Buffer.Length > sizeof(int))
2967 	return (AE_BAD_DATA);
2968 
2969     *number = 0;
2970     val = p->Buffer.Pointer;
2971     for (i = 0; i < p->Buffer.Length; i++)
2972 	*number += val[i] << (i * 8);
2973     return (AE_OK);
2974 }
2975 
2976 /*
2977  * Iterate over the elements of an a package object, calling the supplied
2978  * function for each element.
2979  *
2980  * XXX possible enhancement might be to abort traversal on error.
2981  */
2982 ACPI_STATUS
acpi_ForeachPackageObject(ACPI_OBJECT * pkg,void (* func)(ACPI_OBJECT * comp,void * arg),void * arg)2983 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
2984 	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
2985 {
2986     ACPI_OBJECT	*comp;
2987     int		i;
2988 
2989     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
2990 	return (AE_BAD_PARAMETER);
2991 
2992     /* Iterate over components */
2993     i = 0;
2994     comp = pkg->Package.Elements;
2995     for (; i < pkg->Package.Count; i++, comp++)
2996 	func(comp, arg);
2997 
2998     return (AE_OK);
2999 }
3000 
3001 /*
3002  * Find the (index)th resource object in a set.
3003  */
3004 ACPI_STATUS
acpi_FindIndexedResource(ACPI_BUFFER * buf,int index,ACPI_RESOURCE ** resp)3005 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
3006 {
3007     ACPI_RESOURCE	*rp;
3008     int			i;
3009 
3010     rp = (ACPI_RESOURCE *)buf->Pointer;
3011     i = index;
3012     while (i-- > 0) {
3013 	/* Range check */
3014 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
3015 	    return (AE_BAD_PARAMETER);
3016 
3017 	/* Check for terminator */
3018 	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
3019 	    return (AE_NOT_FOUND);
3020 	rp = ACPI_NEXT_RESOURCE(rp);
3021     }
3022     if (resp != NULL)
3023 	*resp = rp;
3024 
3025     return (AE_OK);
3026 }
3027 
3028 /*
3029  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
3030  *
3031  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
3032  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
3033  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
3034  * resources.
3035  */
3036 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
3037 
3038 ACPI_STATUS
acpi_AppendBufferResource(ACPI_BUFFER * buf,ACPI_RESOURCE * res)3039 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
3040 {
3041     ACPI_RESOURCE	*rp;
3042     void		*newp;
3043 
3044     /* Initialise the buffer if necessary. */
3045     if (buf->Pointer == NULL) {
3046 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
3047 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
3048 	    return (AE_NO_MEMORY);
3049 	rp = (ACPI_RESOURCE *)buf->Pointer;
3050 	rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
3051 	rp->Length = ACPI_RS_SIZE_MIN;
3052     }
3053     if (res == NULL)
3054 	return (AE_OK);
3055 
3056     /*
3057      * Scan the current buffer looking for the terminator.
3058      * This will either find the terminator or hit the end
3059      * of the buffer and return an error.
3060      */
3061     rp = (ACPI_RESOURCE *)buf->Pointer;
3062     for (;;) {
3063 	/* Range check, don't go outside the buffer */
3064 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
3065 	    return (AE_BAD_PARAMETER);
3066 	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
3067 	    break;
3068 	rp = ACPI_NEXT_RESOURCE(rp);
3069     }
3070 
3071     /*
3072      * Check the size of the buffer and expand if required.
3073      *
3074      * Required size is:
3075      *	size of existing resources before terminator +
3076      *	size of new resource and header +
3077      * 	size of terminator.
3078      *
3079      * Note that this loop should really only run once, unless
3080      * for some reason we are stuffing a *really* huge resource.
3081      */
3082     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
3083 	    res->Length + ACPI_RS_SIZE_NO_DATA +
3084 	    ACPI_RS_SIZE_MIN) >= buf->Length) {
3085 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
3086 	    return (AE_NO_MEMORY);
3087 	bcopy(buf->Pointer, newp, buf->Length);
3088 	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
3089 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
3090 	AcpiOsFree(buf->Pointer);
3091 	buf->Pointer = newp;
3092 	buf->Length += buf->Length;
3093     }
3094 
3095     /* Insert the new resource. */
3096     bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
3097 
3098     /* And add the terminator. */
3099     rp = ACPI_NEXT_RESOURCE(rp);
3100     rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
3101     rp->Length = ACPI_RS_SIZE_MIN;
3102 
3103     return (AE_OK);
3104 }
3105 
3106 UINT64
acpi_DSMQuery(ACPI_HANDLE h,const uint8_t * uuid,int revision)3107 acpi_DSMQuery(ACPI_HANDLE h, const uint8_t *uuid, int revision)
3108 {
3109     /*
3110      * ACPI spec 9.1.1 defines this.
3111      *
3112      * "Arg2: Function Index Represents a specific function whose meaning is
3113      * specific to the UUID and Revision ID. Function indices should start
3114      * with 1. Function number zero is a query function (see the special
3115      * return code defined below)."
3116      */
3117     ACPI_BUFFER buf;
3118     ACPI_OBJECT *obj;
3119     UINT64 ret = 0;
3120     int i;
3121 
3122     if (!ACPI_SUCCESS(acpi_EvaluateDSM(h, uuid, revision, 0, NULL, &buf))) {
3123 	ACPI_INFO(("Failed to enumerate DSM functions\n"));
3124 	return (0);
3125     }
3126 
3127     obj = (ACPI_OBJECT *)buf.Pointer;
3128     KASSERT(obj, ("Object not allowed to be NULL\n"));
3129 
3130     /*
3131      * From ACPI 6.2 spec 9.1.1:
3132      * If Function Index = 0, a Buffer containing a function index bitfield.
3133      * Otherwise, the return value and type depends on the UUID and revision
3134      * ID (see below).
3135      */
3136     switch (obj->Type) {
3137     case ACPI_TYPE_BUFFER:
3138 	for (i = 0; i < MIN(obj->Buffer.Length, sizeof(ret)); i++)
3139 	    ret |= (((uint64_t)obj->Buffer.Pointer[i]) << (i * 8));
3140 	break;
3141     case ACPI_TYPE_INTEGER:
3142 	ACPI_BIOS_WARNING((AE_INFO,
3143 	    "Possibly buggy BIOS with ACPI_TYPE_INTEGER for function enumeration\n"));
3144 	ret = obj->Integer.Value;
3145 	break;
3146     default:
3147 	ACPI_WARNING((AE_INFO, "Unexpected return type %u\n", obj->Type));
3148     };
3149 
3150     AcpiOsFree(obj);
3151     return ret;
3152 }
3153 
3154 /*
3155  * DSM may return multiple types depending on the function. It is therefore
3156  * unsafe to use the typed evaluation. It is highly recommended that the caller
3157  * check the type of the returned object.
3158  */
3159 ACPI_STATUS
acpi_EvaluateDSM(ACPI_HANDLE handle,const uint8_t * uuid,int revision,UINT64 function,ACPI_OBJECT * package,ACPI_BUFFER * out_buf)3160 acpi_EvaluateDSM(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
3161     UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf)
3162 {
3163 	return (acpi_EvaluateDSMTyped(handle, uuid, revision, function,
3164 	    package, out_buf, ACPI_TYPE_ANY));
3165 }
3166 
3167 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)3168 acpi_EvaluateDSMTyped(ACPI_HANDLE handle, const uint8_t *uuid, int revision,
3169     UINT64 function, ACPI_OBJECT *package, ACPI_BUFFER *out_buf,
3170     ACPI_OBJECT_TYPE type)
3171 {
3172     ACPI_OBJECT arg[4];
3173     ACPI_OBJECT_LIST arglist;
3174     ACPI_BUFFER buf;
3175     ACPI_STATUS status;
3176 
3177     if (out_buf == NULL)
3178 	return (AE_NO_MEMORY);
3179 
3180     arg[0].Type = ACPI_TYPE_BUFFER;
3181     arg[0].Buffer.Length = ACPI_UUID_LENGTH;
3182     arg[0].Buffer.Pointer = __DECONST(uint8_t *, uuid);
3183     arg[1].Type = ACPI_TYPE_INTEGER;
3184     arg[1].Integer.Value = revision;
3185     arg[2].Type = ACPI_TYPE_INTEGER;
3186     arg[2].Integer.Value = function;
3187     if (package) {
3188 	arg[3] = *package;
3189     } else {
3190 	arg[3].Type = ACPI_TYPE_PACKAGE;
3191 	arg[3].Package.Count = 0;
3192 	arg[3].Package.Elements = NULL;
3193     }
3194 
3195     arglist.Pointer = arg;
3196     arglist.Count = 4;
3197     buf.Pointer = NULL;
3198     buf.Length = ACPI_ALLOCATE_BUFFER;
3199     status = AcpiEvaluateObjectTyped(handle, "_DSM", &arglist, &buf, type);
3200     if (ACPI_FAILURE(status))
3201 	return (status);
3202 
3203     KASSERT(ACPI_SUCCESS(status), ("Unexpected status"));
3204 
3205     *out_buf = buf;
3206     return (status);
3207 }
3208 
3209 ACPI_STATUS
acpi_EvaluateOSC(ACPI_HANDLE handle,uint8_t * uuid,int revision,int count,uint32_t * caps_in,uint32_t * caps_out,bool query)3210 acpi_EvaluateOSC(ACPI_HANDLE handle, uint8_t *uuid, int revision, int count,
3211     uint32_t *caps_in, uint32_t *caps_out, bool query)
3212 {
3213 	ACPI_OBJECT arg[4], *ret;
3214 	ACPI_OBJECT_LIST arglist;
3215 	ACPI_BUFFER buf;
3216 	ACPI_STATUS status;
3217 
3218 	arglist.Pointer = arg;
3219 	arglist.Count = 4;
3220 	arg[0].Type = ACPI_TYPE_BUFFER;
3221 	arg[0].Buffer.Length = ACPI_UUID_LENGTH;
3222 	arg[0].Buffer.Pointer = uuid;
3223 	arg[1].Type = ACPI_TYPE_INTEGER;
3224 	arg[1].Integer.Value = revision;
3225 	arg[2].Type = ACPI_TYPE_INTEGER;
3226 	arg[2].Integer.Value = count;
3227 	arg[3].Type = ACPI_TYPE_BUFFER;
3228 	arg[3].Buffer.Length = count * sizeof(*caps_in);
3229 	arg[3].Buffer.Pointer = (uint8_t *)caps_in;
3230 	caps_in[0] = query ? 1 : 0;
3231 	buf.Pointer = NULL;
3232 	buf.Length = ACPI_ALLOCATE_BUFFER;
3233 	status = AcpiEvaluateObjectTyped(handle, "_OSC", &arglist, &buf,
3234 	    ACPI_TYPE_BUFFER);
3235 	if (ACPI_FAILURE(status))
3236 		return (status);
3237 	if (caps_out != NULL) {
3238 		ret = buf.Pointer;
3239 		if (ret->Buffer.Length != count * sizeof(*caps_out)) {
3240 			AcpiOsFree(buf.Pointer);
3241 			return (AE_BUFFER_OVERFLOW);
3242 		}
3243 		bcopy(ret->Buffer.Pointer, caps_out, ret->Buffer.Length);
3244 	}
3245 	AcpiOsFree(buf.Pointer);
3246 	return (status);
3247 }
3248 
3249 /*
3250  * Set interrupt model.
3251  */
3252 ACPI_STATUS
acpi_SetIntrModel(int model)3253 acpi_SetIntrModel(int model)
3254 {
3255 
3256     return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
3257 }
3258 
3259 /*
3260  * Walk subtables of a table and call a callback routine for each
3261  * subtable.  The caller should provide the first subtable and a
3262  * pointer to the end of the table.  This can be used to walk tables
3263  * such as MADT and SRAT that use subtable entries.
3264  */
3265 void
acpi_walk_subtables(void * first,void * end,acpi_subtable_handler * handler,void * arg)3266 acpi_walk_subtables(void *first, void *end, acpi_subtable_handler *handler,
3267     void *arg)
3268 {
3269     ACPI_SUBTABLE_HEADER *entry;
3270 
3271     for (entry = first; (void *)entry < end; ) {
3272 	/* Avoid an infinite loop if we hit a bogus entry. */
3273 	if (entry->Length < sizeof(ACPI_SUBTABLE_HEADER))
3274 	    return;
3275 
3276 	handler(entry, arg);
3277 	entry = ACPI_ADD_PTR(ACPI_SUBTABLE_HEADER, entry, entry->Length);
3278     }
3279 }
3280 
3281 /*
3282  * DEPRECATED.  This interface has serious deficiencies and will be
3283  * removed.
3284  *
3285  * Immediately enter the sleep state.  In the old model, acpiconf(8) ran
3286  * rc.suspend and rc.resume so we don't have to notify devd(8) to do this.
3287  */
3288 ACPI_STATUS
acpi_SetSleepState(struct acpi_softc * sc,int state)3289 acpi_SetSleepState(struct acpi_softc *sc, int state)
3290 {
3291     static int once;
3292 
3293     if (!once) {
3294 	device_printf(sc->acpi_dev,
3295 "warning: acpi_SetSleepState() deprecated, need to update your software\n");
3296 	once = 1;
3297     }
3298     return (acpi_EnterSleepState(sc, state));
3299 }
3300 
3301 #if defined(__amd64__) || defined(__i386__)
3302 static void
acpi_sleep_force_task(void * context)3303 acpi_sleep_force_task(void *context)
3304 {
3305     struct acpi_softc *sc = (struct acpi_softc *)context;
3306 
3307     if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_stype)))
3308 	device_printf(sc->acpi_dev, "force sleep state %s failed\n",
3309 	    power_stype_to_name(sc->acpi_next_stype));
3310 }
3311 
3312 static void
acpi_sleep_force(void * arg)3313 acpi_sleep_force(void *arg)
3314 {
3315     struct acpi_softc *sc = (struct acpi_softc *)arg;
3316 
3317     device_printf(sc->acpi_dev,
3318 	"suspend request timed out, forcing sleep now\n");
3319     /*
3320      * XXX Suspending from callout causes freezes in DEVICE_SUSPEND().
3321      * Suspend from acpi_task thread instead.
3322      */
3323     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3324 	acpi_sleep_force_task, sc)))
3325 	device_printf(sc->acpi_dev, "AcpiOsExecute() for sleeping failed\n");
3326 }
3327 #endif
3328 
3329 /*
3330  * Request that the system enter the given suspend state.  All /dev/apm
3331  * devices and devd(8) will be notified.  Userland then has a chance to
3332  * save state and acknowledge the request.  The system sleeps once all
3333  * acks are in.
3334  */
3335 int
acpi_ReqSleepState(struct acpi_softc * sc,enum power_stype stype)3336 acpi_ReqSleepState(struct acpi_softc *sc, enum power_stype stype)
3337 {
3338 #if defined(__amd64__) || defined(__i386__)
3339     struct apm_clone_data *clone;
3340     ACPI_STATUS status;
3341 
3342     if (stype < POWER_STYPE_AWAKE || stype >= POWER_STYPE_COUNT)
3343 	return (EINVAL);
3344     if (!acpi_supported_stypes[stype])
3345 	return (EOPNOTSUPP);
3346 
3347     /*
3348      * If a reboot/shutdown/suspend request is already in progress or
3349      * suspend is blocked due to an upcoming shutdown, just return.
3350      */
3351     if (rebooting || sc->acpi_next_stype != POWER_STYPE_AWAKE ||
3352 	suspend_blocked)
3353 	return (0);
3354 
3355     /* Wait until sleep is enabled. */
3356     while (sc->acpi_sleep_disabled) {
3357 	AcpiOsSleep(1000);
3358     }
3359 
3360     ACPI_LOCK(acpi);
3361 
3362     sc->acpi_next_stype = stype;
3363 
3364     /* S5 (soft-off) should be entered directly with no waiting. */
3365     if (stype == POWER_STYPE_POWEROFF) {
3366     	ACPI_UNLOCK(acpi);
3367 	status = acpi_EnterSleepState(sc, stype);
3368 	return (ACPI_SUCCESS(status) ? 0 : ENXIO);
3369     }
3370 
3371     /* Record the pending state and notify all apm devices. */
3372     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
3373 	clone->notify_status = APM_EV_NONE;
3374 	if ((clone->flags & ACPI_EVF_DEVD) == 0) {
3375 	    selwakeuppri(&clone->sel_read, PZERO);
3376 	    KNOTE_LOCKED(&clone->sel_read.si_note, 0);
3377 	}
3378     }
3379 
3380     /* If devd(8) is not running, immediately enter the sleep state. */
3381     if (!devctl_process_running()) {
3382 	ACPI_UNLOCK(acpi);
3383 	status = acpi_EnterSleepState(sc, stype);
3384 	return (ACPI_SUCCESS(status) ? 0 : ENXIO);
3385     }
3386 
3387     /*
3388      * Set a timeout to fire if userland doesn't ack the suspend request
3389      * in time.  This way we still eventually go to sleep if we were
3390      * overheating or running low on battery, even if userland is hung.
3391      * We cancel this timeout once all userland acks are in or the
3392      * suspend request is aborted.
3393      */
3394     callout_reset(&sc->susp_force_to, 10 * hz, acpi_sleep_force, sc);
3395     ACPI_UNLOCK(acpi);
3396 
3397     /* Now notify devd(8) also. */
3398     acpi_UserNotify("Suspend", ACPI_ROOT_OBJECT, stype);
3399 
3400     return (0);
3401 #else
3402     device_printf(sc->acpi_dev, "ACPI suspend not supported on this platform "
3403 	"(TODO suspend to idle should be, however)\n");
3404     return (EOPNOTSUPP);
3405 #endif
3406 }
3407 
3408 /*
3409  * Acknowledge (or reject) a pending sleep state.  The caller has
3410  * prepared for suspend and is now ready for it to proceed.  If the
3411  * error argument is non-zero, it indicates suspend should be cancelled
3412  * and gives an errno value describing why.  Once all votes are in,
3413  * we suspend the system.
3414  */
3415 int
acpi_AckSleepState(struct apm_clone_data * clone,int error)3416 acpi_AckSleepState(struct apm_clone_data *clone, int error)
3417 {
3418     struct acpi_softc *sc = clone->acpi_sc;
3419 
3420 #if defined(__amd64__) || defined(__i386__)
3421     int ret, sleeping;
3422 
3423     /* If no pending sleep type, return an error. */
3424     ACPI_LOCK(acpi);
3425     if (sc->acpi_next_stype == POWER_STYPE_AWAKE) {
3426     	ACPI_UNLOCK(acpi);
3427 	return (ENXIO);
3428     }
3429 
3430     /* Caller wants to abort suspend process. */
3431     if (error) {
3432 	sc->acpi_next_stype = POWER_STYPE_AWAKE;
3433 	callout_stop(&sc->susp_force_to);
3434 	device_printf(sc->acpi_dev,
3435 	    "listener on %s cancelled the pending suspend\n",
3436 	    devtoname(clone->cdev));
3437     	ACPI_UNLOCK(acpi);
3438 	return (0);
3439     }
3440 
3441     /*
3442      * Mark this device as acking the suspend request.  Then, walk through
3443      * all devices, seeing if they agree yet.  We only count devices that
3444      * are writable since read-only devices couldn't ack the request.
3445      */
3446     sleeping = TRUE;
3447     clone->notify_status = APM_EV_ACKED;
3448     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
3449 	if ((clone->flags & ACPI_EVF_WRITE) != 0 &&
3450 	    clone->notify_status != APM_EV_ACKED) {
3451 	    sleeping = FALSE;
3452 	    break;
3453 	}
3454     }
3455 
3456     /* If all devices have voted "yes", we will suspend now. */
3457     if (sleeping)
3458 	callout_stop(&sc->susp_force_to);
3459     ACPI_UNLOCK(acpi);
3460     ret = 0;
3461     if (sleeping) {
3462 	if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_stype)))
3463 		ret = ENODEV;
3464     }
3465     return (ret);
3466 #else
3467     device_printf(sc->acpi_dev, "ACPI suspend not supported on this platform "
3468 	"(TODO suspend to idle should be, however)\n");
3469     return (EOPNOTSUPP);
3470 #endif
3471 }
3472 
3473 static void
acpi_sleep_enable(void * arg)3474 acpi_sleep_enable(void *arg)
3475 {
3476     struct acpi_softc	*sc = (struct acpi_softc *)arg;
3477 
3478     ACPI_LOCK_ASSERT(acpi);
3479 
3480     /* Reschedule if the system is not fully up and running. */
3481     if (!AcpiGbl_SystemAwakeAndRunning) {
3482 	callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3483 	return;
3484     }
3485 
3486     sc->acpi_sleep_disabled = FALSE;
3487 }
3488 
3489 static ACPI_STATUS
acpi_sleep_disable(struct acpi_softc * sc)3490 acpi_sleep_disable(struct acpi_softc *sc)
3491 {
3492     ACPI_STATUS		status;
3493 
3494     /* Fail if the system is not fully up and running. */
3495     if (!AcpiGbl_SystemAwakeAndRunning)
3496 	return (AE_ERROR);
3497 
3498     ACPI_LOCK(acpi);
3499     status = sc->acpi_sleep_disabled ? AE_ERROR : AE_OK;
3500     sc->acpi_sleep_disabled = TRUE;
3501     ACPI_UNLOCK(acpi);
3502 
3503     return (status);
3504 }
3505 
3506 enum acpi_sleep_state {
3507     ACPI_SS_NONE	= 0,
3508     ACPI_SS_GPE_SET	= 1 << 0,
3509     ACPI_SS_DEV_SUSPEND	= 1 << 1,
3510     ACPI_SS_SLP_PREP	= 1 << 2,
3511     ACPI_SS_SLEPT	= 1 << 3,
3512 };
3513 
3514 static void
do_standby(struct acpi_softc * sc,enum acpi_sleep_state * slp_state,register_t rflags)3515 do_standby(struct acpi_softc *sc, enum acpi_sleep_state *slp_state,
3516     register_t rflags)
3517 {
3518     ACPI_STATUS status;
3519 
3520     status = AcpiEnterSleepState(sc->acpi_standby_sx);
3521     intr_restore(rflags);
3522     AcpiLeaveSleepStatePrep(sc->acpi_standby_sx);
3523     if (ACPI_FAILURE(status)) {
3524 	device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
3525 	    AcpiFormatException(status));
3526 	return;
3527     }
3528     *slp_state |= ACPI_SS_SLEPT;
3529 }
3530 
3531 static void
do_sleep(struct acpi_softc * sc,enum acpi_sleep_state * slp_state,register_t rflags,int state)3532 do_sleep(struct acpi_softc *sc, enum acpi_sleep_state *slp_state,
3533     register_t rflags, int state)
3534 {
3535     int sleep_result;
3536     ACPI_EVENT_STATUS power_button_status;
3537 
3538     MPASS(state == ACPI_STATE_S3 || state == ACPI_STATE_S4);
3539 
3540     sleep_result = acpi_sleep_machdep(sc, state);
3541     acpi_wakeup_machdep(sc, state, sleep_result, 0);
3542 
3543     if (sleep_result == 1 && state == ACPI_STATE_S3) {
3544 	/*
3545 	 * XXX According to ACPI specification SCI_EN bit should be restored
3546 	 * by ACPI platform (BIOS, firmware) to its pre-sleep state.
3547 	 * Unfortunately some BIOSes fail to do that and that leads to
3548 	 * unexpected and serious consequences during wake up like a system
3549 	 * getting stuck in SMI handlers.
3550 	 * This hack is picked up from Linux, which claims that it follows
3551 	 * Windows behavior.
3552 	 */
3553 	AcpiWriteBitRegister(ACPI_BITREG_SCI_ENABLE, ACPI_ENABLE_EVENT);
3554 
3555 	/*
3556 	 * Prevent misinterpretation of the wakeup by power button
3557 	 * as a request for power off.
3558 	 * Ideally we should post an appropriate wakeup event,
3559 	 * perhaps using acpi_event_power_button_wake or alike.
3560 	 *
3561 	 * Clearing of power button status after wakeup is mandated
3562 	 * by ACPI specification in section "Fixed Power Button".
3563 	 *
3564 	 * XXX As of ACPICA 20121114 AcpiGetEventStatus provides
3565 	 * status as 0/1 corresponding to inactive/active despite
3566 	 * its type being ACPI_EVENT_STATUS.  In other words,
3567 	 * we should not test for ACPI_EVENT_FLAG_SET for time being.
3568 	 */
3569 	if (ACPI_SUCCESS(AcpiGetEventStatus(ACPI_EVENT_POWER_BUTTON,
3570 	    &power_button_status)) && power_button_status != 0) {
3571 	    AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
3572 	    device_printf(sc->acpi_dev, "cleared fixed power button status\n");
3573 	}
3574     }
3575 
3576     intr_restore(rflags);
3577 
3578     /* call acpi_wakeup_machdep() again with interrupt enabled */
3579     acpi_wakeup_machdep(sc, state, sleep_result, 1);
3580 
3581     AcpiLeaveSleepStatePrep(state);
3582 
3583     if (sleep_result == -1)
3584 	return;
3585 
3586     /* Re-enable ACPI hardware on wakeup from sleep state 4. */
3587     if (state == ACPI_STATE_S4)
3588 	AcpiEnable();
3589     *slp_state |= ACPI_SS_SLEPT;
3590 }
3591 
3592 #if defined(__i386__) || defined(__amd64__)
3593 static void
do_idle(struct acpi_softc * sc,enum acpi_sleep_state * slp_state,register_t rflags)3594 do_idle(struct acpi_softc *sc, enum acpi_sleep_state *slp_state,
3595     register_t rflags)
3596 {
3597 
3598     intr_suspend();
3599 
3600     /*
3601      * The CPU will exit idle when interrupted, so we want to minimize the
3602      * number of interrupts it can receive while idle.  We do this by only
3603      * allowing SCI (system control interrupt) interrupts, which are used by
3604      * the ACPI firmware to send wake GPEs to the OS.
3605      *
3606      * XXX We might still receive other spurious non-wake GPEs from noisy
3607      * devices that can't be disabled, so this will need to end up being a
3608      * suspend-to-idle loop which, when breaking out of idle, will check the
3609      * reason for the wakeup and immediately idle the CPU again if it was not a
3610      * proper wake event.
3611      */
3612     intr_enable_src(AcpiGbl_FADT.SciInterrupt);
3613 
3614     cpu_idle(0);
3615 
3616     intr_resume(false);
3617     intr_restore(rflags);
3618     *slp_state |= ACPI_SS_SLEPT;
3619 }
3620 #endif
3621 
3622 /*
3623  * Enter the desired system sleep state.
3624  *
3625  * Currently we support S1-S5 and suspend-to-idle, but S4 is only S4BIOS.
3626  */
3627 static ACPI_STATUS
acpi_EnterSleepState(struct acpi_softc * sc,enum power_stype stype)3628 acpi_EnterSleepState(struct acpi_softc *sc, enum power_stype stype)
3629 {
3630     register_t intr;
3631     ACPI_STATUS status;
3632     enum acpi_sleep_state slp_state;
3633     int acpi_sstate;
3634 
3635     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, stype);
3636 
3637     if (stype <= POWER_STYPE_AWAKE || stype >= POWER_STYPE_COUNT)
3638 	return_ACPI_STATUS (AE_BAD_PARAMETER);
3639     if (!acpi_supported_stypes[stype]) {
3640 	device_printf(sc->acpi_dev, "Sleep type %s not supported on this "
3641 	    "platform\n", power_stype_to_name(stype));
3642 	return (AE_SUPPORT);
3643     }
3644 
3645     acpi_sstate = acpi_stype_to_sstate(sc, stype);
3646 
3647     /* Re-entry once we're suspending is not allowed. */
3648     status = acpi_sleep_disable(sc);
3649     if (ACPI_FAILURE(status)) {
3650 	device_printf(sc->acpi_dev,
3651 	    "suspend request ignored (not ready yet)\n");
3652 	return (status);
3653     }
3654 
3655     if (stype == POWER_STYPE_POWEROFF) {
3656 	/*
3657 	 * Shut down cleanly and power off.  This will call us back through the
3658 	 * shutdown handlers.
3659 	 */
3660 	shutdown_nice(RB_POWEROFF);
3661 	return_ACPI_STATUS (AE_OK);
3662     }
3663 
3664     EVENTHANDLER_INVOKE(power_suspend_early, stype);
3665     stop_all_proc();
3666     suspend_all_fs();
3667     EVENTHANDLER_INVOKE(power_suspend, stype);
3668 
3669 #ifdef EARLY_AP_STARTUP
3670     MPASS(mp_ncpus == 1 || smp_started);
3671     thread_lock(curthread);
3672     sched_bind(curthread, 0);
3673     thread_unlock(curthread);
3674 #else
3675     if (smp_started) {
3676 	thread_lock(curthread);
3677 	sched_bind(curthread, 0);
3678 	thread_unlock(curthread);
3679     }
3680 #endif
3681 
3682     /*
3683      * Be sure to hold bus topology lock across DEVICE_SUSPEND/RESUME.
3684      */
3685     bus_topo_lock();
3686 
3687     slp_state = ACPI_SS_NONE;
3688 
3689     sc->acpi_stype = stype;
3690 
3691     /* Enable any GPEs as appropriate and requested by the user. */
3692     acpi_wake_prep_walk(sc, stype);
3693     slp_state |= ACPI_SS_GPE_SET;
3694 
3695     /*
3696      * Inform all devices that we are going to sleep.  If at least one
3697      * device fails, DEVICE_SUSPEND() automatically resumes the tree.
3698      *
3699      * XXX Note that a better two-pass approach with a 'veto' pass
3700      * followed by a "real thing" pass would be better, but the current
3701      * bus interface does not provide for this.
3702      */
3703     if (DEVICE_SUSPEND(root_bus) != 0) {
3704         device_printf(sc->acpi_dev, "device_suspend failed\n");
3705         goto backout;
3706     }
3707     EVENTHANDLER_INVOKE(acpi_post_dev_suspend, stype);
3708     slp_state |= ACPI_SS_DEV_SUSPEND;
3709 
3710     if (stype != POWER_STYPE_SUSPEND_TO_IDLE) {
3711 	status = acpi_EnterSleepStatePrep(sc->acpi_dev, acpi_sstate);
3712 	if (ACPI_FAILURE(status))
3713 	    goto backout;
3714 	slp_state |= ACPI_SS_SLP_PREP;
3715     }
3716 
3717     if (sc->acpi_sleep_delay > 0)
3718 	DELAY(sc->acpi_sleep_delay * 1000000);
3719 
3720     suspendclock();
3721     intr = intr_disable();
3722     switch (stype) {
3723     case POWER_STYPE_STANDBY:
3724 	do_standby(sc, &slp_state, intr);
3725 	break;
3726     case POWER_STYPE_FW_SUSPEND:
3727     case POWER_STYPE_FW_HIBERNATE:
3728 	do_sleep(sc, &slp_state, intr, acpi_sstate);
3729 	break;
3730     case POWER_STYPE_SUSPEND_TO_IDLE:
3731 #if defined(__i386__) || defined(__amd64__)
3732 	do_idle(sc, &slp_state, intr);
3733 	break;
3734 #endif
3735     case POWER_STYPE_AWAKE:
3736     case POWER_STYPE_POWEROFF:
3737     case POWER_STYPE_COUNT:
3738     case POWER_STYPE_UNKNOWN:
3739 	__unreachable();
3740     }
3741     resumeclock();
3742 
3743     /*
3744      * Back out state according to how far along we got in the suspend
3745      * process.  This handles both the error and success cases.
3746      */
3747 backout:
3748     if ((slp_state & ACPI_SS_GPE_SET) != 0) {
3749 	acpi_wake_prep_walk(sc, stype);
3750 	sc->acpi_stype = POWER_STYPE_AWAKE;
3751 	slp_state &= ~ACPI_SS_GPE_SET;
3752     }
3753     if ((slp_state & ACPI_SS_DEV_SUSPEND) != 0) {
3754 	EVENTHANDLER_INVOKE(acpi_pre_dev_resume, stype);
3755 	DEVICE_RESUME(root_bus);
3756 	slp_state &= ~ACPI_SS_DEV_SUSPEND;
3757     }
3758     if ((slp_state & ACPI_SS_SLP_PREP) != 0) {
3759 	AcpiLeaveSleepState(acpi_sstate);
3760 	slp_state &= ~ACPI_SS_SLP_PREP;
3761     }
3762     if ((slp_state & ACPI_SS_SLEPT) != 0) {
3763 #if defined(__i386__) || defined(__amd64__)
3764 	/* NB: we are still using ACPI timecounter at this point. */
3765 	resume_TSC();
3766 #endif
3767 	acpi_resync_clock(sc);
3768 	acpi_enable_fixed_events(sc);
3769 	slp_state &= ~ACPI_SS_SLEPT;
3770     }
3771     sc->acpi_next_stype = POWER_STYPE_AWAKE;
3772 
3773     MPASS(slp_state == ACPI_SS_NONE);
3774 
3775     bus_topo_unlock();
3776 
3777 #ifdef EARLY_AP_STARTUP
3778     thread_lock(curthread);
3779     sched_unbind(curthread);
3780     thread_unlock(curthread);
3781 #else
3782     if (smp_started) {
3783 	thread_lock(curthread);
3784 	sched_unbind(curthread);
3785 	thread_unlock(curthread);
3786     }
3787 #endif
3788 
3789     resume_all_fs();
3790     resume_all_proc();
3791 
3792     EVENTHANDLER_INVOKE(power_resume, stype);
3793 
3794     /* Allow another sleep request after a while. */
3795     callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3796 
3797     /* Run /etc/rc.resume after we are back. */
3798     if (devctl_process_running())
3799 	acpi_UserNotify("Resume", ACPI_ROOT_OBJECT, stype);
3800 
3801     return_ACPI_STATUS (status);
3802 }
3803 
3804 static void
acpi_resync_clock(struct acpi_softc * sc)3805 acpi_resync_clock(struct acpi_softc *sc)
3806 {
3807 
3808     /*
3809      * Warm up timecounter again and reset system clock.
3810      */
3811     (void)timecounter->tc_get_timecount(timecounter);
3812     inittodr(time_second + sc->acpi_sleep_delay);
3813 }
3814 
3815 /* Enable or disable the device's wake GPE. */
3816 int
acpi_wake_set_enable(device_t dev,int enable)3817 acpi_wake_set_enable(device_t dev, int enable)
3818 {
3819     struct acpi_prw_data prw;
3820     ACPI_STATUS status;
3821     int flags;
3822 
3823     /* Make sure the device supports waking the system and get the GPE. */
3824     if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
3825 	return (ENXIO);
3826 
3827     flags = acpi_get_flags(dev);
3828     if (enable) {
3829 	status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3830 	    ACPI_GPE_ENABLE);
3831 	if (ACPI_FAILURE(status)) {
3832 	    device_printf(dev, "enable wake failed\n");
3833 	    return (ENXIO);
3834 	}
3835 	acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
3836     } else {
3837 	status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3838 	    ACPI_GPE_DISABLE);
3839 	if (ACPI_FAILURE(status)) {
3840 	    device_printf(dev, "disable wake failed\n");
3841 	    return (ENXIO);
3842 	}
3843 	acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
3844     }
3845 
3846     return (0);
3847 }
3848 
3849 static int
acpi_wake_sleep_prep(struct acpi_softc * sc,ACPI_HANDLE handle,enum power_stype stype)3850 acpi_wake_sleep_prep(struct acpi_softc *sc, ACPI_HANDLE handle,
3851     enum power_stype stype)
3852 {
3853     int sstate;
3854     struct acpi_prw_data prw;
3855     device_t dev;
3856 
3857     /* Check that this is a wake-capable device and get its GPE. */
3858     if (acpi_parse_prw(handle, &prw) != 0)
3859 	return (ENXIO);
3860     dev = acpi_get_device(handle);
3861 
3862     sstate = acpi_stype_to_sstate(sc, stype);
3863 
3864     /*
3865      * The destination sleep state must be less than (i.e., higher power)
3866      * or equal to the value specified by _PRW.  If this GPE cannot be
3867      * enabled for the next sleep state, then disable it.  If it can and
3868      * the user requested it be enabled, turn on any required power resources
3869      * and set _PSW.
3870      */
3871     if (sstate > prw.lowest_wake) {
3872 	AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_DISABLE);
3873 	if (bootverbose)
3874 	    device_printf(dev, "wake_prep disabled wake for %s (%s)\n",
3875 		acpi_name(handle), power_stype_to_name(stype));
3876     } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
3877 	acpi_pwr_wake_enable(handle, 1);
3878 	acpi_SetInteger(handle, "_PSW", 1);
3879 	if (bootverbose)
3880 	    device_printf(dev, "wake_prep enabled for %s (%s)\n",
3881 		acpi_name(handle), power_stype_to_name(stype));
3882     }
3883 
3884     return (0);
3885 }
3886 
3887 static int
acpi_wake_run_prep(struct acpi_softc * sc,ACPI_HANDLE handle,enum power_stype stype)3888 acpi_wake_run_prep(struct acpi_softc *sc, ACPI_HANDLE handle,
3889     enum power_stype stype)
3890 {
3891     int sstate;
3892     struct acpi_prw_data prw;
3893     device_t dev;
3894 
3895     /*
3896      * Check that this is a wake-capable device and get its GPE.  Return
3897      * now if the user didn't enable this device for wake.
3898      */
3899     if (acpi_parse_prw(handle, &prw) != 0)
3900 	return (ENXIO);
3901     dev = acpi_get_device(handle);
3902     if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
3903 	return (0);
3904 
3905     sstate = acpi_stype_to_sstate(sc, stype);
3906 
3907     /*
3908      * If this GPE couldn't be enabled for the previous sleep state, it was
3909      * disabled before going to sleep so re-enable it.  If it was enabled,
3910      * clear _PSW and turn off any power resources it used.
3911      */
3912     if (sstate > prw.lowest_wake) {
3913 	AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_ENABLE);
3914 	if (bootverbose)
3915 	    device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
3916     } else {
3917 	acpi_SetInteger(handle, "_PSW", 0);
3918 	acpi_pwr_wake_enable(handle, 0);
3919 	if (bootverbose)
3920 	    device_printf(dev, "run_prep cleaned up for %s\n",
3921 		acpi_name(handle));
3922     }
3923 
3924     return (0);
3925 }
3926 
3927 static ACPI_STATUS
acpi_wake_prep(ACPI_HANDLE handle,UINT32 level,void * context,void ** status)3928 acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
3929 {
3930     struct acpi_wake_prep_context *ctx = context;
3931 
3932     /* If suspending, run the sleep prep function, otherwise wake. */
3933     if (AcpiGbl_SystemAwakeAndRunning)
3934 	acpi_wake_sleep_prep(ctx->sc, handle, ctx->stype);
3935     else
3936 	acpi_wake_run_prep(ctx->sc, handle, ctx->stype);
3937     return (AE_OK);
3938 }
3939 
3940 /* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
3941 static int
acpi_wake_prep_walk(struct acpi_softc * sc,enum power_stype stype)3942 acpi_wake_prep_walk(struct acpi_softc *sc, enum power_stype stype)
3943 {
3944     ACPI_HANDLE sb_handle;
3945     struct acpi_wake_prep_context ctx = {
3946 	.sc = sc,
3947 	.stype = stype,
3948     };
3949 
3950     if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
3951 	AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
3952 	    acpi_wake_prep, NULL, &ctx, NULL);
3953     return (0);
3954 }
3955 
3956 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
3957 static int
acpi_wake_sysctl_walk(device_t dev)3958 acpi_wake_sysctl_walk(device_t dev)
3959 {
3960     int error, i, numdevs;
3961     device_t *devlist;
3962     device_t child;
3963     ACPI_STATUS status;
3964 
3965     error = device_get_children(dev, &devlist, &numdevs);
3966     if (error != 0 || numdevs == 0) {
3967 	if (numdevs == 0)
3968 	    free(devlist, M_TEMP);
3969 	return (error);
3970     }
3971     for (i = 0; i < numdevs; i++) {
3972 	child = devlist[i];
3973 	acpi_wake_sysctl_walk(child);
3974 	if (!device_is_attached(child) || !acpi_has_flags(child))
3975 	    continue;
3976 	status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
3977 	if (ACPI_SUCCESS(status)) {
3978 	    SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
3979 		SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
3980 		"wake", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, child, 0,
3981 		acpi_wake_set_sysctl, "I", "Device set to wake the system");
3982 	}
3983     }
3984     free(devlist, M_TEMP);
3985 
3986     return (0);
3987 }
3988 
3989 /* Enable or disable wake from userland. */
3990 static int
acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)3991 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
3992 {
3993     int enable, error;
3994     device_t dev;
3995 
3996     dev = (device_t)arg1;
3997     enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
3998 
3999     error = sysctl_handle_int(oidp, &enable, 0, req);
4000     if (error != 0 || req->newptr == NULL)
4001 	return (error);
4002     if (enable != 0 && enable != 1)
4003 	return (EINVAL);
4004 
4005     return (acpi_wake_set_enable(dev, enable));
4006 }
4007 
4008 /* Parse a device's _PRW into a structure. */
4009 int
acpi_parse_prw(ACPI_HANDLE h,struct acpi_prw_data * prw)4010 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
4011 {
4012     ACPI_STATUS			status;
4013     ACPI_BUFFER			prw_buffer;
4014     ACPI_OBJECT			*res, *res2;
4015     int				error, i, power_count;
4016 
4017     if (h == NULL || prw == NULL)
4018 	return (EINVAL);
4019 
4020     /*
4021      * The _PRW object (7.2.9) is only required for devices that have the
4022      * ability to wake the system from a sleeping state.
4023      */
4024     error = EINVAL;
4025     prw_buffer.Pointer = NULL;
4026     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
4027     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
4028     if (ACPI_FAILURE(status))
4029 	return (ENOENT);
4030     res = (ACPI_OBJECT *)prw_buffer.Pointer;
4031     if (res == NULL)
4032 	return (ENOENT);
4033     if (!ACPI_PKG_VALID(res, 2))
4034 	goto out;
4035 
4036     /*
4037      * Element 1 of the _PRW object:
4038      * The lowest power system sleeping state that can be entered while still
4039      * providing wake functionality.  The sleeping state being entered must
4040      * be less than (i.e., higher power) or equal to this value.
4041      */
4042     if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
4043 	goto out;
4044 
4045     /*
4046      * Element 0 of the _PRW object:
4047      */
4048     switch (res->Package.Elements[0].Type) {
4049     case ACPI_TYPE_INTEGER:
4050 	/*
4051 	 * If the data type of this package element is numeric, then this
4052 	 * _PRW package element is the bit index in the GPEx_EN, in the
4053 	 * GPE blocks described in the FADT, of the enable bit that is
4054 	 * enabled for the wake event.
4055 	 */
4056 	prw->gpe_handle = NULL;
4057 	prw->gpe_bit = res->Package.Elements[0].Integer.Value;
4058 	error = 0;
4059 	break;
4060     case ACPI_TYPE_PACKAGE:
4061 	/*
4062 	 * If the data type of this package element is a package, then this
4063 	 * _PRW package element is itself a package containing two
4064 	 * elements.  The first is an object reference to the GPE Block
4065 	 * device that contains the GPE that will be triggered by the wake
4066 	 * event.  The second element is numeric and it contains the bit
4067 	 * index in the GPEx_EN, in the GPE Block referenced by the
4068 	 * first element in the package, of the enable bit that is enabled for
4069 	 * the wake event.
4070 	 *
4071 	 * For example, if this field is a package then it is of the form:
4072 	 * Package() {\_SB.PCI0.ISA.GPE, 2}
4073 	 */
4074 	res2 = &res->Package.Elements[0];
4075 	if (!ACPI_PKG_VALID(res2, 2))
4076 	    goto out;
4077 	prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
4078 	if (prw->gpe_handle == NULL)
4079 	    goto out;
4080 	if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
4081 	    goto out;
4082 	error = 0;
4083 	break;
4084     default:
4085 	goto out;
4086     }
4087 
4088     /* Elements 2 to N of the _PRW object are power resources. */
4089     power_count = res->Package.Count - 2;
4090     if (power_count > ACPI_PRW_MAX_POWERRES) {
4091 	printf("ACPI device %s has too many power resources\n", acpi_name(h));
4092 	power_count = 0;
4093     }
4094     prw->power_res_count = power_count;
4095     for (i = 0; i < power_count; i++)
4096 	prw->power_res[i] = res->Package.Elements[i];
4097 
4098 out:
4099     if (prw_buffer.Pointer != NULL)
4100 	AcpiOsFree(prw_buffer.Pointer);
4101     return (error);
4102 }
4103 
4104 /*
4105  * ACPI Event Handlers
4106  */
4107 
4108 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
4109 
4110 static void
acpi_system_eventhandler_sleep(void * arg,enum power_stype stype)4111 acpi_system_eventhandler_sleep(void *arg, enum power_stype stype)
4112 {
4113     struct acpi_softc *sc = (struct acpi_softc *)arg;
4114     int ret;
4115 
4116     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, stype);
4117 
4118     /* Check if button action is disabled or unknown. */
4119     if (stype == POWER_STYPE_UNKNOWN)
4120 	return;
4121 
4122     /*
4123      * Request that the system prepare to enter the given suspend state. We can
4124      * totally pass an ACPI S-state to an enum power_stype.
4125      */
4126     ret = acpi_ReqSleepState(sc, stype);
4127     if (ret != 0)
4128 	device_printf(sc->acpi_dev,
4129 	    "request to enter state %s failed (err %d)\n",
4130 	    power_stype_to_name(stype), ret);
4131 
4132     return_VOID;
4133 }
4134 
4135 static void
acpi_system_eventhandler_wakeup(void * arg,enum power_stype stype)4136 acpi_system_eventhandler_wakeup(void *arg, enum power_stype stype)
4137 {
4138 
4139     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, stype);
4140 
4141     /* Currently, nothing to do for wakeup. */
4142 
4143     return_VOID;
4144 }
4145 
4146 /*
4147  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
4148  */
4149 static void
acpi_invoke_sleep_eventhandler(void * context)4150 acpi_invoke_sleep_eventhandler(void *context)
4151 {
4152 
4153     EVENTHANDLER_INVOKE(acpi_sleep_event, *(enum power_stype *)context);
4154 }
4155 
4156 static void
acpi_invoke_wake_eventhandler(void * context)4157 acpi_invoke_wake_eventhandler(void *context)
4158 {
4159 
4160     EVENTHANDLER_INVOKE(acpi_wakeup_event, *(enum power_stype *)context);
4161 }
4162 
4163 UINT32
acpi_event_power_button_sleep(void * context)4164 acpi_event_power_button_sleep(void *context)
4165 {
4166 #if defined(__amd64__) || defined(__i386__)
4167     struct acpi_softc	*sc = (struct acpi_softc *)context;
4168 #else
4169     (void)context;
4170 #endif
4171 
4172     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
4173 
4174 #if defined(__amd64__) || defined(__i386__)
4175     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
4176 	acpi_invoke_sleep_eventhandler, &sc->acpi_power_button_stype)))
4177 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
4178 #else
4179     shutdown_nice(RB_POWEROFF);
4180 #endif
4181 
4182     return_VALUE (ACPI_INTERRUPT_HANDLED);
4183 }
4184 
4185 UINT32
acpi_event_power_button_wake(void * context)4186 acpi_event_power_button_wake(void *context)
4187 {
4188     struct acpi_softc	*sc = (struct acpi_softc *)context;
4189 
4190     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
4191 
4192     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
4193 	acpi_invoke_wake_eventhandler, &sc->acpi_power_button_stype)))
4194 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
4195     return_VALUE (ACPI_INTERRUPT_HANDLED);
4196 }
4197 
4198 UINT32
acpi_event_sleep_button_sleep(void * context)4199 acpi_event_sleep_button_sleep(void *context)
4200 {
4201     struct acpi_softc	*sc = (struct acpi_softc *)context;
4202 
4203     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
4204 
4205     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
4206 	acpi_invoke_sleep_eventhandler, &sc->acpi_sleep_button_stype)))
4207 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
4208     return_VALUE (ACPI_INTERRUPT_HANDLED);
4209 }
4210 
4211 UINT32
acpi_event_sleep_button_wake(void * context)4212 acpi_event_sleep_button_wake(void *context)
4213 {
4214     struct acpi_softc	*sc = (struct acpi_softc *)context;
4215 
4216     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
4217 
4218     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
4219 	acpi_invoke_wake_eventhandler, &sc->acpi_sleep_button_stype)))
4220 	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
4221     return_VALUE (ACPI_INTERRUPT_HANDLED);
4222 }
4223 
4224 /*
4225  * XXX This static buffer is suboptimal.  There is no locking so only
4226  * use this for single-threaded callers.
4227  */
4228 char *
acpi_name(ACPI_HANDLE handle)4229 acpi_name(ACPI_HANDLE handle)
4230 {
4231     ACPI_BUFFER buf;
4232     static char data[256];
4233 
4234     buf.Length = sizeof(data);
4235     buf.Pointer = data;
4236 
4237     if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
4238 	return (data);
4239     return ("(unknown)");
4240 }
4241 
4242 /*
4243  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
4244  * parts of the namespace.
4245  */
4246 int
acpi_avoid(ACPI_HANDLE handle)4247 acpi_avoid(ACPI_HANDLE handle)
4248 {
4249     char	*cp, *env, *np;
4250     int		len;
4251 
4252     np = acpi_name(handle);
4253     if (*np == '\\')
4254 	np++;
4255     if ((env = kern_getenv("debug.acpi.avoid")) == NULL)
4256 	return (0);
4257 
4258     /* Scan the avoid list checking for a match */
4259     cp = env;
4260     for (;;) {
4261 	while (*cp != 0 && isspace(*cp))
4262 	    cp++;
4263 	if (*cp == 0)
4264 	    break;
4265 	len = 0;
4266 	while (cp[len] != 0 && !isspace(cp[len]))
4267 	    len++;
4268 	if (!strncmp(cp, np, len)) {
4269 	    freeenv(env);
4270 	    return(1);
4271 	}
4272 	cp += len;
4273     }
4274     freeenv(env);
4275 
4276     return (0);
4277 }
4278 
4279 /*
4280  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
4281  */
4282 int
acpi_disabled(char * subsys)4283 acpi_disabled(char *subsys)
4284 {
4285     char	*cp, *env;
4286     int		len;
4287 
4288     if ((env = kern_getenv("debug.acpi.disabled")) == NULL)
4289 	return (0);
4290     if (strcmp(env, "all") == 0) {
4291 	freeenv(env);
4292 	return (1);
4293     }
4294 
4295     /* Scan the disable list, checking for a match. */
4296     cp = env;
4297     for (;;) {
4298 	while (*cp != '\0' && isspace(*cp))
4299 	    cp++;
4300 	if (*cp == '\0')
4301 	    break;
4302 	len = 0;
4303 	while (cp[len] != '\0' && !isspace(cp[len]))
4304 	    len++;
4305 	if (strncmp(cp, subsys, len) == 0) {
4306 	    freeenv(env);
4307 	    return (1);
4308 	}
4309 	cp += len;
4310     }
4311     freeenv(env);
4312 
4313     return (0);
4314 }
4315 
4316 static void
acpi_lookup(void * arg,const char * name,device_t * dev)4317 acpi_lookup(void *arg, const char *name, device_t *dev)
4318 {
4319     ACPI_HANDLE handle;
4320 
4321     if (*dev != NULL)
4322 	return;
4323 
4324     /*
4325      * Allow any handle name that is specified as an absolute path and
4326      * starts with '\'.  We could restrict this to \_SB and friends,
4327      * but see acpi_probe_children() for notes on why we scan the entire
4328      * namespace for devices.
4329      *
4330      * XXX: The pathname argument to AcpiGetHandle() should be fixed to
4331      * be const.
4332      */
4333     if (name[0] != '\\')
4334 	return;
4335     if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, __DECONST(char *, name),
4336 	&handle)))
4337 	return;
4338     *dev = acpi_get_device(handle);
4339 }
4340 
4341 /*
4342  * Control interface.
4343  *
4344  * We multiplex ioctls for all participating ACPI devices here.  Individual
4345  * drivers wanting to be accessible via /dev/acpi should use the
4346  * register/deregister interface to make their handlers visible.
4347  */
4348 struct acpi_ioctl_hook
4349 {
4350     TAILQ_ENTRY(acpi_ioctl_hook) link;
4351     u_long			 cmd;
4352     acpi_ioctl_fn		 fn;
4353     void			 *arg;
4354 };
4355 
4356 static TAILQ_HEAD(,acpi_ioctl_hook) acpi_ioctl_hooks =
4357 	TAILQ_HEAD_INITIALIZER(acpi_ioctl_hooks);
4358 
4359 int
acpi_register_ioctl(u_long cmd,acpi_ioctl_fn fn,void * arg)4360 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
4361 {
4362     struct acpi_ioctl_hook *hp, *thp;
4363 
4364     hp = malloc(sizeof(*hp), M_ACPIDEV, M_WAITOK);
4365     hp->cmd = cmd;
4366     hp->fn = fn;
4367     hp->arg = arg;
4368 
4369     ACPI_LOCK(acpi);
4370     TAILQ_FOREACH(thp, &acpi_ioctl_hooks, link) {
4371 	if (thp->cmd == cmd) {
4372 	    ACPI_UNLOCK(acpi);
4373 	    free(hp, M_ACPIDEV);
4374 	    return (EBUSY);
4375 	}
4376     }
4377 
4378     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
4379     ACPI_UNLOCK(acpi);
4380 
4381     return (0);
4382 }
4383 
4384 void
acpi_deregister_ioctl(u_long cmd,acpi_ioctl_fn fn)4385 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
4386 {
4387     struct acpi_ioctl_hook	*hp;
4388 
4389     ACPI_LOCK(acpi);
4390     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
4391 	if (hp->cmd == cmd && hp->fn == fn)
4392 	    break;
4393 
4394     if (hp != NULL) {
4395 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
4396 	free(hp, M_ACPIDEV);
4397     }
4398     ACPI_UNLOCK(acpi);
4399 }
4400 
4401 void
acpi_deregister_ioctls(acpi_ioctl_fn fn)4402 acpi_deregister_ioctls(acpi_ioctl_fn fn)
4403 {
4404 	struct acpi_ioctl_hook *hp, *thp;
4405 
4406 	ACPI_LOCK(acpi);
4407 	TAILQ_FOREACH_SAFE(hp, &acpi_ioctl_hooks, link, thp) {
4408 		if (hp->fn == fn) {
4409 			TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
4410 			free(hp, M_ACPIDEV);
4411 		}
4412 	}
4413 	ACPI_UNLOCK(acpi);
4414 }
4415 
4416 static int
acpiopen(struct cdev * dev,int flag,int fmt,struct thread * td)4417 acpiopen(struct cdev *dev, int flag, int fmt, struct thread *td)
4418 {
4419     return (0);
4420 }
4421 
4422 static int
acpiclose(struct cdev * dev,int flag,int fmt,struct thread * td)4423 acpiclose(struct cdev *dev, int flag, int fmt, struct thread *td)
4424 {
4425     return (0);
4426 }
4427 
4428 static int
acpiioctl(struct cdev * dev,u_long cmd,caddr_t addr,int flag,struct thread * td)4429 acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
4430 {
4431     struct acpi_softc		*sc;
4432     struct acpi_ioctl_hook	*hp;
4433     int				error;
4434     int				sstate;
4435 
4436     error = 0;
4437     hp = NULL;
4438     sc = dev->si_drv1;
4439 
4440     /*
4441      * Scan the list of registered ioctls, looking for handlers.
4442      */
4443     ACPI_LOCK(acpi);
4444     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
4445 	if (hp->cmd == cmd)
4446 	    break;
4447     }
4448     ACPI_UNLOCK(acpi);
4449     if (hp)
4450 	return (hp->fn(cmd, addr, hp->arg));
4451 
4452     /*
4453      * Core ioctls are not permitted for non-writable user.
4454      * Currently, other ioctls just fetch information.
4455      * Not changing system behavior.
4456      */
4457     if ((flag & FWRITE) == 0)
4458 	return (EPERM);
4459 
4460     /* Core system ioctls. */
4461     switch (cmd) {
4462     case ACPIIO_REQSLPSTATE:
4463 	sstate = *(int *)addr;
4464 	if (sstate != ACPI_STATE_S5)
4465 	    return (acpi_ReqSleepState(sc, acpi_sstate_to_stype(sstate)));
4466 	device_printf(sc->acpi_dev, "power off via acpi ioctl not supported\n");
4467 	error = EOPNOTSUPP;
4468 	break;
4469     case ACPIIO_ACKSLPSTATE:
4470 	error = *(int *)addr;
4471 	error = acpi_AckSleepState(sc->acpi_clone, error);
4472 	break;
4473     case ACPIIO_SETSLPSTATE:	/* DEPRECATED */
4474 	sstate = *(int *)addr;
4475 	if (sstate < ACPI_STATE_S0 || sstate > ACPI_STATE_S5)
4476 	    return (EINVAL);
4477 	if (!acpi_supported_sstates[sstate])
4478 	    return (EOPNOTSUPP);
4479 	if (ACPI_FAILURE(acpi_SetSleepState(sc, acpi_sstate_to_stype(sstate))))
4480 	    error = ENXIO;
4481 	break;
4482     default:
4483 	error = ENXIO;
4484 	break;
4485     }
4486 
4487     return (error);
4488 }
4489 
4490 static int
acpi_s4bios_sysctl(SYSCTL_HANDLER_ARGS)4491 acpi_s4bios_sysctl(SYSCTL_HANDLER_ARGS)
4492 {
4493     struct acpi_softc *const sc = arg1;
4494     bool val;
4495     int error;
4496 
4497     val = sc->acpi_s4bios;
4498     error = sysctl_handle_bool(oidp, &val, 0, req);
4499     if (error != 0 || req->newptr == NULL)
4500 	return (error);
4501 
4502     if (val && !sc->acpi_s4bios_supported)
4503 	return (EOPNOTSUPP);
4504     sc->acpi_s4bios = val;
4505 
4506     return (0);
4507 }
4508 
4509 static int
acpi_sname_to_sstate(const char * sname)4510 acpi_sname_to_sstate(const char *sname)
4511 {
4512     int sstate;
4513 
4514     if (strcasecmp(sname, "NONE") == 0)
4515 	return (ACPI_STATE_UNKNOWN);
4516 
4517     if (toupper(sname[0]) == 'S') {
4518 	sstate = sname[1] - '0';
4519 	if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5 &&
4520 	    sname[2] == '\0')
4521 	    return (sstate);
4522     }
4523     return (-1);
4524 }
4525 
4526 static const char *
acpi_sstate_to_sname(int state)4527 acpi_sstate_to_sname(int state)
4528 {
4529     static const char *snames[ACPI_S_STATE_COUNT] = {"S0", "S1", "S2", "S3",
4530 	"S4", "S5"};
4531 
4532     if (state == ACPI_STATE_UNKNOWN)
4533 	return ("NONE");
4534     if (state >= ACPI_STATE_S0 && state < ACPI_S_STATE_COUNT)
4535 	return (snames[state]);
4536     return (NULL);
4537 }
4538 
4539 static int
acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)4540 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
4541 {
4542     int error;
4543     struct sbuf sb;
4544     UINT8 state;
4545 
4546     sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
4547     for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
4548 	if (acpi_supported_sstates[state])
4549 	    sbuf_printf(&sb, "%s ", acpi_sstate_to_sname(state));
4550     sbuf_trim(&sb);
4551     sbuf_finish(&sb);
4552     error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
4553     sbuf_delete(&sb);
4554     return (error);
4555 }
4556 
4557 static int
acpi_suspend_state_sysctl(SYSCTL_HANDLER_ARGS)4558 acpi_suspend_state_sysctl(SYSCTL_HANDLER_ARGS)
4559 {
4560     char name[10];
4561     int err;
4562     struct acpi_softc *sc = oidp->oid_arg1;
4563     enum power_stype new_stype;
4564     enum power_stype old_stype = power_suspend_stype;
4565     int old_sstate = acpi_stype_to_sstate(sc, old_stype);
4566     int new_sstate;
4567 
4568     strlcpy(name, acpi_sstate_to_sname(old_sstate), sizeof(name));
4569     err = sysctl_handle_string(oidp, name, sizeof(name), req);
4570     if (err != 0 || req->newptr == NULL)
4571 	return (err);
4572 
4573     new_sstate = acpi_sname_to_sstate(name);
4574     if (new_sstate < 0)
4575 	return (EINVAL);
4576     new_stype = acpi_sstate_to_stype(new_sstate);
4577     if (new_sstate != ACPI_STATE_UNKNOWN &&
4578 	acpi_supported_stypes[new_stype] == false)
4579 	return (EOPNOTSUPP);
4580 
4581     if (new_stype != old_stype)
4582 	power_suspend_stype = new_stype;
4583     return (err);
4584 }
4585 
4586 static int
acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)4587 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
4588 {
4589     char sleep_state[10];
4590     int error;
4591     int new_sstate, old_sstate;
4592 
4593     old_sstate = *(int *)oidp->oid_arg1;
4594     strlcpy(sleep_state, acpi_sstate_to_sname(old_sstate), sizeof(sleep_state));
4595     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
4596     if (error == 0 && req->newptr != NULL) {
4597 	new_sstate = acpi_sname_to_sstate(sleep_state);
4598 	if (new_sstate < 0)
4599 	    return (EINVAL);
4600 	if (new_sstate < ACPI_S_STATE_COUNT &&
4601 	    !acpi_supported_sstates[new_sstate])
4602 	    return (EOPNOTSUPP);
4603 	if (new_sstate != old_sstate)
4604 	    *(int *)oidp->oid_arg1 = new_sstate;
4605     }
4606     return (error);
4607 }
4608 
4609 static int
acpi_stype_sysctl(SYSCTL_HANDLER_ARGS)4610 acpi_stype_sysctl(SYSCTL_HANDLER_ARGS)
4611 {
4612     char name[10];
4613     int err;
4614     int sstate;
4615     enum power_stype new_stype, old_stype;
4616 
4617     old_stype = *(enum power_stype *)oidp->oid_arg1;
4618     strlcpy(name, power_stype_to_name(old_stype), sizeof(name));
4619     err = sysctl_handle_string(oidp, name, sizeof(name), req);
4620     if (err != 0 || req->newptr == NULL)
4621 	return (err);
4622 
4623     if (strcasecmp(name, "NONE") == 0) {
4624 	new_stype = POWER_STYPE_UNKNOWN;
4625     } else {
4626 	new_stype = power_name_to_stype(name);
4627 	if (new_stype == POWER_STYPE_UNKNOWN) {
4628 	    sstate = acpi_sname_to_sstate(name);
4629 	    if (sstate < 0)
4630 		return (EINVAL);
4631 	    printf("warning: the 'hw.acpi.%s' sysctl expects a sleep type, but "
4632 	           "an ACPI S-state has been passed to it. This functionality "
4633 	           "is deprecated; see acpi(4).\n", oidp->oid_name);
4634 	    MPASS(sstate < ACPI_S_STATE_COUNT);
4635 	    if (acpi_supported_sstates[sstate] == false)
4636 		return (EOPNOTSUPP);
4637 	    new_stype = acpi_sstate_to_stype(sstate);
4638 	}
4639 	if (acpi_supported_stypes[new_stype] == false)
4640 	    return (EOPNOTSUPP);
4641     }
4642 
4643     if (new_stype != old_stype)
4644 	*(enum power_stype *)oidp->oid_arg1 = new_stype;
4645     return (0);
4646 }
4647 
4648 /* Inform devctl(4) when we receive a Notify. */
4649 void
acpi_UserNotify(const char * subsystem,ACPI_HANDLE h,uint8_t notify)4650 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
4651 {
4652     char		notify_buf[16];
4653     ACPI_BUFFER		handle_buf;
4654     ACPI_STATUS		status;
4655 
4656     if (subsystem == NULL)
4657 	return;
4658 
4659     handle_buf.Pointer = NULL;
4660     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
4661     status = AcpiNsHandleToPathname(h, &handle_buf, FALSE);
4662     if (ACPI_FAILURE(status))
4663 	return;
4664     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
4665     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
4666     AcpiOsFree(handle_buf.Pointer);
4667 }
4668 
4669 #ifdef ACPI_DEBUG
4670 /*
4671  * Support for parsing debug options from the kernel environment.
4672  *
4673  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
4674  * by specifying the names of the bits in the debug.acpi.layer and
4675  * debug.acpi.level environment variables.  Bits may be unset by
4676  * prefixing the bit name with !.
4677  */
4678 struct debugtag
4679 {
4680     char	*name;
4681     UINT32	value;
4682 };
4683 
4684 static struct debugtag	dbg_layer[] = {
4685     {"ACPI_UTILITIES",		ACPI_UTILITIES},
4686     {"ACPI_HARDWARE",		ACPI_HARDWARE},
4687     {"ACPI_EVENTS",		ACPI_EVENTS},
4688     {"ACPI_TABLES",		ACPI_TABLES},
4689     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
4690     {"ACPI_PARSER",		ACPI_PARSER},
4691     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
4692     {"ACPI_EXECUTER",		ACPI_EXECUTER},
4693     {"ACPI_RESOURCES",		ACPI_RESOURCES},
4694     {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
4695     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
4696     {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
4697     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
4698 
4699     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
4700     {"ACPI_BATTERY",		ACPI_BATTERY},
4701     {"ACPI_BUS",		ACPI_BUS},
4702     {"ACPI_BUTTON",		ACPI_BUTTON},
4703     {"ACPI_EC", 		ACPI_EC},
4704     {"ACPI_FAN",		ACPI_FAN},
4705     {"ACPI_POWERRES",		ACPI_POWERRES},
4706     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
4707     {"ACPI_SPMC",		ACPI_SPMC},
4708     {"ACPI_THERMAL",		ACPI_THERMAL},
4709     {"ACPI_TIMER",		ACPI_TIMER},
4710     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
4711     {NULL, 0}
4712 };
4713 
4714 static struct debugtag dbg_level[] = {
4715     {"ACPI_LV_INIT",		ACPI_LV_INIT},
4716     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
4717     {"ACPI_LV_INFO",		ACPI_LV_INFO},
4718     {"ACPI_LV_REPAIR",		ACPI_LV_REPAIR},
4719     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
4720 
4721     /* Trace verbosity level 1 [Standard Trace Level] */
4722     {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
4723     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
4724     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
4725     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
4726     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
4727     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
4728     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
4729     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
4730     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
4731     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
4732     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
4733     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
4734     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
4735     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
4736     {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
4737 
4738     /* Trace verbosity level 2 [Function tracing and memory allocation] */
4739     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
4740     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
4741     {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
4742     {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
4743     {"ACPI_LV_ALL",		ACPI_LV_ALL},
4744 
4745     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
4746     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
4747     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
4748     {"ACPI_LV_IO",		ACPI_LV_IO},
4749     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
4750     {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
4751 
4752     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
4753     {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
4754     {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
4755     {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
4756     {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
4757     {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
4758     {NULL, 0}
4759 };
4760 
4761 static void
acpi_parse_debug(char * cp,struct debugtag * tag,UINT32 * flag)4762 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
4763 {
4764     char	*ep;
4765     int		i, l;
4766     int		set;
4767 
4768     while (*cp) {
4769 	if (isspace(*cp)) {
4770 	    cp++;
4771 	    continue;
4772 	}
4773 	ep = cp;
4774 	while (*ep && !isspace(*ep))
4775 	    ep++;
4776 	if (*cp == '!') {
4777 	    set = 0;
4778 	    cp++;
4779 	    if (cp == ep)
4780 		continue;
4781 	} else {
4782 	    set = 1;
4783 	}
4784 	l = ep - cp;
4785 	for (i = 0; tag[i].name != NULL; i++) {
4786 	    if (!strncmp(cp, tag[i].name, l)) {
4787 		if (set)
4788 		    *flag |= tag[i].value;
4789 		else
4790 		    *flag &= ~tag[i].value;
4791 	    }
4792 	}
4793 	cp = ep;
4794     }
4795 }
4796 
4797 static void
acpi_set_debugging(void * junk)4798 acpi_set_debugging(void *junk)
4799 {
4800     char	*layer, *level;
4801 
4802     if (cold) {
4803 	AcpiDbgLayer = 0;
4804 	AcpiDbgLevel = 0;
4805     }
4806 
4807     layer = kern_getenv("debug.acpi.layer");
4808     level = kern_getenv("debug.acpi.level");
4809     if (layer == NULL && level == NULL)
4810 	return;
4811 
4812     printf("ACPI set debug");
4813     if (layer != NULL) {
4814 	if (strcmp("NONE", layer) != 0)
4815 	    printf(" layer '%s'", layer);
4816 	acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
4817 	freeenv(layer);
4818     }
4819     if (level != NULL) {
4820 	if (strcmp("NONE", level) != 0)
4821 	    printf(" level '%s'", level);
4822 	acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
4823 	freeenv(level);
4824     }
4825     printf("\n");
4826 }
4827 
4828 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
4829 	NULL);
4830 
4831 static int
acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)4832 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
4833 {
4834     int		 error, *dbg;
4835     struct	 debugtag *tag;
4836     struct	 sbuf sb;
4837     char	 temp[128];
4838 
4839     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
4840 	return (ENOMEM);
4841     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
4842 	tag = &dbg_layer[0];
4843 	dbg = &AcpiDbgLayer;
4844     } else {
4845 	tag = &dbg_level[0];
4846 	dbg = &AcpiDbgLevel;
4847     }
4848 
4849     /* Get old values if this is a get request. */
4850     ACPI_SERIAL_BEGIN(acpi);
4851     if (*dbg == 0) {
4852 	sbuf_cpy(&sb, "NONE");
4853     } else if (req->newptr == NULL) {
4854 	for (; tag->name != NULL; tag++) {
4855 	    if ((*dbg & tag->value) == tag->value)
4856 		sbuf_printf(&sb, "%s ", tag->name);
4857 	}
4858     }
4859     sbuf_trim(&sb);
4860     sbuf_finish(&sb);
4861     strlcpy(temp, sbuf_data(&sb), sizeof(temp));
4862     sbuf_delete(&sb);
4863 
4864     error = sysctl_handle_string(oidp, temp, sizeof(temp), req);
4865 
4866     /* Check for error or no change */
4867     if (error == 0 && req->newptr != NULL) {
4868 	*dbg = 0;
4869 	kern_setenv((char *)oidp->oid_arg1, temp);
4870 	acpi_set_debugging(NULL);
4871     }
4872     ACPI_SERIAL_END(acpi);
4873 
4874     return (error);
4875 }
4876 
4877 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer,
4878     CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, "debug.acpi.layer", 0,
4879     acpi_debug_sysctl, "A",
4880     "");
4881 SYSCTL_PROC(_debug_acpi, OID_AUTO, level,
4882     CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, "debug.acpi.level", 0,
4883     acpi_debug_sysctl, "A",
4884     "");
4885 #endif /* ACPI_DEBUG */
4886 
4887 static int
acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)4888 acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)
4889 {
4890 	int	error;
4891 	int	old;
4892 
4893 	old = acpi_debug_objects;
4894 	error = sysctl_handle_int(oidp, &acpi_debug_objects, 0, req);
4895 	if (error != 0 || req->newptr == NULL)
4896 		return (error);
4897 	if (old == acpi_debug_objects || (old && acpi_debug_objects))
4898 		return (0);
4899 
4900 	ACPI_SERIAL_BEGIN(acpi);
4901 	AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
4902 	ACPI_SERIAL_END(acpi);
4903 
4904 	return (0);
4905 }
4906 
4907 static int
acpi_parse_interfaces(char * str,struct acpi_interface * iface)4908 acpi_parse_interfaces(char *str, struct acpi_interface *iface)
4909 {
4910 	char *p;
4911 	size_t len;
4912 	int i, j;
4913 
4914 	p = str;
4915 	while (isspace(*p) || *p == ',')
4916 		p++;
4917 	len = strlen(p);
4918 	if (len == 0)
4919 		return (0);
4920 	p = strdup(p, M_TEMP);
4921 	for (i = 0; i < len; i++)
4922 		if (p[i] == ',')
4923 			p[i] = '\0';
4924 	i = j = 0;
4925 	while (i < len)
4926 		if (isspace(p[i]) || p[i] == '\0')
4927 			i++;
4928 		else {
4929 			i += strlen(p + i) + 1;
4930 			j++;
4931 		}
4932 	if (j == 0) {
4933 		free(p, M_TEMP);
4934 		return (0);
4935 	}
4936 	iface->data = malloc(sizeof(*iface->data) * j, M_TEMP, M_WAITOK);
4937 	iface->num = j;
4938 	i = j = 0;
4939 	while (i < len)
4940 		if (isspace(p[i]) || p[i] == '\0')
4941 			i++;
4942 		else {
4943 			iface->data[j] = p + i;
4944 			i += strlen(p + i) + 1;
4945 			j++;
4946 		}
4947 
4948 	return (j);
4949 }
4950 
4951 static void
acpi_free_interfaces(struct acpi_interface * iface)4952 acpi_free_interfaces(struct acpi_interface *iface)
4953 {
4954 
4955 	free(iface->data[0], M_TEMP);
4956 	free(iface->data, M_TEMP);
4957 }
4958 
4959 static void
acpi_reset_interfaces(device_t dev)4960 acpi_reset_interfaces(device_t dev)
4961 {
4962 	struct acpi_interface list;
4963 	ACPI_STATUS status;
4964 	int i;
4965 
4966 	if (acpi_parse_interfaces(acpi_install_interface, &list) > 0) {
4967 		for (i = 0; i < list.num; i++) {
4968 			status = AcpiInstallInterface(list.data[i]);
4969 			if (ACPI_FAILURE(status))
4970 				device_printf(dev,
4971 				    "failed to install _OSI(\"%s\"): %s\n",
4972 				    list.data[i], AcpiFormatException(status));
4973 			else if (bootverbose)
4974 				device_printf(dev, "installed _OSI(\"%s\")\n",
4975 				    list.data[i]);
4976 		}
4977 		acpi_free_interfaces(&list);
4978 	}
4979 	if (acpi_parse_interfaces(acpi_remove_interface, &list) > 0) {
4980 		for (i = 0; i < list.num; i++) {
4981 			status = AcpiRemoveInterface(list.data[i]);
4982 			if (ACPI_FAILURE(status))
4983 				device_printf(dev,
4984 				    "failed to remove _OSI(\"%s\"): %s\n",
4985 				    list.data[i], AcpiFormatException(status));
4986 			else if (bootverbose)
4987 				device_printf(dev, "removed _OSI(\"%s\")\n",
4988 				    list.data[i]);
4989 		}
4990 		acpi_free_interfaces(&list);
4991 	}
4992 
4993 	/*
4994 	 * Apple Mac hardware quirk: install Darwin OSI.
4995 	 *
4996 	 * On Apple hardware, install the Darwin OSI and remove the Windows OSI
4997 	 * to match Linux behavior.
4998 	 *
4999 	 * This is required for dual-GPU MacBook Pro systems
5000 	 * (Intel iGPU + AMD/NVIDIA dGPU) where the iGPU is hidden when the
5001 	 * firmware doesn't see Darwin OSI, but it also unlocks additional ACPI
5002 	 * support on non-MacBook Pro Apple platforms.
5003 	 *
5004 	 * Apple's ACPI firmware checks _OSI("Darwin") and sets OSYS=10000
5005 	 * for macOS. Many device methods use OSDW() which checks OSYS==10000
5006 	 * for macOS-specific behavior including GPU visibility and power
5007 	 * management.
5008 	 *
5009 	 * Linux enables Darwin OSI by default on Apple hardware and disables
5010 	 * all Windows OSI strings (drivers/acpi/osi.c). Users can override
5011 	 * this behavior with acpi_osi=!Darwin to get Windows-like behavior,
5012 	 * in general, but this logic makes that process unnecessary.
5013 	 *
5014 	 * Detect Apple via SMBIOS and enable Darwin while disabling Windows
5015 	 * vendor strings. This makes both GPUs visible on dual-GPU MacBook Pro
5016 	 * systems (Intel iGPU + AMD dGPU) and unlocks full platform
5017 	 * ACPI support.
5018 	 */
5019 	if (acpi_apple_darwin_osi) {
5020 		char *vendor = kern_getenv("smbios.system.maker");
5021 		if (vendor != NULL) {
5022 			if (strcmp(vendor, "Apple Inc.") == 0 ||
5023 			    strcmp(vendor, "Apple Computer, Inc.") == 0) {
5024 				/* Disable all other OSI vendor strings. */
5025 				status = AcpiUpdateInterfaces(
5026 				    ACPI_DISABLE_ALL_VENDOR_STRINGS);
5027 				if (ACPI_SUCCESS(status)) {
5028 					/* Install Darwin OSI */
5029 					status = AcpiInstallInterface("Darwin");
5030 				}
5031 				if (bootverbose) {
5032 					if (ACPI_SUCCESS(status)) {
5033 						device_printf(dev,
5034 						    "disabled non-Darwin OSI & "
5035 						    "installed Darwin OSI\n");
5036 					} else {
5037 						device_printf(dev,
5038 						    "could not install "
5039 						    "Darwin OSI: %s\n",
5040 						    AcpiFormatException(status));
5041 					}
5042 				}
5043 			} else if (bootverbose) {
5044 				device_printf(dev,
5045 				    "Not installing Darwin OSI on unsupported platform: %s\n",
5046 				    vendor);
5047 			}
5048 			freeenv(vendor);
5049 		}
5050 	}
5051 }
5052 
5053 static int
acpi_pm_func(u_long cmd,void * arg,enum power_stype stype)5054 acpi_pm_func(u_long cmd, void *arg, enum power_stype stype)
5055 {
5056 	int	error;
5057 	struct	acpi_softc *sc;
5058 
5059 	error = 0;
5060 	switch (cmd) {
5061 	case POWER_CMD_SUSPEND:
5062 		sc = (struct acpi_softc *)arg;
5063 		if (sc == NULL) {
5064 			error = EINVAL;
5065 			goto out;
5066 		}
5067 		if (ACPI_FAILURE(acpi_EnterSleepState(sc, stype)))
5068 			error = ENXIO;
5069 		break;
5070 	default:
5071 		error = EINVAL;
5072 		goto out;
5073 	}
5074 
5075 out:
5076 	return (error);
5077 }
5078 
5079 static void
acpi_pm_register(void * arg)5080 acpi_pm_register(void *arg)
5081 {
5082     if (!cold || resource_disabled("acpi", 0))
5083 	return;
5084 
5085     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL,
5086 	acpi_supported_stypes);
5087 }
5088 
5089 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, NULL);
5090