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