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