xref: /freebsd/sys/dev/acpica/acpi.c (revision c17d43407fe04133a94055b0dbc7ea8965654a9f)
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 ACPI_MODULE_NAME("ACPI")
67 
68 /*
69  * Character device
70  */
71 
72 static d_open_t		acpiopen;
73 static d_close_t	acpiclose;
74 static d_ioctl_t	acpiioctl;
75 
76 #define CDEV_MAJOR 152
77 static struct cdevsw acpi_cdevsw = {
78     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 static 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     ACPI_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 (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
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 	    if (ACPI_FAILURE(error = AcpiSetDsdtTablePtr(*(void **)p))) {
258 		printf("ACPI: DSDT overriding failed: %s\n",
259 		       AcpiFormatException(error));
260 	    } else {
261 		printf("ACPI: DSDT was overridden.\n");
262 	    }
263         }
264     }
265 
266     if (ACPI_FAILURE(error = AcpiLoadTables())) {
267 	printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
268 	return_VOID;
269     }
270 
271     /*
272      * Attach the actual ACPI device.
273      */
274     if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
275 	    device_printf(parent, "ACPI: could not attach\n");
276 	    return_VOID;
277     }
278 }
279 
280 /*
281  * Fetch some descriptive data from ACPI to put in our attach message
282  */
283 static int
284 acpi_probe(device_t dev)
285 {
286     ACPI_TABLE_HEADER	th;
287     char		buf[20];
288     ACPI_STATUS		status;
289     int			error;
290 
291     ACPI_FUNCTION_TRACE(__func__);
292 
293     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
294         power_pm_get_type() != POWER_PM_TYPE_ACPI) {
295 	device_printf(dev, "Other PM system enabled.\n");
296 	return_VALUE(ENXIO);
297     }
298 
299     ACPI_LOCK;
300 
301     if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
302 	device_printf(dev, "couldn't get XSDT header: %s\n", AcpiFormatException(status));
303 	error = ENXIO;
304     } else {
305 	sprintf(buf, "%.6s %.8s", th.OemId, th.OemTableId);
306 	device_set_desc_copy(dev, buf);
307 	error = 0;
308     }
309     ACPI_UNLOCK;
310     return_VALUE(error);
311 }
312 
313 static int
314 acpi_attach(device_t dev)
315 {
316     struct acpi_softc	*sc;
317     ACPI_STATUS		status;
318     int			error;
319     UINT32		flags;
320 
321 #ifdef ENABLE_DEBUGGER
322     char		*debugpoint = getenv("debug.acpi.debugger");
323 #endif
324 
325     ACPI_FUNCTION_TRACE(__func__);
326     ACPI_LOCK;
327     sc = device_get_softc(dev);
328     bzero(sc, sizeof(*sc));
329     sc->acpi_dev = dev;
330 
331 #ifdef ENABLE_DEBUGGER
332     if (debugpoint && !strcmp(debugpoint, "spaces"))
333 	acpi_EnterDebugger();
334 #endif
335 
336     /*
337      * Install the default address space handlers.
338      */
339     error = ENXIO;
340     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
341 						ACPI_ADR_SPACE_SYSTEM_MEMORY,
342 						ACPI_DEFAULT_HANDLER,
343 						NULL, NULL))) {
344 	device_printf(dev, "could not initialise SystemMemory handler: %s\n", AcpiFormatException(status));
345 	goto out;
346     }
347     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
348 						ACPI_ADR_SPACE_SYSTEM_IO,
349 						ACPI_DEFAULT_HANDLER,
350 						NULL, NULL))) {
351 	device_printf(dev, "could not initialise SystemIO handler: %s\n", AcpiFormatException(status));
352 	goto out;
353     }
354     if (ACPI_FAILURE(status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
355 						ACPI_ADR_SPACE_PCI_CONFIG,
356 						ACPI_DEFAULT_HANDLER,
357 						NULL, NULL))) {
358 	device_printf(dev, "could not initialise PciConfig handler: %s\n", AcpiFormatException(status));
359 	goto out;
360     }
361 
362     /*
363      * Bring ACPI fully online.
364      *
365      * Note that some systems (specifically, those with namespace evaluation issues
366      * that require the avoidance of parts of the namespace) must avoid running _INI
367      * and _STA on everything, as well as dodging the final object init pass.
368      *
369      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
370      *
371      * XXX We should arrange for the object init pass after we have attached all our
372      *     child devices, but on many systems it works here.
373      */
374 #ifdef ENABLE_DEBUGGER
375     if (debugpoint && !strcmp(debugpoint, "enable"))
376 	acpi_EnterDebugger();
377 #endif
378     flags = 0;
379     if (getenv("debug.acpi.avoid") != NULL)
380 	flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
381     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
382 	device_printf(dev, "could not enable ACPI: %s\n", AcpiFormatException(status));
383 	goto out;
384     }
385 
386     /*
387      * Setup our sysctl tree.
388      *
389      * XXX: This doesn't check to make sure that none of these fail.
390      */
391     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
392     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
393 			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
394 			       device_get_name(dev), CTLFLAG_RD, 0, "");
395     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
396 	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
397 	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
398     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
399 	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
400 	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
401     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
402 	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
403 	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
404     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
405 	OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
406 	&sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
407     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
408 	OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
409 	&sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
410     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
411 	OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
412 	&sc->acpi_s4bios, 0, "S4BIOS mode");
413     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
414 	OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
415 	&sc->acpi_verbose, 0, "verbose mode");
416     sc->acpi_s4bios = 1;
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     sc->acpi_sleep_disabled = 0;
461 
462     /*
463      * Create the control device
464      */
465     sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, 0, 5, 0660, "acpi");
466     sc->acpi_dev_t->si_drv1 = sc;
467 
468 #ifdef ENABLE_DEBUGGER
469     if (debugpoint && !strcmp(debugpoint, "running"))
470 	acpi_EnterDebugger();
471 #endif
472 
473 #if defined(ACPI_MAX_THREADS) && ACPI_MAX_THREADS > 0
474     if ((error = acpi_task_thread_init())) {
475 	goto out;
476     }
477 #endif
478 
479     if ((error = acpi_machdep_init(dev))) {
480 	goto out;
481     }
482 
483     /* Register ACPI again to pass the correct argument of pm_func. */
484     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
485 
486     error = 0;
487 
488  out:
489     ACPI_UNLOCK;
490     return_VALUE(error);
491 }
492 
493 /*
494  * Handle a new device being added
495  */
496 static device_t
497 acpi_add_child(device_t bus, int order, const char *name, int unit)
498 {
499     struct acpi_device	*ad;
500     device_t		child;
501 
502     if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT)) == NULL)
503 	return(NULL);
504     bzero(ad, sizeof(*ad));
505 
506     resource_list_init(&ad->ad_rl);
507 
508     child = device_add_child_ordered(bus, order, name, unit);
509     if (child != NULL)
510 	device_set_ivars(child, ad);
511     return(child);
512 }
513 
514 /*
515  * Print child device resource usage
516  */
517 static int
518 acpi_print_resources(struct resource_list *rl, const char *name, int type, const char *format)
519 {
520     struct resource_list_entry	*rle;
521     int				printed, retval;
522 
523     printed = 0;
524     retval = 0;
525 
526     if (!SLIST_FIRST(rl))
527 	return(0);
528 
529     /* Yes, this is kinda cheating */
530     SLIST_FOREACH(rle, rl, link) {
531 	if (rle->type == type) {
532 	    if (printed == 0)
533 		retval += printf(" %s ", name);
534 	    else if (printed > 0)
535 		retval += printf(",");
536 	    printed++;
537 	    retval += printf(format, rle->start);
538 	    if (rle->count > 1) {
539 		retval += printf("-");
540 		retval += printf(format, rle->start +
541 				 rle->count - 1);
542 	    }
543 	}
544     }
545     return(retval);
546 }
547 
548 static int
549 acpi_print_child(device_t bus, device_t child)
550 {
551     struct acpi_device		*adev = device_get_ivars(child);
552     struct resource_list	*rl = &adev->ad_rl;
553     int retval = 0;
554 
555     retval += bus_print_child_header(bus, child);
556     retval += acpi_print_resources(rl, "port",  SYS_RES_IOPORT, "%#lx");
557     retval += acpi_print_resources(rl, "iomem", SYS_RES_MEMORY, "%#lx");
558     retval += acpi_print_resources(rl, "irq",   SYS_RES_IRQ,    "%ld");
559     retval += bus_print_child_footer(bus, child);
560 
561     return(retval);
562 }
563 
564 
565 /*
566  * Handle per-device ivars
567  */
568 static int
569 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
570 {
571     struct acpi_device	*ad;
572 
573     if ((ad = device_get_ivars(child)) == NULL) {
574 	printf("device has no ivars\n");
575 	return(ENOENT);
576     }
577 
578     switch(index) {
579 	/* ACPI ivars */
580     case ACPI_IVAR_HANDLE:
581 	*(ACPI_HANDLE *)result = ad->ad_handle;
582 	break;
583     case ACPI_IVAR_MAGIC:
584 	*(int *)result = ad->ad_magic;
585 	break;
586     case ACPI_IVAR_PRIVATE:
587 	*(void **)result = ad->ad_private;
588 	break;
589 
590 	/* ISA compatibility */
591     case ISA_IVAR_VENDORID:
592     case ISA_IVAR_SERIAL:
593     case ISA_IVAR_COMPATID:
594 	*(int *)result = -1;
595 	break;
596 
597     case ISA_IVAR_LOGICALID:
598 	*(int *)result = acpi_isa_get_logicalid(child);
599 	break;
600 
601     default:
602 	panic("bad ivar read request (%d)\n", index);
603 	return(ENOENT);
604     }
605     return(0);
606 }
607 
608 static int
609 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
610 {
611     struct acpi_device	*ad;
612 
613     if ((ad = device_get_ivars(child)) == NULL) {
614 	printf("device has no ivars\n");
615 	return(ENOENT);
616     }
617 
618     switch(index) {
619 	/* ACPI ivars */
620     case ACPI_IVAR_HANDLE:
621 	ad->ad_handle = (ACPI_HANDLE)value;
622 	break;
623     case ACPI_IVAR_MAGIC:
624 	ad->ad_magic = (int )value;
625 	break;
626     case ACPI_IVAR_PRIVATE:
627 	ad->ad_private = (void *)value;
628 	break;
629 
630     default:
631 	panic("bad ivar write request (%d)\n", index);
632 	return(ENOENT);
633     }
634     return(0);
635 }
636 
637 /*
638  * Handle child resource allocation/removal
639  */
640 static int
641 acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start, u_long count)
642 {
643     struct acpi_device		*ad = device_get_ivars(child);
644     struct resource_list	*rl = &ad->ad_rl;
645 
646     resource_list_add(rl, type, rid, start, start + count -1, count);
647 
648     return(0);
649 }
650 
651 static int
652 acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp, u_long *countp)
653 {
654     struct acpi_device		*ad = device_get_ivars(child);
655     struct resource_list	*rl = &ad->ad_rl;
656     struct resource_list_entry	*rle;
657 
658     rle = resource_list_find(rl, type, rid);
659     if (!rle)
660 	return(ENOENT);
661 
662     if (startp)
663 	*startp = rle->start;
664     if (countp)
665 	*countp = rle->count;
666 
667     return(0);
668 }
669 
670 static struct resource *
671 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
672 		    u_long start, u_long end, u_long count, u_int flags)
673 {
674     struct acpi_device *ad = device_get_ivars(child);
675     struct resource_list *rl = &ad->ad_rl;
676 
677     return(resource_list_alloc(rl, bus, child, type, rid, start, end, count, flags));
678 }
679 
680 static int
681 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
682 {
683     struct acpi_device *ad = device_get_ivars(child);
684     struct resource_list *rl = &ad->ad_rl;
685 
686     return(resource_list_release(rl, bus, child, type, rid, r));
687 }
688 
689 /*
690  * Handle ISA-like devices probing for a PnP ID to match.
691  */
692 #define PNP_EISAID(s)				\
693 	((((s[0] - '@') & 0x1f) << 2)		\
694 	 | (((s[1] - '@') & 0x18) >> 3)		\
695 	 | (((s[1] - '@') & 0x07) << 13)	\
696 	 | (((s[2] - '@') & 0x1f) << 8)		\
697 	 | (PNP_HEXTONUM(s[4]) << 16)		\
698 	 | (PNP_HEXTONUM(s[3]) << 20)		\
699 	 | (PNP_HEXTONUM(s[6]) << 24)		\
700 	 | (PNP_HEXTONUM(s[5]) << 28))
701 
702 static u_int32_t
703 acpi_isa_get_logicalid(device_t dev)
704 {
705     ACPI_HANDLE		h;
706     ACPI_DEVICE_INFO	devinfo;
707     ACPI_STATUS		error;
708     u_int32_t		pnpid;
709 
710     ACPI_FUNCTION_TRACE(__func__);
711 
712     pnpid = 0;
713     ACPI_LOCK;
714 
715     /* fetch and validate the HID */
716     if ((h = acpi_get_handle(dev)) == NULL)
717 	goto out;
718     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
719 	goto out;
720     if (!(devinfo.Valid & ACPI_VALID_HID))
721 	goto out;
722 
723     pnpid = PNP_EISAID(devinfo.HardwareId);
724 out:
725     ACPI_UNLOCK;
726     return_VALUE(pnpid);
727 }
728 
729 static int
730 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
731 {
732     int			result;
733     u_int32_t		pnpid;
734 
735     ACPI_FUNCTION_TRACE(__func__);
736 
737     /*
738      * ISA-style drivers attached to ACPI may persist and
739      * probe manually if we return ENOENT.  We never want
740      * that to happen, so don't ever return it.
741      */
742     result = ENXIO;
743 
744     /* scan the supplied IDs for a match */
745     pnpid = acpi_isa_get_logicalid(child);
746     while (ids && ids->ip_id) {
747 	if (pnpid == ids->ip_id) {
748 	    result = 0;
749 	    goto out;
750 	}
751 	ids++;
752     }
753  out:
754     return_VALUE(result);
755 }
756 
757 /*
758  * Scan relevant portions of the ACPI namespace and attach child devices.
759  *
760  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and \_SB_ scopes,
761  * and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
762  */
763 static void
764 acpi_probe_children(device_t bus)
765 {
766     ACPI_HANDLE		parent;
767     static char		*scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
768     int			i;
769 
770     ACPI_FUNCTION_TRACE(__func__);
771     ACPI_ASSERTLOCK;
772 
773     /*
774      * Create any static children by calling device identify methods.
775      */
776     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
777     bus_generic_probe(bus);
778 
779     /*
780      * Scan the namespace and insert placeholders for all the devices that
781      * we find.
782      *
783      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
784      * we want to create nodes for all devices, not just those that are currently
785      * present. (This assumes that we don't want to create/remove devices as they
786      * appear, which might be smarter.)
787      */
788     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
789     for (i = 0; scopes[i] != NULL; i++)
790 	if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent)))
791 	    AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child, bus, NULL);
792 
793     /*
794      * Scan all of the child devices we have created and let them probe/attach.
795      */
796     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
797     bus_generic_attach(bus);
798 
799     /*
800      * Some of these children may have attached others as part of their attach
801      * process (eg. the root PCI bus driver), so rescan.
802      */
803     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
804     bus_generic_attach(bus);
805 
806     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
807     return_VOID;
808 }
809 
810 /*
811  * Evaluate a child device and determine whether we might attach a device to
812  * it.
813  */
814 static ACPI_STATUS
815 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
816 {
817     ACPI_OBJECT_TYPE	type;
818     device_t		child, bus = (device_t)context;
819 
820     ACPI_FUNCTION_TRACE(__func__);
821 
822     /*
823      * Skip this device if we think we'll have trouble with it.
824      */
825     if (acpi_avoid(handle))
826 	return_ACPI_STATUS(AE_OK);
827 
828     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
829 	switch(type) {
830 	case ACPI_TYPE_DEVICE:
831 	case ACPI_TYPE_PROCESSOR:
832 	case ACPI_TYPE_THERMAL:
833 	case ACPI_TYPE_POWER:
834 	    if (acpi_disabled("children"))
835 		break;
836 	    /*
837 	     * Create a placeholder device for this node.  Sort the placeholder
838 	     * so that the probe/attach passes will run breadth-first.
839 	     */
840 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", acpi_name(handle)));
841 	    child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
842 	    if (child == NULL)
843 		break;
844 	    acpi_set_handle(child, handle);
845 
846 	    /*
847 	     * Check that the device is present.  If it's not present,
848 	     * leave it disabled (so that we have a device_t attached to
849 	     * the handle, but we don't probe it).
850 	     */
851 	    if ((type == ACPI_TYPE_DEVICE) && (!acpi_DeviceIsPresent(child))) {
852 		device_disable(child);
853 		break;
854 	    }
855 
856 	    /*
857 	     * Get the device's resource settings and attach them.
858 	     * Note that if the device has _PRS but no _CRS, we need
859 	     * to decide when it's appropriate to try to configure the
860 	     * device.  Ignore the return value here; it's OK for the
861 	     * device not to have any resources.
862 	     */
863 	    acpi_parse_resources(child, handle, &acpi_res_parse_set);
864 
865 	    /* if we're debugging, probe/attach now rather than later */
866 	    ACPI_DEBUG_EXEC(device_probe_and_attach(child));
867 	    break;
868 	}
869     }
870     return_ACPI_STATUS(AE_OK);
871 }
872 
873 static void
874 acpi_shutdown_pre_sync(void *arg, int howto)
875 {
876 
877     ACPI_ASSERTLOCK;
878 
879     /*
880      * Disable all ACPI events before soft off, otherwise the system
881      * will be turned on again on some laptops.
882      *
883      * XXX this should probably be restricted to masking some events just
884      *     before powering down, since we may still need ACPI during the
885      *     shutdown process.
886      */
887     acpi_Disable((struct acpi_softc *)arg);
888 }
889 
890 static void
891 acpi_shutdown_final(void *arg, int howto)
892 {
893     ACPI_STATUS	status;
894 
895     ACPI_ASSERTLOCK;
896 
897     if (howto & RB_POWEROFF) {
898 	printf("Power system off using ACPI...\n");
899 	if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(acpi_off_state))) {
900 	    printf("AcpiEnterSleepStatePrep failed - %s\n",
901 		   AcpiFormatException(status));
902 	    return;
903 	}
904 	if (ACPI_FAILURE(status = AcpiEnterSleepState(acpi_off_state))) {
905 	    printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
906 	} else {
907 	    DELAY(1000000);
908 	    printf("ACPI power-off failed - timeout\n");
909 	}
910     }
911 }
912 
913 static void
914 acpi_enable_fixed_events(struct acpi_softc *sc)
915 {
916     static int	first_time = 1;
917 #define MSGFORMAT "%s button is handled as a fixed feature programming model.\n"
918 
919     ACPI_ASSERTLOCK;
920 
921     /* Enable and clear fixed events and install handlers. */
922     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->PwrButton == 0)) {
923 	AcpiEnableEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED, 0);
924 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
925 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
926 				     acpi_eventhandler_power_button_for_sleep, sc);
927 	if (first_time) {
928 	    device_printf(sc->acpi_dev, MSGFORMAT, "power");
929 	}
930     }
931     if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->SleepButton == 0)) {
932 	AcpiEnableEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED, 0);
933 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
934 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
935 				     acpi_eventhandler_sleep_button_for_sleep, sc);
936 	if (first_time) {
937 	    device_printf(sc->acpi_dev, MSGFORMAT, "sleep");
938 	}
939     }
940 
941     first_time = 0;
942 }
943 
944 /*
945  * Returns true if the device is actually present and should
946  * be attached to.  This requires the present, enabled, UI-visible
947  * and diagnostics-passed bits to be set.
948  */
949 BOOLEAN
950 acpi_DeviceIsPresent(device_t dev)
951 {
952     ACPI_HANDLE		h;
953     ACPI_DEVICE_INFO	devinfo;
954     ACPI_STATUS		error;
955 
956     ACPI_ASSERTLOCK;
957 
958     if ((h = acpi_get_handle(dev)) == NULL)
959 	return(FALSE);
960     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
961 	return(FALSE);
962     /* if no _STA method, must be present */
963     if (!(devinfo.Valid & ACPI_VALID_STA))
964 	return(TRUE);
965     /* return true for 'present' and 'functioning' */
966     if ((devinfo.CurrentStatus & 0x9) == 0x9)
967 	return(TRUE);
968     return(FALSE);
969 }
970 
971 /*
972  * Returns true if the battery is actually present and inserted.
973  */
974 BOOLEAN
975 acpi_BatteryIsPresent(device_t dev)
976 {
977     ACPI_HANDLE		h;
978     ACPI_DEVICE_INFO	devinfo;
979     ACPI_STATUS		error;
980 
981     ACPI_ASSERTLOCK;
982 
983     if ((h = acpi_get_handle(dev)) == NULL)
984 	return(FALSE);
985     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
986 	return(FALSE);
987     /* if no _STA method, must be present */
988     if (!(devinfo.Valid & ACPI_VALID_STA))
989 	return(TRUE);
990     /* return true for 'present' and 'functioning' */
991     if ((devinfo.CurrentStatus & 0x19) == 0x19)
992 	return(TRUE);
993     return(FALSE);
994 }
995 
996 /*
997  * Match a HID string against a device
998  */
999 BOOLEAN
1000 acpi_MatchHid(device_t dev, char *hid)
1001 {
1002     ACPI_HANDLE		h;
1003     ACPI_DEVICE_INFO	devinfo;
1004     ACPI_STATUS		error;
1005     int			cid;
1006 
1007     ACPI_ASSERTLOCK;
1008 
1009     if (hid == NULL)
1010 	return(FALSE);
1011     if ((h = acpi_get_handle(dev)) == NULL)
1012 	return(FALSE);
1013     if (ACPI_FAILURE(error = AcpiGetObjectInfo(h, &devinfo)))
1014 	return(FALSE);
1015     if ((devinfo.Valid & ACPI_VALID_HID) && !strcmp(hid, devinfo.HardwareId))
1016 	return(TRUE);
1017     if (ACPI_FAILURE(error = acpi_EvaluateInteger(h, "_CID", &cid)))
1018 	return(FALSE);
1019     if (cid == PNP_EISAID(hid))
1020 	return(TRUE);
1021     return(FALSE);
1022 }
1023 
1024 /*
1025  * Return the handle of a named object within our scope, ie. that of (parent)
1026  * or one if its parents.
1027  */
1028 ACPI_STATUS
1029 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1030 {
1031     ACPI_HANDLE		r;
1032     ACPI_STATUS		status;
1033 
1034     ACPI_ASSERTLOCK;
1035 
1036     /* walk back up the tree to the root */
1037     for (;;) {
1038 	if (ACPI_SUCCESS(status = AcpiGetHandle(parent, path, &r))) {
1039 	    *result = r;
1040 	    return(AE_OK);
1041 	}
1042 	if (status != AE_NOT_FOUND)
1043 	    return(AE_OK);
1044 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1045 	    return(AE_NOT_FOUND);
1046 	parent = r;
1047     }
1048 }
1049 
1050 /*
1051  * Allocate a buffer with a preset data size.
1052  */
1053 ACPI_BUFFER *
1054 acpi_AllocBuffer(int size)
1055 {
1056     ACPI_BUFFER	*buf;
1057 
1058     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1059 	return(NULL);
1060     buf->Length = size;
1061     buf->Pointer = (void *)(buf + 1);
1062     return(buf);
1063 }
1064 
1065 /*
1066  * Evaluate a path that should return an integer.
1067  */
1068 ACPI_STATUS
1069 acpi_EvaluateInteger(ACPI_HANDLE handle, char *path, int *number)
1070 {
1071     ACPI_STATUS	error;
1072     ACPI_BUFFER	buf;
1073     ACPI_OBJECT	param;
1074 
1075     ACPI_ASSERTLOCK;
1076 
1077     if (handle == NULL)
1078 	handle = ACPI_ROOT_OBJECT;
1079 
1080     /*
1081      * Assume that what we've been pointed at is an Integer object, or
1082      * a method that will return an Integer.
1083      */
1084     buf.Pointer = &param;
1085     buf.Length = sizeof(param);
1086     if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
1087 	if (param.Type == ACPI_TYPE_INTEGER) {
1088 	    *number = param.Integer.Value;
1089 	} else {
1090 	    error = AE_TYPE;
1091 	}
1092     }
1093 
1094     /*
1095      * In some applications, a method that's expected to return an Integer
1096      * may instead return a Buffer (probably to simplify some internal
1097      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1098      * convert it into an Integer as best we can.
1099      *
1100      * This is a hack.
1101      */
1102     if (error == AE_BUFFER_OVERFLOW) {
1103 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1104 	    error = AE_NO_MEMORY;
1105 	} else {
1106 	    if (ACPI_SUCCESS(error = AcpiEvaluateObject(handle, path, NULL, &buf))) {
1107 		error = acpi_ConvertBufferToInteger(&buf, number);
1108 	    }
1109 	}
1110 	AcpiOsFree(buf.Pointer);
1111     }
1112     return(error);
1113 }
1114 
1115 ACPI_STATUS
1116 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, int *number)
1117 {
1118     ACPI_OBJECT	*p;
1119     int		i;
1120 
1121     p = (ACPI_OBJECT *)bufp->Pointer;
1122     if (p->Type == ACPI_TYPE_INTEGER) {
1123 	*number = p->Integer.Value;
1124 	return(AE_OK);
1125     }
1126     if (p->Type != ACPI_TYPE_BUFFER)
1127 	return(AE_TYPE);
1128     if (p->Buffer.Length > sizeof(int))
1129 	return(AE_BAD_DATA);
1130     *number = 0;
1131     for (i = 0; i < p->Buffer.Length; i++)
1132 	*number += (*(p->Buffer.Pointer + i) << (i * 8));
1133     return(AE_OK);
1134 }
1135 
1136 /*
1137  * Iterate over the elements of an a package object, calling the supplied
1138  * function for each element.
1139  *
1140  * XXX possible enhancement might be to abort traversal on error.
1141  */
1142 ACPI_STATUS
1143 acpi_ForeachPackageObject(ACPI_OBJECT *pkg, void (* func)(ACPI_OBJECT *comp, void *arg), void *arg)
1144 {
1145     ACPI_OBJECT	*comp;
1146     int		i;
1147 
1148     if ((pkg == NULL) || (pkg->Type != ACPI_TYPE_PACKAGE))
1149 	return(AE_BAD_PARAMETER);
1150 
1151     /* iterate over components */
1152     for (i = 0, comp = pkg->Package.Elements; i < pkg->Package.Count; i++, comp++)
1153 	func(comp, arg);
1154 
1155     return(AE_OK);
1156 }
1157 
1158 /*
1159  * Find the (index)th resource object in a set.
1160  */
1161 ACPI_STATUS
1162 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1163 {
1164     ACPI_RESOURCE	*rp;
1165     int			i;
1166 
1167     rp = (ACPI_RESOURCE *)buf->Pointer;
1168     i = index;
1169     while (i-- > 0) {
1170 	/* range check */
1171 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1172 	    return(AE_BAD_PARAMETER);
1173 	/* check for terminator */
1174 	if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1175 	    (rp->Length == 0))
1176 	    return(AE_NOT_FOUND);
1177 	rp = ACPI_RESOURCE_NEXT(rp);
1178     }
1179     if (resp != NULL)
1180 	*resp = rp;
1181     return(AE_OK);
1182 }
1183 
1184 /*
1185  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1186  *
1187  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1188  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1189  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1190  * resources.
1191  */
1192 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
1193 
1194 ACPI_STATUS
1195 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1196 {
1197     ACPI_RESOURCE	*rp;
1198     void		*newp;
1199 
1200     /*
1201      * Initialise the buffer if necessary.
1202      */
1203     if (buf->Pointer == NULL) {
1204 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1205 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1206 	    return(AE_NO_MEMORY);
1207 	rp = (ACPI_RESOURCE *)buf->Pointer;
1208 	rp->Id = ACPI_RSTYPE_END_TAG;
1209 	rp->Length = 0;
1210     }
1211     if (res == NULL)
1212 	return(AE_OK);
1213 
1214     /*
1215      * Scan the current buffer looking for the terminator.
1216      * This will either find the terminator or hit the end
1217      * of the buffer and return an error.
1218      */
1219     rp = (ACPI_RESOURCE *)buf->Pointer;
1220     for (;;) {
1221 	/* range check, don't go outside the buffer */
1222 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1223 	    return(AE_BAD_PARAMETER);
1224 	if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1225 	    (rp->Length == 0)) {
1226 	    break;
1227 	}
1228 	rp = ACPI_RESOURCE_NEXT(rp);
1229     }
1230 
1231     /*
1232      * Check the size of the buffer and expand if required.
1233      *
1234      * Required size is:
1235      *	size of existing resources before terminator +
1236      *	size of new resource and header +
1237      * 	size of terminator.
1238      *
1239      * Note that this loop should really only run once, unless
1240      * for some reason we are stuffing a *really* huge resource.
1241      */
1242     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
1243 	    res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1244 	    ACPI_RESOURCE_LENGTH) >= buf->Length) {
1245 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1246 	    return(AE_NO_MEMORY);
1247 	bcopy(buf->Pointer, newp, buf->Length);
1248         rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1249 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1250 	AcpiOsFree(buf->Pointer);
1251 	buf->Pointer = newp;
1252 	buf->Length += buf->Length;
1253     }
1254 
1255     /*
1256      * Insert the new resource.
1257      */
1258     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1259 
1260     /*
1261      * And add the terminator.
1262      */
1263     rp = ACPI_RESOURCE_NEXT(rp);
1264     rp->Id = ACPI_RSTYPE_END_TAG;
1265     rp->Length = 0;
1266 
1267     return(AE_OK);
1268 }
1269 
1270 #define ACPI_MINIMUM_AWAKETIME	5
1271 
1272 static void
1273 acpi_sleep_enable(void *arg)
1274 {
1275     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1276 }
1277 
1278 /*
1279  * Set the system sleep state
1280  *
1281  * Currently we only support S1 and S5
1282  */
1283 ACPI_STATUS
1284 acpi_SetSleepState(struct acpi_softc *sc, int state)
1285 {
1286     ACPI_STATUS	status = AE_OK;
1287     UINT8	TypeA;
1288     UINT8	TypeB;
1289 
1290     ACPI_FUNCTION_TRACE_U32(__func__, state);
1291     ACPI_ASSERTLOCK;
1292 
1293     if (sc->acpi_sstate != ACPI_STATE_S0)
1294 	return_ACPI_STATUS(AE_BAD_PARAMETER);	/* avoid reentry */
1295 
1296     if (sc->acpi_sleep_disabled)
1297 	return_ACPI_STATUS(AE_OK);
1298 
1299     switch (state) {
1300     case ACPI_STATE_S0:	/* XXX only for testing */
1301 	if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
1302 	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1303 	}
1304 	break;
1305 
1306     case ACPI_STATE_S1:
1307     case ACPI_STATE_S2:
1308     case ACPI_STATE_S3:
1309     case ACPI_STATE_S4:
1310 	if (ACPI_FAILURE(status = AcpiHwGetSleepTypeData((UINT8)state, &TypeA, &TypeB))) {
1311 	    device_printf(sc->acpi_dev, "AcpiHwGetSleepTypeData failed - %s\n", AcpiFormatException(status));
1312 	    break;
1313 	}
1314 
1315 	/*
1316 	 * Inform all devices that we are going to sleep.
1317 	 */
1318 	if (DEVICE_SUSPEND(root_bus) != 0) {
1319 	    /*
1320 	     * Re-wake the system.
1321 	     *
1322 	     * XXX note that a better two-pass approach with a 'veto' pass
1323 	     *     followed by a "real thing" pass would be better, but the
1324 	     *     current bus interface does not provide for this.
1325 	     */
1326 	    DEVICE_RESUME(root_bus);
1327 	    return_ACPI_STATUS(AE_ERROR);
1328 	}
1329 
1330 	if (ACPI_FAILURE(status = AcpiEnterSleepStatePrep(state))) {
1331 	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1332 			  AcpiFormatException(status));
1333 	    break;
1334 	}
1335 
1336 	sc->acpi_sstate = state;
1337 	sc->acpi_sleep_disabled = 1;
1338 
1339 	if (state != ACPI_STATE_S1) {
1340 	    acpi_sleep_machdep(sc, state);
1341 
1342 	    /* AcpiEnterSleepState() maybe incompleted, unlock here. */
1343 	    AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1344 
1345 	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1346 	    if (state == ACPI_STATE_S4) {
1347 		AcpiEnable();
1348 	    }
1349 	} else {
1350 	    if (ACPI_FAILURE(status = AcpiEnterSleepState((UINT8)state))) {
1351 		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1352 		break;
1353 	    }
1354 	}
1355 	AcpiLeaveSleepState((UINT8)state);
1356 	DEVICE_RESUME(root_bus);
1357 	sc->acpi_sstate = ACPI_STATE_S0;
1358 	acpi_enable_fixed_events(sc);
1359 	break;
1360 
1361     case ACPI_STATE_S5:
1362 	/*
1363 	 * Shut down cleanly and power off.  This will call us back through the
1364 	 * shutdown handlers.
1365 	 */
1366 	shutdown_nice(RB_POWEROFF);
1367 	break;
1368 
1369     default:
1370 	status = AE_BAD_PARAMETER;
1371 	break;
1372     }
1373 
1374     if (sc->acpi_sleep_disabled)
1375 	timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
1376 
1377     return_ACPI_STATUS(status);
1378 }
1379 
1380 /*
1381  * Enable/Disable ACPI
1382  */
1383 ACPI_STATUS
1384 acpi_Enable(struct acpi_softc *sc)
1385 {
1386     ACPI_STATUS	status;
1387     u_int32_t	flags;
1388 
1389     ACPI_FUNCTION_TRACE(__func__);
1390     ACPI_ASSERTLOCK;
1391 
1392     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
1393             ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
1394     if (!sc->acpi_enabled) {
1395 	status = AcpiEnableSubsystem(flags);
1396     } else {
1397 	status = AE_OK;
1398     }
1399     if (status == AE_OK)
1400 	sc->acpi_enabled = 1;
1401     return_ACPI_STATUS(status);
1402 }
1403 
1404 ACPI_STATUS
1405 acpi_Disable(struct acpi_softc *sc)
1406 {
1407     ACPI_STATUS	status;
1408 
1409     ACPI_FUNCTION_TRACE(__func__);
1410     ACPI_ASSERTLOCK;
1411 
1412     if (sc->acpi_enabled) {
1413 	status = AcpiDisable();
1414     } else {
1415 	status = AE_OK;
1416     }
1417     if (status == AE_OK)
1418 	sc->acpi_enabled = 0;
1419     return_ACPI_STATUS(status);
1420 }
1421 
1422 /*
1423  * ACPI Event Handlers
1424  */
1425 
1426 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1427 
1428 static void
1429 acpi_system_eventhandler_sleep(void *arg, int state)
1430 {
1431     ACPI_FUNCTION_TRACE_U32(__func__, state);
1432 
1433     ACPI_LOCK;
1434     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
1435 	acpi_SetSleepState((struct acpi_softc *)arg, state);
1436     ACPI_UNLOCK;
1437     return_VOID;
1438 }
1439 
1440 static void
1441 acpi_system_eventhandler_wakeup(void *arg, int state)
1442 {
1443     ACPI_FUNCTION_TRACE_U32(__func__, state);
1444 
1445     /* Well, what to do? :-) */
1446 
1447     ACPI_LOCK;
1448     ACPI_UNLOCK;
1449 
1450     return_VOID;
1451 }
1452 
1453 /*
1454  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1455  */
1456 UINT32
1457 acpi_eventhandler_power_button_for_sleep(void *context)
1458 {
1459     struct acpi_softc	*sc = (struct acpi_softc *)context;
1460 
1461     ACPI_FUNCTION_TRACE(__func__);
1462 
1463     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1464 
1465     return_VALUE(ACPI_INTERRUPT_HANDLED);
1466 }
1467 
1468 UINT32
1469 acpi_eventhandler_power_button_for_wakeup(void *context)
1470 {
1471     struct acpi_softc	*sc = (struct acpi_softc *)context;
1472 
1473     ACPI_FUNCTION_TRACE(__func__);
1474 
1475     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1476 
1477     return_VALUE(ACPI_INTERRUPT_HANDLED);
1478 }
1479 
1480 UINT32
1481 acpi_eventhandler_sleep_button_for_sleep(void *context)
1482 {
1483     struct acpi_softc	*sc = (struct acpi_softc *)context;
1484 
1485     ACPI_FUNCTION_TRACE(__func__);
1486 
1487     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1488 
1489     return_VALUE(ACPI_INTERRUPT_HANDLED);
1490 }
1491 
1492 UINT32
1493 acpi_eventhandler_sleep_button_for_wakeup(void *context)
1494 {
1495     struct acpi_softc	*sc = (struct acpi_softc *)context;
1496 
1497     ACPI_FUNCTION_TRACE(__func__);
1498 
1499     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1500 
1501     return_VALUE(ACPI_INTERRUPT_HANDLED);
1502 }
1503 
1504 /*
1505  * XXX This is kinda ugly, and should not be here.
1506  */
1507 struct acpi_staticbuf {
1508     ACPI_BUFFER	buffer;
1509     char	data[512];
1510 };
1511 
1512 char *
1513 acpi_name(ACPI_HANDLE handle)
1514 {
1515     static struct acpi_staticbuf	buf;
1516 
1517     ACPI_ASSERTLOCK;
1518 
1519     buf.buffer.Length = 512;
1520     buf.buffer.Pointer = &buf.data[0];
1521 
1522     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
1523 	return(buf.buffer.Pointer);
1524     return("(unknown path)");
1525 }
1526 
1527 /*
1528  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1529  * parts of the namespace.
1530  */
1531 int
1532 acpi_avoid(ACPI_HANDLE handle)
1533 {
1534     char	*cp, *np;
1535     int		len;
1536 
1537     np = acpi_name(handle);
1538     if (*np == '\\')
1539 	np++;
1540     if ((cp = getenv("debug.acpi.avoid")) == NULL)
1541 	return(0);
1542 
1543     /* scan the avoid list checking for a match */
1544     for (;;) {
1545 	while ((*cp != 0) && isspace(*cp))
1546 	    cp++;
1547 	if (*cp == 0)
1548 	    break;
1549 	len = 0;
1550 	while ((cp[len] != 0) && !isspace(cp[len]))
1551 	    len++;
1552 	if (!strncmp(cp, np, len))
1553 	    return(1);
1554 	cp += len;
1555     }
1556     return(0);
1557 }
1558 
1559 /*
1560  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1561  */
1562 int
1563 acpi_disabled(char *subsys)
1564 {
1565     char	*cp;
1566     int		len;
1567 
1568     if ((cp = getenv("debug.acpi.disable")) == NULL)
1569 	return(0);
1570     if (!strcmp(cp, "all"))
1571 	return(1);
1572 
1573     /* scan the disable list checking for a match */
1574     for (;;) {
1575 	while ((*cp != 0) && isspace(*cp))
1576 	    cp++;
1577 	if (*cp == 0)
1578 	    break;
1579 	len = 0;
1580 	while ((cp[len] != 0) && !isspace(cp[len]))
1581 	    len++;
1582 	if (!strncmp(cp, subsys, len))
1583 	    return(1);
1584 	cp += len;
1585     }
1586     return(0);
1587 }
1588 
1589 /*
1590  * Control interface.
1591  *
1592  * We multiplex ioctls for all participating ACPI devices here.  Individual
1593  * drivers wanting to be accessible via /dev/acpi should use the register/deregister
1594  * interface to make their handlers visible.
1595  */
1596 struct acpi_ioctl_hook
1597 {
1598     TAILQ_ENTRY(acpi_ioctl_hook)	link;
1599     u_long				cmd;
1600     int					(* fn)(u_long cmd, caddr_t addr, void *arg);
1601     void				*arg;
1602 };
1603 
1604 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
1605 static int				acpi_ioctl_hooks_initted;
1606 
1607 /*
1608  * Register an ioctl handler.
1609  */
1610 int
1611 acpi_register_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg), void *arg)
1612 {
1613     struct acpi_ioctl_hook	*hp;
1614 
1615     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
1616 	return(ENOMEM);
1617     hp->cmd = cmd;
1618     hp->fn = fn;
1619     hp->arg = arg;
1620     if (acpi_ioctl_hooks_initted == 0) {
1621 	TAILQ_INIT(&acpi_ioctl_hooks);
1622 	acpi_ioctl_hooks_initted = 1;
1623     }
1624     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
1625     return(0);
1626 }
1627 
1628 /*
1629  * Deregister an ioctl handler.
1630  */
1631 void
1632 acpi_deregister_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg))
1633 {
1634     struct acpi_ioctl_hook	*hp;
1635 
1636     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
1637 	if ((hp->cmd == cmd) && (hp->fn == fn))
1638 	    break;
1639 
1640     if (hp != NULL) {
1641 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
1642 	free(hp, M_ACPIDEV);
1643     }
1644 }
1645 
1646 static int
1647 acpiopen(dev_t dev, int flag, int fmt, struct thread *td)
1648 {
1649     return(0);
1650 }
1651 
1652 static int
1653 acpiclose(dev_t dev, int flag, int fmt, struct thread *td)
1654 {
1655     return(0);
1656 }
1657 
1658 static int
1659 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1660 {
1661     struct acpi_softc		*sc;
1662     struct acpi_ioctl_hook	*hp;
1663     int				error, xerror, state;
1664 
1665     ACPI_LOCK;
1666 
1667     error = state = 0;
1668     sc = dev->si_drv1;
1669 
1670     /*
1671      * Scan the list of registered ioctls, looking for handlers.
1672      */
1673     if (acpi_ioctl_hooks_initted) {
1674 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
1675 	    if (hp->cmd == cmd) {
1676 		xerror = hp->fn(cmd, addr, hp->arg);
1677 		if (xerror != 0)
1678 		    error = xerror;
1679 		goto out;
1680 	    }
1681 	}
1682     }
1683 
1684     /*
1685      * Core system ioctls.
1686      */
1687     switch (cmd) {
1688     case ACPIIO_ENABLE:
1689 	if (ACPI_FAILURE(acpi_Enable(sc)))
1690 	    error = ENXIO;
1691 	break;
1692 
1693     case ACPIIO_DISABLE:
1694 	if (ACPI_FAILURE(acpi_Disable(sc)))
1695 	    error = ENXIO;
1696 	break;
1697 
1698     case ACPIIO_SETSLPSTATE:
1699 	if (!sc->acpi_enabled) {
1700 	    error = ENXIO;
1701 	    break;
1702 	}
1703 	state = *(int *)addr;
1704 	if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
1705 	    acpi_SetSleepState(sc, state);
1706 	} else {
1707 	    error = EINVAL;
1708 	}
1709 	break;
1710 
1711     default:
1712 	if (error == 0)
1713 	    error = EINVAL;
1714 	break;
1715     }
1716 
1717 out:
1718     ACPI_UNLOCK;
1719     return(error);
1720 }
1721 
1722 static int
1723 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
1724 {
1725     char sleep_state[10];
1726     int error;
1727     u_int new_state, old_state;
1728 
1729     old_state = *(u_int *)oidp->oid_arg1;
1730     if (old_state > ACPI_S_STATES_MAX+1) {
1731 	strcpy(sleep_state, "unknown");
1732     } else {
1733 	bzero(sleep_state, sizeof(sleep_state));
1734 	strncpy(sleep_state, sleep_state_names[old_state],
1735 		sizeof(sleep_state_names[old_state]));
1736     }
1737     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
1738     if (error == 0 && req->newptr != NULL) {
1739 	for (new_state = ACPI_STATE_S0; new_state <= ACPI_S_STATES_MAX+1; new_state++) {
1740 	    if (strncmp(sleep_state, sleep_state_names[new_state],
1741 			sizeof(sleep_state)) == 0)
1742 		break;
1743 	}
1744 	if (new_state <= ACPI_S_STATES_MAX+1) {
1745 	    if (new_state != old_state) {
1746 		*(u_int *)oidp->oid_arg1 = new_state;
1747 	    }
1748 	} else {
1749 	    error = EINVAL;
1750 	}
1751     }
1752     return(error);
1753 }
1754 
1755 #ifdef ACPI_DEBUG
1756 /*
1757  * Support for parsing debug options from the kernel environment.
1758  *
1759  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
1760  * by specifying the names of the bits in the debug.acpi.layer and
1761  * debug.acpi.level environment variables.  Bits may be unset by
1762  * prefixing the bit name with !.
1763  */
1764 struct debugtag
1765 {
1766     char	*name;
1767     UINT32	value;
1768 };
1769 
1770 static struct debugtag	dbg_layer[] = {
1771     {"ACPI_UTILITIES",		ACPI_UTILITIES},
1772     {"ACPI_HARDWARE",		ACPI_HARDWARE},
1773     {"ACPI_EVENTS",		ACPI_EVENTS},
1774     {"ACPI_TABLES",		ACPI_TABLES},
1775     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
1776     {"ACPI_PARSER",		ACPI_PARSER},
1777     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
1778     {"ACPI_EXECUTER",		ACPI_EXECUTER},
1779     {"ACPI_RESOURCES",		ACPI_RESOURCES},
1780     {"ACPI_DEBUGGER",		ACPI_DEBUGGER},
1781     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
1782 
1783     {"ACPI_BUS",		ACPI_BUS},
1784     {"ACPI_SYSTEM",		ACPI_SYSTEM},
1785     {"ACPI_POWER",		ACPI_POWER},
1786     {"ACPI_EC", 		ACPI_EC},
1787     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
1788     {"ACPI_BATTERY",		ACPI_BATTERY},
1789     {"ACPI_BUTTON",		ACPI_BUTTON},
1790     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
1791     {"ACPI_THERMAL",		ACPI_THERMAL},
1792     {"ACPI_FAN",		ACPI_FAN},
1793 
1794     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
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