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