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