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