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