acpi.c revision 129783
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 129783 2004-05-27 18:38:45Z njl $
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/fcntl.h>
37#include <sys/malloc.h>
38#include <sys/bus.h>
39#include <sys/conf.h>
40#include <sys/ioccom.h>
41#include <sys/reboot.h>
42#include <sys/sysctl.h>
43#include <sys/ctype.h>
44#include <sys/linker.h>
45#include <sys/power.h>
46#include <sys/sbuf.h>
47#include <sys/smp.h>
48
49#include <machine/clock.h>
50#include <machine/resource.h>
51#include <machine/bus.h>
52#include <sys/rman.h>
53#include <isa/isavar.h>
54
55#include "acpi.h"
56#include <dev/acpica/acpivar.h>
57#include <dev/acpica/acpiio.h>
58#include <contrib/dev/acpica/acnamesp.h>
59
60MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
61
62/* Hooks for the ACPI CA debugging infrastructure */
63#define _COMPONENT	ACPI_BUS
64ACPI_MODULE_NAME("ACPI")
65
66static d_open_t		acpiopen;
67static d_close_t	acpiclose;
68static d_ioctl_t	acpiioctl;
69
70static struct cdevsw acpi_cdevsw = {
71	.d_version =	D_VERSION,
72	.d_flags =	D_NEEDGIANT,
73	.d_open =	acpiopen,
74	.d_close =	acpiclose,
75	.d_ioctl =	acpiioctl,
76	.d_name =	"acpi",
77};
78
79#if __FreeBSD_version >= 500000
80struct mtx	acpi_mutex;
81#endif
82
83struct acpi_quirks {
84    char	*OemId;
85    uint32_t	OemRevision;
86    char	*value;
87};
88
89#define ACPI_OEM_REV_ANY	0
90
91static struct acpi_quirks acpi_quirks_table[] = {
92#ifdef notyet
93    /* Bad PCI routing table.  Used on some SuperMicro boards. */
94    { "PTLTD ", 0x06040000, "pci_link" },
95#endif
96
97    { NULL, 0, NULL }
98};
99
100static int	acpi_modevent(struct module *mod, int event, void *junk);
101static void	acpi_identify(driver_t *driver, device_t parent);
102static int	acpi_probe(device_t dev);
103static int	acpi_attach(device_t dev);
104static void	acpi_quirks_set(void);
105static device_t	acpi_add_child(device_t bus, int order, const char *name,
106			int unit);
107static int	acpi_print_child(device_t bus, device_t child);
108static int	acpi_read_ivar(device_t dev, device_t child, int index,
109			uintptr_t *result);
110static int	acpi_write_ivar(device_t dev, device_t child, int index,
111			uintptr_t value);
112static int	acpi_set_resource(device_t dev, device_t child, int type,
113			int rid, u_long start, u_long count);
114static int	acpi_get_resource(device_t dev, device_t child, int type,
115			int rid, u_long *startp, u_long *countp);
116static struct resource *acpi_alloc_resource(device_t bus, device_t child,
117			int type, int *rid, u_long start, u_long end,
118			u_long count, u_int flags);
119static int	acpi_release_resource(device_t bus, device_t child, int type,
120			int rid, struct resource *r);
121static uint32_t	acpi_isa_get_logicalid(device_t dev);
122static int	acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
123static int	acpi_isa_pnp_probe(device_t bus, device_t child,
124			struct isa_pnp_id *ids);
125static void	acpi_probe_children(device_t bus);
126static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
127			void *context, void **status);
128static void	acpi_shutdown_pre_sync(void *arg, int howto);
129static void	acpi_shutdown_final(void *arg, int howto);
130static void	acpi_shutdown_poweroff(void *arg);
131static void	acpi_enable_fixed_events(struct acpi_softc *sc);
132static int	acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw);
133static ACPI_STATUS acpi_wake_limit(ACPI_HANDLE h, UINT32 level, void *context,
134		    void **status);
135static int	acpi_wake_limit_walk(int sstate);
136static void	acpi_system_eventhandler_sleep(void *arg, int state);
137static void	acpi_system_eventhandler_wakeup(void *arg, int state);
138static int	acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
139static int	acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
140static int	acpi_pm_func(u_long cmd, void *arg, ...);
141static int	acpi_child_location_str_method(device_t acdev, device_t child,
142					       char *buf, size_t buflen);
143static int	acpi_child_pnpinfo_str_method(device_t acdev, device_t child,
144					      char *buf, size_t buflen);
145
146static device_method_t acpi_methods[] = {
147    /* Device interface */
148    DEVMETHOD(device_identify,		acpi_identify),
149    DEVMETHOD(device_probe,		acpi_probe),
150    DEVMETHOD(device_attach,		acpi_attach),
151    DEVMETHOD(device_detach,		bus_generic_detach),
152    DEVMETHOD(device_shutdown,		bus_generic_shutdown),
153    DEVMETHOD(device_suspend,		bus_generic_suspend),
154    DEVMETHOD(device_resume,		bus_generic_resume),
155
156    /* Bus interface */
157    DEVMETHOD(bus_add_child,		acpi_add_child),
158    DEVMETHOD(bus_print_child,		acpi_print_child),
159    DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
160    DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
161    DEVMETHOD(bus_set_resource,		acpi_set_resource),
162    DEVMETHOD(bus_get_resource,		acpi_get_resource),
163    DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
164    DEVMETHOD(bus_release_resource,	acpi_release_resource),
165    DEVMETHOD(bus_child_pnpinfo_str,	acpi_child_pnpinfo_str_method),
166    DEVMETHOD(bus_child_location_str,	acpi_child_location_str_method),
167    DEVMETHOD(bus_driver_added,		bus_generic_driver_added),
168    DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
169    DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
170    DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
171    DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
172
173    /* ISA emulation */
174    DEVMETHOD(isa_pnp_probe,		acpi_isa_pnp_probe),
175
176    {0, 0}
177};
178
179static driver_t acpi_driver = {
180    "acpi",
181    acpi_methods,
182    sizeof(struct acpi_softc),
183};
184
185static devclass_t acpi_devclass;
186DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
187MODULE_VERSION(acpi, 1);
188
189static const char* sleep_state_names[] = {
190    "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
191
192SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RW, NULL, "ACPI debugging");
193static char acpi_ca_version[12];
194SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
195	      acpi_ca_version, 0, "Version of Intel ACPI-CA");
196
197/*
198 * Allow override of whether methods execute in parallel or not.
199 * Enable this for serial behavior, which fixes "AE_ALREADY_EXISTS"
200 * errors for AML that really can't handle parallel method execution.
201 * It is off by default since this breaks recursive methods and
202 * some IBMs use such code.
203 */
204static int acpi_serialize_methods;
205TUNABLE_INT("hw.acpi.serialize_methods", &acpi_serialize_methods);
206
207/*
208 * ACPI can only be loaded as a module by the loader; activating it after
209 * system bootstrap time is not useful, and can be fatal to the system.
210 * It also cannot be unloaded, since the entire system bus heirarchy hangs
211 * off it.
212 */
213static int
214acpi_modevent(struct module *mod, int event, void *junk)
215{
216    switch(event) {
217    case MOD_LOAD:
218	if (!cold) {
219	    printf("The ACPI driver cannot be loaded after boot.\n");
220	    return (EPERM);
221	}
222	break;
223    case MOD_UNLOAD:
224	if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
225	    return (EBUSY);
226	break;
227    default:
228	break;
229    }
230    return (0);
231}
232
233/*
234 * Perform early initialization.
235 */
236ACPI_STATUS
237acpi_Startup(void)
238{
239#ifdef ACPI_DEBUGGER
240    char *debugpoint;
241#endif
242    static int error, started = 0;
243
244    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
245
246    if (started)
247	return_VALUE (error);
248    started = 1;
249
250#if __FreeBSD_version >= 500000
251    /* Initialise the ACPI mutex */
252    mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
253#endif
254
255    /*
256     * Set the globals from our tunables.  This is needed because ACPI-CA
257     * uses UINT8 for some values and we have no tunable_byte.
258     */
259    AcpiGbl_AllMethodsSerialized = (UINT8)acpi_serialize_methods;
260
261    /* Start up the ACPI CA subsystem. */
262#ifdef ACPI_DEBUGGER
263    debugpoint = getenv("debug.acpi.debugger");
264    if (debugpoint) {
265	if (!strcmp(debugpoint, "init"))
266	    acpi_EnterDebugger();
267	freeenv(debugpoint);
268    }
269#endif
270    if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
271	printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
272	return_VALUE (error);
273    }
274#ifdef ACPI_DEBUGGER
275    debugpoint = getenv("debug.acpi.debugger");
276    if (debugpoint) {
277	if (!strcmp(debugpoint, "tables"))
278	    acpi_EnterDebugger();
279	freeenv(debugpoint);
280    }
281#endif
282
283    if (ACPI_FAILURE(error = AcpiLoadTables())) {
284	printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
285	return_VALUE(error);
286    }
287
288    /* Set up any quirks we have for this XSDT. */
289    acpi_quirks_set();
290    if (acpi_disabled("acpi"))
291	return_VALUE (AE_ERROR);
292
293    return_VALUE (AE_OK);
294}
295
296/*
297 * Detect ACPI, perform early initialisation
298 */
299static void
300acpi_identify(driver_t *driver, device_t parent)
301{
302    device_t	child;
303
304    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
305
306    if (!cold)
307	return_VOID;
308
309    /* Check that we haven't been disabled with a hint. */
310    if (resource_disabled("acpi", 0))
311	return_VOID;
312
313    /* Make sure we're not being doubly invoked. */
314    if (device_find_child(parent, "acpi", 0) != NULL)
315	return_VOID;
316
317    /* Initialize ACPI-CA. */
318    if (ACPI_FAILURE(acpi_Startup()))
319	return_VOID;
320
321    snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%#x", ACPI_CA_VERSION);
322
323    /* Attach the actual ACPI device. */
324    if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
325	device_printf(parent, "ACPI: could not attach\n");
326	return_VOID;
327    }
328}
329
330/*
331 * Fetch some descriptive data from ACPI to put in our attach message
332 */
333static int
334acpi_probe(device_t dev)
335{
336    ACPI_TABLE_HEADER	th;
337    char		buf[20];
338    int			error;
339    struct sbuf		sb;
340    ACPI_STATUS		status;
341    ACPI_LOCK_DECL;
342
343    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
344
345    if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
346	power_pm_get_type() != POWER_PM_TYPE_ACPI) {
347
348	device_printf(dev, "Other PM system enabled.\n");
349	return_VALUE(ENXIO);
350    }
351
352    ACPI_LOCK;
353
354    if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
355	device_printf(dev, "couldn't get XSDT header: %s\n",
356		      AcpiFormatException(status));
357	error = ENXIO;
358    } else {
359	sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
360	sbuf_bcat(&sb, th.OemId, 6);
361	sbuf_trim(&sb);
362	sbuf_putc(&sb, ' ');
363	sbuf_bcat(&sb, th.OemTableId, 8);
364	sbuf_trim(&sb);
365	sbuf_finish(&sb);
366	device_set_desc_copy(dev, sbuf_data(&sb));
367	sbuf_delete(&sb);
368	error = 0;
369    }
370    ACPI_UNLOCK;
371    return_VALUE(error);
372}
373
374static int
375acpi_attach(device_t dev)
376{
377    struct acpi_softc	*sc;
378    ACPI_STATUS		status;
379    int			error, state;
380    UINT32		flags;
381    UINT8		TypeA, TypeB;
382    char		*env;
383#ifdef ACPI_DEBUGGER
384    char		*debugpoint;
385#endif
386    ACPI_LOCK_DECL;
387
388    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
389    ACPI_LOCK;
390    sc = device_get_softc(dev);
391    bzero(sc, sizeof(*sc));
392    sc->acpi_dev = dev;
393
394#ifdef ACPI_DEBUGGER
395    debugpoint = getenv("debug.acpi.debugger");
396    if (debugpoint) {
397	if (!strcmp(debugpoint, "spaces"))
398	    acpi_EnterDebugger();
399	freeenv(debugpoint);
400    }
401#endif
402
403    /* Install the default address space handlers. */
404    error = ENXIO;
405    status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
406		ACPI_ADR_SPACE_SYSTEM_MEMORY, ACPI_DEFAULT_HANDLER, NULL, NULL);
407    if (ACPI_FAILURE(status)) {
408	device_printf(dev, "Could not initialise SystemMemory handler: %s\n",
409		      AcpiFormatException(status));
410	goto out;
411    }
412    status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
413		ACPI_ADR_SPACE_SYSTEM_IO, ACPI_DEFAULT_HANDLER, NULL, NULL);
414    if (ACPI_FAILURE(status)) {
415	device_printf(dev, "Could not initialise SystemIO handler: %s\n",
416		      AcpiFormatException(status));
417	goto out;
418    }
419    status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
420		ACPI_ADR_SPACE_PCI_CONFIG, ACPI_DEFAULT_HANDLER, NULL, NULL);
421    if (ACPI_FAILURE(status)) {
422	device_printf(dev, "could not initialise PciConfig handler: %s\n",
423		      AcpiFormatException(status));
424	goto out;
425    }
426
427    /*
428     * Bring ACPI fully online.
429     *
430     * Note that some systems (specifically, those with namespace evaluation
431     * issues that require the avoidance of parts of the namespace) must
432     * avoid running _INI and _STA on everything, as well as dodging the final
433     * object init pass.
434     *
435     * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
436     *
437     * XXX We should arrange for the object init pass after we have attached
438     *     all our child devices, but on many systems it works here.
439     */
440#ifdef ACPI_DEBUGGER
441    debugpoint = getenv("debug.acpi.debugger");
442    if (debugpoint) {
443	if (!strcmp(debugpoint, "enable"))
444	    acpi_EnterDebugger();
445	freeenv(debugpoint);
446    }
447#endif
448    flags = 0;
449    if (testenv("debug.acpi.avoid"))
450	flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
451    if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
452	device_printf(dev, "Could not enable ACPI: %s\n",
453		      AcpiFormatException(status));
454	goto out;
455    }
456
457    /*
458     * Call the ECDT probe function to provide EC functionality before
459     * the namespace has been evaluated.
460     */
461    acpi_ec_ecdt_probe(dev);
462
463    if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
464	device_printf(dev, "Could not initialize ACPI objects: %s\n",
465		      AcpiFormatException(status));
466	goto out;
467    }
468
469    /*
470     * Setup our sysctl tree.
471     *
472     * XXX: This doesn't check to make sure that none of these fail.
473     */
474    sysctl_ctx_init(&sc->acpi_sysctl_ctx);
475    sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
476			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
477			       device_get_name(dev), CTLFLAG_RD, 0, "");
478    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
479	OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
480	0, 0, acpi_supported_sleep_state_sysctl, "A", "");
481    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
482	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
483	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
484    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
485	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
486	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
487    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
488	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
489	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
490    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
491	OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
492	&sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
493    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
494	OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
495	&sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
496    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
497	OID_AUTO, "sleep_delay", CTLFLAG_RD | CTLFLAG_RW,
498	&sc->acpi_sleep_delay, 0, "sleep delay");
499    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
500	OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
501	&sc->acpi_s4bios, 0, "S4BIOS mode");
502    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
503	OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
504	&sc->acpi_verbose, 0, "verbose mode");
505    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
506	OID_AUTO, "disable_on_poweroff", CTLFLAG_RD | CTLFLAG_RW,
507	&sc->acpi_disable_on_poweroff, 0, "ACPI subsystem disable on poweroff");
508
509    /*
510     * Default to 5 seconds before sleeping to give some machines time to
511     * stabilize.
512     */
513    sc->acpi_sleep_delay = 5;
514    sc->acpi_disable_on_poweroff = 1;
515    if (bootverbose)
516	sc->acpi_verbose = 1;
517    if ((env = getenv("hw.acpi.verbose")) && strcmp(env, "0")) {
518	sc->acpi_verbose = 1;
519	freeenv(env);
520    }
521
522    /* Only enable S4BIOS by default if the FACS says it is available. */
523    if (AcpiGbl_FACS->S4Bios_f != 0)
524	    sc->acpi_s4bios = 1;
525
526    /*
527     * Dispatch the default sleep state to devices.  The lid switch is set
528     * to NONE by default to avoid surprising users.
529     */
530    sc->acpi_power_button_sx = ACPI_STATE_S5;
531    sc->acpi_lid_switch_sx = ACPI_S_STATES_MAX + 1;
532    sc->acpi_standby_sx = ACPI_STATE_S1;
533    sc->acpi_suspend_sx = ACPI_STATE_S3;
534
535    /* Pick the first valid sleep state for the sleep button default. */
536    sc->acpi_sleep_button_sx = ACPI_S_STATES_MAX + 1;
537    for (state = ACPI_STATE_S1; state < ACPI_STATE_S5; state++)
538	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
539	    sc->acpi_sleep_button_sx = state;
540	    break;
541	}
542
543    acpi_enable_fixed_events(sc);
544
545    /*
546     * Scan the namespace and attach/initialise children.
547     */
548#ifdef ACPI_DEBUGGER
549    debugpoint = getenv("debug.acpi.debugger");
550    if (debugpoint) {
551	if (!strcmp(debugpoint, "probe"))
552	    acpi_EnterDebugger();
553	freeenv(debugpoint);
554    }
555#endif
556
557    /* Register our shutdown handlers */
558    EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc,
559	SHUTDOWN_PRI_LAST);
560    EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
561	SHUTDOWN_PRI_LAST);
562
563    /*
564     * Register our acpi event handlers.
565     * XXX should be configurable eg. via userland policy manager.
566     */
567    EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
568	sc, ACPI_EVENT_PRI_LAST);
569    EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
570	sc, ACPI_EVENT_PRI_LAST);
571
572    /* Flag our initial states. */
573    sc->acpi_enabled = 1;
574    sc->acpi_sstate = ACPI_STATE_S0;
575    sc->acpi_sleep_disabled = 0;
576
577    /* Create the control device */
578    sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_WHEEL, 0644,
579			      "acpi");
580    sc->acpi_dev_t->si_drv1 = sc;
581
582#ifdef ACPI_DEBUGGER
583    debugpoint = getenv("debug.acpi.debugger");
584    if (debugpoint) {
585	if (strcmp(debugpoint, "running") == 0)
586	    acpi_EnterDebugger();
587	freeenv(debugpoint);
588    }
589#endif
590
591#ifdef ACPI_USE_THREADS
592    if ((error = acpi_task_thread_init()))
593	goto out;
594#endif
595
596    if ((error = acpi_machdep_init(dev)))
597	goto out;
598
599    /* Register ACPI again to pass the correct argument of pm_func. */
600    power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
601
602    if (!acpi_disabled("bus"))
603	acpi_probe_children(dev);
604
605    error = 0;
606
607 out:
608    ACPI_UNLOCK;
609    return_VALUE (error);
610}
611
612static void
613acpi_quirks_set()
614{
615    XSDT_DESCRIPTOR *xsdt;
616    struct acpi_quirks *quirk;
617    char *env, *tmp;
618    int len;
619
620    /*
621     * If the user loaded a custom table or disabled "quirks", leave
622     * the settings alone.
623     */
624    len = 0;
625    if ((env = getenv("acpi_dsdt_load")) != NULL) {
626	/* XXX No strcasecmp but this is good enough. */
627	if (*env == 'Y' || *env == 'y')
628	    goto out;
629	freeenv(env);
630    }
631    if ((env = getenv("debug.acpi.disabled")) != NULL) {
632	if (strstr("quirks", env) != NULL)
633	    goto out;
634	len = strlen(env);
635    }
636
637    /*
638     * Search through our quirk table and concatenate the disabled
639     * values with whatever we find.
640     */
641    xsdt = AcpiGbl_XSDT;
642    for (quirk = acpi_quirks_table; quirk->OemId; quirk++) {
643	if (!strncmp(xsdt->OemId, quirk->OemId, strlen(quirk->OemId)) &&
644	    (xsdt->OemRevision == quirk->OemRevision ||
645	    quirk->OemRevision == ACPI_OEM_REV_ANY)) {
646		len += strlen(quirk->value) + 2;
647		if ((tmp = malloc(len, M_TEMP, M_NOWAIT)) == NULL)
648		    goto out;
649		sprintf(tmp, "%s %s", env ? env : "", quirk->value);
650		setenv("debug.acpi.disabled", tmp);
651		free(tmp, M_TEMP);
652		break;
653	}
654    }
655
656out:
657    if (env)
658	freeenv(env);
659}
660
661/*
662 * Handle a new device being added
663 */
664static device_t
665acpi_add_child(device_t bus, int order, const char *name, int unit)
666{
667    struct acpi_device	*ad;
668    device_t		child;
669
670    if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT | M_ZERO)) == NULL)
671	return (NULL);
672
673    resource_list_init(&ad->ad_rl);
674
675    child = device_add_child_ordered(bus, order, name, unit);
676    if (child != NULL)
677	device_set_ivars(child, ad);
678    return (child);
679}
680
681static int
682acpi_print_child(device_t bus, device_t child)
683{
684    struct acpi_device	 *adev = device_get_ivars(child);
685    struct resource_list *rl = &adev->ad_rl;
686    int retval = 0;
687
688    retval += bus_print_child_header(bus, child);
689    retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
690    retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
691    retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
692    retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
693    retval += bus_print_child_footer(bus, child);
694
695    return (retval);
696}
697
698/* Location hint for devctl(8) */
699static int
700acpi_child_location_str_method(device_t cbdev, device_t child, char *buf,
701    size_t buflen)
702{
703    struct acpi_device *dinfo = device_get_ivars(child);
704
705    if (dinfo->ad_handle)
706	snprintf(buf, buflen, "path=%s", acpi_name(dinfo->ad_handle));
707    else
708	snprintf(buf, buflen, "magic=unknown");
709    return (0);
710}
711
712/* PnP information for devctl(8) */
713static int
714acpi_child_pnpinfo_str_method(device_t cbdev, device_t child, char *buf,
715    size_t buflen)
716{
717    ACPI_BUFFER adbuf = {ACPI_ALLOCATE_BUFFER, NULL};
718    ACPI_DEVICE_INFO *adinfo;
719    struct acpi_device *dinfo = device_get_ivars(child);
720    char *end;
721    int error;
722
723    error = AcpiGetObjectInfo(dinfo->ad_handle, &adbuf);
724    adinfo = (ACPI_DEVICE_INFO *) adbuf.Pointer;
725
726    if (error)
727	snprintf(buf, buflen, "Unknown");
728    else
729	snprintf(buf, buflen, "_HID=%s _UID=%lu",
730		 (adinfo->Valid & ACPI_VALID_HID) ?
731		 adinfo->HardwareId.Value : "UNKNOWN",
732		 (adinfo->Valid & ACPI_VALID_UID) ?
733		 strtoul(adinfo->UniqueId.Value, &end, 10) : 0);
734
735    if (adinfo)
736	AcpiOsFree(adinfo);
737
738    return (0);
739}
740
741/*
742 * Handle per-device ivars
743 */
744static int
745acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
746{
747    struct acpi_device	*ad;
748
749    if ((ad = device_get_ivars(child)) == NULL) {
750	printf("device has no ivars\n");
751	return (ENOENT);
752    }
753
754    /* ACPI and ISA compatibility ivars */
755    switch(index) {
756    case ACPI_IVAR_HANDLE:
757	*(ACPI_HANDLE *)result = ad->ad_handle;
758	break;
759    case ACPI_IVAR_MAGIC:
760	*(int *)result = ad->ad_magic;
761	break;
762    case ACPI_IVAR_PRIVATE:
763	*(void **)result = ad->ad_private;
764	break;
765    case ISA_IVAR_VENDORID:
766    case ISA_IVAR_SERIAL:
767    case ISA_IVAR_COMPATID:
768	*(int *)result = -1;
769	break;
770    case ISA_IVAR_LOGICALID:
771	*(int *)result = acpi_isa_get_logicalid(child);
772	break;
773    default:
774	return (ENOENT);
775    }
776
777    return (0);
778}
779
780static int
781acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
782{
783    struct acpi_device	*ad;
784
785    if ((ad = device_get_ivars(child)) == NULL) {
786	printf("device has no ivars\n");
787	return (ENOENT);
788    }
789
790    switch(index) {
791    case ACPI_IVAR_HANDLE:
792	ad->ad_handle = (ACPI_HANDLE)value;
793	break;
794    case ACPI_IVAR_MAGIC:
795	ad->ad_magic = (int)value;
796	break;
797    case ACPI_IVAR_PRIVATE:
798	ad->ad_private = (void *)value;
799	break;
800    default:
801	panic("bad ivar write request (%d)", index);
802	return (ENOENT);
803    }
804
805    return (0);
806}
807
808/*
809 * Handle child resource allocation/removal
810 */
811static int
812acpi_set_resource(device_t dev, device_t child, int type, int rid,
813		  u_long start, u_long count)
814{
815    struct acpi_device		*ad = device_get_ivars(child);
816    struct resource_list	*rl = &ad->ad_rl;
817
818    resource_list_add(rl, type, rid, start, start + count -1, count);
819
820    return(0);
821}
822
823static int
824acpi_get_resource(device_t dev, device_t child, int type, int rid,
825		  u_long *startp, u_long *countp)
826{
827    struct acpi_device		*ad = device_get_ivars(child);
828    struct resource_list	*rl = &ad->ad_rl;
829    struct resource_list_entry	*rle;
830
831    rle = resource_list_find(rl, type, rid);
832    if (!rle)
833	return(ENOENT);
834
835    if (startp)
836	*startp = rle->start;
837    if (countp)
838	*countp = rle->count;
839
840    return (0);
841}
842
843static struct resource *
844acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
845		    u_long start, u_long end, u_long count, u_int flags)
846{
847    struct acpi_device *ad = device_get_ivars(child);
848    struct resource_list *rl = &ad->ad_rl;
849
850    return (resource_list_alloc(rl, bus, child, type, rid, start, end, count,
851	    flags));
852}
853
854static int
855acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
856{
857    struct acpi_device *ad = device_get_ivars(child);
858    struct resource_list *rl = &ad->ad_rl;
859
860    return (resource_list_release(rl, bus, child, type, rid, r));
861}
862
863/* Allocate an IO port or memory resource, given its GAS. */
864struct resource *
865acpi_bus_alloc_gas(device_t dev, int *rid, ACPI_GENERIC_ADDRESS *gas)
866{
867    int type;
868
869    if (gas == NULL || !ACPI_VALID_ADDRESS(gas->Address) ||
870	gas->RegisterBitWidth < 8)
871	return (NULL);
872
873    switch (gas->AddressSpaceId) {
874    case ACPI_ADR_SPACE_SYSTEM_MEMORY:
875	type = SYS_RES_MEMORY;
876	break;
877    case ACPI_ADR_SPACE_SYSTEM_IO:
878	type = SYS_RES_IOPORT;
879	break;
880    default:
881	return (NULL);
882    }
883
884    bus_set_resource(dev, type, *rid, gas->Address, gas->RegisterBitWidth / 8);
885    return (bus_alloc_resource_any(dev, type, rid, RF_ACTIVE));
886}
887
888/*
889 * Handle ISA-like devices probing for a PnP ID to match.
890 */
891#define PNP_EISAID(s)				\
892	((((s[0] - '@') & 0x1f) << 2)		\
893	 | (((s[1] - '@') & 0x18) >> 3)		\
894	 | (((s[1] - '@') & 0x07) << 13)	\
895	 | (((s[2] - '@') & 0x1f) << 8)		\
896	 | (PNP_HEXTONUM(s[4]) << 16)		\
897	 | (PNP_HEXTONUM(s[3]) << 20)		\
898	 | (PNP_HEXTONUM(s[6]) << 24)		\
899	 | (PNP_HEXTONUM(s[5]) << 28))
900
901static uint32_t
902acpi_isa_get_logicalid(device_t dev)
903{
904    ACPI_DEVICE_INFO	*devinfo;
905    ACPI_BUFFER		buf;
906    ACPI_HANDLE		h;
907    ACPI_STATUS		error;
908    u_int32_t		pnpid;
909    ACPI_LOCK_DECL;
910
911    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
912
913    pnpid = 0;
914    buf.Pointer = NULL;
915    buf.Length = ACPI_ALLOCATE_BUFFER;
916
917    ACPI_LOCK;
918
919    /* Fetch and validate the HID. */
920    if ((h = acpi_get_handle(dev)) == NULL)
921	goto out;
922    error = AcpiGetObjectInfo(h, &buf);
923    if (ACPI_FAILURE(error))
924	goto out;
925    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
926
927    if ((devinfo->Valid & ACPI_VALID_HID) != 0)
928	pnpid = PNP_EISAID(devinfo->HardwareId.Value);
929
930out:
931    if (buf.Pointer != NULL)
932	AcpiOsFree(buf.Pointer);
933    ACPI_UNLOCK;
934    return_VALUE (pnpid);
935}
936
937static int
938acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
939{
940    ACPI_DEVICE_INFO	*devinfo;
941    ACPI_BUFFER		buf;
942    ACPI_HANDLE		h;
943    ACPI_STATUS		error;
944    uint32_t		*pnpid;
945    int			valid, i;
946    ACPI_LOCK_DECL;
947
948    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
949
950    pnpid = cids;
951    valid = 0;
952    buf.Pointer = NULL;
953    buf.Length = ACPI_ALLOCATE_BUFFER;
954
955    ACPI_LOCK;
956
957    /* Fetch and validate the CID */
958    if ((h = acpi_get_handle(dev)) == NULL)
959	goto out;
960    error = AcpiGetObjectInfo(h, &buf);
961    if (ACPI_FAILURE(error))
962	goto out;
963    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
964    if ((devinfo->Valid & ACPI_VALID_CID) == 0)
965	goto out;
966
967    if (devinfo->CompatibilityId.Count < count)
968	count = devinfo->CompatibilityId.Count;
969    for (i = 0; i < count; i++) {
970	if (strncmp(devinfo->CompatibilityId.Id[i].Value, "PNP", 3) != 0)
971	    continue;
972	*pnpid++ = PNP_EISAID(devinfo->CompatibilityId.Id[i].Value);
973	valid++;
974    }
975
976out:
977    if (buf.Pointer != NULL)
978	AcpiOsFree(buf.Pointer);
979    ACPI_UNLOCK;
980    return_VALUE (valid);
981}
982
983static int
984acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
985{
986    int			result, cid_count, i;
987    uint32_t		lid, cids[8];
988
989    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
990
991    /*
992     * ISA-style drivers attached to ACPI may persist and
993     * probe manually if we return ENOENT.  We never want
994     * that to happen, so don't ever return it.
995     */
996    result = ENXIO;
997
998    /* Scan the supplied IDs for a match */
999    lid = acpi_isa_get_logicalid(child);
1000    cid_count = acpi_isa_get_compatid(child, cids, 8);
1001    while (ids && ids->ip_id) {
1002	if (lid == ids->ip_id) {
1003	    result = 0;
1004	    goto out;
1005	}
1006	for (i = 0; i < cid_count; i++) {
1007	    if (cids[i] == ids->ip_id) {
1008		result = 0;
1009		goto out;
1010	    }
1011	}
1012	ids++;
1013    }
1014
1015 out:
1016    return_VALUE (result);
1017}
1018
1019/*
1020 * Scan relevant portions of the ACPI namespace and attach child devices.
1021 *
1022 * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and
1023 * \_SB_ scopes, and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
1024 */
1025static void
1026acpi_probe_children(device_t bus)
1027{
1028    ACPI_HANDLE	parent;
1029    ACPI_STATUS	status;
1030    static char	*scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
1031    int		i;
1032
1033    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1034    ACPI_ASSERTLOCK;
1035
1036    /* Create any static children by calling device identify methods. */
1037    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
1038    bus_generic_probe(bus);
1039
1040    /*
1041     * Scan the namespace and insert placeholders for all the devices that
1042     * we find.
1043     *
1044     * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
1045     * we want to create nodes for all devices, not just those that are
1046     * currently present. (This assumes that we don't want to create/remove
1047     * devices as they appear, which might be smarter.)
1048     */
1049    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
1050    for (i = 0; scopes[i] != NULL; i++) {
1051	status = AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent);
1052	if (ACPI_SUCCESS(status)) {
1053	    AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child,
1054			      bus, NULL);
1055	}
1056    }
1057
1058    /*
1059     * Scan all of the child devices we have created and let them probe/attach.
1060     */
1061    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
1062    bus_generic_attach(bus);
1063
1064    /*
1065     * Some of these children may have attached others as part of their attach
1066     * process (eg. the root PCI bus driver), so rescan.
1067     */
1068    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
1069    bus_generic_attach(bus);
1070
1071    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
1072    return_VOID;
1073}
1074
1075/*
1076 * Evaluate a child device and determine whether we might attach a device to
1077 * it.
1078 */
1079static ACPI_STATUS
1080acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
1081{
1082    ACPI_OBJECT_TYPE	type;
1083    device_t		child, bus = (device_t)context;
1084
1085    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1086
1087    /* Skip this device if we think we'll have trouble with it. */
1088    if (acpi_avoid(handle))
1089	return_ACPI_STATUS (AE_OK);
1090
1091    if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
1092	switch(type) {
1093	case ACPI_TYPE_DEVICE:
1094	case ACPI_TYPE_PROCESSOR:
1095	case ACPI_TYPE_THERMAL:
1096	case ACPI_TYPE_POWER:
1097	    if (acpi_disabled("children"))
1098		break;
1099
1100	    /*
1101	     * Create a placeholder device for this node.  Sort the placeholder
1102	     * so that the probe/attach passes will run breadth-first.
1103	     */
1104	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n",
1105			     acpi_name(handle)));
1106	    child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
1107	    if (child == NULL)
1108		break;
1109	    acpi_set_handle(child, handle);
1110
1111	    /* Check if the device can generate wake events. */
1112	    if (ACPI_SUCCESS(AcpiEvaluateObject(handle, "_PRW", NULL, NULL)))
1113		device_set_flags(child, ACPI_FLAG_WAKE_CAPABLE);
1114
1115	    /*
1116	     * Check that the device is present.  If it's not present,
1117	     * leave it disabled (so that we have a device_t attached to
1118	     * the handle, but we don't probe it).
1119	     */
1120	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1121		device_disable(child);
1122		break;
1123	    }
1124
1125	    /*
1126	     * Get the device's resource settings and attach them.
1127	     * Note that if the device has _PRS but no _CRS, we need
1128	     * to decide when it's appropriate to try to configure the
1129	     * device.  Ignore the return value here; it's OK for the
1130	     * device not to have any resources.
1131	     */
1132	    acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
1133
1134	    /* If we're debugging, probe/attach now rather than later */
1135	    ACPI_DEBUG_EXEC(device_probe_and_attach(child));
1136	    break;
1137	}
1138    }
1139
1140    return_ACPI_STATUS (AE_OK);
1141}
1142
1143static void
1144acpi_shutdown_pre_sync(void *arg, int howto)
1145{
1146    struct acpi_softc *sc = arg;
1147
1148    ACPI_ASSERTLOCK;
1149
1150    /* Disable all wake GPEs not appropriate for this state. */
1151    acpi_wake_limit_walk(ACPI_STATE_S5);
1152
1153    /*
1154     * Disable all ACPI events before soft off, otherwise the system
1155     * will be turned on again on some laptops.
1156     *
1157     * XXX this should probably be restricted to masking some events just
1158     *     before powering down, since we may still need ACPI during the
1159     *     shutdown process.
1160     */
1161    if (sc->acpi_disable_on_poweroff)
1162	acpi_Disable(sc);
1163}
1164
1165static void
1166acpi_shutdown_final(void *arg, int howto)
1167{
1168    ACPI_STATUS	status;
1169    ACPI_ASSERTLOCK;
1170
1171    /*
1172     * If powering off, run the actual shutdown code on each processor.
1173     * It will only perform the shutdown on the BSP.  Some chipsets do
1174     * not power off the system correctly if called from an AP.
1175     */
1176    if ((howto & RB_POWEROFF) != 0) {
1177	status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
1178	if (ACPI_FAILURE(status)) {
1179	    printf("AcpiEnterSleepStatePrep failed - %s\n",
1180		   AcpiFormatException(status));
1181	    return;
1182	}
1183	printf("Powering system off using ACPI\n");
1184	smp_rendezvous(NULL, acpi_shutdown_poweroff, NULL, NULL);
1185    } else {
1186	printf("Shutting down ACPI\n");
1187	AcpiTerminate();
1188    }
1189}
1190
1191/*
1192 * Since this function may be called with locks held or in an unknown
1193 * context, it cannot allocate memory, acquire locks, sleep, etc.
1194 */
1195static void
1196acpi_shutdown_poweroff(void *arg)
1197{
1198    ACPI_STATUS	status;
1199
1200    ACPI_ASSERTLOCK;
1201
1202    /* Only attempt to power off if this is the BSP (cpuid 0). */
1203    if (PCPU_GET(cpuid) != 0)
1204	return;
1205
1206    ACPI_DISABLE_IRQS();
1207    status = AcpiEnterSleepState(ACPI_STATE_S5);
1208    if (ACPI_FAILURE(status)) {
1209	printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
1210    } else {
1211	DELAY(1000000);
1212	printf("ACPI power-off failed - timeout\n");
1213    }
1214}
1215
1216static void
1217acpi_enable_fixed_events(struct acpi_softc *sc)
1218{
1219    static int	first_time = 1;
1220
1221    ACPI_ASSERTLOCK;
1222
1223    /* Enable and clear fixed events and install handlers. */
1224    if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->PwrButton == 0) {
1225	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
1226	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
1227				     acpi_event_power_button_sleep, sc);
1228	if (first_time)
1229	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
1230    }
1231    if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->SleepButton == 0) {
1232	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
1233	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
1234				     acpi_event_sleep_button_sleep, sc);
1235	if (first_time)
1236	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
1237    }
1238
1239    first_time = 0;
1240}
1241
1242/*
1243 * Returns true if the device is actually present and should
1244 * be attached to.  This requires the present, enabled, UI-visible
1245 * and diagnostics-passed bits to be set.
1246 */
1247BOOLEAN
1248acpi_DeviceIsPresent(device_t dev)
1249{
1250    ACPI_DEVICE_INFO	*devinfo;
1251    ACPI_HANDLE		h;
1252    ACPI_BUFFER		buf;
1253    ACPI_STATUS		error;
1254    int			ret;
1255
1256    ACPI_ASSERTLOCK;
1257
1258    ret = FALSE;
1259    if ((h = acpi_get_handle(dev)) == NULL)
1260	return (FALSE);
1261    buf.Pointer = NULL;
1262    buf.Length = ACPI_ALLOCATE_BUFFER;
1263    error = AcpiGetObjectInfo(h, &buf);
1264    if (ACPI_FAILURE(error))
1265	return (FALSE);
1266    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1267
1268    /* If no _STA method, must be present */
1269    if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1270	ret = TRUE;
1271
1272    /* Return true for 'present' and 'functioning' */
1273    if ((devinfo->CurrentStatus & 0x9) == 0x9)
1274	ret = TRUE;
1275
1276    AcpiOsFree(buf.Pointer);
1277    return (ret);
1278}
1279
1280/*
1281 * Returns true if the battery is actually present and inserted.
1282 */
1283BOOLEAN
1284acpi_BatteryIsPresent(device_t dev)
1285{
1286    ACPI_DEVICE_INFO	*devinfo;
1287    ACPI_HANDLE		h;
1288    ACPI_BUFFER		buf;
1289    ACPI_STATUS		error;
1290    int			ret;
1291
1292    ACPI_ASSERTLOCK;
1293
1294    ret = FALSE;
1295    if ((h = acpi_get_handle(dev)) == NULL)
1296	return (FALSE);
1297    buf.Pointer = NULL;
1298    buf.Length = ACPI_ALLOCATE_BUFFER;
1299    error = AcpiGetObjectInfo(h, &buf);
1300    if (ACPI_FAILURE(error))
1301	return (FALSE);
1302    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1303
1304    /* If no _STA method, must be present */
1305    if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1306	ret = TRUE;
1307
1308    /* Return true for 'present' and 'functioning' */
1309    if ((devinfo->CurrentStatus & 0x19) == 0x19)
1310	ret = TRUE;
1311
1312    AcpiOsFree(buf.Pointer);
1313    return (ret);
1314}
1315
1316/*
1317 * Match a HID string against a device
1318 */
1319BOOLEAN
1320acpi_MatchHid(device_t dev, char *hid)
1321{
1322    ACPI_DEVICE_INFO	*devinfo;
1323    ACPI_HANDLE		h;
1324    ACPI_BUFFER		buf;
1325    ACPI_STATUS		error;
1326    int			ret, i;
1327
1328    ACPI_ASSERTLOCK;
1329
1330    ret = FALSE;
1331    if (hid == NULL)
1332	return (FALSE);
1333    if ((h = acpi_get_handle(dev)) == NULL)
1334	return (FALSE);
1335    buf.Pointer = NULL;
1336    buf.Length = ACPI_ALLOCATE_BUFFER;
1337    error = AcpiGetObjectInfo(h, &buf);
1338    if (ACPI_FAILURE(error))
1339	return (FALSE);
1340    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1341
1342    if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
1343	strcmp(hid, devinfo->HardwareId.Value) == 0)
1344	    ret = TRUE;
1345    else if ((devinfo->Valid & ACPI_VALID_CID) != 0) {
1346	for (i = 0; i < devinfo->CompatibilityId.Count; i++) {
1347	    if (strcmp(hid, devinfo->CompatibilityId.Id[i].Value) == 0) {
1348		ret = TRUE;
1349		break;
1350	    }
1351	}
1352    }
1353
1354    AcpiOsFree(buf.Pointer);
1355    return (ret);
1356}
1357
1358/*
1359 * Return the handle of a named object within our scope, ie. that of (parent)
1360 * or one if its parents.
1361 */
1362ACPI_STATUS
1363acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1364{
1365    ACPI_HANDLE		r;
1366    ACPI_STATUS		status;
1367
1368    ACPI_ASSERTLOCK;
1369
1370    /* Walk back up the tree to the root */
1371    for (;;) {
1372	status = AcpiGetHandle(parent, path, &r);
1373	if (ACPI_SUCCESS(status)) {
1374	    *result = r;
1375	    return (AE_OK);
1376	}
1377	if (status != AE_NOT_FOUND)
1378	    return (AE_OK);
1379	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1380	    return (AE_NOT_FOUND);
1381	parent = r;
1382    }
1383}
1384
1385/* Find the difference between two PM tick counts. */
1386uint32_t
1387acpi_TimerDelta(uint32_t end, uint32_t start)
1388{
1389    uint32_t delta;
1390
1391    if (end >= start)
1392	delta = end - start;
1393    else if (AcpiGbl_FADT->TmrValExt == 0)
1394	delta = ((0x00FFFFFF - start) + end + 1) & 0x00FFFFFF;
1395    else
1396	delta = ((0xFFFFFFFF - start) + end + 1);
1397    return (delta);
1398}
1399
1400/*
1401 * Allocate a buffer with a preset data size.
1402 */
1403ACPI_BUFFER *
1404acpi_AllocBuffer(int size)
1405{
1406    ACPI_BUFFER	*buf;
1407
1408    if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1409	return (NULL);
1410    buf->Length = size;
1411    buf->Pointer = (void *)(buf + 1);
1412    return (buf);
1413}
1414
1415ACPI_STATUS
1416acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
1417{
1418    ACPI_OBJECT arg1;
1419    ACPI_OBJECT_LIST args;
1420
1421    ACPI_ASSERTLOCK;
1422
1423    arg1.Type = ACPI_TYPE_INTEGER;
1424    arg1.Integer.Value = number;
1425    args.Count = 1;
1426    args.Pointer = &arg1;
1427
1428    return (AcpiEvaluateObject(handle, path, &args, NULL));
1429}
1430
1431/*
1432 * Evaluate a path that should return an integer.
1433 */
1434ACPI_STATUS
1435acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
1436{
1437    ACPI_STATUS	status;
1438    ACPI_BUFFER	buf;
1439    ACPI_OBJECT	param;
1440
1441    ACPI_ASSERTLOCK;
1442
1443    if (handle == NULL)
1444	handle = ACPI_ROOT_OBJECT;
1445
1446    /*
1447     * Assume that what we've been pointed at is an Integer object, or
1448     * a method that will return an Integer.
1449     */
1450    buf.Pointer = &param;
1451    buf.Length = sizeof(param);
1452    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1453    if (ACPI_SUCCESS(status)) {
1454	if (param.Type == ACPI_TYPE_INTEGER)
1455	    *number = param.Integer.Value;
1456	else
1457	    status = AE_TYPE;
1458    }
1459
1460    /*
1461     * In some applications, a method that's expected to return an Integer
1462     * may instead return a Buffer (probably to simplify some internal
1463     * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1464     * convert it into an Integer as best we can.
1465     *
1466     * This is a hack.
1467     */
1468    if (status == AE_BUFFER_OVERFLOW) {
1469	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1470	    status = AE_NO_MEMORY;
1471	} else {
1472	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1473	    if (ACPI_SUCCESS(status))
1474		status = acpi_ConvertBufferToInteger(&buf, number);
1475	    AcpiOsFree(buf.Pointer);
1476	}
1477    }
1478    return (status);
1479}
1480
1481ACPI_STATUS
1482acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
1483{
1484    ACPI_OBJECT	*p;
1485    UINT8	*val;
1486    int		i;
1487
1488    p = (ACPI_OBJECT *)bufp->Pointer;
1489    if (p->Type == ACPI_TYPE_INTEGER) {
1490	*number = p->Integer.Value;
1491	return (AE_OK);
1492    }
1493    if (p->Type != ACPI_TYPE_BUFFER)
1494	return (AE_TYPE);
1495    if (p->Buffer.Length > sizeof(int))
1496	return (AE_BAD_DATA);
1497
1498    *number = 0;
1499    val = p->Buffer.Pointer;
1500    for (i = 0; i < p->Buffer.Length; i++)
1501	*number += val[i] << (i * 8);
1502    return (AE_OK);
1503}
1504
1505/*
1506 * Iterate over the elements of an a package object, calling the supplied
1507 * function for each element.
1508 *
1509 * XXX possible enhancement might be to abort traversal on error.
1510 */
1511ACPI_STATUS
1512acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
1513	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
1514{
1515    ACPI_OBJECT	*comp;
1516    int		i;
1517
1518    if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
1519	return (AE_BAD_PARAMETER);
1520
1521    /* Iterate over components */
1522    i = 0;
1523    comp = pkg->Package.Elements;
1524    for (; i < pkg->Package.Count; i++, comp++)
1525	func(comp, arg);
1526
1527    return (AE_OK);
1528}
1529
1530/*
1531 * Find the (index)th resource object in a set.
1532 */
1533ACPI_STATUS
1534acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1535{
1536    ACPI_RESOURCE	*rp;
1537    int			i;
1538
1539    rp = (ACPI_RESOURCE *)buf->Pointer;
1540    i = index;
1541    while (i-- > 0) {
1542	/* Range check */
1543	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1544	    return (AE_BAD_PARAMETER);
1545
1546	/* Check for terminator */
1547	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1548	    return (AE_NOT_FOUND);
1549	rp = ACPI_NEXT_RESOURCE(rp);
1550    }
1551    if (resp != NULL)
1552	*resp = rp;
1553
1554    return (AE_OK);
1555}
1556
1557/*
1558 * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1559 *
1560 * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1561 * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1562 * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1563 * resources.
1564 */
1565#define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
1566
1567ACPI_STATUS
1568acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1569{
1570    ACPI_RESOURCE	*rp;
1571    void		*newp;
1572
1573    /* Initialise the buffer if necessary. */
1574    if (buf->Pointer == NULL) {
1575	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1576	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1577	    return (AE_NO_MEMORY);
1578	rp = (ACPI_RESOURCE *)buf->Pointer;
1579	rp->Id = ACPI_RSTYPE_END_TAG;
1580	rp->Length = 0;
1581    }
1582    if (res == NULL)
1583	return (AE_OK);
1584
1585    /*
1586     * Scan the current buffer looking for the terminator.
1587     * This will either find the terminator or hit the end
1588     * of the buffer and return an error.
1589     */
1590    rp = (ACPI_RESOURCE *)buf->Pointer;
1591    for (;;) {
1592	/* Range check, don't go outside the buffer */
1593	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1594	    return (AE_BAD_PARAMETER);
1595	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1596	    break;
1597	rp = ACPI_NEXT_RESOURCE(rp);
1598    }
1599
1600    /*
1601     * Check the size of the buffer and expand if required.
1602     *
1603     * Required size is:
1604     *	size of existing resources before terminator +
1605     *	size of new resource and header +
1606     * 	size of terminator.
1607     *
1608     * Note that this loop should really only run once, unless
1609     * for some reason we are stuffing a *really* huge resource.
1610     */
1611    while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
1612	    res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1613	    ACPI_RESOURCE_LENGTH) >= buf->Length) {
1614	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1615	    return (AE_NO_MEMORY);
1616	bcopy(buf->Pointer, newp, buf->Length);
1617	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1618			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1619	AcpiOsFree(buf->Pointer);
1620	buf->Pointer = newp;
1621	buf->Length += buf->Length;
1622    }
1623
1624    /* Insert the new resource. */
1625    bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1626
1627    /* And add the terminator. */
1628    rp = ACPI_NEXT_RESOURCE(rp);
1629    rp->Id = ACPI_RSTYPE_END_TAG;
1630    rp->Length = 0;
1631
1632    return (AE_OK);
1633}
1634
1635/*
1636 * Set interrupt model.
1637 */
1638ACPI_STATUS
1639acpi_SetIntrModel(int model)
1640{
1641
1642    return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
1643}
1644
1645#define ACPI_MINIMUM_AWAKETIME	5
1646
1647static void
1648acpi_sleep_enable(void *arg)
1649{
1650    ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1651}
1652
1653/*
1654 * Set the system sleep state
1655 *
1656 * Currently we support S1-S5 but S4 is only S4BIOS
1657 */
1658ACPI_STATUS
1659acpi_SetSleepState(struct acpi_softc *sc, int state)
1660{
1661    ACPI_STATUS	status = AE_OK;
1662    UINT8	TypeA;
1663    UINT8	TypeB;
1664
1665    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1666    ACPI_ASSERTLOCK;
1667
1668    /* Avoid reentry if already attempting to suspend. */
1669    if (sc->acpi_sstate != ACPI_STATE_S0)
1670	return_ACPI_STATUS (AE_BAD_PARAMETER);
1671
1672    /* We recently woke up so don't suspend again for a while. */
1673    if (sc->acpi_sleep_disabled)
1674	return_ACPI_STATUS (AE_OK);
1675
1676    switch (state) {
1677    case ACPI_STATE_S1:
1678    case ACPI_STATE_S2:
1679    case ACPI_STATE_S3:
1680    case ACPI_STATE_S4:
1681	status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB);
1682	if (status == AE_NOT_FOUND) {
1683	    device_printf(sc->acpi_dev,
1684			  "Sleep state S%d not supported by BIOS\n", state);
1685	    break;
1686	} else if (ACPI_FAILURE(status)) {
1687	    device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n",
1688			  AcpiFormatException(status));
1689	    break;
1690	}
1691
1692	sc->acpi_sstate = state;
1693	sc->acpi_sleep_disabled = 1;
1694
1695	/* Disable all wake GPEs not appropriate for this state. */
1696	acpi_wake_limit_walk(state);
1697
1698	/* Inform all devices that we are going to sleep. */
1699	if (DEVICE_SUSPEND(root_bus) != 0) {
1700	    /*
1701	     * Re-wake the system.
1702	     *
1703	     * XXX note that a better two-pass approach with a 'veto' pass
1704	     *     followed by a "real thing" pass would be better, but the
1705	     *     current bus interface does not provide for this.
1706	     */
1707	    DEVICE_RESUME(root_bus);
1708	    return_ACPI_STATUS (AE_ERROR);
1709	}
1710
1711	status = AcpiEnterSleepStatePrep(state);
1712	if (ACPI_FAILURE(status)) {
1713	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1714			  AcpiFormatException(status));
1715	    break;
1716	}
1717
1718	if (sc->acpi_sleep_delay > 0)
1719	    DELAY(sc->acpi_sleep_delay * 1000000);
1720
1721	if (state != ACPI_STATE_S1) {
1722	    acpi_sleep_machdep(sc, state);
1723
1724	    /* AcpiEnterSleepState() may be incomplete, unlock if locked. */
1725	    if (AcpiGbl_MutexInfo[ACPI_MTX_HARDWARE].OwnerId !=
1726		ACPI_MUTEX_NOT_ACQUIRED) {
1727
1728		AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1729	    }
1730
1731	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1732	    if (state == ACPI_STATE_S4)
1733		AcpiEnable();
1734	} else {
1735	    status = AcpiEnterSleepState((UINT8)state);
1736	    if (ACPI_FAILURE(status)) {
1737		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
1738			      AcpiFormatException(status));
1739		break;
1740	    }
1741	}
1742	AcpiLeaveSleepState((UINT8)state);
1743	DEVICE_RESUME(root_bus);
1744	sc->acpi_sstate = ACPI_STATE_S0;
1745	acpi_enable_fixed_events(sc);
1746	break;
1747    case ACPI_STATE_S5:
1748	/*
1749	 * Shut down cleanly and power off.  This will call us back through the
1750	 * shutdown handlers.
1751	 */
1752	shutdown_nice(RB_POWEROFF);
1753	break;
1754    case ACPI_STATE_S0:
1755    default:
1756	status = AE_BAD_PARAMETER;
1757	break;
1758    }
1759
1760    /* Disable a second sleep request for a short period */
1761    if (sc->acpi_sleep_disabled)
1762	timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
1763
1764    return_ACPI_STATUS (status);
1765}
1766
1767/* Initialize a device's wake GPE. */
1768int
1769acpi_wake_init(device_t dev, int type)
1770{
1771    struct acpi_prw_data prw;
1772
1773    /* Check that the device can wake the system. */
1774    if ((device_get_flags(dev) & ACPI_FLAG_WAKE_CAPABLE) == 0)
1775	return (ENXIO);
1776
1777    /* Evaluate _PRW to find the GPE. */
1778    if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
1779	return (ENXIO);
1780
1781    /* Set the requested type for the GPE (runtime, wake, or both). */
1782    if (ACPI_FAILURE(AcpiSetGpeType(prw.gpe_handle, prw.gpe_bit, type))) {
1783	device_printf(dev, "set GPE type failed\n");
1784	return (ENXIO);
1785    }
1786
1787    return (0);
1788}
1789
1790/* Enable or disable the device's wake GPE. */
1791int
1792acpi_wake_set_enable(device_t dev, int enable)
1793{
1794    struct acpi_prw_data prw;
1795    ACPI_HANDLE handle;
1796    ACPI_STATUS status;
1797    int flags;
1798
1799    /* Make sure the device supports waking the system. */
1800    flags = device_get_flags(dev);
1801    handle = acpi_get_handle(dev);
1802    if ((flags & ACPI_FLAG_WAKE_CAPABLE) == 0 || handle == NULL)
1803	return (ENXIO);
1804
1805    /* Evaluate _PRW to find the GPE. */
1806    if (acpi_parse_prw(handle, &prw) != 0)
1807	return (ENXIO);
1808
1809    if (enable) {
1810	status = AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1811	if (ACPI_FAILURE(status)) {
1812	    device_printf(dev, "enable wake failed\n");
1813	    return (ENXIO);
1814	}
1815	device_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
1816    } else {
1817	status = AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1818	if (ACPI_FAILURE(status)) {
1819	    device_printf(dev, "disable wake failed\n");
1820	    return (ENXIO);
1821	}
1822	device_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
1823    }
1824
1825    return (0);
1826}
1827
1828/* Configure a device's GPE appropriately for the new sleep state. */
1829int
1830acpi_wake_sleep_prep(device_t dev, int sstate)
1831{
1832    struct acpi_prw_data prw;
1833    ACPI_HANDLE handle;
1834
1835    /* Check that this is an ACPI device and get its GPE. */
1836    handle = acpi_get_handle(dev);
1837    if (handle == NULL)
1838	return (ENXIO);
1839    if (acpi_parse_prw(handle, &prw) != 0)
1840	return (ENXIO);
1841
1842    /*
1843     * The sleeping state being entered must be less than (i.e., higher power)
1844     * or equal to the value specified by _PRW.  If not, disable this GPE.
1845     */
1846    if (sstate > prw.lowest_wake) {
1847	if (bootverbose)
1848	    device_printf(dev, "wake_prep disabled gpe %#x for state %d\n",
1849		prw.gpe_bit, sstate);
1850	AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1851	acpi_SetInteger(handle, "_PSW", 0);
1852	return (0);
1853    }
1854
1855    /*
1856     * If requested, enable the device's wake capability.
1857     *
1858     * TBD: All Power Resources referenced by elements 2 through N
1859     *      of the _PRW object are put into the ON state.
1860     */
1861    if ((device_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
1862	if (bootverbose)
1863	    device_printf(dev, "wake_prep enabled _PSW for state %d\n", sstate);
1864	acpi_SetInteger(handle, "_PSW", 1);
1865    }
1866
1867    return (0);
1868}
1869
1870static ACPI_STATUS
1871acpi_wake_limit(ACPI_HANDLE h, UINT32 level, void *context, void **status)
1872{
1873    struct acpi_prw_data prw;
1874    int sstate;
1875
1876    /* It's ok not to have _PRW if the device can't wake the system. */
1877    if (acpi_parse_prw(h, &prw) != 0)
1878	return (AE_OK);
1879
1880    sstate = (int)context;
1881    if (sstate > prw.lowest_wake)
1882	AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
1883
1884    return (AE_OK);
1885}
1886
1887/* Walk all system devices, disabling them if necessary for sstate. */
1888static int
1889acpi_wake_limit_walk(int sstate)
1890{
1891    ACPI_HANDLE sb_handle;
1892
1893    if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
1894	AcpiWalkNamespace(ACPI_TYPE_ANY, sb_handle, 100,
1895	    acpi_wake_limit, (void *)sstate, NULL);
1896    return (0);
1897}
1898
1899/* Parse a device's _PRW into a structure. */
1900static int
1901acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
1902{
1903    ACPI_STATUS			status;
1904    ACPI_BUFFER			prw_buffer;
1905    ACPI_OBJECT			*res, *res2;
1906    int error;
1907
1908    if (h == NULL || prw == NULL)
1909	return (EINVAL);
1910
1911    /*
1912     * The _PRW object (7.2.9) is only required for devices that have the
1913     * ability to wake the system from a sleeping state.
1914     */
1915    error = EINVAL;
1916    prw_buffer.Pointer = NULL;
1917    prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
1918    status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
1919    if (ACPI_FAILURE(status))
1920	return (ENOENT);
1921    res = (ACPI_OBJECT *)prw_buffer.Pointer;
1922    if (res == NULL)
1923	return (ENOENT);
1924    if (!ACPI_PKG_VALID(res, 2))
1925	goto out;
1926
1927    /*
1928     * Element 1 of the _PRW object:
1929     * The lowest power system sleeping state that can be entered while still
1930     * providing wake functionality.  The sleeping state being entered must
1931     * be less than (i.e., higher power) or equal to this value.
1932     */
1933    if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
1934	goto out;
1935
1936    /*
1937     * Element 0 of the _PRW object:
1938     */
1939    switch (res->Package.Elements[0].Type) {
1940    case ACPI_TYPE_INTEGER:
1941	/*
1942	 * If the data type of this package element is numeric, then this
1943	 * _PRW package element is the bit index in the GPEx_EN, in the
1944	 * GPE blocks described in the FADT, of the enable bit that is
1945	 * enabled for the wake event.
1946	 */
1947	prw->gpe_handle = NULL;
1948	prw->gpe_bit = res->Package.Elements[0].Integer.Value;
1949	error = 0;
1950	break;
1951    case ACPI_TYPE_PACKAGE:
1952	/*
1953	 * If the data type of this package element is a package, then this
1954	 * _PRW package element is itself a package containing two
1955	 * elements.  The first is an object reference to the GPE Block
1956	 * device that contains the GPE that will be triggered by the wake
1957	 * event.  The second element is numeric and it contains the bit
1958	 * index in the GPEx_EN, in the GPE Block referenced by the
1959	 * first element in the package, of the enable bit that is enabled for
1960	 * the wake event.
1961	 *
1962	 * For example, if this field is a package then it is of the form:
1963	 * Package() {\_SB.PCI0.ISA.GPE, 2}
1964	 */
1965	res2 = &res->Package.Elements[0];
1966	if (!ACPI_PKG_VALID(res2, 2))
1967	    goto out;
1968	prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
1969	if (prw->gpe_handle == NULL)
1970	    goto out;
1971	if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
1972	    goto out;
1973	error = 0;
1974	break;
1975    default:
1976	goto out;
1977    }
1978
1979    /* XXX No power resource handling yet. */
1980    prw->power_res = NULL;
1981
1982out:
1983    if (prw_buffer.Pointer != NULL)
1984	AcpiOsFree(prw_buffer.Pointer);
1985    return (error);
1986}
1987
1988/*
1989 * Enable/Disable ACPI
1990 */
1991ACPI_STATUS
1992acpi_Enable(struct acpi_softc *sc)
1993{
1994    ACPI_STATUS	status;
1995    u_int32_t	flags;
1996
1997    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1998    ACPI_ASSERTLOCK;
1999
2000    flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
2001	    ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
2002    if (!sc->acpi_enabled)
2003	status = AcpiEnableSubsystem(flags);
2004    else
2005	status = AE_OK;
2006
2007    if (status == AE_OK)
2008	sc->acpi_enabled = 1;
2009
2010    return_ACPI_STATUS (status);
2011}
2012
2013ACPI_STATUS
2014acpi_Disable(struct acpi_softc *sc)
2015{
2016    ACPI_STATUS	status;
2017
2018    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2019    ACPI_ASSERTLOCK;
2020
2021    if (sc->acpi_enabled)
2022	status = AcpiDisable();
2023    else
2024	status = AE_OK;
2025
2026    if (status == AE_OK)
2027	sc->acpi_enabled = 0;
2028
2029    return_ACPI_STATUS (status);
2030}
2031
2032/*
2033 * ACPI Event Handlers
2034 */
2035
2036/* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
2037
2038static void
2039acpi_system_eventhandler_sleep(void *arg, int state)
2040{
2041    ACPI_LOCK_DECL;
2042    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2043
2044    ACPI_LOCK;
2045    if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
2046	acpi_SetSleepState((struct acpi_softc *)arg, state);
2047    ACPI_UNLOCK;
2048    return_VOID;
2049}
2050
2051static void
2052acpi_system_eventhandler_wakeup(void *arg, int state)
2053{
2054    ACPI_LOCK_DECL;
2055    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2056
2057    /* Well, what to do? :-) */
2058
2059    ACPI_LOCK;
2060    ACPI_UNLOCK;
2061
2062    return_VOID;
2063}
2064
2065/*
2066 * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
2067 */
2068UINT32
2069acpi_event_power_button_sleep(void *context)
2070{
2071    struct acpi_softc	*sc = (struct acpi_softc *)context;
2072
2073    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2074
2075    EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
2076
2077    return_VALUE (ACPI_INTERRUPT_HANDLED);
2078}
2079
2080UINT32
2081acpi_event_power_button_wake(void *context)
2082{
2083    struct acpi_softc	*sc = (struct acpi_softc *)context;
2084
2085    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2086
2087    EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
2088
2089    return_VALUE (ACPI_INTERRUPT_HANDLED);
2090}
2091
2092UINT32
2093acpi_event_sleep_button_sleep(void *context)
2094{
2095    struct acpi_softc	*sc = (struct acpi_softc *)context;
2096
2097    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2098
2099    EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
2100
2101    return_VALUE (ACPI_INTERRUPT_HANDLED);
2102}
2103
2104UINT32
2105acpi_event_sleep_button_wake(void *context)
2106{
2107    struct acpi_softc	*sc = (struct acpi_softc *)context;
2108
2109    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2110
2111    EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
2112
2113    return_VALUE (ACPI_INTERRUPT_HANDLED);
2114}
2115
2116/*
2117 * XXX This is kinda ugly, and should not be here.
2118 */
2119struct acpi_staticbuf {
2120    ACPI_BUFFER	buffer;
2121    char	data[512];
2122};
2123
2124char *
2125acpi_name(ACPI_HANDLE handle)
2126{
2127    static struct acpi_staticbuf	buf;
2128
2129    ACPI_ASSERTLOCK;
2130
2131    buf.buffer.Length = 512;
2132    buf.buffer.Pointer = &buf.data[0];
2133
2134    if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
2135	return (buf.buffer.Pointer);
2136
2137    return ("(unknown path)");
2138}
2139
2140/*
2141 * Debugging/bug-avoidance.  Avoid trying to fetch info on various
2142 * parts of the namespace.
2143 */
2144int
2145acpi_avoid(ACPI_HANDLE handle)
2146{
2147    char	*cp, *env, *np;
2148    int		len;
2149
2150    np = acpi_name(handle);
2151    if (*np == '\\')
2152	np++;
2153    if ((env = getenv("debug.acpi.avoid")) == NULL)
2154	return (0);
2155
2156    /* Scan the avoid list checking for a match */
2157    cp = env;
2158    for (;;) {
2159	while ((*cp != 0) && isspace(*cp))
2160	    cp++;
2161	if (*cp == 0)
2162	    break;
2163	len = 0;
2164	while ((cp[len] != 0) && !isspace(cp[len]))
2165	    len++;
2166	if (!strncmp(cp, np, len)) {
2167	    freeenv(env);
2168	    return(1);
2169	}
2170	cp += len;
2171    }
2172    freeenv(env);
2173
2174    return (0);
2175}
2176
2177/*
2178 * Debugging/bug-avoidance.  Disable ACPI subsystem components.
2179 */
2180int
2181acpi_disabled(char *subsys)
2182{
2183    char	*cp, *env;
2184    int		len;
2185
2186    if ((env = getenv("debug.acpi.disabled")) == NULL)
2187	return (0);
2188    if (strcmp(env, "all") == 0) {
2189	freeenv(env);
2190	return (1);
2191    }
2192
2193    /* Scan the disable list, checking for a match. */
2194    cp = env;
2195    for (;;) {
2196	while (*cp != '\0' && isspace(*cp))
2197	    cp++;
2198	if (*cp == '\0')
2199	    break;
2200	len = 0;
2201	while (cp[len] != '\0' && !isspace(cp[len]))
2202	    len++;
2203	if (strncmp(cp, subsys, len) == 0) {
2204	    freeenv(env);
2205	    return (1);
2206	}
2207	cp += len;
2208    }
2209    freeenv(env);
2210
2211    return (0);
2212}
2213
2214/*
2215 * Control interface.
2216 *
2217 * We multiplex ioctls for all participating ACPI devices here.  Individual
2218 * drivers wanting to be accessible via /dev/acpi should use the
2219 * register/deregister interface to make their handlers visible.
2220 */
2221struct acpi_ioctl_hook
2222{
2223    TAILQ_ENTRY(acpi_ioctl_hook) link;
2224    u_long			 cmd;
2225    acpi_ioctl_fn		 fn;
2226    void			 *arg;
2227};
2228
2229static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
2230static int				acpi_ioctl_hooks_initted;
2231
2232/*
2233 * Register an ioctl handler.
2234 */
2235int
2236acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
2237{
2238    struct acpi_ioctl_hook	*hp;
2239
2240    if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
2241	return (ENOMEM);
2242    hp->cmd = cmd;
2243    hp->fn = fn;
2244    hp->arg = arg;
2245    if (acpi_ioctl_hooks_initted == 0) {
2246	TAILQ_INIT(&acpi_ioctl_hooks);
2247	acpi_ioctl_hooks_initted = 1;
2248    }
2249    TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
2250    return (0);
2251}
2252
2253/*
2254 * Deregister an ioctl handler.
2255 */
2256void
2257acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
2258{
2259    struct acpi_ioctl_hook	*hp;
2260
2261    TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
2262	if ((hp->cmd == cmd) && (hp->fn == fn))
2263	    break;
2264
2265    if (hp != NULL) {
2266	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
2267	free(hp, M_ACPIDEV);
2268    }
2269}
2270
2271static int
2272acpiopen(dev_t dev, int flag, int fmt, d_thread_t *td)
2273{
2274    return (0);
2275}
2276
2277static int
2278acpiclose(dev_t dev, int flag, int fmt, d_thread_t *td)
2279{
2280    return (0);
2281}
2282
2283static int
2284acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
2285{
2286    struct acpi_softc		*sc;
2287    struct acpi_ioctl_hook	*hp;
2288    int				error, xerror, state;
2289    ACPI_LOCK_DECL;
2290
2291    ACPI_LOCK;
2292
2293    error = state = 0;
2294    sc = dev->si_drv1;
2295
2296    /*
2297     * Scan the list of registered ioctls, looking for handlers.
2298     */
2299    if (acpi_ioctl_hooks_initted) {
2300	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
2301	    if (hp->cmd == cmd) {
2302		xerror = hp->fn(cmd, addr, hp->arg);
2303		if (xerror != 0)
2304		    error = xerror;
2305		goto out;
2306	    }
2307	}
2308    }
2309
2310    /*
2311     * Core ioctls are not permitted for non-writable user.
2312     * Currently, other ioctls just fetch information.
2313     * Not changing system behavior.
2314     */
2315    if((flag & FWRITE) == 0)
2316	return (EPERM);
2317
2318    /* Core system ioctls. */
2319    switch (cmd) {
2320    case ACPIIO_ENABLE:
2321	if (ACPI_FAILURE(acpi_Enable(sc)))
2322	    error = ENXIO;
2323	break;
2324    case ACPIIO_DISABLE:
2325	if (ACPI_FAILURE(acpi_Disable(sc)))
2326	    error = ENXIO;
2327	break;
2328    case ACPIIO_SETSLPSTATE:
2329	if (!sc->acpi_enabled) {
2330	    error = ENXIO;
2331	    break;
2332	}
2333	state = *(int *)addr;
2334	if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
2335	    if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
2336		error = EINVAL;
2337	} else {
2338	    error = EINVAL;
2339	}
2340	break;
2341    default:
2342	if (error == 0)
2343	    error = EINVAL;
2344	break;
2345    }
2346
2347out:
2348    ACPI_UNLOCK;
2349    return (error);
2350}
2351
2352static int
2353acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2354{
2355    char sleep_state[4];
2356    char buf[16];
2357    int error;
2358    UINT8 state, TypeA, TypeB;
2359
2360    buf[0] = '\0';
2361    for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX + 1; state++) {
2362	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
2363	    sprintf(sleep_state, "S%d ", state);
2364	    strcat(buf, sleep_state);
2365	}
2366    }
2367    error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2368    return (error);
2369}
2370
2371static int
2372acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2373{
2374    char sleep_state[10];
2375    int error;
2376    u_int new_state, old_state;
2377
2378    old_state = *(u_int *)oidp->oid_arg1;
2379    if (old_state > ACPI_S_STATES_MAX + 1) {
2380	strcpy(sleep_state, "unknown");
2381    } else {
2382	bzero(sleep_state, sizeof(sleep_state));
2383	strncpy(sleep_state, sleep_state_names[old_state],
2384		sizeof(sleep_state_names[old_state]));
2385    }
2386    error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
2387    if (error == 0 && req->newptr != NULL) {
2388	new_state = ACPI_STATE_S0;
2389	for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++) {
2390	    if (strncmp(sleep_state, sleep_state_names[new_state],
2391			sizeof(sleep_state)) == 0)
2392		break;
2393	}
2394	if (new_state <= ACPI_S_STATES_MAX + 1) {
2395	    if (new_state != old_state)
2396		*(u_int *)oidp->oid_arg1 = new_state;
2397	} else {
2398	    error = EINVAL;
2399	}
2400    }
2401
2402    return (error);
2403}
2404
2405/* Inform devctl(4) when we receive a Notify. */
2406void
2407acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
2408{
2409    char		notify_buf[16];
2410    ACPI_BUFFER		handle_buf;
2411    ACPI_STATUS		status;
2412
2413    if (subsystem == NULL)
2414	return;
2415
2416    handle_buf.Pointer = NULL;
2417    handle_buf.Length = ACPI_ALLOCATE_BUFFER;
2418    status = AcpiNsHandleToPathname(h, &handle_buf);
2419    if (ACPI_FAILURE(status))
2420	return;
2421    snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
2422    devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
2423    AcpiOsFree(handle_buf.Pointer);
2424}
2425
2426#ifdef ACPI_DEBUG
2427/*
2428 * Support for parsing debug options from the kernel environment.
2429 *
2430 * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
2431 * by specifying the names of the bits in the debug.acpi.layer and
2432 * debug.acpi.level environment variables.  Bits may be unset by
2433 * prefixing the bit name with !.
2434 */
2435struct debugtag
2436{
2437    char	*name;
2438    UINT32	value;
2439};
2440
2441static struct debugtag	dbg_layer[] = {
2442    {"ACPI_UTILITIES",		ACPI_UTILITIES},
2443    {"ACPI_HARDWARE",		ACPI_HARDWARE},
2444    {"ACPI_EVENTS",		ACPI_EVENTS},
2445    {"ACPI_TABLES",		ACPI_TABLES},
2446    {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
2447    {"ACPI_PARSER",		ACPI_PARSER},
2448    {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
2449    {"ACPI_EXECUTER",		ACPI_EXECUTER},
2450    {"ACPI_RESOURCES",		ACPI_RESOURCES},
2451    {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
2452    {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
2453    {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
2454    {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
2455
2456    {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
2457    {"ACPI_BATTERY",		ACPI_BATTERY},
2458    {"ACPI_BUS",		ACPI_BUS},
2459    {"ACPI_BUTTON",		ACPI_BUTTON},
2460    {"ACPI_EC", 		ACPI_EC},
2461    {"ACPI_FAN",		ACPI_FAN},
2462    {"ACPI_POWERRES",		ACPI_POWERRES},
2463    {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
2464    {"ACPI_THERMAL",		ACPI_THERMAL},
2465    {"ACPI_TIMER",		ACPI_TIMER},
2466    {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
2467    {NULL, 0}
2468};
2469
2470static struct debugtag dbg_level[] = {
2471    {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
2472    {"ACPI_LV_WARN",		ACPI_LV_WARN},
2473    {"ACPI_LV_INIT",		ACPI_LV_INIT},
2474    {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
2475    {"ACPI_LV_INFO",		ACPI_LV_INFO},
2476    {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
2477
2478    /* Trace verbosity level 1 [Standard Trace Level] */
2479    {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
2480    {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
2481    {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
2482    {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
2483    {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
2484    {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
2485    {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
2486    {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
2487    {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
2488    {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
2489    {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
2490    {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
2491    {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
2492    {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
2493    {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
2494
2495    /* Trace verbosity level 2 [Function tracing and memory allocation] */
2496    {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
2497    {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
2498    {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
2499    {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
2500    {"ACPI_LV_ALL",		ACPI_LV_ALL},
2501
2502    /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2503    {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
2504    {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
2505    {"ACPI_LV_IO",		ACPI_LV_IO},
2506    {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
2507    {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
2508
2509    /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2510    {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
2511    {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
2512    {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
2513    {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
2514    {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
2515    {NULL, 0}
2516};
2517
2518static void
2519acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2520{
2521    char	*ep;
2522    int		i, l;
2523    int		set;
2524
2525    while (*cp) {
2526	if (isspace(*cp)) {
2527	    cp++;
2528	    continue;
2529	}
2530	ep = cp;
2531	while (*ep && !isspace(*ep))
2532	    ep++;
2533	if (*cp == '!') {
2534	    set = 0;
2535	    cp++;
2536	    if (cp == ep)
2537		continue;
2538	} else {
2539	    set = 1;
2540	}
2541	l = ep - cp;
2542	for (i = 0; tag[i].name != NULL; i++) {
2543	    if (!strncmp(cp, tag[i].name, l)) {
2544		if (set)
2545		    *flag |= tag[i].value;
2546		else
2547		    *flag &= ~tag[i].value;
2548	    }
2549	}
2550	cp = ep;
2551    }
2552}
2553
2554static void
2555acpi_set_debugging(void *junk)
2556{
2557    char	*layer, *level;
2558
2559    if (cold) {
2560	AcpiDbgLayer = 0;
2561	AcpiDbgLevel = 0;
2562    }
2563
2564    layer = getenv("debug.acpi.layer");
2565    level = getenv("debug.acpi.level");
2566    if (layer == NULL && level == NULL)
2567	return;
2568
2569    printf("ACPI set debug");
2570    if (layer != NULL) {
2571	if (strcmp("NONE", layer) != 0)
2572	    printf(" layer '%s'", layer);
2573	acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
2574	freeenv(layer);
2575    }
2576    if (level != NULL) {
2577	if (strcmp("NONE", level) != 0)
2578	    printf(" level '%s'", level);
2579	acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
2580	freeenv(level);
2581    }
2582    printf("\n");
2583}
2584SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
2585	NULL);
2586
2587static int
2588acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
2589{
2590    int		 error, *dbg;
2591    struct	 debugtag *tag;
2592    struct	 sbuf sb;
2593
2594    if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
2595	return (ENOMEM);
2596    if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
2597	tag = &dbg_layer[0];
2598	dbg = &AcpiDbgLayer;
2599    } else {
2600	tag = &dbg_level[0];
2601	dbg = &AcpiDbgLevel;
2602    }
2603
2604    /* Get old values if this is a get request. */
2605    if (*dbg == 0) {
2606	sbuf_cpy(&sb, "NONE");
2607    } else if (req->newptr == NULL) {
2608	for (; tag->name != NULL; tag++) {
2609	    if ((*dbg & tag->value) == tag->value)
2610		sbuf_printf(&sb, "%s ", tag->name);
2611	}
2612    }
2613    sbuf_trim(&sb);
2614    sbuf_finish(&sb);
2615
2616    /* Copy out the old values to the user. */
2617    error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
2618    sbuf_delete(&sb);
2619
2620    /* If the user is setting a string, parse it. */
2621    if (error == 0 && req->newptr != NULL) {
2622	*dbg = 0;
2623	setenv((char *)oidp->oid_arg1, (char *)req->newptr);
2624	acpi_set_debugging(NULL);
2625    }
2626
2627    return (error);
2628}
2629SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
2630	    "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
2631SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
2632	    "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
2633#endif
2634
2635static int
2636acpi_pm_func(u_long cmd, void *arg, ...)
2637{
2638	int	state, acpi_state;
2639	int	error;
2640	struct	acpi_softc *sc;
2641	va_list	ap;
2642
2643	error = 0;
2644	switch (cmd) {
2645	case POWER_CMD_SUSPEND:
2646		sc = (struct acpi_softc *)arg;
2647		if (sc == NULL) {
2648			error = EINVAL;
2649			goto out;
2650		}
2651
2652		va_start(ap, arg);
2653		state = va_arg(ap, int);
2654		va_end(ap);
2655
2656		switch (state) {
2657		case POWER_SLEEP_STATE_STANDBY:
2658			acpi_state = sc->acpi_standby_sx;
2659			break;
2660		case POWER_SLEEP_STATE_SUSPEND:
2661			acpi_state = sc->acpi_suspend_sx;
2662			break;
2663		case POWER_SLEEP_STATE_HIBERNATE:
2664			acpi_state = ACPI_STATE_S4;
2665			break;
2666		default:
2667			error = EINVAL;
2668			goto out;
2669		}
2670
2671		acpi_SetSleepState(sc, acpi_state);
2672		break;
2673	default:
2674		error = EINVAL;
2675		goto out;
2676	}
2677
2678out:
2679	return (error);
2680}
2681
2682static void
2683acpi_pm_register(void *arg)
2684{
2685    if (!cold || resource_disabled("acpi", 0))
2686	return;
2687
2688    power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2689}
2690
2691SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
2692