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