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