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