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