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