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