xref: /freebsd/sys/dev/acpica/acpi.c (revision 99e8005137088aafb1350e23b113d69b01b0820f)
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 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 
46 #include <machine/clock.h>
47 
48 #include <machine/resource.h>
49 
50 #include "acpi.h"
51 
52 #include <dev/acpica/acpivar.h>
53 #include <dev/acpica/acpiio.h>
54 
55 MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
56 
57 /*
58  * Hooks for the ACPI CA debugging infrastructure
59  */
60 #define _COMPONENT	BUS_MANAGER
61 MODULE_NAME("ACPI")
62 
63 /*
64  * Character device
65  */
66 
67 static d_open_t		acpiopen;
68 static d_close_t	acpiclose;
69 static d_ioctl_t	acpiioctl;
70 
71 #define CDEV_MAJOR 152
72 static struct cdevsw acpi_cdevsw = {
73     acpiopen,
74     acpiclose,
75     noread,
76     nowrite,
77     acpiioctl,
78     nopoll,
79     nommap,
80     nostrategy,
81     "acpi",
82     CDEV_MAJOR,
83     nodump,
84     nopsize,
85     0
86 };
87 
88 static const char* sleep_state_names[] = {
89     "S0", "S1", "S2", "S3", "S4", "S4B", "S5" };
90 
91 static void	acpi_identify(driver_t *driver, device_t parent);
92 static int	acpi_probe(device_t dev);
93 static int	acpi_attach(device_t dev);
94 static device_t	acpi_add_child(device_t bus, int order, const char *name, int unit);
95 static int	acpi_print_resources(struct resource_list *rl, const char *name, int type,
96 				     const char *format);
97 static int	acpi_print_child(device_t bus, device_t child);
98 static int	acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result);
99 static int	acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value);
100 static int	acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start,
101 				  u_long count);
102 static int	acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp,
103 				  u_long *countp);
104 static struct resource *acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
105 					    u_long start, u_long end, u_long count, u_int flags);
106 static int	acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r);
107 
108 static void	acpi_probe_children(device_t bus);
109 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status);
110 
111 static void	acpi_shutdown_pre_sync(void *arg, int howto);
112 static void	acpi_shutdown_final(void *arg, int howto);
113 
114 static void	acpi_enable_fixed_events(struct acpi_softc *sc);
115 
116 #ifdef ACPI_DEBUG
117 static void	acpi_set_debugging(void);
118 #endif
119 
120 static void	acpi_system_eventhandler_sleep(void *arg, int state);
121 static void	acpi_system_eventhandler_wakeup(void *arg, int state);
122 static int	acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
123 
124 static device_method_t acpi_methods[] = {
125     /* Device interface */
126     DEVMETHOD(device_identify,		acpi_identify),
127     DEVMETHOD(device_probe,		acpi_probe),
128     DEVMETHOD(device_attach,		acpi_attach),
129     DEVMETHOD(device_shutdown,		bus_generic_shutdown),
130     DEVMETHOD(device_suspend,		bus_generic_suspend),
131     DEVMETHOD(device_resume,		bus_generic_resume),
132 
133     /* Bus interface */
134     DEVMETHOD(bus_add_child,		acpi_add_child),
135     DEVMETHOD(bus_print_child,		acpi_print_child),
136     DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
137     DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
138     DEVMETHOD(bus_set_resource,		acpi_set_resource),
139     DEVMETHOD(bus_get_resource,		acpi_get_resource),
140     DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
141     DEVMETHOD(bus_release_resource,	acpi_release_resource),
142     DEVMETHOD(bus_driver_added,		bus_generic_driver_added),
143     DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
144     DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
145     DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
146     DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
147 
148     {0, 0}
149 };
150 
151 static driver_t acpi_driver = {
152     "acpi",
153     acpi_methods,
154     sizeof(struct acpi_softc),
155 };
156 
157 devclass_t acpi_devclass;
158 DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, 0, 0);
159 
160 SYSCTL_INT(_debug, OID_AUTO, acpi_debug_layer, CTLFLAG_RW, &AcpiDbgLayer, 0, "");
161 SYSCTL_INT(_debug, OID_AUTO, acpi_debug_level, CTLFLAG_RW, &AcpiDbgLevel, 0, "");
162 
163 /*
164  * Detect ACPI, perform early initialisation
165  */
166 static void
167 acpi_identify(driver_t *driver, device_t parent)
168 {
169     device_t			child;
170     ACPI_PHYSICAL_ADDRESS	rsdp;
171     int				error;
172 #ifdef ENABLE_DEBUGGER
173     char			*debugpoint = getenv("debug.acpi.debugger");
174 #endif
175 
176     FUNCTION_TRACE(__FUNCTION__);
177 
178     if(!cold){
179 	    printf("Don't load this driver from userland!!\n");
180 	    return ;
181     }
182 
183     /*
184      * Make sure we're not being doubly invoked.
185      */
186     if (device_find_child(parent, "acpi", 0) != NULL)
187 	return_VOID;
188 
189 #ifdef ACPI_DEBUG
190     acpi_set_debugging();
191 #endif
192 
193     /*
194      * Start up ACPICA
195      */
196 #ifdef ENABLE_DEBUGGER
197     if (debugpoint && !strcmp(debugpoint, "init"))
198 	acpi_EnterDebugger();
199 #endif
200     if ((error = AcpiInitializeSubsystem()) != AE_OK) {
201 	printf("ACPI: initialisation failed: %s\n", acpi_strerror(error));
202 	return_VOID;
203     }
204 #ifdef ENABLE_DEBUGGER
205     if (debugpoint && !strcmp(debugpoint, "tables"))
206 	acpi_EnterDebugger();
207 #endif
208     if (((error = AcpiFindRootPointer(&rsdp)) != AE_OK) ||
209 	((error = AcpiLoadTables(rsdp)) != AE_OK)) {
210 	printf("ACPI: table load failed: %s\n", acpi_strerror(error));
211 	return_VOID;
212     }
213 
214     /*
215      * Attach the actual ACPI device.
216      */
217     if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
218 	    device_printf(parent, "ACPI: could not attach\n");
219 	    return_VOID;
220     }
221 }
222 
223 /*
224  * Fetch some descriptive data from ACPI to put in our attach message
225  */
226 static int
227 acpi_probe(device_t dev)
228 {
229     ACPI_TABLE_HEADER	th;
230     char		buf[20];
231     int			error;
232 
233     FUNCTION_TRACE(__FUNCTION__);
234 
235     if ((error = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th)) != AE_OK) {
236 	device_printf(dev, "couldn't get XSDT header: %s\n", acpi_strerror(error));
237 	return_VALUE(ENXIO);
238     }
239     sprintf(buf, "%.6s %.8s", th.OemId, th.OemTableId);
240     device_set_desc_copy(dev, buf);
241 
242     return_VALUE(0);
243 }
244 
245 static int
246 acpi_attach(device_t dev)
247 {
248     struct acpi_softc	*sc;
249     int			error;
250 #ifdef ENABLE_DEBUGGER
251     char		*debugpoint = getenv("debug.acpi.debugger");
252 #endif
253 
254     FUNCTION_TRACE(__FUNCTION__);
255 
256     sc = device_get_softc(dev);
257     bzero(sc, sizeof(*sc));
258     sc->acpi_dev = dev;
259 
260 #ifdef ENABLE_DEBUGGER
261     if (debugpoint && !strcmp(debugpoint, "spaces"))
262 	acpi_EnterDebugger();
263 #endif
264 
265     /*
266      * Install the default address space handlers.
267      */
268     if ((error = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
269 						ADDRESS_SPACE_SYSTEM_MEMORY,
270 						ACPI_DEFAULT_HANDLER,
271 						NULL, NULL)) != AE_OK) {
272 	device_printf(dev, "could not initialise SystemMemory handler: %s\n", acpi_strerror(error));
273 	return_VALUE(ENXIO);
274     }
275     if ((error = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
276 						ADDRESS_SPACE_SYSTEM_IO,
277 						ACPI_DEFAULT_HANDLER,
278 						NULL, NULL)) != AE_OK) {
279 	device_printf(dev, "could not initialise SystemIO handler: %s\n", acpi_strerror(error));
280 	return_VALUE(ENXIO);
281     }
282     if ((error = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
283 						ADDRESS_SPACE_PCI_CONFIG,
284 						ACPI_DEFAULT_HANDLER,
285 						NULL, NULL)) != AE_OK) {
286 	device_printf(dev, "could not initialise PciConfig handler: %s\n", acpi_strerror(error));
287 	return_VALUE(ENXIO);
288     }
289 
290     /*
291      * Bring ACPI fully online.
292      *
293      * Note that we request that device _STA and _INI methods not be run (ACPI_NO_DEVICE_INIT)
294      * and the final object initialisation pass be skipped (ACPI_NO_OBJECT_INIT).
295      *
296      * XXX We need to arrange for the object init pass after we have attached all our
297      *     child devices.
298      */
299 #ifdef ENABLE_DEBUGGER
300     if (debugpoint && !strcmp(debugpoint, "enable"))
301 	acpi_EnterDebugger();
302 #endif
303     if ((error = AcpiEnableSubsystem(ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT)) != AE_OK) {
304 	device_printf(dev, "could not enable ACPI: %s\n", acpi_strerror(error));
305 	return_VALUE(ENXIO);
306     }
307 
308     /*
309      * Setup our sysctl tree.
310      *
311      * XXX: This doesn't check to make sure that none of these fail.
312      */
313     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
314     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
315 			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
316 			       device_get_name(dev), CTLFLAG_RD, 0, "");
317     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
318 	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
319 	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
320     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
321 	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
322 	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
323     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
324 	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
325 	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
326 
327     /*
328      * Dispatch the default sleep state to devices.
329      * TBD: should be configured from userland policy manager.
330      */
331     sc->acpi_power_button_sx = ACPI_POWER_BUTTON_DEFAULT_SX;
332     sc->acpi_sleep_button_sx = ACPI_SLEEP_BUTTON_DEFAULT_SX;
333     sc->acpi_lid_switch_sx = ACPI_LID_SWITCH_DEFAULT_SX;
334 
335     acpi_enable_fixed_events(sc);
336 
337     /*
338      * Scan the namespace and attach/initialise children.
339      */
340 #ifdef ENABLE_DEBUGGER
341     if (debugpoint && !strcmp(debugpoint, "probe"))
342 	acpi_EnterDebugger();
343 #endif
344     if (!acpi_disabled("bus"))
345 	acpi_probe_children(dev);
346 
347     /*
348      * Register our shutdown handlers
349      */
350     EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc, SHUTDOWN_PRI_LAST);
351     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc, SHUTDOWN_PRI_LAST);
352 
353     /*
354      * Register our acpi event handlers.
355      * XXX should be configurable eg. via userland policy manager.
356      */
357     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep, sc, ACPI_EVENT_PRI_LAST);
358     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup, sc, ACPI_EVENT_PRI_LAST);
359 
360     /*
361      * Flag our initial states.
362      */
363     sc->acpi_enabled = 1;
364     sc->acpi_sstate = ACPI_STATE_S0;
365 
366     /*
367      * Create the control device
368      */
369     sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, 0, 5, 0660, "acpi");
370     sc->acpi_dev_t->si_drv1 = sc;
371 
372 #ifdef ENABLE_DEBUGGER
373     if (debugpoint && !strcmp(debugpoint, "running"))
374 	acpi_EnterDebugger();
375 #endif
376     return_VALUE(0);
377 }
378 
379 /*
380  * Handle a new device being added
381  */
382 static device_t
383 acpi_add_child(device_t bus, int order, const char *name, int unit)
384 {
385     struct acpi_device	*ad;
386     device_t		child;
387 
388     if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT)) == NULL)
389 	return(NULL);
390     bzero(ad, sizeof(*ad));
391 
392     resource_list_init(&ad->ad_rl);
393 
394     child = device_add_child_ordered(bus, order, name, unit);
395     if (child != NULL)
396 	device_set_ivars(child, ad);
397     return(child);
398 }
399 
400 /*
401  * Print child device resource usage
402  */
403 static int
404 acpi_print_resources(struct resource_list *rl, const char *name, int type, const char *format)
405 {
406     struct resource_list_entry	*rle;
407     int				printed, retval;
408 
409     printed = 0;
410     retval = 0;
411 
412     if (!SLIST_FIRST(rl))
413 	return(0);
414 
415     /* Yes, this is kinda cheating */
416     SLIST_FOREACH(rle, rl, link) {
417 	if (rle->type == type) {
418 	    if (printed == 0)
419 		retval += printf(" %s ", name);
420 	    else if (printed > 0)
421 		retval += printf(",");
422 	    printed++;
423 	    retval += printf(format, rle->start);
424 	    if (rle->count > 1) {
425 		retval += printf("-");
426 		retval += printf(format, rle->start +
427 				 rle->count - 1);
428 	    }
429 	}
430     }
431     return(retval);
432 }
433 
434 static int
435 acpi_print_child(device_t bus, device_t child)
436 {
437     struct acpi_device		*adev = device_get_ivars(child);
438     struct resource_list	*rl = &adev->ad_rl;
439     int retval = 0;
440 
441     retval += bus_print_child_header(bus, child);
442     retval += acpi_print_resources(rl, "port",  SYS_RES_IOPORT, "%#lx");
443     retval += acpi_print_resources(rl, "iomem", SYS_RES_MEMORY, "%#lx");
444     retval += acpi_print_resources(rl, "irq",   SYS_RES_IRQ,    "%ld");
445     retval += bus_print_child_footer(bus, child);
446 
447     return(retval);
448 }
449 
450 
451 /*
452  * Handle per-device ivars
453  */
454 static int
455 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
456 {
457     struct acpi_device	*ad;
458 
459     if ((ad = device_get_ivars(child)) == NULL) {
460 	printf("device has no ivars\n");
461 	return(ENOENT);
462     }
463 
464     switch(index) {
465 	/* ACPI ivars */
466     case ACPI_IVAR_HANDLE:
467 	*(ACPI_HANDLE *)result = ad->ad_handle;
468 	break;
469     case ACPI_IVAR_MAGIC:
470 	*(int *)result = ad->ad_magic;
471 	break;
472     case ACPI_IVAR_PRIVATE:
473 	*(void **)result = ad->ad_private;
474 	break;
475 
476     default:
477 	panic("bad ivar read request (%d)\n", index);
478 	return(ENOENT);
479     }
480     return(0);
481 }
482 
483 static int
484 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
485 {
486     struct acpi_device	*ad;
487 
488     if ((ad = device_get_ivars(child)) == NULL) {
489 	printf("device has no ivars\n");
490 	return(ENOENT);
491     }
492 
493     switch(index) {
494 	/* ACPI ivars */
495     case ACPI_IVAR_HANDLE:
496 	ad->ad_handle = (ACPI_HANDLE)value;
497 	break;
498     case ACPI_IVAR_MAGIC:
499 	ad->ad_magic = (int )value;
500 	break;
501     case ACPI_IVAR_PRIVATE:
502 	ad->ad_private = (void *)value;
503 	break;
504 
505     default:
506 	panic("bad ivar write request (%d)\n", index);
507 	return(ENOENT);
508     }
509     return(0);
510 }
511 
512 /*
513  * Handle child resource allocation/removal
514  */
515 static int
516 acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start, u_long count)
517 {
518     struct acpi_device		*ad = device_get_ivars(child);
519     struct resource_list	*rl = &ad->ad_rl;
520 
521     resource_list_add(rl, type, rid, start, start + count -1, count);
522 
523     return(0);
524 }
525 
526 static int
527 acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp, u_long *countp)
528 {
529     struct acpi_device		*ad = device_get_ivars(child);
530     struct resource_list	*rl = &ad->ad_rl;
531     struct resource_list_entry	*rle;
532 
533     rle = resource_list_find(rl, type, rid);
534     if (!rle)
535 	return(ENOENT);
536 
537     if (startp)
538 	*startp = rle->start;
539     if (countp)
540 	*countp = rle->count;
541 
542     return(0);
543 }
544 
545 static struct resource *
546 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
547 		    u_long start, u_long end, u_long count, u_int flags)
548 {
549     struct acpi_device *ad = device_get_ivars(child);
550     struct resource_list *rl = &ad->ad_rl;
551 
552     return(resource_list_alloc(rl, bus, child, type, rid, start, end, count, flags));
553 }
554 
555 static int
556 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
557 {
558     struct acpi_device *ad = device_get_ivars(child);
559     struct resource_list *rl = &ad->ad_rl;
560 
561     return(resource_list_release(rl, bus, child, type, rid, r));
562 }
563 
564 /*
565  * Scan relevant portions of the ACPI namespace and attach child devices.
566  *
567  * Note that we only expect to find devices in the \_TZ_, \_SI_ and \_SB_ scopes,
568  * and \_TZ_ becomes obsolete in the ACPI 2.0 spec.
569  */
570 static void
571 acpi_probe_children(device_t bus)
572 {
573     ACPI_HANDLE		parent;
574     static char		*scopes[] = {"\\_TZ_", "\\_SI", "\\_SB_", NULL};
575     int			i;
576 
577     FUNCTION_TRACE(__FUNCTION__);
578 
579     /*
580      * Create any static children by calling device identify methods.
581      */
582     DEBUG_PRINT(TRACE_OBJECTS, ("device identify routines\n"));
583     bus_generic_probe(bus);
584 
585     /*
586      * Scan the namespace and insert placeholders for all the devices that
587      * we find.
588      *
589      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
590      * we want to create nodes for all devices, not just those that are currently
591      * present. (This assumes that we don't want to create/remove devices as they
592      * appear, which might be smarter.)
593      */
594     DEBUG_PRINT(TRACE_OBJECTS, ("namespace scan\n"));
595     for (i = 0; scopes[i] != NULL; i++)
596 	if ((AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent)) == AE_OK)
597 	    AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child, bus, NULL);
598 
599     /*
600      * Scan all of the child devices we have created and let them probe/attach.
601      */
602     DEBUG_PRINT(TRACE_OBJECTS, ("first bus_generic_attach\n"));
603     bus_generic_attach(bus);
604 
605     /*
606      * Some of these children may have attached others as part of their attach
607      * process (eg. the root PCI bus driver), so rescan.
608      */
609     DEBUG_PRINT(TRACE_OBJECTS, ("second bus_generic_attach\n"));
610     bus_generic_attach(bus);
611 
612     return_VOID;
613 }
614 
615 /*
616  * Evaluate a child device and determine whether we might attach a device to
617  * it.
618  */
619 static ACPI_STATUS
620 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
621 {
622     ACPI_OBJECT_TYPE	type;
623     device_t		child, bus = (device_t)context;
624 
625     FUNCTION_TRACE(__FUNCTION__);
626 
627     /*
628      * Skip this device if we think we'll have trouble with it.
629      */
630     if (acpi_avoid(handle))
631 	return_ACPI_STATUS(AE_OK);
632 
633     if (AcpiGetType(handle, &type) == AE_OK) {
634 	switch(type) {
635 	case ACPI_TYPE_DEVICE:
636 	case ACPI_TYPE_PROCESSOR:
637 	case ACPI_TYPE_THERMAL:
638 	case ACPI_TYPE_POWER:
639 	    if (acpi_disabled("children"))
640 		break;
641 	    /*
642 	     * Create a placeholder device for this node.  Sort the placeholder
643 	     * so that the probe/attach passes will run breadth-first.
644 	     */
645 	    DEBUG_PRINT(TRACE_OBJECTS, ("scanning '%s'\n", acpi_name(handle)))
646 	    child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
647 	    acpi_set_handle(child, handle);
648 	    DEBUG_EXEC(device_probe_and_attach(child));
649 	    break;
650 	}
651     }
652     return_ACPI_STATUS(AE_OK);
653 }
654 
655 static void
656 acpi_shutdown_pre_sync(void *arg, int howto)
657 {
658     /*
659      * Disable all ACPI events before soft off, otherwise the system
660      * will be turned on again on some laptops.
661      *
662      * XXX this should probably be restricted to masking some events just
663      *     before powering down, since we may still need ACPI during the
664      *     shutdown process.
665      */
666     acpi_Disable((struct acpi_softc *)arg);
667 }
668 
669 static void
670 acpi_shutdown_final(void *arg, int howto)
671 {
672     ACPI_STATUS	status;
673 
674     if (howto & RB_POWEROFF) {
675 	printf("Power system off using ACPI...\n");
676 	if ((status = AcpiEnterSleepState(ACPI_STATE_S5)) != AE_OK) {
677 	    printf("ACPI power-off failed - %s\n", acpi_strerror(status));
678 	} else {
679 	    DELAY(1000000);
680 	    printf("ACPI power-off failed - timeout\n");
681 	}
682     }
683 }
684 
685 static void
686 acpi_enable_fixed_events(struct acpi_softc *sc)
687 {
688 	static int	first_time = 1;
689 #define MSGFORMAT "%s button is handled as a fixed feature programming model.\n"
690 
691 	/* Enable and clear fixed events and install handlers. */
692 	if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->PwrButton == 0) {
693 		AcpiEnableEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
694 		AcpiClearEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
695 		AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
696 		    acpi_eventhandler_power_button_for_sleep, sc);
697 		if (first_time) {
698 			device_printf(sc->acpi_dev, MSGFORMAT, "power");
699 		}
700 	}
701 	if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->SleepButton == 0) {
702 		AcpiEnableEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
703 		AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
704 		AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
705 		    acpi_eventhandler_sleep_button_for_sleep, sc);
706 		if (first_time) {
707 			device_printf(sc->acpi_dev, MSGFORMAT, "sleep");
708 		}
709 	}
710 
711 	first_time = 0;
712 }
713 
714 /*
715  * Match a HID string against a device
716  */
717 BOOLEAN
718 acpi_MatchHid(device_t dev, char *hid)
719 {
720     ACPI_HANDLE		h;
721     ACPI_DEVICE_INFO	devinfo;
722     ACPI_STATUS		error;
723 
724     if (hid == NULL)
725 	return(FALSE);
726     if ((h = acpi_get_handle(dev)) == NULL)
727 	return(FALSE);
728     if ((error = AcpiGetObjectInfo(h, &devinfo)) != AE_OK)
729 	return(FALSE);
730     if ((devinfo.Valid & ACPI_VALID_HID) && !strcmp(hid, devinfo.HardwareId))
731 	return(TRUE);
732     return(FALSE);
733 }
734 
735 /*
736  * Perform the tedious double-get procedure required for fetching something into
737  * an ACPI_BUFFER that has not been initialised.
738  */
739 ACPI_STATUS
740 acpi_GetIntoBuffer(ACPI_HANDLE handle, ACPI_STATUS (*func)(ACPI_HANDLE, ACPI_BUFFER *), ACPI_BUFFER *buf)
741 {
742     ACPI_STATUS	status;
743 
744     buf->Length = 0;
745     buf->Pointer = NULL;
746 
747     if ((status = func(handle, buf)) != AE_BUFFER_OVERFLOW)
748 	return(status);
749     if ((buf->Pointer = AcpiOsCallocate(buf->Length)) == NULL)
750 	return(AE_NO_MEMORY);
751     return(func(handle, buf));
752 }
753 
754 /*
755  * Allocate a buffer with a preset data size.
756  */
757 ACPI_BUFFER *
758 acpi_AllocBuffer(int size)
759 {
760     ACPI_BUFFER	*buf;
761 
762     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
763 	return(NULL);
764     buf->Length = size;
765     buf->Pointer = (void *)(buf + 1);
766     return(buf);
767 }
768 
769 static ACPI_STATUS __inline
770 acpi_wakeup(UINT8 state)
771 {
772 	UINT16			Count;
773 	ACPI_STATUS		Status;
774 	ACPI_OBJECT_LIST	Arg_list;
775 	ACPI_OBJECT		Arg;
776 	ACPI_OBJECT		Objects[3]; /* package plus 2 number objects */
777 	ACPI_BUFFER		ReturnBuffer;
778 
779 	FUNCTION_TRACE_U32(__FUNCTION__, state);
780 
781 	/* wait for the WAK_STS bit */
782 	Count = 0;
783 	while (!(AcpiHwRegisterBitAccess(ACPI_READ, ACPI_MTX_LOCK, WAK_STS))) {
784 		AcpiOsSleepUsec(1000);
785 		/*
786 		 * Some BIOSes don't set WAK_STS at all,
787 		 * give up waiting for wakeup if we time out.
788 		 */
789 		if (Count > 1000) {
790 			break;	/* giving up */
791 		}
792 		Count++;
793 	}
794 
795 	/*
796 	 * Evaluate the _WAK method
797 	 */
798 	MEMSET(&Arg_list, 0, sizeof(Arg_list));
799 	Arg_list.Count = 1;
800 	Arg_list.Pointer = &Arg;
801 
802 	MEMSET(&Arg, 0, sizeof(Arg));
803 	Arg.Type = ACPI_TYPE_INTEGER;
804 	Arg.Integer.Value = state;
805 
806 	/* Set up _WAK result code buffer */
807 	MEMSET(Objects, 0, sizeof(Objects));
808 	ReturnBuffer.Length = sizeof(Objects);
809 	ReturnBuffer.Pointer = Objects;
810 
811 	AcpiEvaluateObject (NULL, "\\_WAK", &Arg_list, &ReturnBuffer);
812 
813 	Status = AE_OK;
814 	/* Check result code for _WAK */
815 	if (Objects[0].Type != ACPI_TYPE_PACKAGE ||
816 	    Objects[1].Type != ACPI_TYPE_INTEGER  ||
817 	    Objects[2].Type != ACPI_TYPE_INTEGER) {
818 		/*
819 		 * In many BIOSes, _WAK doesn't return a result code.
820 		 * We don't need to worry about it too much :-).
821 		 */
822 		DEBUG_PRINT (ACPI_INFO,
823 		    ("acpi_wakeup: _WAK result code is corrupted, "
824 		     "but should be OK.\n"));
825 	} else {
826 		/* evaluate status code */
827 		switch (Objects[1].Integer.Value) {
828 		case 0x00000001:
829 			DEBUG_PRINT (ACPI_ERROR,
830 			    ("acpi_wakeup: Wake was signaled "
831 			     "but failed due to lack of power.\n"));
832 			Status = AE_ERROR;
833 			break;
834 
835 		case 0x00000002:
836 			DEBUG_PRINT (ACPI_ERROR,
837 			    ("acpi_wakeup: Wake was signaled "
838 			     "but failed due to thermal condition.\n"));
839 			Status = AE_ERROR;
840 			break;
841 		}
842 		/* evaluate PSS code */
843 		if (Objects[2].Integer.Value == 0) {
844 			DEBUG_PRINT (ACPI_ERROR,
845 			    ("acpi_wakeup: The targeted S-state "
846 			     "was not entered because of too much current "
847 			     "being drawn from the power supply.\n"));
848 			Status = AE_ERROR;
849 		}
850 	}
851 
852 	return_ACPI_STATUS(Status);
853 }
854 
855 /*
856  * Set the system sleep state
857  *
858  * Currently we only support S1 and S5
859  */
860 ACPI_STATUS
861 acpi_SetSleepState(struct acpi_softc *sc, int state)
862 {
863     ACPI_STATUS	status = AE_OK;
864 
865     FUNCTION_TRACE_U32(__FUNCTION__, state);
866 
867     switch (state) {
868     case ACPI_STATE_S0:	/* XXX only for testing */
869 	status = AcpiEnterSleepState((UINT8)state);
870 	if (status != AE_OK) {
871 	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", acpi_strerror(status));
872 	}
873 	break;
874 
875     case ACPI_STATE_S1:
876 	/*
877 	 * Inform all devices that we are going to sleep.
878 	 */
879 	if (DEVICE_SUSPEND(root_bus) != 0) {
880 	    /*
881 	     * Re-wake the system.
882 	     *
883 	     * XXX note that a better two-pass approach with a 'veto' pass
884 	     *     followed by a "real thing" pass would be better, but the
885 	     *     current bus interface does not provide for this.
886 	     */
887 	    DEVICE_RESUME(root_bus);
888 	    return_ACPI_STATUS(AE_ERROR);
889 	}
890 	sc->acpi_sstate = state;
891 	status = AcpiEnterSleepState((UINT8)state);
892 	if (status != AE_OK) {
893 	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", acpi_strerror(status));
894 	    break;
895 	}
896 	acpi_wakeup((UINT8)state);
897 	DEVICE_RESUME(root_bus);
898 	sc->acpi_sstate = ACPI_STATE_S0;
899 	acpi_enable_fixed_events(sc);
900 	break;
901 
902     case ACPI_STATE_S5:
903 	/*
904 	 * Shut down cleanly and power off.  This will call us back through the
905 	 * shutdown handlers.
906 	 */
907 	shutdown_nice(RB_POWEROFF);
908 	break;
909 
910     default:
911 	status = AE_BAD_PARAMETER;
912 	break;
913     }
914     return_ACPI_STATUS(status);
915 }
916 
917 /*
918  * Enable/Disable ACPI
919  */
920 ACPI_STATUS
921 acpi_Enable(struct acpi_softc *sc)
922 {
923     ACPI_STATUS	status;
924     u_int32_t	flags;
925 
926     FUNCTION_TRACE(__FUNCTION__);
927 
928     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
929             ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
930     if (!sc->acpi_enabled) {
931 	status = AcpiEnableSubsystem(flags);
932     } else {
933 	status = AE_OK;
934     }
935     if (status == AE_OK)
936 	sc->acpi_enabled = 1;
937     return_ACPI_STATUS(status);
938 }
939 
940 ACPI_STATUS
941 acpi_Disable(struct acpi_softc *sc)
942 {
943     ACPI_STATUS	status;
944 
945     FUNCTION_TRACE(__FUNCTION__);
946 
947     if (sc->acpi_enabled) {
948 	status = AcpiDisable();
949     } else {
950 	status = AE_OK;
951     }
952     if (status == AE_OK)
953 	sc->acpi_enabled = 0;
954     return_ACPI_STATUS(status);
955 }
956 
957 /*
958  * Returns true if the device is actually present and should
959  * be attached to.  This requires the present, enabled, UI-visible
960  * and diagnostics-passed bits to be set.
961  */
962 BOOLEAN
963 acpi_DeviceIsPresent(device_t dev)
964 {
965     ACPI_HANDLE		h;
966     ACPI_DEVICE_INFO	devinfo;
967     ACPI_STATUS		error;
968 
969     if ((h = acpi_get_handle(dev)) == NULL)
970 	return(FALSE);
971     if ((error = AcpiGetObjectInfo(h, &devinfo)) != AE_OK)
972 	return(FALSE);
973     if ((devinfo.Valid & ACPI_VALID_HID) && (devinfo.CurrentStatus & 0xf))
974 	return(TRUE);
975     return(FALSE);
976 }
977 
978 /*
979  * Evaluate a path that should return an integer.
980  */
981 ACPI_STATUS
982 acpi_EvaluateInteger(ACPI_HANDLE handle, char *path, int *number)
983 {
984     ACPI_STATUS	error;
985     ACPI_BUFFER	buf;
986     ACPI_OBJECT	param;
987 
988     if (handle == NULL)
989 	handle = ACPI_ROOT_OBJECT;
990     buf.Pointer = &param;
991     buf.Length = sizeof(param);
992     if ((error = AcpiEvaluateObject(handle, path, NULL, &buf)) == AE_OK) {
993 	if (param.Type == ACPI_TYPE_INTEGER) {
994 	    *number = param.Integer.Value;
995 	} else {
996 	    error = AE_TYPE;
997 	}
998     }
999     return(error);
1000 }
1001 
1002 /*
1003  * ACPI Event Handlers
1004  */
1005 
1006 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1007 
1008 static void
1009 acpi_system_eventhandler_sleep(void *arg, int state)
1010 {
1011     FUNCTION_TRACE_U32(__FUNCTION__, state);
1012 
1013     if (state >= ACPI_STATE_S0 && state <= ACPI_STATE_S5)
1014 	acpi_SetSleepState((struct acpi_softc *)arg, state);
1015     return_VOID;
1016 }
1017 
1018 static void
1019 acpi_system_eventhandler_wakeup(void *arg, int state)
1020 {
1021     FUNCTION_TRACE_U32(__FUNCTION__, state);
1022 
1023     /* Well, what to do? :-) */
1024 
1025     return_VOID;
1026 }
1027 
1028 /*
1029  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1030  */
1031 UINT32
1032 acpi_eventhandler_power_button_for_sleep(void *context)
1033 {
1034     struct acpi_softc	*sc = (struct acpi_softc *)context;
1035 
1036     FUNCTION_TRACE(__FUNCTION__);
1037 
1038     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1039 
1040     return_VALUE(INTERRUPT_HANDLED);
1041 }
1042 
1043 UINT32
1044 acpi_eventhandler_power_button_for_wakeup(void *context)
1045 {
1046     struct acpi_softc	*sc = (struct acpi_softc *)context;
1047 
1048     FUNCTION_TRACE(__FUNCTION__);
1049 
1050     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1051 
1052     return_VALUE(INTERRUPT_HANDLED);
1053 }
1054 
1055 UINT32
1056 acpi_eventhandler_sleep_button_for_sleep(void *context)
1057 {
1058     struct acpi_softc	*sc = (struct acpi_softc *)context;
1059 
1060     FUNCTION_TRACE(__FUNCTION__);
1061 
1062     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1063 
1064     return_VALUE(INTERRUPT_HANDLED);
1065 }
1066 
1067 UINT32
1068 acpi_eventhandler_sleep_button_for_wakeup(void *context)
1069 {
1070     struct acpi_softc	*sc = (struct acpi_softc *)context;
1071 
1072     FUNCTION_TRACE(__FUNCTION__);
1073 
1074     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1075 
1076     return_VALUE(INTERRUPT_HANDLED);
1077 }
1078 
1079 /*
1080  * XXX This is kinda ugly, and should not be here.
1081  */
1082 struct acpi_staticbuf {
1083     ACPI_BUFFER	buffer;
1084     char	data[512];
1085 };
1086 
1087 char *
1088 acpi_strerror(ACPI_STATUS excep)
1089 {
1090     static struct acpi_staticbuf	buf;
1091 
1092     buf.buffer.Length = 512;
1093     buf.buffer.Pointer = &buf.data[0];
1094 
1095     if (AcpiFormatException(excep, &buf.buffer) == AE_OK)
1096 	return(buf.buffer.Pointer);
1097     return("(error formatting exception)");
1098 }
1099 
1100 char *
1101 acpi_name(ACPI_HANDLE handle)
1102 {
1103     static struct acpi_staticbuf	buf;
1104 
1105     buf.buffer.Length = 512;
1106     buf.buffer.Pointer = &buf.data[0];
1107 
1108     if (AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer) == AE_OK)
1109 	return(buf.buffer.Pointer);
1110     return("(unknown path)");
1111 }
1112 
1113 /*
1114  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1115  * parts of the namespace.
1116  */
1117 int
1118 acpi_avoid(ACPI_HANDLE handle)
1119 {
1120     char	*cp, *np;
1121     int		len;
1122 
1123     np = acpi_name(handle);
1124     if (*np == '\\')
1125 	np++;
1126     if ((cp = getenv("debug.acpi.avoid")) == NULL)
1127 	return(0);
1128 
1129     /* scan the avoid list checking for a match */
1130     for (;;) {
1131 	while ((*cp != 0) && isspace(*cp))
1132 	    cp++;
1133 	if (*cp == 0)
1134 	    break;
1135 	len = 0;
1136 	while ((cp[len] != 0) && !isspace(cp[len]))
1137 	    len++;
1138 	if (!strncmp(cp, np, len)) {
1139 	    DEBUG_PRINT(TRACE_OBJECTS, ("avoiding '%s'\n", np));
1140 	    return(1);
1141 	}
1142 	cp += len;
1143     }
1144     return(0);
1145 }
1146 
1147 /*
1148  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1149  */
1150 int
1151 acpi_disabled(char *subsys)
1152 {
1153     char	*cp;
1154     int		len;
1155 
1156     if ((cp = getenv("debug.acpi.disable")) == NULL)
1157 	return(0);
1158     if (!strcmp(cp, "all"))
1159 	return(1);
1160 
1161     /* scan the disable list checking for a match */
1162     for (;;) {
1163 	while ((*cp != 0) && isspace(*cp))
1164 	    cp++;
1165 	if (*cp == 0)
1166 	    break;
1167 	len = 0;
1168 	while ((cp[len] != 0) && !isspace(cp[len]))
1169 	    len++;
1170 	if (!strncmp(cp, subsys, len)) {
1171 	    DEBUG_PRINT(TRACE_OBJECTS, ("disabled '%s'\n", subsys));
1172 	    return(1);
1173 	}
1174 	cp += len;
1175     }
1176     return(0);
1177 }
1178 
1179 /*
1180  * Control interface.
1181  *
1182  * We multiplex ioctls for all participating ACPI devices here.  Individual
1183  * drivers wanting to be accessible via /dev/acpi should use the register/deregister
1184  * interface to make their handlers visible.
1185  */
1186 struct acpi_ioctl_hook
1187 {
1188     TAILQ_ENTRY(acpi_ioctl_hook)	link;
1189     u_long				cmd;
1190     int					(* fn)(u_long cmd, caddr_t addr, void *arg);
1191     void				*arg;
1192 };
1193 
1194 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
1195 static int				acpi_ioctl_hooks_initted;
1196 
1197 /*
1198  * Register an ioctl handler.
1199  */
1200 int
1201 acpi_register_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg), void *arg)
1202 {
1203     struct acpi_ioctl_hook	*hp;
1204 
1205     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
1206 	return(ENOMEM);
1207     hp->cmd = cmd;
1208     hp->fn = fn;
1209     hp->arg = arg;
1210     if (acpi_ioctl_hooks_initted == 0) {
1211 	TAILQ_INIT(&acpi_ioctl_hooks);
1212 	acpi_ioctl_hooks_initted = 1;
1213     }
1214     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
1215     return(0);
1216 }
1217 
1218 /*
1219  * Deregister an ioctl handler.
1220  */
1221 void
1222 acpi_deregister_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg))
1223 {
1224     struct acpi_ioctl_hook	*hp;
1225 
1226     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
1227 	if ((hp->cmd == cmd) && (hp->fn == fn))
1228 	    break;
1229 
1230     if (hp != NULL) {
1231 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
1232 	free(hp, M_ACPIDEV);
1233     }
1234 }
1235 
1236 static int
1237 acpiopen(dev_t dev, int flag, int fmt, struct proc *p)
1238 {
1239     return(0);
1240 }
1241 
1242 static int
1243 acpiclose(dev_t dev, int flag, int fmt, struct proc *p)
1244 {
1245     return(0);
1246 }
1247 
1248 static int
1249 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1250 {
1251     struct acpi_softc		*sc;
1252     struct acpi_ioctl_hook	*hp;
1253     int				error, xerror, state;
1254 
1255     error = state = 0;
1256     sc = dev->si_drv1;
1257 
1258     /*
1259      * Scan the list of registered ioctls, looking for handlers.
1260      */
1261     if (acpi_ioctl_hooks_initted) {
1262 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
1263 	    if (hp->cmd == cmd) {
1264 		xerror = hp->fn(cmd, addr, hp->arg);
1265 		if (xerror != 0)
1266 		    error = xerror;
1267 		goto out;
1268 	    }
1269 	}
1270     }
1271 
1272     /*
1273      * Core system ioctls.
1274      */
1275     switch (cmd) {
1276     case ACPIIO_ENABLE:
1277 	if (ACPI_FAILURE(acpi_Enable(sc)))
1278 	    error = ENXIO;
1279 	break;
1280 
1281     case ACPIIO_DISABLE:
1282 	if (ACPI_FAILURE(acpi_Disable(sc)))
1283 	    error = ENXIO;
1284 	break;
1285 
1286     case ACPIIO_SETSLPSTATE:
1287 	if (!sc->acpi_enabled) {
1288 	    error = ENXIO;
1289 	    break;
1290 	}
1291 	state = *(int *)addr;
1292 	if (state >= ACPI_STATE_S0  && state <= ACPI_STATE_S5) {
1293 	    acpi_SetSleepState(sc, state);
1294 	} else {
1295 	    error = EINVAL;
1296 	}
1297 	break;
1298 
1299     default:
1300 	if (error == 0)
1301 	    error = EINVAL;
1302 	break;
1303     }
1304 
1305 out:
1306     return(error);
1307 }
1308 
1309 static int
1310 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
1311 {
1312     char sleep_state[10];
1313     int error;
1314     u_int new_state, old_state;
1315 
1316     old_state = *(u_int *)oidp->oid_arg1;
1317     if (old_state > ACPI_STATE_S5)
1318 	strcpy(sleep_state, "unknown");
1319     else
1320 	strncpy(sleep_state, sleep_state_names[old_state],
1321 	    sizeof(sleep_state_names[old_state]));
1322     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
1323     if (error == 0 && req->newptr != NULL) {
1324 	for (new_state = ACPI_STATE_S0; new_state <= ACPI_STATE_S5; new_state++)
1325 	    if (strncmp(sleep_state, sleep_state_names[new_state],
1326 		sizeof(sleep_state)) == 0)
1327 		break;
1328 	if (new_state != old_state && new_state <= ACPI_STATE_S5)
1329 	    *(u_int *)oidp->oid_arg1 = new_state;
1330 	else
1331 	    error = EINVAL;
1332     }
1333     return(error);
1334 }
1335 
1336 #ifdef ACPI_DEBUG
1337 /*
1338  * Support for parsing debug options from the kernel environment.
1339  *
1340  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
1341  * by specifying the names of the bits in the debug.acpi.layer and
1342  * debug.acpi.level environment variables.  Bits may be unset by
1343  * prefixing the bit name with !.
1344  */
1345 struct debugtag
1346 {
1347     char	*name;
1348     UINT32	value;
1349 };
1350 
1351 static struct debugtag	dbg_layer[] = {
1352     {"GLOBAL",			0x00000001},
1353     {"COMMON",			0x00000002},
1354     {"PARSER",			0x00000004},
1355     {"DISPATCHER",		0x00000008},
1356     {"INTERPRETER",		0x00000010},
1357     {"NAMESPACE",		0x00000020},
1358     {"RESOURCE_MANAGER",	0x00000040},
1359     {"TABLE_MANAGER",		0x00000080},
1360     {"EVENT_HANDLING",		0x00000100},
1361     {"HARDWARE",		0x00000200},
1362     {"MISCELLANEOUS",		0x00000400},
1363     {"OS_DEPENDENT",		0x00000800},
1364     {"BUS_MANAGER",		0x00001000},
1365     {"PROCESSOR_CONTROL",	0x00002000},
1366     {"SYSTEM_CONTROL",		0x00004000},
1367     {"THERMAL_CONTROL",		0x00008000},
1368     {"POWER_CONTROL",		0x00010000},
1369     {"EMBEDDED_CONTROLLER",	0x00020000},
1370     {"BATTERY",			0x00040000},
1371     {"DEBUGGER",		0x00100000},
1372     {"ALL_COMPONENTS",		0x001FFFFF},
1373     {NULL, 0}
1374 };
1375 
1376 static struct debugtag dbg_level[] = {
1377     {"ACPI_OK",                     0x00000001},
1378     {"ACPI_INFO",                   0x00000002},
1379     {"ACPI_WARN",                   0x00000004},
1380     {"ACPI_ERROR",                  0x00000008},
1381     {"ACPI_FATAL",                  0x00000010},
1382     {"ACPI_DEBUG_OBJECT",           0x00000020},
1383     {"ACPI_ALL",                    0x0000003F},
1384     {"TRACE_PARSE",                 0x00000100},
1385     {"TRACE_DISPATCH",              0x00000200},
1386     {"TRACE_LOAD",                  0x00000400},
1387     {"TRACE_EXEC",                  0x00000800},
1388     {"TRACE_NAMES",                 0x00001000},
1389     {"TRACE_OPREGION",              0x00002000},
1390     {"TRACE_BFIELD",                0x00004000},
1391     {"TRACE_TRASH",                 0x00008000},
1392     {"TRACE_TABLES",                0x00010000},
1393     {"TRACE_FUNCTIONS",             0x00020000},
1394     {"TRACE_VALUES",                0x00040000},
1395     {"TRACE_OBJECTS",               0x00080000},
1396     {"TRACE_ALLOCATIONS",           0x00100000},
1397     {"TRACE_RESOURCES",             0x00200000},
1398     {"TRACE_IO",                    0x00400000},
1399     {"TRACE_INTERRUPTS",            0x00800000},
1400     {"TRACE_USER_REQUESTS",         0x01000000},
1401     {"TRACE_PACKAGE",               0x02000000},
1402     {"TRACE_MUTEX",                 0x04000000},
1403     {"TRACE_ALL",                   0x0FFFFF00},
1404     {"VERBOSE_AML_DISASSEMBLE",     0x10000000},
1405     {"VERBOSE_INFO",                0x20000000},
1406     {"VERBOSE_TABLES",              0x40000000},
1407     {"VERBOSE_EVENTS",              0x80000000},
1408     {"VERBOSE_ALL",                 0xF0000000},
1409     {NULL, 0}
1410 };
1411 
1412 static void
1413 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
1414 {
1415     char	*ep;
1416     int		i, l;
1417     int		set;
1418 
1419     while (*cp) {
1420 	if (isspace(*cp)) {
1421 	    cp++;
1422 	    continue;
1423 	}
1424 	ep = cp;
1425 	while (*ep && !isspace(*ep))
1426 	    ep++;
1427 	if (*cp == '!') {
1428 	    set = 0;
1429 	    cp++;
1430 	    if (cp == ep)
1431 		continue;
1432 	} else {
1433 	    set = 1;
1434 	}
1435 	l = ep - cp;
1436 	for (i = 0; tag[i].name != NULL; i++) {
1437 	    if (!strncmp(cp, tag[i].name, l)) {
1438 		if (set) {
1439 		    *flag |= tag[i].value;
1440 		} else {
1441 		    *flag &= ~tag[i].value;
1442 		}
1443 		printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
1444 	    }
1445 	}
1446 	cp = ep;
1447     }
1448 }
1449 
1450 static void
1451 acpi_set_debugging(void)
1452 {
1453     char	*cp;
1454 
1455     AcpiDbgLayer = 0;
1456     AcpiDbgLevel = 0;
1457     if ((cp = getenv("debug.acpi.layer")) != NULL)
1458 	acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
1459     if ((cp = getenv("debug.acpi.level")) != NULL)
1460 	acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
1461 
1462     printf("ACPI debug layer 0x%x  debug level 0x%x\n", AcpiDbgLayer, AcpiDbgLevel);
1463 }
1464 #endif
1465