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