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