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