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