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