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