xref: /dragonfly/sys/dev/acpica/acpi.c (revision b40e316c)
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  *	$FreeBSD: src/sys/dev/acpica/acpi.c,v 1.95.2.1 2003/08/22 20:49:20 jhb Exp $
30  *      $DragonFly: src/sys/dev/acpica/Attic/acpi.c,v 1.7 2004/09/15 01:39:10 joerg Exp $
31  */
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/bus.h>
40 #include <sys/conf.h>
41 #include <sys/ioccom.h>
42 #include <sys/reboot.h>
43 #include <sys/sysctl.h>
44 #include <sys/ctype.h>
45 #include <sys/linker.h>
46 #include <sys/power.h>
47 
48 #include <machine/clock.h>
49 #include <machine/resource.h>
50 
51 #include <bus/isa/isavar.h>
52 
53 #include "acpi.h"
54 
55 #include <dev/acpica/acpica_support.h>
56 
57 #include <dev/acpica/acpivar.h>
58 #include <dev/acpica/acpiio.h>
59 
60 MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
61 
62 /*
63  * Hooks for the ACPI CA debugging infrastructure
64  */
65 #define _COMPONENT	ACPI_BUS
66 ACPI_MODULE_NAME("ACPI")
67 
68 /*
69  * Character device
70  */
71 
72 static d_open_t		acpiopen;
73 static d_close_t	acpiclose;
74 static d_ioctl_t	acpiioctl;
75 
76 #define CDEV_MAJOR 152
77 static struct cdevsw acpi_cdevsw = {
78 
79        .d_name    = "acpi",
80        .d_maj     = CDEV_MAJOR,
81        .d_flags   = 0,
82        .d_port    = NULL,
83        .d_clone   = NULL,
84        .old_open  = acpiopen,
85        .old_close = acpiclose,
86        .old_ioctl = acpiioctl,
87 /*
88 	.d_open =       acpiopen,
89        .d_close =      acpiclose,
90        .d_ioctl =      acpiioctl,
91 */
92 
93 
94 };
95 
96 static const char* sleep_state_names[] = {
97     "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
98 
99 /* this has to be static, as the softc is gone when we need it */
100 static int acpi_off_state = ACPI_STATE_S5;
101 
102 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
103 struct mtx	acpi_mutex;
104 #endif
105 
106 static int	acpi_modevent(struct module *mod, int event, void *junk);
107 static void	acpi_identify(driver_t *driver, device_t parent);
108 static int	acpi_probe(device_t dev);
109 static int	acpi_attach(device_t dev);
110 static device_t	acpi_add_child(device_t bus, int order, const char *name, int unit);
111 static int	acpi_print_child(device_t bus, device_t child);
112 static int	acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result);
113 static int	acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value);
114 static int	acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start,
115 				  u_long count);
116 static int	acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp,
117 				  u_long *countp);
118 static struct resource *acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
119 					    u_long start, u_long end, u_long count, u_int flags);
120 static int	acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r);
121 static u_int32_t acpi_isa_get_logicalid(device_t dev);
122 static u_int32_t acpi_isa_get_compatid(device_t dev);
123 static int	acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids);
124 
125 static void	acpi_probe_children(device_t bus);
126 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status);
127 
128 static void	acpi_shutdown_pre_sync(void *arg, int howto);
129 static void	acpi_shutdown_final(void *arg, int howto);
130 
131 static void	acpi_enable_fixed_events(struct acpi_softc *sc);
132 
133 static void	acpi_system_eventhandler_sleep(void *arg, int state);
134 static void	acpi_system_eventhandler_wakeup(void *arg, int state);
135 static int	acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
136 static int	acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
137 
138 static int	acpi_pm_func(u_long cmd, void *arg, ...);
139 
140 static device_method_t acpi_methods[] = {
141     /* Device interface */
142     DEVMETHOD(device_identify,		acpi_identify),
143     DEVMETHOD(device_probe,		acpi_probe),
144     DEVMETHOD(device_attach,		acpi_attach),
145     DEVMETHOD(device_shutdown,		bus_generic_shutdown),
146     DEVMETHOD(device_suspend,		bus_generic_suspend),
147     DEVMETHOD(device_resume,		bus_generic_resume),
148 
149     /* Bus interface */
150     DEVMETHOD(bus_add_child,		acpi_add_child),
151     DEVMETHOD(bus_print_child,		acpi_print_child),
152     DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
153     DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
154     DEVMETHOD(bus_set_resource,		acpi_set_resource),
155     DEVMETHOD(bus_get_resource,		acpi_get_resource),
156     DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
157     DEVMETHOD(bus_release_resource,	acpi_release_resource),
158     DEVMETHOD(bus_driver_added,		bus_generic_driver_added),
159     DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
160     DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
161     DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
162     DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
163 
164     /* ISA emulation */
165     DEVMETHOD(isa_pnp_probe,		acpi_isa_pnp_probe),
166 
167     {0, 0}
168 };
169 
170 static driver_t acpi_driver = {
171     "acpi",
172     acpi_methods,
173     sizeof(struct acpi_softc),
174 };
175 
176 static devclass_t acpi_devclass;
177 DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
178 MODULE_VERSION(acpi, 100);
179 
180 SYSCTL_INT(_debug, OID_AUTO, acpi_debug_layer, CTLFLAG_RW, &AcpiDbgLayer, 0, "");
181 SYSCTL_INT(_debug, OID_AUTO, acpi_debug_level, CTLFLAG_RW, &AcpiDbgLevel, 0, "");
182 static int acpi_ca_version = ACPI_CA_VERSION;
183 SYSCTL_INT(_debug, OID_AUTO, acpi_ca_version, CTLFLAG_RD, &acpi_ca_version, 0, "");
184 
185 /*
186  * ACPI can only be loaded as a module by the loader; activating it after
187  * system bootstrap time is not useful, and can be fatal to the system.
188  * It also cannot be unloaded, since the entire system bus heirarchy hangs off it.
189  */
190 static int
191 acpi_modevent(struct module *mod, int event, void *junk)
192 {
193     switch(event) {
194     case MOD_LOAD:
195 	if (!cold) {
196 	    printf("The ACPI driver cannot be loaded after boot.\n");
197 	    return(EPERM);
198 	}
199 	break;
200     case MOD_UNLOAD:
201 	if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
202 	    return(EBUSY);
203 	break;
204     default:
205 	break;
206     }
207     return(0);
208 }
209 
210 /*
211  * Detect ACPI, perform early initialisation
212  */
213 static void
214 acpi_identify(driver_t *driver, device_t parent)
215 {
216     device_t			child;
217     int				error;
218 #ifdef ACPI_DEBUGGER
219     char			*debugpoint;
220 #endif
221 
222     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
223 
224     if (!cold)
225 	return_VOID;
226 
227     /*
228      * Check that we haven't been disabled with a hint.
229      */
230     if (!resource_int_value("acpi", 0, "disabled", &error) &&
231 	(error != 0))
232 	return_VOID;
233 
234     /*
235      * Make sure we're not being doubly invoked.
236      */
237     if (device_find_child(parent, "acpi", 0) != NULL)
238 	return_VOID;
239 
240 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
241     /* initialise the ACPI mutex */
242     mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
243 #endif
244 
245     /*
246      * Start up the ACPI CA subsystem.
247      */
248 #ifdef ACPI_DEBUGGER
249     debugpoint = getenv("debug.acpi.debugger");
250     if (debugpoint) {
251 	if (!strcmp(debugpoint, "init"))
252 	    acpi_EnterDebugger();
253         freeenv(debugpoint);
254     }
255 #endif
256     if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
257 	printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
258 	return_VOID;
259     }
260 #ifdef ACPI_DEBUGGER
261     debugpoint = getenv("debug.acpi.debugger");
262     if (debugpoint) {
263 	if (!strcmp(debugpoint, "tables"))
264 	    acpi_EnterDebugger();
265         freeenv(debugpoint);
266     }
267 #endif
268 
269     if (ACPI_FAILURE(error = AcpiLoadTables())) {
270 	printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
271 	return_VOID;
272     }
273 
274     /*
275      * Attach the actual ACPI device.
276      */
277     if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
278 	    device_printf(parent, "ACPI: could not attach\n");
279 	    return_VOID;
280     }
281 }
282 
283 /*
284  * Fetch some descriptive data from ACPI to put in our attach message
285  */
286 static int
287 acpi_probe(device_t dev)
288 {
289     ACPI_TABLE_HEADER	th;
290     char		buf[20];
291     ACPI_STATUS		status;
292     int			error;
293     ACPI_LOCK_DECL;
294 
295     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
296 
297     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
298         power_pm_get_type() != POWER_PM_TYPE_ACPI) {
299 	device_printf(dev, "Other PM system enabled.\n");
300 	return_VALUE(ENXIO);
301     }
302 
303     ACPI_LOCK;
304 
305     if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
306 	device_printf(dev, "couldn't get XSDT header: %s\n", AcpiFormatException(status));
307 	error = ENXIO;
308     } else {
309 	sprintf(buf, "%.6s %.8s", th.OemId, th.OemTableId);
310 	device_set_desc_copy(dev, buf);
311 	error = 0;
312     }
313     ACPI_UNLOCK;
314     return_VALUE(error);
315 }
316 
317 static int
318 acpi_attach(device_t dev)
319 {
320     struct acpi_softc	*sc;
321     ACPI_STATUS		status;
322     int			error;
323     UINT32		flags;
324     char		*env;
325 #ifdef ACPI_DEBUGGER
326     char		*debugpoint;
327 #endif
328     ACPI_LOCK_DECL;
329 
330     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
331     ACPI_LOCK;
332     sc = device_get_softc(dev);
333     bzero(sc, sizeof(*sc));
334     sc->acpi_dev = dev;
335     callout_init(&sc->acpi_sleep_timer);
336 
337 #ifdef ACPI_DEBUGGER
338     debugpoint = getenv("debug.acpi.debugger");
339     if (debugpoint) {
340 	if (!strcmp(debugpoint, "spaces"))
341 	    acpi_EnterDebugger();
342         freeenv(debugpoint);
343     }
344 #endif
345 
346     /*
347      * Install the default address space handlers.
348      */
349     error = ENXIO;
350     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
351 						ACPI_ADR_SPACE_SYSTEM_MEMORY,
352 						ACPI_DEFAULT_HANDLER,
353 						NULL, NULL))) {
354 	device_printf(dev, "could not initialise SystemMemory handler: %s\n", AcpiFormatException(status));
355 	goto out;
356     }
357     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
358 						ACPI_ADR_SPACE_SYSTEM_IO,
359 						ACPI_DEFAULT_HANDLER,
360 						NULL, NULL))) {
361 	device_printf(dev, "could not initialise SystemIO handler: %s\n", AcpiFormatException(status));
362 	goto out;
363     }
364     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
365 						ACPI_ADR_SPACE_PCI_CONFIG,
366 						ACPI_DEFAULT_HANDLER,
367 						NULL, NULL))) {
368 	device_printf(dev, "could not initialise PciConfig handler: %s\n", AcpiFormatException(status));
369 	goto out;
370     }
371 
372     /*
373      * Bring ACPI fully online.
374      *
375      * Note that some systems (specifically, those with namespace evaluation issues
376      * that require the avoidance of parts of the namespace) must avoid running _INI
377      * and _STA on everything, as well as dodging the final object init pass.
378      *
379      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
380      *
381      * XXX We should arrange for the object init pass after we have attached all our
382      *     child devices, but on many systems it works here.
383      */
384 #ifdef ACPI_DEBUGGER
385     debugpoint = getenv("debug.acpi.debugger");
386     if (debugpoint) {
387 	if (!strcmp(debugpoint, "enable"))
388 	    acpi_EnterDebugger();
389         freeenv(debugpoint);
390     }
391 #endif
392     flags = 0;
393     if (testenv("debug.acpi.avoid"))
394 	flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
395     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
396 	device_printf(dev, "could not enable ACPI: %s\n", AcpiFormatException(status));
397 	goto out;
398     }
399 
400     if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
401 	device_printf(dev, "could not initialize ACPI objects: %s\n", AcpiFormatException(status));
402 	goto out;
403     }
404 
405     /*
406      * Setup our sysctl tree.
407      *
408      * XXX: This doesn't check to make sure that none of these fail.
409      */
410     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
411     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
412 			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
413 			       device_get_name(dev), CTLFLAG_RD, 0, "");
414     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
415 	OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
416 	0, 0, acpi_supported_sleep_state_sysctl, "A", "");
417     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
418 	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
419 	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
420     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
421 	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
422 	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
423     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
424 	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
425 	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
426     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
427 	OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
428 	&sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
429     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
430 	OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
431 	&sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
432     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
433 	OID_AUTO, "sleep_delay", CTLFLAG_RD | CTLFLAG_RW,
434 	&sc->acpi_sleep_delay, 0, "sleep delay");
435     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
436 	OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
437 	&sc->acpi_s4bios, 0, "S4BIOS mode");
438     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
439 	OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
440 	&sc->acpi_verbose, 0, "verbose mode");
441     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
442 		   OID_AUTO, "disable_on_poweroff", CTLFLAG_RD | CTLFLAG_RW,
443 		   &sc->acpi_disable_on_poweroff, 0, "ACPI subsystem disable on poweroff");
444     sc->acpi_disable_on_poweroff = 1;
445     sc->acpi_sleep_delay = 0;
446     sc->acpi_s4bios = 1;
447     if (bootverbose)
448 	sc->acpi_verbose = 1;
449     if ((env = getenv("hw.acpi.verbose")) && strcmp(env, "0")) {
450 	sc->acpi_verbose = 1;
451 	freeenv(env);
452     }
453 
454     /*
455      * Dispatch the default sleep state to devices.
456      * TBD: should be configured from userland policy manager.
457      */
458     sc->acpi_power_button_sx = ACPI_POWER_BUTTON_DEFAULT_SX;
459     sc->acpi_sleep_button_sx = ACPI_SLEEP_BUTTON_DEFAULT_SX;
460     sc->acpi_lid_switch_sx = ACPI_LID_SWITCH_DEFAULT_SX;
461     sc->acpi_standby_sx = ACPI_STATE_S1;
462     sc->acpi_suspend_sx = ACPI_STATE_S3;
463 
464     acpi_enable_fixed_events(sc);
465 
466     /*
467      * Scan the namespace and attach/initialise children.
468      */
469 #ifdef ACPI_DEBUGGER
470     debugpoint = getenv("debug.acpi.debugger");
471     if (debugpoint) {
472 	if (!strcmp(debugpoint, "probe"))
473 	    acpi_EnterDebugger();
474 	freeenv(debugpoint);
475     }
476 #endif
477 
478     /*
479      * Register our shutdown handlers
480      */
481     EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc, SHUTDOWN_PRI_LAST);
482     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc, SHUTDOWN_PRI_LAST);
483 
484     /*
485      * Register our acpi event handlers.
486      * XXX should be configurable eg. via userland policy manager.
487      */
488     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep, sc, ACPI_EVENT_PRI_LAST);
489     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup, sc, ACPI_EVENT_PRI_LAST);
490 
491     /*
492      * Flag our initial states.
493      */
494     sc->acpi_enabled = 1;
495     sc->acpi_sstate = ACPI_STATE_S0;
496     sc->acpi_sleep_disabled = 0;
497 
498     /*
499      * Create the control device
500      */
501     cdevsw_add(&acpi_cdevsw, 0, 0);
502     sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_WHEEL, 0644,
503 	"acpi");
504     sc->acpi_dev_t->si_drv1 = sc;
505 
506 #ifdef ACPI_DEBUGGER
507     debugpoint = getenv("debug.acpi.debugger");
508     if (debugpoint) {
509 	if (!strcmp(debugpoint, "running"))
510 	    acpi_EnterDebugger();
511 	freeenv(debugpoint);
512     }
513 #endif
514 
515 #ifdef ACPI_USE_THREADS
516     if ((error = acpi_task_thread_init())) {
517 	goto out;
518     }
519 #endif
520 
521     if ((error = acpi_machdep_init(dev))) {
522 	goto out;
523     }
524 
525     /* Register ACPI again to pass the correct argument of pm_func. */
526     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
527 
528     if (!acpi_disabled("bus"))
529 	acpi_probe_children(dev);
530 
531     error = 0;
532 
533  out:
534     ACPI_UNLOCK;
535     return_VALUE(error);
536 }
537 
538 /*
539  * Handle a new device being added
540  */
541 static device_t
542 acpi_add_child(device_t bus, int order, const char *name, int unit)
543 {
544     struct acpi_device	*ad;
545     device_t		child;
546 
547     ad = malloc(sizeof(*ad), M_ACPIDEV, M_INTWAIT | M_ZERO);
548 
549     resource_list_init(&ad->ad_rl);
550 
551     child = device_add_child_ordered(bus, order, name, unit);
552     if (child != NULL)
553 	device_set_ivars(child, ad);
554     return(child);
555 }
556 
557 static int
558 acpi_print_child(device_t bus, device_t child)
559 {
560     struct acpi_device		*adev = device_get_ivars(child);
561     struct resource_list	*rl = &adev->ad_rl;
562     int retval = 0;
563 
564     retval += bus_print_child_header(bus, child);
565     retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
566     retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
567     retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
568     retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
569     retval += bus_print_child_footer(bus, child);
570 
571     return(retval);
572 }
573 
574 
575 /*
576  * Handle per-device ivars
577  */
578 static int
579 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
580 {
581     struct acpi_device	*ad;
582 
583     if ((ad = device_get_ivars(child)) == NULL) {
584 	printf("device has no ivars\n");
585 	return(ENOENT);
586     }
587 
588     switch(index) {
589 	/* ACPI ivars */
590     case ACPI_IVAR_HANDLE:
591 	*(ACPI_HANDLE *)result = ad->ad_handle;
592 	break;
593     case ACPI_IVAR_MAGIC:
594 	*(int *)result = ad->ad_magic;
595 	break;
596     case ACPI_IVAR_PRIVATE:
597 	*(void **)result = ad->ad_private;
598 	break;
599 
600 	/* ISA compatibility */
601     case ISA_IVAR_VENDORID:
602     case ISA_IVAR_SERIAL:
603     case ISA_IVAR_COMPATID:
604 	*(int *)result = -1;
605 	break;
606 
607     case ISA_IVAR_LOGICALID:
608 	*(int *)result = acpi_isa_get_logicalid(child);
609 	break;
610 
611     default:
612 	return(ENOENT);
613     }
614     return(0);
615 }
616 
617 static int
618 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
619 {
620     struct acpi_device	*ad;
621 
622     if ((ad = device_get_ivars(child)) == NULL) {
623 	printf("device has no ivars\n");
624 	return(ENOENT);
625     }
626 
627     switch(index) {
628 	/* ACPI ivars */
629     case ACPI_IVAR_HANDLE:
630 	ad->ad_handle = (ACPI_HANDLE)value;
631 	break;
632     case ACPI_IVAR_MAGIC:
633 	ad->ad_magic = (int )value;
634 	break;
635     case ACPI_IVAR_PRIVATE:
636 	ad->ad_private = (void *)value;
637 	break;
638 
639     default:
640 	panic("bad ivar write request (%d)", index);
641 	return(ENOENT);
642     }
643     return(0);
644 }
645 
646 /*
647  * Handle child resource allocation/removal
648  */
649 static int
650 acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start, u_long count)
651 {
652     struct acpi_device		*ad = device_get_ivars(child);
653     struct resource_list	*rl = &ad->ad_rl;
654 
655     resource_list_add(rl, type, rid, start, start + count -1, count);
656 
657     return(0);
658 }
659 
660 static int
661 acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp, u_long *countp)
662 {
663     struct acpi_device		*ad = device_get_ivars(child);
664     struct resource_list	*rl = &ad->ad_rl;
665     struct resource_list_entry	*rle;
666 
667     rle = resource_list_find(rl, type, rid);
668     if (!rle)
669 	return(ENOENT);
670 
671     if (startp)
672 	*startp = rle->start;
673     if (countp)
674 	*countp = rle->count;
675 
676     return(0);
677 }
678 
679 static struct resource *
680 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
681 		    u_long start, u_long end, u_long count, u_int flags)
682 {
683     struct acpi_device *ad = device_get_ivars(child);
684     struct resource_list *rl = &ad->ad_rl;
685 
686     return(resource_list_alloc(rl, bus, child, type, rid, start, end, count, flags));
687 }
688 
689 static int
690 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
691 {
692     struct acpi_device *ad = device_get_ivars(child);
693     struct resource_list *rl = &ad->ad_rl;
694 
695     return(resource_list_release(rl, bus, child, type, rid, r));
696 }
697 
698 /*
699  * Handle ISA-like devices probing for a PnP ID to match.
700  */
701 #define PNP_EISAID(s)				\
702 	((((s[0] - '@') & 0x1f) << 2)		\
703 	 | (((s[1] - '@') & 0x18) >> 3)		\
704 	 | (((s[1] - '@') & 0x07) << 13)	\
705 	 | (((s[2] - '@') & 0x1f) << 8)		\
706 	 | (PNP_HEXTONUM(s[4]) << 16)		\
707 	 | (PNP_HEXTONUM(s[3]) << 20)		\
708 	 | (PNP_HEXTONUM(s[6]) << 24)		\
709 	 | (PNP_HEXTONUM(s[5]) << 28))
710 
711 static u_int32_t
712 acpi_isa_get_logicalid(device_t dev)
713 {
714     ACPI_HANDLE		h;
715     ACPI_DEVICE_INFO	devinfo;
716     ACPI_STATUS		error;
717     u_int32_t		pnpid;
718     ACPI_LOCK_DECL;
719 
720     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
721 
722     pnpid = 0;
723     ACPI_LOCK;
724 
725     /* fetch and validate the HID */
726     if ((h = acpi_get_handle(dev)) == NULL)
727 	goto out;
728     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
729 	goto out;
730     if (!(devinfo.Valid & ACPI_VALID_HID))
731 	goto out;
732 
733     pnpid = PNP_EISAID(devinfo.HardwareId);
734 out:
735     ACPI_UNLOCK;
736     return_VALUE(pnpid);
737 }
738 
739 static u_int32_t
740 acpi_isa_get_compatid(device_t dev)
741 {
742     ACPI_HANDLE		h;
743     ACPI_DEVICE_INFO	devinfo;
744     ACPI_STATUS		error;
745     u_int32_t		pnpid;
746     ACPI_LOCK_DECL;
747 
748     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
749 
750     pnpid = 0;
751     ACPI_LOCK;
752 
753     /* fetch and validate the HID */
754     if ((h = acpi_get_handle(dev)) == NULL)
755 	goto out;
756     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
757 	goto out;
758     if (ACPI_FAILURE(error = acpi_EvaluateInteger(h, "_CID", &pnpid)))
759 	goto out;
760 
761 out:
762     ACPI_UNLOCK;
763     return_VALUE(pnpid);
764 }
765 
766 
767 static int
768 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
769 {
770     int			result;
771     u_int32_t		lid, cid;
772 
773     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
774 
775     /*
776      * ISA-style drivers attached to ACPI may persist and
777      * probe manually if we return ENOENT.  We never want
778      * that to happen, so don't ever return it.
779      */
780     result = ENXIO;
781 
782     /* scan the supplied IDs for a match */
783     lid = acpi_isa_get_logicalid(child);
784     cid = acpi_isa_get_compatid(child);
785     while (ids && ids->ip_id) {
786 	if (lid == ids->ip_id || cid == ids->ip_id) {
787 	    result = 0;
788 	    goto out;
789 	}
790 	ids++;
791     }
792  out:
793     return_VALUE(result);
794 }
795 
796 /*
797  * Scan relevant portions of the ACPI namespace and attach child devices.
798  *
799  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and \_SB_ scopes,
800  * and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
801  */
802 static void
803 acpi_probe_children(device_t bus)
804 {
805     ACPI_HANDLE		parent;
806     static char		*scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
807     int			i;
808 
809     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
810     ACPI_ASSERTLOCK;
811 
812     /*
813      * Create any static children by calling device identify methods.
814      */
815     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
816     bus_generic_probe(bus);
817 
818     /*
819      * Scan the namespace and insert placeholders for all the devices that
820      * we find.
821      *
822      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
823      * we want to create nodes for all devices, not just those that are currently
824      * present. (This assumes that we don't want to create/remove devices as they
825      * appear, which might be smarter.)
826      */
827     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
828     for (i = 0; scopes[i] != NULL; i++)
829 	if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent)))
830 	    AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child, bus, NULL);
831 
832     /*
833      * Scan all of the child devices we have created and let them probe/attach.
834      */
835     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
836     bus_generic_attach(bus);
837 
838     /*
839      * Some of these children may have attached others as part of their attach
840      * process (eg. the root PCI bus driver), so rescan.
841      */
842     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
843     bus_generic_attach(bus);
844 
845     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
846     return_VOID;
847 }
848 
849 /*
850  * Evaluate a child device and determine whether we might attach a device to
851  * it.
852  */
853 static ACPI_STATUS
854 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
855 {
856     ACPI_OBJECT_TYPE	type;
857     device_t		child, bus = (device_t)context;
858 
859     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
860 
861     /*
862      * Skip this device if we think we'll have trouble with it.
863      */
864     if (acpi_avoid(handle))
865 	return_ACPI_STATUS(AE_OK);
866 
867     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
868 	switch(type) {
869 	case ACPI_TYPE_DEVICE:
870 	case ACPI_TYPE_PROCESSOR:
871 	case ACPI_TYPE_THERMAL:
872 	case ACPI_TYPE_POWER:
873 	    if (acpi_disabled("children"))
874 		break;
875 	    /*
876 	     * Create a placeholder device for this node.  Sort the placeholder
877 	     * so that the probe/attach passes will run breadth-first.
878 	     */
879 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", acpi_name(handle)));
880 	    child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
881 	    if (child == NULL)
882 		break;
883 	    acpi_set_handle(child, handle);
884 
885 	    /*
886 	     * Check that the device is present.  If it's not present,
887 	     * leave it disabled (so that we have a device_t attached to
888 	     * the handle, but we don't probe it).
889 	     */
890 	    if ((type == ACPI_TYPE_DEVICE) && (!acpi_DeviceIsPresent(child))) {
891 		device_disable(child);
892 		break;
893 	    }
894 
895 	    /*
896 	     * Get the device's resource settings and attach them.
897 	     * Note that if the device has _PRS but no _CRS, we need
898 	     * to decide when it's appropriate to try to configure the
899 	     * device.  Ignore the return value here; it's OK for the
900 	     * device not to have any resources.
901 	     */
902 	    acpi_parse_resources(child, handle, &acpi_res_parse_set);
903 
904 	    /* if we're debugging, probe/attach now rather than later */
905 	    ACPI_DEBUG_EXEC(device_probe_and_attach(child));
906 	    break;
907 	}
908     }
909     return_ACPI_STATUS(AE_OK);
910 }
911 
912 static void
913 acpi_shutdown_pre_sync(void *arg, int howto)
914 {
915 
916     struct acpi_softc *sc = arg;
917 
918     ACPI_ASSERTLOCK;
919 
920     /*
921      * Disable all ACPI events before soft off, otherwise the system
922      * will be turned on again on some laptops.
923      *
924      * XXX this should probably be restricted to masking some events just
925      *     before powering down, since we may still need ACPI during the
926      *     shutdown process.
927      */
928     if (sc->acpi_disable_on_poweroff)
929 	acpi_Disable(sc);
930 }
931 
932 static void
933 acpi_shutdown_final(void *arg, int howto)
934 {
935     ACPI_STATUS	status;
936 
937     ACPI_ASSERTLOCK;
938 
939     if (howto & RB_POWEROFF) {
940 	printf("Power system off using ACPI...\n");
941 	if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(acpi_off_state))) {
942 	    printf("AcpiEnterSleepStatePrep failed - %s\n",
943 		   AcpiFormatException(status));
944 	    return;
945 	}
946 	if (ACPI_FAILURE(status = AcpiEnterSleepState(acpi_off_state))) {
947 	    printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
948 	} else {
949 	    DELAY(1000000);
950 	    printf("ACPI power-off failed - timeout\n");
951 	}
952     } else {
953 	printf("Terminate ACPI\n");
954 	AcpiTerminate();
955     }
956 }
957 
958 static void
959 acpi_enable_fixed_events(struct acpi_softc *sc)
960 {
961     static int	first_time = 1;
962 #define MSGFORMAT "%s button is handled as a fixed feature programming model.\n"
963 
964     ACPI_ASSERTLOCK;
965 
966     /* Enable and clear fixed events and install handlers. */
967     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->PwrButton == 0)) {
968 	AcpiEnableEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED, 0);
969 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
970 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
971 				     acpi_eventhandler_power_button_for_sleep, sc);
972 	if (first_time) {
973 	    device_printf(sc->acpi_dev, MSGFORMAT, "power");
974 	}
975     }
976     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->SleepButton == 0)) {
977 	AcpiEnableEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED, 0);
978 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
979 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
980 				     acpi_eventhandler_sleep_button_for_sleep, sc);
981 	if (first_time) {
982 	    device_printf(sc->acpi_dev, MSGFORMAT, "sleep");
983 	}
984     }
985 
986     first_time = 0;
987 }
988 
989 /*
990  * Returns true if the device is actually present and should
991  * be attached to.  This requires the present, enabled, UI-visible
992  * and diagnostics-passed bits to be set.
993  */
994 BOOLEAN
995 acpi_DeviceIsPresent(device_t dev)
996 {
997     ACPI_HANDLE		h;
998     ACPI_DEVICE_INFO	devinfo;
999     ACPI_STATUS		error;
1000 
1001     ACPI_ASSERTLOCK;
1002 
1003     if ((h = acpi_get_handle(dev)) == NULL)
1004 	return(FALSE);
1005     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
1006 	return(FALSE);
1007     /* if no _STA method, must be present */
1008     if (!(devinfo.Valid & ACPI_VALID_STA))
1009 	return(TRUE);
1010     /* return true for 'present' and 'functioning' */
1011     if ((devinfo.CurrentStatus & 0x9) == 0x9)
1012 	return(TRUE);
1013     return(FALSE);
1014 }
1015 
1016 /*
1017  * Returns true if the battery is actually present and inserted.
1018  */
1019 BOOLEAN
1020 acpi_BatteryIsPresent(device_t dev)
1021 {
1022     ACPI_HANDLE		h;
1023     ACPI_DEVICE_INFO	devinfo;
1024     ACPI_STATUS		error;
1025 
1026     ACPI_ASSERTLOCK;
1027 
1028     if ((h = acpi_get_handle(dev)) == NULL)
1029 	return(FALSE);
1030     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
1031 	return(FALSE);
1032     /* if no _STA method, must be present */
1033     if (!(devinfo.Valid & ACPI_VALID_STA))
1034 	return(TRUE);
1035     /* return true for 'present' and 'functioning' */
1036     if ((devinfo.CurrentStatus & 0x19) == 0x19)
1037 	return(TRUE);
1038     return(FALSE);
1039 }
1040 
1041 /*
1042  * Match a HID string against a device
1043  */
1044 BOOLEAN
1045 acpi_MatchHid(device_t dev, char *hid)
1046 {
1047     ACPI_HANDLE		h;
1048     ACPI_DEVICE_INFO	devinfo;
1049     ACPI_STATUS		error;
1050     int			cid;
1051 
1052     ACPI_ASSERTLOCK;
1053 
1054     if (hid == NULL)
1055 	return(FALSE);
1056     if ((h = acpi_get_handle(dev)) == NULL)
1057 	return(FALSE);
1058     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
1059 	return(FALSE);
1060     if ((devinfo.Valid & ACPI_VALID_HID) && !strcmp(hid, devinfo.HardwareId))
1061 	return(TRUE);
1062     if (ACPI_FAILURE(error = acpi_EvaluateInteger(h, "_CID", &cid)))
1063 	return(FALSE);
1064     if (cid == PNP_EISAID(hid))
1065 	return(TRUE);
1066     return(FALSE);
1067 }
1068 
1069 /*
1070  * Return the handle of a named object within our scope, ie. that of (parent)
1071  * or one if its parents.
1072  */
1073 ACPI_STATUS
1074 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1075 {
1076     ACPI_HANDLE		r;
1077     ACPI_STATUS		status;
1078 
1079     ACPI_ASSERTLOCK;
1080 
1081     /* walk back up the tree to the root */
1082     for (;;) {
1083 	if (ACPI_SUCCESS(status = AcpiGetHandle(parent, path, &r))) {
1084 	    *result = r;
1085 	    return(AE_OK);
1086 	}
1087 	if (status != AE_NOT_FOUND)
1088 	    return(AE_OK);
1089 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1090 	    return(AE_NOT_FOUND);
1091 	parent = r;
1092     }
1093 }
1094 
1095 /*
1096  * Allocate a buffer with a preset data size.
1097  */
1098 ACPI_BUFFER *
1099 acpi_AllocBuffer(int size)
1100 {
1101     ACPI_BUFFER	*buf;
1102 
1103     buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_INTWAIT);
1104     buf->Length = size;
1105     buf->Pointer = (void *)(buf + 1);
1106     return(buf);
1107 }
1108 
1109 /*
1110  * Evaluate a path that should return an integer.
1111  */
1112 ACPI_STATUS
1113 acpi_EvaluateInteger(ACPI_HANDLE handle, char *path, int *number)
1114 {
1115     ACPI_STATUS	error;
1116     ACPI_BUFFER	buf;
1117     ACPI_OBJECT	param;
1118 
1119     ACPI_ASSERTLOCK;
1120 
1121     if (handle == NULL)
1122 	handle = ACPI_ROOT_OBJECT;
1123 
1124     /*
1125      * Assume that what we've been pointed at is an Integer object, or
1126      * a method that will return an Integer.
1127      */
1128     buf.Pointer = &param;
1129     buf.Length = sizeof(param);
1130     if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
1131 	if (param.Type == ACPI_TYPE_INTEGER) {
1132 	    *number = param.Integer.Value;
1133 	} else {
1134 	    error = AE_TYPE;
1135 	}
1136     }
1137 
1138     /*
1139      * In some applications, a method that's expected to return an Integer
1140      * may instead return a Buffer (probably to simplify some internal
1141      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1142      * convert it into an Integer as best we can.
1143      *
1144      * This is a hack.
1145      */
1146     if (error == AE_BUFFER_OVERFLOW) {
1147 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1148 	    error = AE_NO_MEMORY;
1149 	} else {
1150 	    if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
1151 		error = acpi_ConvertBufferToInteger(&buf, number);
1152 	    }
1153 	}
1154 	AcpiOsFree(buf.Pointer);
1155     }
1156     return(error);
1157 }
1158 
1159 ACPI_STATUS
1160 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, int *number)
1161 {
1162     ACPI_OBJECT	*p;
1163     int		i;
1164 
1165     p = (ACPI_OBJECT *)bufp->Pointer;
1166     if (p->Type == ACPI_TYPE_INTEGER) {
1167 	*number = p->Integer.Value;
1168 	return(AE_OK);
1169     }
1170     if (p->Type != ACPI_TYPE_BUFFER)
1171 	return(AE_TYPE);
1172     if (p->Buffer.Length > sizeof(int))
1173 	return(AE_BAD_DATA);
1174     *number = 0;
1175     for (i = 0; i < p->Buffer.Length; i++)
1176 	*number += (*(p->Buffer.Pointer + i) << (i * 8));
1177     return(AE_OK);
1178 }
1179 
1180 /*
1181  * Iterate over the elements of an a package object, calling the supplied
1182  * function for each element.
1183  *
1184  * XXX possible enhancement might be to abort traversal on error.
1185  */
1186 ACPI_STATUS
1187 acpi_ForeachPackageObject(ACPI_OBJECT *pkg, void (* func)(ACPI_OBJECT *comp, void *arg), void *arg)
1188 {
1189     ACPI_OBJECT	*comp;
1190     int		i;
1191 
1192     if ((pkg == NULL) || (pkg->Type != ACPI_TYPE_PACKAGE))
1193 	return(AE_BAD_PARAMETER);
1194 
1195     /* iterate over components */
1196     for (i = 0, comp = pkg->Package.Elements; i < pkg->Package.Count; i++, comp++)
1197 	func(comp, arg);
1198 
1199     return(AE_OK);
1200 }
1201 
1202 /*
1203  * Find the (index)th resource object in a set.
1204  */
1205 ACPI_STATUS
1206 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1207 {
1208     ACPI_RESOURCE	*rp;
1209     int			i;
1210 
1211     rp = (ACPI_RESOURCE *)buf->Pointer;
1212     i = index;
1213     while (i-- > 0) {
1214 	/* range check */
1215 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1216 	    return(AE_BAD_PARAMETER);
1217 	/* check for terminator */
1218 	if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1219 	    (rp->Length == 0))
1220 	    return(AE_NOT_FOUND);
1221 	rp = ACPI_RESOURCE_NEXT(rp);
1222     }
1223     if (resp != NULL)
1224 	*resp = rp;
1225     return(AE_OK);
1226 }
1227 
1228 /*
1229  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1230  *
1231  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1232  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1233  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1234  * resources.
1235  */
1236 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
1237 
1238 ACPI_STATUS
1239 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1240 {
1241     ACPI_RESOURCE	*rp;
1242     void		*newp;
1243 
1244     /*
1245      * Initialise the buffer if necessary.
1246      */
1247     if (buf->Pointer == NULL) {
1248 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1249 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1250 	    return(AE_NO_MEMORY);
1251 	rp = (ACPI_RESOURCE *)buf->Pointer;
1252 	rp->Id = ACPI_RSTYPE_END_TAG;
1253 	rp->Length = 0;
1254     }
1255     if (res == NULL)
1256 	return(AE_OK);
1257 
1258     /*
1259      * Scan the current buffer looking for the terminator.
1260      * This will either find the terminator or hit the end
1261      * of the buffer and return an error.
1262      */
1263     rp = (ACPI_RESOURCE *)buf->Pointer;
1264     for (;;) {
1265 	/* range check, don't go outside the buffer */
1266 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1267 	    return(AE_BAD_PARAMETER);
1268 	if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1269 	    (rp->Length == 0)) {
1270 	    break;
1271 	}
1272 	rp = ACPI_RESOURCE_NEXT(rp);
1273     }
1274 
1275     /*
1276      * Check the size of the buffer and expand if required.
1277      *
1278      * Required size is:
1279      *	size of existing resources before terminator +
1280      *	size of new resource and header +
1281      * 	size of terminator.
1282      *
1283      * Note that this loop should really only run once, unless
1284      * for some reason we are stuffing a *really* huge resource.
1285      */
1286     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
1287 	    res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1288 	    ACPI_RESOURCE_LENGTH) >= buf->Length) {
1289 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1290 	    return(AE_NO_MEMORY);
1291 	bcopy(buf->Pointer, newp, buf->Length);
1292         rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1293 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1294 	AcpiOsFree(buf->Pointer);
1295 	buf->Pointer = newp;
1296 	buf->Length += buf->Length;
1297     }
1298 
1299     /*
1300      * Insert the new resource.
1301      */
1302     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1303 
1304     /*
1305      * And add the terminator.
1306      */
1307     rp = ACPI_RESOURCE_NEXT(rp);
1308     rp->Id = ACPI_RSTYPE_END_TAG;
1309     rp->Length = 0;
1310 
1311     return(AE_OK);
1312 }
1313 
1314 /*
1315  * Set interrupt model.
1316  */
1317 ACPI_STATUS
1318 acpi_SetIntrModel(int model)
1319 {
1320 	ACPI_OBJECT_LIST ArgList;
1321 	ACPI_OBJECT Arg;
1322 
1323 	Arg.Type = ACPI_TYPE_INTEGER;
1324 	Arg.Integer.Value = model;
1325 	ArgList.Count = 1;
1326 	ArgList.Pointer = &Arg;
1327 	return (AcpiEvaluateObject(ACPI_ROOT_OBJECT, "_PIC", &ArgList, NULL));
1328 }
1329 
1330 #define ACPI_MINIMUM_AWAKETIME	5
1331 
1332 static void
1333 acpi_sleep_enable(void *arg)
1334 {
1335     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1336 }
1337 
1338 /*
1339  * Set the system sleep state
1340  *
1341  * Currently we only support S1 and S5
1342  */
1343 ACPI_STATUS
1344 acpi_SetSleepState(struct acpi_softc *sc, int state)
1345 {
1346     ACPI_STATUS	status = AE_OK;
1347     UINT8	TypeA;
1348     UINT8	TypeB;
1349 
1350     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1351     ACPI_ASSERTLOCK;
1352 
1353     if (sc->acpi_sstate != ACPI_STATE_S0)
1354 	return_ACPI_STATUS(AE_BAD_PARAMETER);	/* avoid reentry */
1355 
1356     if (sc->acpi_sleep_disabled)
1357 	return_ACPI_STATUS(AE_OK);
1358 
1359     switch (state) {
1360     case ACPI_STATE_S0:	/* XXX only for testing */
1361 	if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
1362 	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1363 	}
1364 	break;
1365 
1366     case ACPI_STATE_S1:
1367     case ACPI_STATE_S2:
1368     case ACPI_STATE_S3:
1369     case ACPI_STATE_S4:
1370 	if (ACPI_FAILURE(status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB))) {
1371 	    device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n", AcpiFormatException(status));
1372 	    break;
1373 	}
1374 
1375 	sc->acpi_sstate = state;
1376 	sc->acpi_sleep_disabled = 1;
1377 
1378 	/*
1379 	 * Inform all devices that we are going to sleep.
1380 	 */
1381 	if (DEVICE_SUSPEND(root_bus) != 0) {
1382 	    /*
1383 	     * Re-wake the system.
1384 	     *
1385 	     * XXX note that a better two-pass approach with a 'veto' pass
1386 	     *     followed by a "real thing" pass would be better, but the
1387 	     *     current bus interface does not provide for this.
1388 	     */
1389 	    DEVICE_RESUME(root_bus);
1390 	    return_ACPI_STATUS(AE_ERROR);
1391 	}
1392 
1393 	if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(state))) {
1394 	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1395 			  AcpiFormatException(status));
1396 	    break;
1397 	}
1398 
1399 	if (sc->acpi_sleep_delay > 0) {
1400 	    DELAY(sc->acpi_sleep_delay * 1000000);
1401 	}
1402 
1403 	if (state != ACPI_STATE_S1) {
1404 	    acpi_sleep_machdep(sc, state);
1405 
1406 	    /* AcpiEnterSleepState() maybe incompleted, unlock here if locked. */
1407 	    if (AcpiGbl_AcpiMutexInfo[ACPI_MTX_HARDWARE].OwnerId != ACPI_MUTEX_NOT_ACQUIRED) {
1408 		AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1409 	    }
1410 
1411 	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1412 	    if (state == ACPI_STATE_S4) {
1413 		AcpiEnable();
1414 	    }
1415 	} else {
1416 	    if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
1417 		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1418 		break;
1419 	    }
1420 	}
1421 	AcpiLeaveSleepState((UINT8)state);
1422 	DEVICE_RESUME(root_bus);
1423 	sc->acpi_sstate = ACPI_STATE_S0;
1424 	acpi_enable_fixed_events(sc);
1425 	break;
1426 
1427     case ACPI_STATE_S5:
1428 	/*
1429 	 * Shut down cleanly and power off.  This will call us back through the
1430 	 * shutdown handlers.
1431 	 */
1432 	shutdown_nice(RB_POWEROFF);
1433 	break;
1434 
1435     default:
1436 	status = AE_BAD_PARAMETER;
1437 	break;
1438     }
1439 
1440     if (sc->acpi_sleep_disabled)
1441         callout_reset(&sc->acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME,
1442 		      acpi_sleep_enable, sc);
1443 
1444     return_ACPI_STATUS(status);
1445 }
1446 
1447 /*
1448  * Enable/Disable ACPI
1449  */
1450 ACPI_STATUS
1451 acpi_Enable(struct acpi_softc *sc)
1452 {
1453     ACPI_STATUS	status;
1454     u_int32_t	flags;
1455 
1456     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1457     ACPI_ASSERTLOCK;
1458 
1459     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
1460             ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
1461     if (!sc->acpi_enabled) {
1462 	status = AcpiEnableSubsystem(flags);
1463     } else {
1464 	status = AE_OK;
1465     }
1466     if (status == AE_OK)
1467 	sc->acpi_enabled = 1;
1468     return_ACPI_STATUS(status);
1469 }
1470 
1471 ACPI_STATUS
1472 acpi_Disable(struct acpi_softc *sc)
1473 {
1474     ACPI_STATUS	status;
1475 
1476     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1477     ACPI_ASSERTLOCK;
1478 
1479     if (sc->acpi_enabled) {
1480 	status = AcpiDisable();
1481     } else {
1482 	status = AE_OK;
1483     }
1484     if (status == AE_OK)
1485 	sc->acpi_enabled = 0;
1486     return_ACPI_STATUS(status);
1487 }
1488 
1489 /*
1490  * ACPI Event Handlers
1491  */
1492 
1493 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1494 
1495 static void
1496 acpi_system_eventhandler_sleep(void *arg, int state)
1497 {
1498     ACPI_LOCK_DECL;
1499     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1500 
1501     ACPI_LOCK;
1502     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
1503 	acpi_SetSleepState((struct acpi_softc *)arg, state);
1504     ACPI_UNLOCK;
1505     return_VOID;
1506 }
1507 
1508 static void
1509 acpi_system_eventhandler_wakeup(void *arg, int state)
1510 {
1511     ACPI_LOCK_DECL;
1512     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1513 
1514     /* Well, what to do? :-) */
1515 
1516     ACPI_LOCK;
1517     ACPI_UNLOCK;
1518 
1519     return_VOID;
1520 }
1521 
1522 /*
1523  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1524  */
1525 UINT32
1526 acpi_eventhandler_power_button_for_sleep(void *context)
1527 {
1528     struct acpi_softc	*sc = (struct acpi_softc *)context;
1529 
1530     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1531 
1532     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1533 
1534     return_VALUE(ACPI_INTERRUPT_HANDLED);
1535 }
1536 
1537 UINT32
1538 acpi_eventhandler_power_button_for_wakeup(void *context)
1539 {
1540     struct acpi_softc	*sc = (struct acpi_softc *)context;
1541 
1542     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1543 
1544     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1545 
1546     return_VALUE(ACPI_INTERRUPT_HANDLED);
1547 }
1548 
1549 UINT32
1550 acpi_eventhandler_sleep_button_for_sleep(void *context)
1551 {
1552     struct acpi_softc	*sc = (struct acpi_softc *)context;
1553 
1554     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1555 
1556     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1557 
1558     return_VALUE(ACPI_INTERRUPT_HANDLED);
1559 }
1560 
1561 UINT32
1562 acpi_eventhandler_sleep_button_for_wakeup(void *context)
1563 {
1564     struct acpi_softc	*sc = (struct acpi_softc *)context;
1565 
1566     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1567 
1568     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1569 
1570     return_VALUE(ACPI_INTERRUPT_HANDLED);
1571 }
1572 
1573 /*
1574  * XXX This is kinda ugly, and should not be here.
1575  */
1576 struct acpi_staticbuf {
1577     ACPI_BUFFER	buffer;
1578     char	data[512];
1579 };
1580 
1581 char *
1582 acpi_name(ACPI_HANDLE handle)
1583 {
1584     static struct acpi_staticbuf	buf;
1585 
1586     ACPI_ASSERTLOCK;
1587 
1588     buf.buffer.Length = 512;
1589     buf.buffer.Pointer = &buf.data[0];
1590 
1591     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
1592 	return(buf.buffer.Pointer);
1593     return("(unknown path)");
1594 }
1595 
1596 /*
1597  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1598  * parts of the namespace.
1599  */
1600 int
1601 acpi_avoid(ACPI_HANDLE handle)
1602 {
1603     char	*cp, *env, *np;
1604     int		len;
1605 
1606     np = acpi_name(handle);
1607     if (*np == '\\')
1608 	np++;
1609     if ((env = getenv("debug.acpi.avoid")) == NULL)
1610 	return(0);
1611 
1612     /* scan the avoid list checking for a match */
1613     cp = env;
1614     for (;;) {
1615 	while ((*cp != 0) && isspace(*cp))
1616 	    cp++;
1617 	if (*cp == 0)
1618 	    break;
1619 	len = 0;
1620 	while ((cp[len] != 0) && !isspace(cp[len]))
1621 	    len++;
1622 	if (!strncmp(cp, np, len)) {
1623 	    freeenv(env);
1624 	    return(1);
1625 	}
1626 	cp += len;
1627     }
1628     freeenv(env);
1629     return(0);
1630 }
1631 
1632 /*
1633  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1634  */
1635 int
1636 acpi_disabled(char *subsys)
1637 {
1638     char	*cp, *env;
1639     int		len;
1640 
1641     if ((env = getenv("debug.acpi.disable")) == NULL)
1642 	return(0);
1643     if (!strcmp(env, "all")) {
1644 	freeenv(env);
1645 	return(1);
1646     }
1647 
1648     /* scan the disable list checking for a match */
1649     cp = env;
1650     for (;;) {
1651 	while ((*cp != 0) && isspace(*cp))
1652 	    cp++;
1653 	if (*cp == 0)
1654 	    break;
1655 	len = 0;
1656 	while ((cp[len] != 0) && !isspace(cp[len]))
1657 	    len++;
1658 	if (!strncmp(cp, subsys, len)) {
1659 	    freeenv(env);
1660 	    return(1);
1661 	}
1662 	cp += len;
1663     }
1664     freeenv(env);
1665     return(0);
1666 }
1667 
1668 /*
1669  * Device wake capability enable/disable.
1670  */
1671 void
1672 acpi_device_enable_wake_capability(ACPI_HANDLE h, int enable)
1673 {
1674     ACPI_OBJECT_LIST		ArgList;
1675     ACPI_OBJECT			Arg;
1676 
1677     /*
1678      * TBD: All Power Resources referenced by elements 2 through N
1679      *      of the _PRW object are put into the ON state.
1680      */
1681 
1682     /*
1683      * enable/disable device wake function.
1684      */
1685 
1686     ArgList.Count = 1;
1687     ArgList.Pointer = &Arg;
1688 
1689     Arg.Type = ACPI_TYPE_INTEGER;
1690     Arg.Integer.Value = enable;
1691 
1692     (void)AcpiEvaluateObject(h, "_PSW", &ArgList, NULL);
1693 }
1694 
1695 void
1696 acpi_device_enable_wake_event(ACPI_HANDLE h)
1697 {
1698     struct acpi_softc		*sc;
1699     ACPI_STATUS			status;
1700     ACPI_BUFFER			prw_buffer;
1701     ACPI_OBJECT			*res;
1702 
1703     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1704 
1705     if ((sc = devclass_get_softc(acpi_devclass, 0)) == NULL) {
1706 	return;
1707     }
1708 
1709     /*
1710      * _PRW object is only required for devices that have the ability
1711      * to wake the system from a system sleeping state.
1712      */
1713     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
1714     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
1715     if (ACPI_FAILURE(status)) {
1716 	return;
1717     }
1718 
1719     res = (ACPI_OBJECT *)prw_buffer.Pointer;
1720     if (res == NULL) {
1721 	return;
1722     }
1723 
1724     if ((res->Type != ACPI_TYPE_PACKAGE) || (res->Package.Count < 2)) {
1725 	goto out;
1726     }
1727 
1728     /*
1729      * The element 1 of the _PRW object:
1730      * The lowest power system sleeping state that can be entered
1731      * while still providing wake functionality.
1732      * The sleeping state being entered must be greater or equal to
1733      * the power state declared in element 1 of the _PRW object.
1734      */
1735     if (res->Package.Elements[1].Type != ACPI_TYPE_INTEGER) {
1736 	goto out;
1737     }
1738 
1739     if (sc->acpi_sstate > res->Package.Elements[1].Integer.Value) {
1740 	goto out;
1741     }
1742 
1743     /*
1744      * The element 0 of the _PRW object:
1745      */
1746     switch(res->Package.Elements[0].Type) {
1747     case ACPI_TYPE_INTEGER:
1748 	/*
1749 	 * If the data type of this package element is numeric, then this
1750 	 * _PRW package element is the bit index in the GPEx_EN, in the
1751 	 * GPE blocks described in the FADT, of the enable bit that is
1752 	 * enabled for the wake event.
1753 	 */
1754 
1755 	status = AcpiEnableEvent(res->Package.Elements[0].Integer.Value,
1756 				 ACPI_EVENT_GPE, ACPI_EVENT_WAKE_ENABLE);
1757 	if (ACPI_FAILURE(status))
1758             printf("%s: EnableEvent Failed\n", __func__);
1759 	break;
1760 
1761     case ACPI_TYPE_PACKAGE:
1762 	/* XXX TBD */
1763 
1764 	/*
1765 	 * If the data type of this package element is a package, then this
1766 	 * _PRW package element is itself a package containing two
1767 	 * elements. The first is an object reference to the GPE Block
1768 	 * device that contains the GPE that will be triggered by the wake
1769 	 * event. The second element is numeric and it contains the bit
1770 	 * index in the GPEx_EN, in the GPE Block referenced by the
1771 	 * first element in the package, of the enable bit that is enabled for
1772 	 * the wake event.
1773 	 * For example, if this field is a package then it is of the form:
1774 	 * Package() {\_SB.PCI0.ISA.GPE, 2}
1775 	 */
1776 
1777 	break;
1778 
1779     default:
1780 	break;
1781     }
1782 
1783 out:
1784     if (prw_buffer.Pointer != NULL)
1785 	AcpiOsFree(prw_buffer.Pointer);
1786     return;
1787 }
1788 
1789 /*
1790  * Control interface.
1791  *
1792  * We multiplex ioctls for all participating ACPI devices here.  Individual
1793  * drivers wanting to be accessible via /dev/acpi should use the register/deregister
1794  * interface to make their handlers visible.
1795  */
1796 struct acpi_ioctl_hook
1797 {
1798     TAILQ_ENTRY(acpi_ioctl_hook)	link;
1799     u_long				cmd;
1800     int					(* fn)(u_long cmd, caddr_t addr, void *arg);
1801     void				*arg;
1802 };
1803 
1804 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
1805 static int				acpi_ioctl_hooks_initted;
1806 
1807 /*
1808  * Register an ioctl handler.
1809  */
1810 int
1811 acpi_register_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg), void *arg)
1812 {
1813     struct acpi_ioctl_hook	*hp;
1814 
1815     hp = malloc(sizeof(*hp), M_ACPIDEV, M_INTWAIT);
1816     hp->cmd = cmd;
1817     hp->fn = fn;
1818     hp->arg = arg;
1819     if (acpi_ioctl_hooks_initted == 0) {
1820 	TAILQ_INIT(&acpi_ioctl_hooks);
1821 	acpi_ioctl_hooks_initted = 1;
1822     }
1823     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
1824     return(0);
1825 }
1826 
1827 /*
1828  * Deregister an ioctl handler.
1829  */
1830 void
1831 acpi_deregister_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg))
1832 {
1833     struct acpi_ioctl_hook	*hp;
1834 
1835     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
1836 	if ((hp->cmd == cmd) && (hp->fn == fn))
1837 	    break;
1838 
1839     if (hp != NULL) {
1840 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
1841 	free(hp, M_ACPIDEV);
1842     }
1843 }
1844 
1845 static int
1846 acpiopen(dev_t dev, int flag, int fmt, d_thread_t *td)
1847 {
1848     return(0);
1849 }
1850 
1851 static int
1852 acpiclose(dev_t dev, int flag, int fmt, d_thread_t *td)
1853 {
1854     return(0);
1855 }
1856 
1857 static int
1858 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
1859 {
1860     struct acpi_softc		*sc;
1861     struct acpi_ioctl_hook	*hp;
1862     int				error, xerror, state;
1863     ACPI_LOCK_DECL;
1864 
1865     ACPI_LOCK;
1866 
1867     error = state = 0;
1868     sc = dev->si_drv1;
1869 
1870     /*
1871      * Scan the list of registered ioctls, looking for handlers.
1872      */
1873     if (acpi_ioctl_hooks_initted) {
1874 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
1875 	    if (hp->cmd == cmd) {
1876 		xerror = hp->fn(cmd, addr, hp->arg);
1877 		if (xerror != 0)
1878 		    error = xerror;
1879 		goto out;
1880 	    }
1881 	}
1882     }
1883 
1884     /*
1885      * Core ioctls are  not permitted for non-writable user.
1886      * Currently, other ioctls just fetch information.
1887      * Not changing system behavior.
1888      */
1889     if(!(flag & FWRITE)){
1890 	    return EPERM;
1891     }
1892 
1893     /*
1894      * Core system ioctls.
1895      */
1896     switch (cmd) {
1897     case ACPIIO_ENABLE:
1898 	if (ACPI_FAILURE(acpi_Enable(sc)))
1899 	    error = ENXIO;
1900 	break;
1901 
1902     case ACPIIO_DISABLE:
1903 	if (ACPI_FAILURE(acpi_Disable(sc)))
1904 	    error = ENXIO;
1905 	break;
1906 
1907     case ACPIIO_SETSLPSTATE:
1908 	if (!sc->acpi_enabled) {
1909 	    error = ENXIO;
1910 	    break;
1911 	}
1912 	state = *(int *)addr;
1913 	if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
1914 	    acpi_SetSleepState(sc, state);
1915 	} else {
1916 	    error = EINVAL;
1917 	}
1918 	break;
1919 
1920     default:
1921 	if (error == 0)
1922 	    error = EINVAL;
1923 	break;
1924     }
1925 
1926 out:
1927     ACPI_UNLOCK;
1928     return(error);
1929 }
1930 
1931 static int
1932 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
1933 {
1934     char sleep_state[4];
1935     char buf[16];
1936     int error;
1937     UINT8 state, TypeA, TypeB;
1938 
1939     buf[0] = '\0';
1940     for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX+1; state++) {
1941 	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
1942 	    sprintf(sleep_state, "S%d ", state);
1943 	    strcat(buf, sleep_state);
1944 	}
1945     }
1946     error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
1947     return(error);
1948 }
1949 
1950 static int
1951 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
1952 {
1953     char sleep_state[10];
1954     int error;
1955     u_int new_state, old_state;
1956 
1957     old_state = *(u_int *)oidp->oid_arg1;
1958     if (old_state > ACPI_S_STATES_MAX+1) {
1959 	strcpy(sleep_state, "unknown");
1960     } else {
1961 	bzero(sleep_state, sizeof(sleep_state));
1962 	strncpy(sleep_state, sleep_state_names[old_state],
1963 		sizeof(sleep_state_names[old_state]));
1964     }
1965     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
1966     if (error == 0 && req->newptr != NULL) {
1967 	for (new_state = ACPI_STATE_S0; new_state <= ACPI_S_STATES_MAX+1; new_state++) {
1968 	    if (strncmp(sleep_state, sleep_state_names[new_state],
1969 			sizeof(sleep_state)) == 0)
1970 		break;
1971 	}
1972 	if (new_state <= ACPI_S_STATES_MAX+1) {
1973 	    if (new_state != old_state) {
1974 		*(u_int *)oidp->oid_arg1 = new_state;
1975 	    }
1976 	} else {
1977 	    error = EINVAL;
1978 	}
1979     }
1980     return(error);
1981 }
1982 
1983 #ifdef ACPI_DEBUG
1984 /*
1985  * Support for parsing debug options from the kernel environment.
1986  *
1987  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
1988  * by specifying the names of the bits in the debug.acpi.layer and
1989  * debug.acpi.level environment variables.  Bits may be unset by
1990  * prefixing the bit name with !.
1991  */
1992 struct debugtag
1993 {
1994     char	*name;
1995     UINT32	value;
1996 };
1997 
1998 static struct debugtag	dbg_layer[] = {
1999     {"ACPI_UTILITIES",		ACPI_UTILITIES},
2000     {"ACPI_HARDWARE",		ACPI_HARDWARE},
2001     {"ACPI_EVENTS",		ACPI_EVENTS},
2002     {"ACPI_TABLES",		ACPI_TABLES},
2003     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
2004     {"ACPI_PARSER",		ACPI_PARSER},
2005     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
2006     {"ACPI_EXECUTER",		ACPI_EXECUTER},
2007     {"ACPI_RESOURCES",		ACPI_RESOURCES},
2008     {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
2009     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
2010     {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
2011 
2012     {"ACPI_BUS",		ACPI_BUS},
2013     {"ACPI_SYSTEM",		ACPI_SYSTEM},
2014     {"ACPI_POWER",		ACPI_POWER},
2015     {"ACPI_EC", 		ACPI_EC},
2016     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
2017     {"ACPI_BATTERY",		ACPI_BATTERY},
2018     {"ACPI_BUTTON",		ACPI_BUTTON},
2019     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
2020     {"ACPI_THERMAL",		ACPI_THERMAL},
2021     {"ACPI_FAN",		ACPI_FAN},
2022 
2023     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
2024     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
2025     {NULL, 0}
2026 };
2027 
2028 static struct debugtag dbg_level[] = {
2029     {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
2030     {"ACPI_LV_WARN",		ACPI_LV_WARN},
2031     {"ACPI_LV_INIT",		ACPI_LV_INIT},
2032     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
2033     {"ACPI_LV_INFO",		ACPI_LV_INFO},
2034     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
2035 
2036     /* Trace verbosity level 1 [Standard Trace Level] */
2037     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
2038     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
2039     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
2040     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
2041     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
2042     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
2043     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
2044     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
2045     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
2046     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
2047     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
2048     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
2049     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
2050     {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
2051     {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
2052 
2053     /* Trace verbosity level 2 [Function tracing and memory allocation] */
2054     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
2055     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
2056     {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
2057     {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
2058     {"ACPI_LV_ALL",		ACPI_LV_ALL},
2059 
2060     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2061     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
2062     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
2063     {"ACPI_LV_IO",		ACPI_LV_IO},
2064     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
2065     {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
2066 
2067     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2068     {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
2069     {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
2070     {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
2071     {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
2072     {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
2073     {NULL, 0}
2074 };
2075 
2076 static void
2077 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2078 {
2079     char	*ep;
2080     int		i, l;
2081     int		set;
2082 
2083     while (*cp) {
2084 	if (isspace(*cp)) {
2085 	    cp++;
2086 	    continue;
2087 	}
2088 	ep = cp;
2089 	while (*ep && !isspace(*ep))
2090 	    ep++;
2091 	if (*cp == '!') {
2092 	    set = 0;
2093 	    cp++;
2094 	    if (cp == ep)
2095 		continue;
2096 	} else {
2097 	    set = 1;
2098 	}
2099 	l = ep - cp;
2100 	for (i = 0; tag[i].name != NULL; i++) {
2101 	    if (!strncmp(cp, tag[i].name, l)) {
2102 		if (set) {
2103 		    *flag |= tag[i].value;
2104 		} else {
2105 		    *flag &= ~tag[i].value;
2106 		}
2107 		printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
2108 	    }
2109 	}
2110 	cp = ep;
2111     }
2112 }
2113 
2114 static void
2115 acpi_set_debugging(void *junk)
2116 {
2117     char	*cp;
2118 
2119     if (!cold)
2120 	return;
2121 
2122     AcpiDbgLayer = 0;
2123     AcpiDbgLevel = 0;
2124     if ((cp = getenv("debug.acpi.layer")) != NULL) {
2125 	acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
2126 	freeenv(cp);
2127     }
2128     if ((cp = getenv("debug.acpi.level")) != NULL) {
2129 	acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
2130 	freeenv(cp);
2131     }
2132 
2133     printf("ACPI debug layer 0x%x  debug level 0x%x\n", AcpiDbgLayer, AcpiDbgLevel);
2134 }
2135 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging, NULL);
2136 #endif
2137 
2138 static int
2139 acpi_pm_func(u_long cmd, void *arg, ...)
2140 {
2141 	int	state, acpi_state;
2142 	int	error;
2143 	struct	acpi_softc *sc;
2144 	__va_list	ap;
2145 
2146 	error = 0;
2147 	switch (cmd) {
2148 	case POWER_CMD_SUSPEND:
2149 		sc = (struct acpi_softc *)arg;
2150 		if (sc == NULL) {
2151 			error = EINVAL;
2152 			goto out;
2153 		}
2154 
2155 		__va_start(ap, arg);
2156 		state = __va_arg(ap, int);
2157 		__va_end(ap);
2158 
2159 		switch (state) {
2160 		case POWER_SLEEP_STATE_STANDBY:
2161 			acpi_state = sc->acpi_standby_sx;
2162 			break;
2163 		case POWER_SLEEP_STATE_SUSPEND:
2164 			acpi_state = sc->acpi_suspend_sx;
2165 			break;
2166 		case POWER_SLEEP_STATE_HIBERNATE:
2167 			acpi_state = ACPI_STATE_S4;
2168 			break;
2169 		default:
2170 			error = EINVAL;
2171 			goto out;
2172 		}
2173 
2174 		acpi_SetSleepState(sc, acpi_state);
2175 		break;
2176 
2177 	default:
2178 		error = EINVAL;
2179 		goto out;
2180 	}
2181 
2182 out:
2183 	return (error);
2184 }
2185 
2186 static void
2187 acpi_pm_register(void *arg)
2188 {
2189     int	error;
2190 
2191     if (!cold)
2192 	return;
2193 
2194     if (!resource_int_value("acpi", 0, "disabled", &error) &&
2195        (error != 0))
2196 		return;
2197 
2198     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2199 }
2200 
2201 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
2202 
2203