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