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