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