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