acpi.c revision 126767
1178173Simp/*-
2178173Simp * Copyright (c) 2000 Takanori Watanabe <takawata@jp.freebsd.org>
3178173Simp * Copyright (c) 2000 Mitsuru IWASAKI <iwasaki@jp.freebsd.org>
4178173Simp * Copyright (c) 2000, 2001 Michael Smith
5178173Simp * Copyright (c) 2000 BSDi
6178173Simp * All rights reserved.
7178173Simp *
8178173Simp * Redistribution and use in source and binary forms, with or without
9178173Simp * modification, are permitted provided that the following conditions
10178173Simp * are met:
11178173Simp * 1. Redistributions of source code must retain the above copyright
12178173Simp *    notice, this list of conditions and the following disclaimer.
13178173Simp * 2. Redistributions in binary form must reproduce the above copyright
14178173Simp *    notice, this list of conditions and the following disclaimer in the
15178173Simp *    documentation and/or other materials provided with the distribution.
16178173Simp *
17178173Simp * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18178173Simp * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19178173Simp * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20178173Simp * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21178173Simp * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22178173Simp * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23178173Simp * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24178173Simp * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25178173Simp * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26178173Simp * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27178173Simp * SUCH DAMAGE.
28178173Simp *
29178173Simp *	$FreeBSD: head/sys/dev/acpica/acpi.c 126767 2004-03-09 05:44:47Z njl $
30178173Simp */
31178173Simp
32178173Simp#include "opt_acpi.h"
33178173Simp#include <sys/param.h>
34178173Simp#include <sys/kernel.h>
35178173Simp#include <sys/proc.h>
36178173Simp#include <sys/fcntl.h>
37178173Simp#include <sys/malloc.h>
38178173Simp#include <sys/bus.h>
39178173Simp#include <sys/conf.h>
40178173Simp#include <sys/ioccom.h>
41178173Simp#include <sys/reboot.h>
42178173Simp#include <sys/sysctl.h>
43178173Simp#include <sys/ctype.h>
44178173Simp#include <sys/linker.h>
45178173Simp#include <sys/power.h>
46178173Simp#include <sys/sbuf.h>
47178173Simp
48178173Simp#include <machine/clock.h>
49178173Simp#include <machine/resource.h>
50178173Simp#include <machine/bus.h>
51178173Simp#include <sys/rman.h>
52178173Simp#include <isa/isavar.h>
53178173Simp
54178173Simp#include "acpi.h"
55178173Simp#include <dev/acpica/acpivar.h>
56178173Simp#include <dev/acpica/acpiio.h>
57178173Simp#include <contrib/dev/acpica/acnamesp.h>
58178173Simp
59MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
60
61/* Hooks for the ACPI CA debugging infrastructure */
62#define _COMPONENT	ACPI_BUS
63ACPI_MODULE_NAME("ACPI")
64
65static d_open_t		acpiopen;
66static d_close_t	acpiclose;
67static d_ioctl_t	acpiioctl;
68
69static struct cdevsw acpi_cdevsw = {
70	.d_version =	D_VERSION,
71	.d_flags =	D_NEEDGIANT,
72	.d_open =	acpiopen,
73	.d_close =	acpiclose,
74	.d_ioctl =	acpiioctl,
75	.d_name =	"acpi",
76};
77
78static const char* sleep_state_names[] = {
79    "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
80
81/* this has to be static, as the softc is gone when we need it */
82static int acpi_off_state = ACPI_STATE_S5;
83
84#if __FreeBSD_version >= 500000
85struct mtx	acpi_mutex;
86#endif
87
88struct acpi_quirks {
89    char	*OemId;
90    uint32_t	OemRevision;
91    char	*value;
92};
93
94#define ACPI_OEM_REV_ANY	0
95
96static struct acpi_quirks acpi_quirks_table[] = {
97#ifdef notyet
98    /* Bad PCI routing table.  Used on some SuperMicro boards. */
99    { "PTLTD ", 0x06040000, "pci_link" },
100#endif
101
102    { NULL, 0, NULL }
103};
104
105static int	acpi_modevent(struct module *mod, int event, void *junk);
106static void	acpi_identify(driver_t *driver, device_t parent);
107static int	acpi_probe(device_t dev);
108static int	acpi_attach(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 int	acpi_set_resource(device_t dev, device_t child, int type,
118			int rid, u_long start, u_long count);
119static int	acpi_get_resource(device_t dev, device_t child, int type,
120			int rid, u_long *startp, u_long *countp);
121static struct resource *acpi_alloc_resource(device_t bus, device_t child,
122			int type, int *rid, u_long start, u_long end,
123			u_long count, u_int flags);
124static int	acpi_release_resource(device_t bus, device_t child, int type,
125			int rid, struct resource *r);
126static uint32_t	acpi_isa_get_logicalid(device_t dev);
127static int	acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
128static int	acpi_isa_pnp_probe(device_t bus, device_t child,
129			struct isa_pnp_id *ids);
130static void	acpi_probe_children(device_t bus);
131static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
132			void *context, void **status);
133static void	acpi_shutdown_pre_sync(void *arg, int howto);
134static void	acpi_shutdown_final(void *arg, int howto);
135static void	acpi_enable_fixed_events(struct acpi_softc *sc);
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, ...);
141
142static device_method_t acpi_methods[] = {
143    /* Device interface */
144    DEVMETHOD(device_identify,		acpi_identify),
145    DEVMETHOD(device_probe,		acpi_probe),
146    DEVMETHOD(device_attach,		acpi_attach),
147    DEVMETHOD(device_detach,		bus_generic_detach),
148    DEVMETHOD(device_shutdown,		bus_generic_shutdown),
149    DEVMETHOD(device_suspend,		bus_generic_suspend),
150    DEVMETHOD(device_resume,		bus_generic_resume),
151
152    /* Bus interface */
153    DEVMETHOD(bus_add_child,		acpi_add_child),
154    DEVMETHOD(bus_print_child,		acpi_print_child),
155    DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
156    DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
157    DEVMETHOD(bus_set_resource,		acpi_set_resource),
158    DEVMETHOD(bus_get_resource,		acpi_get_resource),
159    DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
160    DEVMETHOD(bus_release_resource,	acpi_release_resource),
161    DEVMETHOD(bus_driver_added,		bus_generic_driver_added),
162    DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
163    DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
164    DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
165    DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
166
167    /* ISA emulation */
168    DEVMETHOD(isa_pnp_probe,		acpi_isa_pnp_probe),
169
170    {0, 0}
171};
172
173static driver_t acpi_driver = {
174    "acpi",
175    acpi_methods,
176    sizeof(struct acpi_softc),
177};
178
179static devclass_t acpi_devclass;
180DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
181MODULE_VERSION(acpi, 100);
182
183SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RW, NULL, "ACPI debugging");
184static char acpi_ca_version[12];
185SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
186	      acpi_ca_version, 0, "Version of Intel ACPI-CA");
187
188/*
189 * ACPI can only be loaded as a module by the loader; activating it after
190 * system bootstrap time is not useful, and can be fatal to the system.
191 * It also cannot be unloaded, since the entire system bus heirarchy hangs
192 * off it.
193 */
194static int
195acpi_modevent(struct module *mod, int event, void *junk)
196{
197    switch(event) {
198    case MOD_LOAD:
199	if (!cold) {
200	    printf("The ACPI driver cannot be loaded after boot.\n");
201	    return (EPERM);
202	}
203	break;
204    case MOD_UNLOAD:
205	if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
206	    return (EBUSY);
207	break;
208    default:
209	break;
210    }
211    return (0);
212}
213
214/*
215 * Perform early initialization.
216 */
217ACPI_STATUS
218acpi_Startup(void)
219{
220#ifdef ACPI_DEBUGGER
221    char *debugpoint;
222#endif
223    static int error, started = 0;
224
225    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
226
227    if (started)
228	return_VALUE (error);
229    started = 1;
230
231#if __FreeBSD_version >= 500000
232    /* Initialise the ACPI mutex */
233    mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
234#endif
235
236    /* Start up the ACPI CA subsystem. */
237#ifdef ACPI_DEBUGGER
238    debugpoint = getenv("debug.acpi.debugger");
239    if (debugpoint) {
240	if (!strcmp(debugpoint, "init"))
241	    acpi_EnterDebugger();
242	freeenv(debugpoint);
243    }
244#endif
245    if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
246	printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
247	return_VALUE (error);
248    }
249#ifdef ACPI_DEBUGGER
250    debugpoint = getenv("debug.acpi.debugger");
251    if (debugpoint) {
252	if (!strcmp(debugpoint, "tables"))
253	    acpi_EnterDebugger();
254	freeenv(debugpoint);
255    }
256#endif
257
258    if (ACPI_FAILURE(error = AcpiLoadTables())) {
259	printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
260	return_VALUE(error);
261    }
262
263    /* Set up any quirks we have for this XSDT. */
264    acpi_quirks_set();
265    if (acpi_disabled("acpi"))
266	return_VALUE (AE_ERROR);
267
268    return_VALUE (AE_OK);
269}
270
271/*
272 * Detect ACPI, perform early initialisation
273 */
274static void
275acpi_identify(driver_t *driver, device_t parent)
276{
277    device_t	child;
278
279    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
280
281    if (!cold)
282	return_VOID;
283
284    /* Check that we haven't been disabled with a hint. */
285    if (resource_disabled("acpi", 0))
286	return_VOID;
287
288    /* Make sure we're not being doubly invoked. */
289    if (device_find_child(parent, "acpi", 0) != NULL)
290	return_VOID;
291
292    /* Initialize ACPI-CA. */
293    if (ACPI_FAILURE(acpi_Startup()))
294	return_VOID;
295
296    snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%#x", ACPI_CA_VERSION);
297
298    /* Attach the actual ACPI device. */
299    if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
300	device_printf(parent, "ACPI: could not attach\n");
301	return_VOID;
302    }
303}
304
305/*
306 * Fetch some descriptive data from ACPI to put in our attach message
307 */
308static int
309acpi_probe(device_t dev)
310{
311    ACPI_TABLE_HEADER	th;
312    char		buf[20];
313    int			error;
314    struct sbuf		sb;
315    ACPI_STATUS		status;
316    ACPI_LOCK_DECL;
317
318    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
319
320    if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
321	power_pm_get_type() != POWER_PM_TYPE_ACPI) {
322
323	device_printf(dev, "Other PM system enabled.\n");
324	return_VALUE(ENXIO);
325    }
326
327    ACPI_LOCK;
328
329    if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
330	device_printf(dev, "couldn't get XSDT header: %s\n",
331		      AcpiFormatException(status));
332	error = ENXIO;
333    } else {
334	sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
335	sbuf_bcat(&sb, th.OemId, 6);
336	sbuf_trim(&sb);
337	sbuf_putc(&sb, ' ');
338	sbuf_bcat(&sb, th.OemTableId, 8);
339	sbuf_trim(&sb);
340	sbuf_finish(&sb);
341	device_set_desc_copy(dev, sbuf_data(&sb));
342	sbuf_delete(&sb);
343	error = 0;
344    }
345    ACPI_UNLOCK;
346    return_VALUE(error);
347}
348
349static int
350acpi_attach(device_t dev)
351{
352    struct acpi_softc	*sc;
353    ACPI_STATUS		status;
354    int			error;
355    UINT32		flags;
356    char		*env;
357#ifdef ACPI_DEBUGGER
358    char		*debugpoint;
359#endif
360    ACPI_LOCK_DECL;
361
362    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
363    ACPI_LOCK;
364    sc = device_get_softc(dev);
365    bzero(sc, sizeof(*sc));
366    sc->acpi_dev = dev;
367
368#ifdef ACPI_DEBUGGER
369    debugpoint = getenv("debug.acpi.debugger");
370    if (debugpoint) {
371	if (!strcmp(debugpoint, "spaces"))
372	    acpi_EnterDebugger();
373	freeenv(debugpoint);
374    }
375#endif
376
377    /* Install the default address space handlers. */
378    error = ENXIO;
379    status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
380		ACPI_ADR_SPACE_SYSTEM_MEMORY, ACPI_DEFAULT_HANDLER, NULL, NULL);
381    if (ACPI_FAILURE(status)) {
382	device_printf(dev, "Could not initialise SystemMemory handler: %s\n",
383		      AcpiFormatException(status));
384	goto out;
385    }
386    status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
387		ACPI_ADR_SPACE_SYSTEM_IO, ACPI_DEFAULT_HANDLER, NULL, NULL);
388    if (ACPI_FAILURE(status)) {
389	device_printf(dev, "Could not initialise SystemIO handler: %s\n",
390		      AcpiFormatException(status));
391	goto out;
392    }
393    status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
394		ACPI_ADR_SPACE_PCI_CONFIG, ACPI_DEFAULT_HANDLER, NULL, NULL);
395    if (ACPI_FAILURE(status)) {
396	device_printf(dev, "could not initialise PciConfig handler: %s\n",
397		      AcpiFormatException(status));
398	goto out;
399    }
400
401    /*
402     * Bring ACPI fully online.
403     *
404     * Note that some systems (specifically, those with namespace evaluation
405     * issues that require the avoidance of parts of the namespace) must
406     * avoid running _INI and _STA on everything, as well as dodging the final
407     * object init pass.
408     *
409     * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
410     *
411     * XXX We should arrange for the object init pass after we have attached
412     *     all our child devices, but on many systems it works here.
413     */
414#ifdef ACPI_DEBUGGER
415    debugpoint = getenv("debug.acpi.debugger");
416    if (debugpoint) {
417	if (!strcmp(debugpoint, "enable"))
418	    acpi_EnterDebugger();
419	freeenv(debugpoint);
420    }
421#endif
422    flags = 0;
423    if (testenv("debug.acpi.avoid"))
424	flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
425    if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
426	device_printf(dev, "Could not enable ACPI: %s\n",
427		      AcpiFormatException(status));
428	goto out;
429    }
430
431    /*
432     * Call the ECDT probe function to provide EC functionality before
433     * the namespace has been evaluated.
434     */
435    acpi_ec_ecdt_probe(dev);
436
437    if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
438	device_printf(dev, "Could not initialize ACPI objects: %s\n",
439		      AcpiFormatException(status));
440	goto out;
441    }
442
443    /*
444     * Setup our sysctl tree.
445     *
446     * XXX: This doesn't check to make sure that none of these fail.
447     */
448    sysctl_ctx_init(&sc->acpi_sysctl_ctx);
449    sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
450			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
451			       device_get_name(dev), CTLFLAG_RD, 0, "");
452    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
453	OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
454	0, 0, acpi_supported_sleep_state_sysctl, "A", "");
455    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
456	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
457	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
458    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
459	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
460	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
461    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
462	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
463	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
464    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
465	OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
466	&sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
467    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
468	OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
469	&sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
470    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
471	OID_AUTO, "sleep_delay", CTLFLAG_RD | CTLFLAG_RW,
472	&sc->acpi_sleep_delay, 0, "sleep delay");
473    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
474	OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
475	&sc->acpi_s4bios, 0, "S4BIOS mode");
476    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
477	OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
478	&sc->acpi_verbose, 0, "verbose mode");
479    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
480	OID_AUTO, "disable_on_poweroff", CTLFLAG_RD | CTLFLAG_RW,
481	&sc->acpi_disable_on_poweroff, 0, "ACPI subsystem disable on poweroff");
482
483    /*
484     * Default to 5 seconds before sleeping to give some machines time to
485     * stabilize.
486     */
487    sc->acpi_sleep_delay = 5;
488    sc->acpi_disable_on_poweroff = 1;
489    if (bootverbose)
490	sc->acpi_verbose = 1;
491    if ((env = getenv("hw.acpi.verbose")) && strcmp(env, "0")) {
492	sc->acpi_verbose = 1;
493	freeenv(env);
494    }
495
496    /* Only enable S4BIOS by default if the FACS says it is available. */
497    if (AcpiGbl_FACS->S4Bios_f != 0)
498	    sc->acpi_s4bios = 1;
499
500    /*
501     * Dispatch the default sleep state to devices.
502     * TBD: should be configured from userland policy manager.
503     */
504    sc->acpi_power_button_sx = ACPI_POWER_BUTTON_DEFAULT_SX;
505    sc->acpi_sleep_button_sx = ACPI_SLEEP_BUTTON_DEFAULT_SX;
506    sc->acpi_lid_switch_sx = ACPI_LID_SWITCH_DEFAULT_SX;
507    sc->acpi_standby_sx = ACPI_STATE_S1;
508    sc->acpi_suspend_sx = ACPI_STATE_S3;
509
510    acpi_enable_fixed_events(sc);
511
512    /*
513     * Scan the namespace and attach/initialise children.
514     */
515#ifdef ACPI_DEBUGGER
516    debugpoint = getenv("debug.acpi.debugger");
517    if (debugpoint) {
518	if (!strcmp(debugpoint, "probe"))
519	    acpi_EnterDebugger();
520	freeenv(debugpoint);
521    }
522#endif
523
524    /* Register our shutdown handlers */
525    EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc,
526	SHUTDOWN_PRI_LAST);
527    EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
528	SHUTDOWN_PRI_LAST);
529
530    /*
531     * Register our acpi event handlers.
532     * XXX should be configurable eg. via userland policy manager.
533     */
534    EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
535	sc, ACPI_EVENT_PRI_LAST);
536    EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
537	sc, ACPI_EVENT_PRI_LAST);
538
539    /* Flag our initial states. */
540    sc->acpi_enabled = 1;
541    sc->acpi_sstate = ACPI_STATE_S0;
542    sc->acpi_sleep_disabled = 0;
543
544    /* Create the control device */
545    sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_WHEEL, 0644,
546			      "acpi");
547    sc->acpi_dev_t->si_drv1 = sc;
548
549#ifdef ACPI_DEBUGGER
550    debugpoint = getenv("debug.acpi.debugger");
551    if (debugpoint) {
552	if (strcmp(debugpoint, "running") == 0)
553	    acpi_EnterDebugger();
554	freeenv(debugpoint);
555    }
556#endif
557
558#ifdef ACPI_USE_THREADS
559    if ((error = acpi_task_thread_init()))
560	goto out;
561#endif
562
563    if ((error = acpi_machdep_init(dev)))
564	goto out;
565
566    /* Register ACPI again to pass the correct argument of pm_func. */
567    power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
568
569    if (!acpi_disabled("bus"))
570	acpi_probe_children(dev);
571
572    error = 0;
573
574 out:
575    ACPI_UNLOCK;
576    return_VALUE (error);
577}
578
579static void
580acpi_quirks_set()
581{
582    XSDT_DESCRIPTOR *xsdt;
583    struct acpi_quirks *quirk;
584    char *env, *tmp;
585    int len;
586
587    /*
588     * If the user loaded a custom table or disabled "quirks", leave
589     * the settings alone.
590     */
591    len = 0;
592    if ((env = getenv("acpi_dsdt_load")) != NULL) {
593	/* XXX No strcasecmp but this is good enough. */
594	if (*env == 'Y' || *env == 'y')
595	    goto out;
596	freeenv(env);
597    }
598    if ((env = getenv("debug.acpi.disabled")) != NULL) {
599	if (strstr("quirks", env) != NULL)
600	    goto out;
601	len = strlen(env);
602    }
603
604    /*
605     * Search through our quirk table and concatenate the disabled
606     * values with whatever we find.
607     */
608    xsdt = AcpiGbl_XSDT;
609    for (quirk = acpi_quirks_table; quirk->OemId; quirk++) {
610	if (!strncmp(xsdt->OemId, quirk->OemId, strlen(quirk->OemId)) &&
611	    (xsdt->OemRevision == quirk->OemRevision ||
612	    quirk->OemRevision == ACPI_OEM_REV_ANY)) {
613		len += strlen(quirk->value) + 2;
614		if ((tmp = malloc(len, M_TEMP, M_NOWAIT)) == NULL)
615		    goto out;
616		sprintf(tmp, "%s %s", env ? env : "", quirk->value);
617		setenv("debug.acpi.disabled", tmp);
618		free(tmp, M_TEMP);
619		break;
620	}
621    }
622
623out:
624    if (env)
625	freeenv(env);
626}
627
628/*
629 * Handle a new device being added
630 */
631static device_t
632acpi_add_child(device_t bus, int order, const char *name, int unit)
633{
634    struct acpi_device	*ad;
635    device_t		child;
636
637    if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT | M_ZERO)) == NULL)
638	return (NULL);
639
640    resource_list_init(&ad->ad_rl);
641
642    child = device_add_child_ordered(bus, order, name, unit);
643    if (child != NULL)
644	device_set_ivars(child, ad);
645    return (child);
646}
647
648static int
649acpi_print_child(device_t bus, device_t child)
650{
651    struct acpi_device	 *adev = device_get_ivars(child);
652    struct resource_list *rl = &adev->ad_rl;
653    int retval = 0;
654
655    retval += bus_print_child_header(bus, child);
656    retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
657    retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
658    retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
659    retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
660    retval += bus_print_child_footer(bus, child);
661
662    return (retval);
663}
664
665/*
666 * Handle per-device ivars
667 */
668static int
669acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
670{
671    struct acpi_device	*ad;
672
673    if ((ad = device_get_ivars(child)) == NULL) {
674	printf("device has no ivars\n");
675	return (ENOENT);
676    }
677
678    /* ACPI and ISA compatibility ivars */
679    switch(index) {
680    case ACPI_IVAR_HANDLE:
681	*(ACPI_HANDLE *)result = ad->ad_handle;
682	break;
683    case ACPI_IVAR_MAGIC:
684	*(int *)result = ad->ad_magic;
685	break;
686    case ACPI_IVAR_PRIVATE:
687	*(void **)result = ad->ad_private;
688	break;
689    case ISA_IVAR_VENDORID:
690    case ISA_IVAR_SERIAL:
691    case ISA_IVAR_COMPATID:
692	*(int *)result = -1;
693	break;
694    case ISA_IVAR_LOGICALID:
695	*(int *)result = acpi_isa_get_logicalid(child);
696	break;
697    default:
698	return (ENOENT);
699    }
700
701    return (0);
702}
703
704static int
705acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
706{
707    struct acpi_device	*ad;
708
709    if ((ad = device_get_ivars(child)) == NULL) {
710	printf("device has no ivars\n");
711	return (ENOENT);
712    }
713
714    switch(index) {
715    case ACPI_IVAR_HANDLE:
716	ad->ad_handle = (ACPI_HANDLE)value;
717	break;
718    case ACPI_IVAR_MAGIC:
719	ad->ad_magic = (int)value;
720	break;
721    case ACPI_IVAR_PRIVATE:
722	ad->ad_private = (void *)value;
723	break;
724    default:
725	panic("bad ivar write request (%d)", index);
726	return (ENOENT);
727    }
728
729    return (0);
730}
731
732ACPI_HANDLE
733acpi_get_handle(device_t dev)
734{
735    uintptr_t up;
736    ACPI_HANDLE	h;
737
738    if (BUS_READ_IVAR(device_get_parent(dev), dev, ACPI_IVAR_HANDLE, &up))
739	return(NULL);
740    h = (ACPI_HANDLE)up;
741    return (h);
742}
743
744int
745acpi_set_handle(device_t dev, ACPI_HANDLE h)
746{
747    uintptr_t up;
748
749    up = (uintptr_t)h;
750    return (BUS_WRITE_IVAR(device_get_parent(dev), dev, ACPI_IVAR_HANDLE, up));
751}
752
753int
754acpi_get_magic(device_t dev)
755{
756    uintptr_t up;
757    int	m;
758
759    if (BUS_READ_IVAR(device_get_parent(dev), dev, ACPI_IVAR_MAGIC, &up))
760	return(0);
761    m = (int)up;
762    return (m);
763}
764
765int
766acpi_set_magic(device_t dev, int m)
767{
768    uintptr_t up;
769
770    up = (uintptr_t)m;
771    return (BUS_WRITE_IVAR(device_get_parent(dev), dev, ACPI_IVAR_MAGIC, up));
772}
773
774void *
775acpi_get_private(device_t dev)
776{
777    uintptr_t up;
778    void *p;
779
780    if (BUS_READ_IVAR(device_get_parent(dev), dev, ACPI_IVAR_PRIVATE, &up))
781	return (NULL);
782    p = (void *)up;
783    return (p);
784}
785
786int
787acpi_set_private(device_t dev, void *p)
788{
789    uintptr_t up;
790
791    up = (uintptr_t)p;
792    return (BUS_WRITE_IVAR(device_get_parent(dev), dev, ACPI_IVAR_PRIVATE, up));
793}
794
795ACPI_OBJECT_TYPE
796acpi_get_type(device_t dev)
797{
798    ACPI_HANDLE		h;
799    ACPI_OBJECT_TYPE	t;
800
801    if ((h = acpi_get_handle(dev)) == NULL)
802	return (ACPI_TYPE_NOT_FOUND);
803    if (AcpiGetType(h, &t) != AE_OK)
804	return (ACPI_TYPE_NOT_FOUND);
805    return (t);
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(dev, type, rid, 0, ~0, 1, 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	    /*
1112	     * Check that the device is present.  If it's not present,
1113	     * leave it disabled (so that we have a device_t attached to
1114	     * the handle, but we don't probe it).
1115	     */
1116	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1117		device_disable(child);
1118		break;
1119	    }
1120
1121	    /*
1122	     * Get the device's resource settings and attach them.
1123	     * Note that if the device has _PRS but no _CRS, we need
1124	     * to decide when it's appropriate to try to configure the
1125	     * device.  Ignore the return value here; it's OK for the
1126	     * device not to have any resources.
1127	     */
1128	    acpi_parse_resources(child, handle, &acpi_res_parse_set);
1129
1130	    /* If we're debugging, probe/attach now rather than later */
1131	    ACPI_DEBUG_EXEC(device_probe_and_attach(child));
1132	    break;
1133	}
1134    }
1135
1136    return_ACPI_STATUS (AE_OK);
1137}
1138
1139static void
1140acpi_shutdown_pre_sync(void *arg, int howto)
1141{
1142    struct acpi_softc *sc = arg;
1143
1144    ACPI_ASSERTLOCK;
1145
1146    /*
1147     * Disable all ACPI events before soft off, otherwise the system
1148     * will be turned on again on some laptops.
1149     *
1150     * XXX this should probably be restricted to masking some events just
1151     *     before powering down, since we may still need ACPI during the
1152     *     shutdown process.
1153     */
1154    if (sc->acpi_disable_on_poweroff)
1155	acpi_Disable(sc);
1156}
1157
1158static void
1159acpi_shutdown_final(void *arg, int howto)
1160{
1161    ACPI_STATUS	status;
1162
1163    ACPI_ASSERTLOCK;
1164
1165    if ((howto & RB_POWEROFF) != 0) {
1166	printf("Powering system off using ACPI\n");
1167	status = AcpiEnterSleepStatePrep(acpi_off_state);
1168	if (ACPI_FAILURE(status)) {
1169	    printf("AcpiEnterSleepStatePrep failed - %s\n",
1170		   AcpiFormatException(status));
1171	    return;
1172	}
1173	ACPI_DISABLE_IRQS();
1174	status = AcpiEnterSleepState(acpi_off_state);
1175	if (ACPI_FAILURE(status)) {
1176	    printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
1177	} else {
1178	    DELAY(1000000);
1179	    printf("ACPI power-off failed - timeout\n");
1180	}
1181    } else {
1182	printf("Shutting down ACPI\n");
1183	AcpiTerminate();
1184    }
1185}
1186
1187static void
1188acpi_enable_fixed_events(struct acpi_softc *sc)
1189{
1190    static int	first_time = 1;
1191
1192    ACPI_ASSERTLOCK;
1193
1194    /* Enable and clear fixed events and install handlers. */
1195    if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->PwrButton == 0) {
1196	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
1197	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
1198				     acpi_event_power_button_sleep, sc);
1199	if (first_time)
1200	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
1201    }
1202    if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->SleepButton == 0) {
1203	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
1204	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
1205				     acpi_event_sleep_button_sleep, sc);
1206	if (first_time)
1207	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
1208    }
1209
1210    first_time = 0;
1211}
1212
1213/*
1214 * Returns true if the device is actually present and should
1215 * be attached to.  This requires the present, enabled, UI-visible
1216 * and diagnostics-passed bits to be set.
1217 */
1218BOOLEAN
1219acpi_DeviceIsPresent(device_t dev)
1220{
1221    ACPI_DEVICE_INFO	*devinfo;
1222    ACPI_HANDLE		h;
1223    ACPI_BUFFER		buf;
1224    ACPI_STATUS		error;
1225    int			ret;
1226
1227    ACPI_ASSERTLOCK;
1228
1229    ret = FALSE;
1230    if ((h = acpi_get_handle(dev)) == NULL)
1231	return (FALSE);
1232    buf.Pointer = NULL;
1233    buf.Length = ACPI_ALLOCATE_BUFFER;
1234    error = AcpiGetObjectInfo(h, &buf);
1235    if (ACPI_FAILURE(error))
1236	return (FALSE);
1237    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1238
1239    /* If no _STA method, must be present */
1240    if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1241	ret = TRUE;
1242
1243    /* Return true for 'present' and 'functioning' */
1244    if ((devinfo->CurrentStatus & 0x9) == 0x9)
1245	ret = TRUE;
1246
1247    AcpiOsFree(buf.Pointer);
1248    return (ret);
1249}
1250
1251/*
1252 * Returns true if the battery is actually present and inserted.
1253 */
1254BOOLEAN
1255acpi_BatteryIsPresent(device_t dev)
1256{
1257    ACPI_DEVICE_INFO	*devinfo;
1258    ACPI_HANDLE		h;
1259    ACPI_BUFFER		buf;
1260    ACPI_STATUS		error;
1261    int			ret;
1262
1263    ACPI_ASSERTLOCK;
1264
1265    ret = FALSE;
1266    if ((h = acpi_get_handle(dev)) == NULL)
1267	return (FALSE);
1268    buf.Pointer = NULL;
1269    buf.Length = ACPI_ALLOCATE_BUFFER;
1270    error = AcpiGetObjectInfo(h, &buf);
1271    if (ACPI_FAILURE(error))
1272	return (FALSE);
1273    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1274
1275    /* If no _STA method, must be present */
1276    if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1277	ret = TRUE;
1278
1279    /* Return true for 'present' and 'functioning' */
1280    if ((devinfo->CurrentStatus & 0x19) == 0x19)
1281	ret = TRUE;
1282
1283    AcpiOsFree(buf.Pointer);
1284    return (ret);
1285}
1286
1287/*
1288 * Match a HID string against a device
1289 */
1290BOOLEAN
1291acpi_MatchHid(device_t dev, char *hid)
1292{
1293    ACPI_DEVICE_INFO	*devinfo;
1294    ACPI_HANDLE		h;
1295    ACPI_BUFFER		buf;
1296    ACPI_STATUS		error;
1297    int			ret, i;
1298
1299    ACPI_ASSERTLOCK;
1300
1301    ret = FALSE;
1302    if (hid == NULL)
1303	return (FALSE);
1304    if ((h = acpi_get_handle(dev)) == NULL)
1305	return (FALSE);
1306    buf.Pointer = NULL;
1307    buf.Length = ACPI_ALLOCATE_BUFFER;
1308    error = AcpiGetObjectInfo(h, &buf);
1309    if (ACPI_FAILURE(error))
1310	return (FALSE);
1311    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1312
1313    if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
1314	strcmp(hid, devinfo->HardwareId.Value) == 0)
1315	    ret = TRUE;
1316    else if ((devinfo->Valid & ACPI_VALID_CID) != 0) {
1317	for (i = 0; i < devinfo->CompatibilityId.Count; i++) {
1318	    if (strcmp(hid, devinfo->CompatibilityId.Id[i].Value) == 0) {
1319		ret = TRUE;
1320		break;
1321	    }
1322	}
1323    }
1324
1325    AcpiOsFree(buf.Pointer);
1326    return (ret);
1327}
1328
1329/*
1330 * Return the handle of a named object within our scope, ie. that of (parent)
1331 * or one if its parents.
1332 */
1333ACPI_STATUS
1334acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1335{
1336    ACPI_HANDLE		r;
1337    ACPI_STATUS		status;
1338
1339    ACPI_ASSERTLOCK;
1340
1341    /* Walk back up the tree to the root */
1342    for (;;) {
1343	status = AcpiGetHandle(parent, path, &r);
1344	if (ACPI_SUCCESS(status)) {
1345	    *result = r;
1346	    return (AE_OK);
1347	}
1348	if (status != AE_NOT_FOUND)
1349	    return (AE_OK);
1350	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1351	    return (AE_NOT_FOUND);
1352	parent = r;
1353    }
1354}
1355
1356/*
1357 * Allocate a buffer with a preset data size.
1358 */
1359ACPI_BUFFER *
1360acpi_AllocBuffer(int size)
1361{
1362    ACPI_BUFFER	*buf;
1363
1364    if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1365	return (NULL);
1366    buf->Length = size;
1367    buf->Pointer = (void *)(buf + 1);
1368    return (buf);
1369}
1370
1371ACPI_STATUS
1372acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
1373{
1374    ACPI_OBJECT arg1;
1375    ACPI_OBJECT_LIST args;
1376
1377    ACPI_ASSERTLOCK;
1378
1379    arg1.Type = ACPI_TYPE_INTEGER;
1380    arg1.Integer.Value = number;
1381    args.Count = 1;
1382    args.Pointer = &arg1;
1383
1384    return (AcpiEvaluateObject(handle, path, &args, NULL));
1385}
1386
1387/*
1388 * Evaluate a path that should return an integer.
1389 */
1390ACPI_STATUS
1391acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
1392{
1393    ACPI_STATUS	status;
1394    ACPI_BUFFER	buf;
1395    ACPI_OBJECT	param;
1396
1397    ACPI_ASSERTLOCK;
1398
1399    if (handle == NULL)
1400	handle = ACPI_ROOT_OBJECT;
1401
1402    /*
1403     * Assume that what we've been pointed at is an Integer object, or
1404     * a method that will return an Integer.
1405     */
1406    buf.Pointer = &param;
1407    buf.Length = sizeof(param);
1408    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1409    if (ACPI_SUCCESS(status)) {
1410	if (param.Type == ACPI_TYPE_INTEGER)
1411	    *number = param.Integer.Value;
1412	else
1413	    status = AE_TYPE;
1414    }
1415
1416    /*
1417     * In some applications, a method that's expected to return an Integer
1418     * may instead return a Buffer (probably to simplify some internal
1419     * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1420     * convert it into an Integer as best we can.
1421     *
1422     * This is a hack.
1423     */
1424    if (status == AE_BUFFER_OVERFLOW) {
1425	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1426	    status = AE_NO_MEMORY;
1427	} else {
1428	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1429	    if (ACPI_SUCCESS(status))
1430		status = acpi_ConvertBufferToInteger(&buf, number);
1431	    AcpiOsFree(buf.Pointer);
1432	}
1433    }
1434    return (status);
1435}
1436
1437ACPI_STATUS
1438acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
1439{
1440    ACPI_OBJECT	*p;
1441    UINT8	*val;
1442    int		i;
1443
1444    p = (ACPI_OBJECT *)bufp->Pointer;
1445    if (p->Type == ACPI_TYPE_INTEGER) {
1446	*number = p->Integer.Value;
1447	return (AE_OK);
1448    }
1449    if (p->Type != ACPI_TYPE_BUFFER)
1450	return (AE_TYPE);
1451    if (p->Buffer.Length > sizeof(int))
1452	return (AE_BAD_DATA);
1453
1454    *number = 0;
1455    val = p->Buffer.Pointer;
1456    for (i = 0; i < p->Buffer.Length; i++)
1457	*number += val[i] << (i * 8);
1458    return (AE_OK);
1459}
1460
1461/*
1462 * Iterate over the elements of an a package object, calling the supplied
1463 * function for each element.
1464 *
1465 * XXX possible enhancement might be to abort traversal on error.
1466 */
1467ACPI_STATUS
1468acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
1469	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
1470{
1471    ACPI_OBJECT	*comp;
1472    int		i;
1473
1474    if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
1475	return (AE_BAD_PARAMETER);
1476
1477    /* Iterate over components */
1478    i = 0;
1479    comp = pkg->Package.Elements;
1480    for (; i < pkg->Package.Count; i++, comp++)
1481	func(comp, arg);
1482
1483    return (AE_OK);
1484}
1485
1486/*
1487 * Find the (index)th resource object in a set.
1488 */
1489ACPI_STATUS
1490acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1491{
1492    ACPI_RESOURCE	*rp;
1493    int			i;
1494
1495    rp = (ACPI_RESOURCE *)buf->Pointer;
1496    i = index;
1497    while (i-- > 0) {
1498	/* Range check */
1499	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1500	    return (AE_BAD_PARAMETER);
1501
1502	/* Check for terminator */
1503	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1504	    return (AE_NOT_FOUND);
1505	rp = ACPI_NEXT_RESOURCE(rp);
1506    }
1507    if (resp != NULL)
1508	*resp = rp;
1509
1510    return (AE_OK);
1511}
1512
1513/*
1514 * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1515 *
1516 * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1517 * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1518 * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1519 * resources.
1520 */
1521#define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
1522
1523ACPI_STATUS
1524acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1525{
1526    ACPI_RESOURCE	*rp;
1527    void		*newp;
1528
1529    /* Initialise the buffer if necessary. */
1530    if (buf->Pointer == NULL) {
1531	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1532	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1533	    return (AE_NO_MEMORY);
1534	rp = (ACPI_RESOURCE *)buf->Pointer;
1535	rp->Id = ACPI_RSTYPE_END_TAG;
1536	rp->Length = 0;
1537    }
1538    if (res == NULL)
1539	return (AE_OK);
1540
1541    /*
1542     * Scan the current buffer looking for the terminator.
1543     * This will either find the terminator or hit the end
1544     * of the buffer and return an error.
1545     */
1546    rp = (ACPI_RESOURCE *)buf->Pointer;
1547    for (;;) {
1548	/* Range check, don't go outside the buffer */
1549	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1550	    return (AE_BAD_PARAMETER);
1551	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1552	    break;
1553	rp = ACPI_NEXT_RESOURCE(rp);
1554    }
1555
1556    /*
1557     * Check the size of the buffer and expand if required.
1558     *
1559     * Required size is:
1560     *	size of existing resources before terminator +
1561     *	size of new resource and header +
1562     * 	size of terminator.
1563     *
1564     * Note that this loop should really only run once, unless
1565     * for some reason we are stuffing a *really* huge resource.
1566     */
1567    while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
1568	    res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1569	    ACPI_RESOURCE_LENGTH) >= buf->Length) {
1570	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1571	    return (AE_NO_MEMORY);
1572	bcopy(buf->Pointer, newp, buf->Length);
1573	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1574			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1575	AcpiOsFree(buf->Pointer);
1576	buf->Pointer = newp;
1577	buf->Length += buf->Length;
1578    }
1579
1580    /* Insert the new resource. */
1581    bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1582
1583    /* And add the terminator. */
1584    rp = ACPI_NEXT_RESOURCE(rp);
1585    rp->Id = ACPI_RSTYPE_END_TAG;
1586    rp->Length = 0;
1587
1588    return (AE_OK);
1589}
1590
1591/*
1592 * Set interrupt model.
1593 */
1594ACPI_STATUS
1595acpi_SetIntrModel(int model)
1596{
1597
1598    return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
1599}
1600
1601#define ACPI_MINIMUM_AWAKETIME	5
1602
1603static void
1604acpi_sleep_enable(void *arg)
1605{
1606    ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1607}
1608
1609/*
1610 * Set the system sleep state
1611 *
1612 * Currently we support S1-S5 but S4 is only S4BIOS
1613 */
1614ACPI_STATUS
1615acpi_SetSleepState(struct acpi_softc *sc, int state)
1616{
1617    ACPI_STATUS	status = AE_OK;
1618    UINT8	TypeA;
1619    UINT8	TypeB;
1620
1621    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1622    ACPI_ASSERTLOCK;
1623
1624    /* Avoid reentry if already attempting to suspend. */
1625    if (sc->acpi_sstate != ACPI_STATE_S0)
1626	return_ACPI_STATUS (AE_BAD_PARAMETER);
1627
1628    /* We recently woke up so don't suspend again for a while. */
1629    if (sc->acpi_sleep_disabled)
1630	return_ACPI_STATUS (AE_OK);
1631
1632    switch (state) {
1633    case ACPI_STATE_S1:
1634    case ACPI_STATE_S2:
1635    case ACPI_STATE_S3:
1636    case ACPI_STATE_S4:
1637	status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB);
1638	if (status == AE_NOT_FOUND) {
1639	    device_printf(sc->acpi_dev,
1640			  "Sleep state S%d not supported by BIOS\n", state);
1641	    break;
1642	} else if (ACPI_FAILURE(status)) {
1643	    device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n",
1644			  AcpiFormatException(status));
1645	    break;
1646	}
1647
1648	sc->acpi_sstate = state;
1649	sc->acpi_sleep_disabled = 1;
1650
1651	/* Inform all devices that we are going to sleep. */
1652	if (DEVICE_SUSPEND(root_bus) != 0) {
1653	    /*
1654	     * Re-wake the system.
1655	     *
1656	     * XXX note that a better two-pass approach with a 'veto' pass
1657	     *     followed by a "real thing" pass would be better, but the
1658	     *     current bus interface does not provide for this.
1659	     */
1660	    DEVICE_RESUME(root_bus);
1661	    return_ACPI_STATUS (AE_ERROR);
1662	}
1663
1664	status = AcpiEnterSleepStatePrep(state);
1665	if (ACPI_FAILURE(status)) {
1666	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1667			  AcpiFormatException(status));
1668	    break;
1669	}
1670
1671	if (sc->acpi_sleep_delay > 0)
1672	    DELAY(sc->acpi_sleep_delay * 1000000);
1673
1674	if (state != ACPI_STATE_S1) {
1675	    acpi_sleep_machdep(sc, state);
1676
1677	    /* AcpiEnterSleepState() may be incomplete, unlock if locked. */
1678	    if (AcpiGbl_MutexInfo[ACPI_MTX_HARDWARE].OwnerId !=
1679		ACPI_MUTEX_NOT_ACQUIRED) {
1680
1681		AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1682	    }
1683
1684	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1685	    if (state == ACPI_STATE_S4)
1686		AcpiEnable();
1687	} else {
1688	    status = AcpiEnterSleepState((UINT8)state);
1689	    if (ACPI_FAILURE(status)) {
1690		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
1691			      AcpiFormatException(status));
1692		break;
1693	    }
1694	}
1695	AcpiLeaveSleepState((UINT8)state);
1696	DEVICE_RESUME(root_bus);
1697	sc->acpi_sstate = ACPI_STATE_S0;
1698	acpi_enable_fixed_events(sc);
1699	break;
1700    case ACPI_STATE_S5:
1701	/*
1702	 * Shut down cleanly and power off.  This will call us back through the
1703	 * shutdown handlers.
1704	 */
1705	shutdown_nice(RB_POWEROFF);
1706	break;
1707    case ACPI_STATE_S0:
1708    default:
1709	status = AE_BAD_PARAMETER;
1710	break;
1711    }
1712
1713    /* Disable a second sleep request for a short period */
1714    if (sc->acpi_sleep_disabled)
1715	timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
1716
1717    return_ACPI_STATUS (status);
1718}
1719
1720/*
1721 * Enable/Disable ACPI
1722 */
1723ACPI_STATUS
1724acpi_Enable(struct acpi_softc *sc)
1725{
1726    ACPI_STATUS	status;
1727    u_int32_t	flags;
1728
1729    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1730    ACPI_ASSERTLOCK;
1731
1732    flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
1733	    ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
1734    if (!sc->acpi_enabled)
1735	status = AcpiEnableSubsystem(flags);
1736    else
1737	status = AE_OK;
1738
1739    if (status == AE_OK)
1740	sc->acpi_enabled = 1;
1741
1742    return_ACPI_STATUS (status);
1743}
1744
1745ACPI_STATUS
1746acpi_Disable(struct acpi_softc *sc)
1747{
1748    ACPI_STATUS	status;
1749
1750    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1751    ACPI_ASSERTLOCK;
1752
1753    if (sc->acpi_enabled)
1754	status = AcpiDisable();
1755    else
1756	status = AE_OK;
1757
1758    if (status == AE_OK)
1759	sc->acpi_enabled = 0;
1760
1761    return_ACPI_STATUS (status);
1762}
1763
1764/*
1765 * ACPI Event Handlers
1766 */
1767
1768/* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1769
1770static void
1771acpi_system_eventhandler_sleep(void *arg, int state)
1772{
1773    ACPI_LOCK_DECL;
1774    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1775
1776    ACPI_LOCK;
1777    if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
1778	acpi_SetSleepState((struct acpi_softc *)arg, state);
1779    ACPI_UNLOCK;
1780    return_VOID;
1781}
1782
1783static void
1784acpi_system_eventhandler_wakeup(void *arg, int state)
1785{
1786    ACPI_LOCK_DECL;
1787    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1788
1789    /* Well, what to do? :-) */
1790
1791    ACPI_LOCK;
1792    ACPI_UNLOCK;
1793
1794    return_VOID;
1795}
1796
1797/*
1798 * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1799 */
1800UINT32
1801acpi_event_power_button_sleep(void *context)
1802{
1803    struct acpi_softc	*sc = (struct acpi_softc *)context;
1804
1805    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1806
1807    EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1808
1809    return_VALUE (ACPI_INTERRUPT_HANDLED);
1810}
1811
1812UINT32
1813acpi_event_power_button_wake(void *context)
1814{
1815    struct acpi_softc	*sc = (struct acpi_softc *)context;
1816
1817    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1818
1819    EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1820
1821    return_VALUE (ACPI_INTERRUPT_HANDLED);
1822}
1823
1824UINT32
1825acpi_event_sleep_button_sleep(void *context)
1826{
1827    struct acpi_softc	*sc = (struct acpi_softc *)context;
1828
1829    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1830
1831    EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1832
1833    return_VALUE (ACPI_INTERRUPT_HANDLED);
1834}
1835
1836UINT32
1837acpi_event_sleep_button_wake(void *context)
1838{
1839    struct acpi_softc	*sc = (struct acpi_softc *)context;
1840
1841    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1842
1843    EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1844
1845    return_VALUE (ACPI_INTERRUPT_HANDLED);
1846}
1847
1848/*
1849 * XXX This is kinda ugly, and should not be here.
1850 */
1851struct acpi_staticbuf {
1852    ACPI_BUFFER	buffer;
1853    char	data[512];
1854};
1855
1856char *
1857acpi_name(ACPI_HANDLE handle)
1858{
1859    static struct acpi_staticbuf	buf;
1860
1861    ACPI_ASSERTLOCK;
1862
1863    buf.buffer.Length = 512;
1864    buf.buffer.Pointer = &buf.data[0];
1865
1866    if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
1867	return (buf.buffer.Pointer);
1868
1869    return ("(unknown path)");
1870}
1871
1872/*
1873 * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1874 * parts of the namespace.
1875 */
1876int
1877acpi_avoid(ACPI_HANDLE handle)
1878{
1879    char	*cp, *env, *np;
1880    int		len;
1881
1882    np = acpi_name(handle);
1883    if (*np == '\\')
1884	np++;
1885    if ((env = getenv("debug.acpi.avoid")) == NULL)
1886	return (0);
1887
1888    /* Scan the avoid list checking for a match */
1889    cp = env;
1890    for (;;) {
1891	while ((*cp != 0) && isspace(*cp))
1892	    cp++;
1893	if (*cp == 0)
1894	    break;
1895	len = 0;
1896	while ((cp[len] != 0) && !isspace(cp[len]))
1897	    len++;
1898	if (!strncmp(cp, np, len)) {
1899	    freeenv(env);
1900	    return(1);
1901	}
1902	cp += len;
1903    }
1904    freeenv(env);
1905
1906    return (0);
1907}
1908
1909/*
1910 * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1911 */
1912int
1913acpi_disabled(char *subsys)
1914{
1915    char	*cp, *env;
1916    int		len;
1917
1918    if ((env = getenv("debug.acpi.disabled")) == NULL)
1919	return (0);
1920    if (strcmp(env, "all") == 0) {
1921	freeenv(env);
1922	return (1);
1923    }
1924
1925    /* Scan the disable list, checking for a match. */
1926    cp = env;
1927    for (;;) {
1928	while (*cp != '\0' && isspace(*cp))
1929	    cp++;
1930	if (*cp == '\0')
1931	    break;
1932	len = 0;
1933	while (cp[len] != '\0' && !isspace(cp[len]))
1934	    len++;
1935	if (strncmp(cp, subsys, len) == 0) {
1936	    freeenv(env);
1937	    return (1);
1938	}
1939	cp += len;
1940    }
1941    freeenv(env);
1942
1943    return (0);
1944}
1945
1946/*
1947 * Device wake capability enable/disable.
1948 */
1949void
1950acpi_device_enable_wake_capability(ACPI_HANDLE h, int enable)
1951{
1952    /*
1953     * TBD: All Power Resources referenced by elements 2 through N
1954     *      of the _PRW object are put into the ON state.
1955     */
1956
1957    (void)acpi_SetInteger(h, "_PSW", enable);
1958}
1959
1960void
1961acpi_device_enable_wake_event(ACPI_HANDLE h)
1962{
1963    struct acpi_softc		*sc;
1964    ACPI_STATUS			status;
1965    ACPI_BUFFER			prw_buffer;
1966    ACPI_OBJECT			*res;
1967
1968    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1969
1970    sc = devclass_get_softc(acpi_devclass, 0);
1971    if (sc == NULL)
1972	return;
1973
1974    /*
1975     * _PRW object is only required for devices that have the ability
1976     * to wake the system from a system sleeping state.
1977     */
1978    prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
1979    status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
1980    if (ACPI_FAILURE(status))
1981	return;
1982
1983    res = (ACPI_OBJECT *)prw_buffer.Pointer;
1984    if (res == NULL)
1985	return;
1986
1987    if ((res->Type != ACPI_TYPE_PACKAGE) || (res->Package.Count < 2)) {
1988	goto out;
1989    }
1990
1991    /*
1992     * The element 1 of the _PRW object:
1993     * The lowest power system sleeping state that can be entered
1994     * while still providing wake functionality.
1995     * The sleeping state being entered must be greater or equal to
1996     * the power state declared in element 1 of the _PRW object.
1997     */
1998    if (res->Package.Elements[1].Type != ACPI_TYPE_INTEGER)
1999	goto out;
2000
2001    if (sc->acpi_sstate > res->Package.Elements[1].Integer.Value)
2002	goto out;
2003
2004    /*
2005     * The element 0 of the _PRW object:
2006     */
2007    switch(res->Package.Elements[0].Type) {
2008    case ACPI_TYPE_INTEGER:
2009	/*
2010	 * If the data type of this package element is numeric, then this
2011	 * _PRW package element is the bit index in the GPEx_EN, in the
2012	 * GPE blocks described in the FADT, of the enable bit that is
2013	 * enabled for the wake event.
2014	 */
2015
2016	status = AcpiEnableGpe(NULL, res->Package.Elements[0].Integer.Value,
2017			       ACPI_EVENT_WAKE_ENABLE);
2018	if (ACPI_FAILURE(status))
2019	    printf("%s: EnableEvent Failed\n", __func__);
2020	break;
2021    case ACPI_TYPE_PACKAGE:
2022	/*
2023	 * XXX TBD
2024	 *
2025	 * If the data type of this package element is a package, then this
2026	 * _PRW package element is itself a package containing two
2027	 * elements. The first is an object reference to the GPE Block
2028	 * device that contains the GPE that will be triggered by the wake
2029	 * event. The second element is numeric and it contains the bit
2030	 * index in the GPEx_EN, in the GPE Block referenced by the
2031	 * first element in the package, of the enable bit that is enabled for
2032	 * the wake event.
2033	 * For example, if this field is a package then it is of the form:
2034	 * Package() {\_SB.PCI0.ISA.GPE, 2}
2035	 */
2036	break;
2037    default:
2038	break;
2039    }
2040
2041out:
2042    if (prw_buffer.Pointer != NULL)
2043	AcpiOsFree(prw_buffer.Pointer);
2044}
2045
2046/*
2047 * Control interface.
2048 *
2049 * We multiplex ioctls for all participating ACPI devices here.  Individual
2050 * drivers wanting to be accessible via /dev/acpi should use the
2051 * register/deregister interface to make their handlers visible.
2052 */
2053struct acpi_ioctl_hook
2054{
2055    TAILQ_ENTRY(acpi_ioctl_hook) link;
2056    u_long			 cmd;
2057    acpi_ioctl_fn		 fn;
2058    void			 *arg;
2059};
2060
2061static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
2062static int				acpi_ioctl_hooks_initted;
2063
2064/*
2065 * Register an ioctl handler.
2066 */
2067int
2068acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
2069{
2070    struct acpi_ioctl_hook	*hp;
2071
2072    if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
2073	return (ENOMEM);
2074    hp->cmd = cmd;
2075    hp->fn = fn;
2076    hp->arg = arg;
2077    if (acpi_ioctl_hooks_initted == 0) {
2078	TAILQ_INIT(&acpi_ioctl_hooks);
2079	acpi_ioctl_hooks_initted = 1;
2080    }
2081    TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
2082    return (0);
2083}
2084
2085/*
2086 * Deregister an ioctl handler.
2087 */
2088void
2089acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
2090{
2091    struct acpi_ioctl_hook	*hp;
2092
2093    TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
2094	if ((hp->cmd == cmd) && (hp->fn == fn))
2095	    break;
2096
2097    if (hp != NULL) {
2098	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
2099	free(hp, M_ACPIDEV);
2100    }
2101}
2102
2103static int
2104acpiopen(dev_t dev, int flag, int fmt, d_thread_t *td)
2105{
2106    return (0);
2107}
2108
2109static int
2110acpiclose(dev_t dev, int flag, int fmt, d_thread_t *td)
2111{
2112    return (0);
2113}
2114
2115static int
2116acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
2117{
2118    struct acpi_softc		*sc;
2119    struct acpi_ioctl_hook	*hp;
2120    int				error, xerror, state;
2121    ACPI_LOCK_DECL;
2122
2123    ACPI_LOCK;
2124
2125    error = state = 0;
2126    sc = dev->si_drv1;
2127
2128    /*
2129     * Scan the list of registered ioctls, looking for handlers.
2130     */
2131    if (acpi_ioctl_hooks_initted) {
2132	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
2133	    if (hp->cmd == cmd) {
2134		xerror = hp->fn(cmd, addr, hp->arg);
2135		if (xerror != 0)
2136		    error = xerror;
2137		goto out;
2138	    }
2139	}
2140    }
2141
2142    /*
2143     * Core ioctls are not permitted for non-writable user.
2144     * Currently, other ioctls just fetch information.
2145     * Not changing system behavior.
2146     */
2147    if((flag & FWRITE) == 0)
2148	return (EPERM);
2149
2150    /* Core system ioctls. */
2151    switch (cmd) {
2152    case ACPIIO_ENABLE:
2153	if (ACPI_FAILURE(acpi_Enable(sc)))
2154	    error = ENXIO;
2155	break;
2156    case ACPIIO_DISABLE:
2157	if (ACPI_FAILURE(acpi_Disable(sc)))
2158	    error = ENXIO;
2159	break;
2160    case ACPIIO_SETSLPSTATE:
2161	if (!sc->acpi_enabled) {
2162	    error = ENXIO;
2163	    break;
2164	}
2165	state = *(int *)addr;
2166	if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
2167	    if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
2168		error = EINVAL;
2169	} else {
2170	    error = EINVAL;
2171	}
2172	break;
2173    default:
2174	if (error == 0)
2175	    error = EINVAL;
2176	break;
2177    }
2178
2179out:
2180    ACPI_UNLOCK;
2181    return (error);
2182}
2183
2184static int
2185acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2186{
2187    char sleep_state[4];
2188    char buf[16];
2189    int error;
2190    UINT8 state, TypeA, TypeB;
2191
2192    buf[0] = '\0';
2193    for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX+1; state++) {
2194	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
2195	    sprintf(sleep_state, "S%d ", state);
2196	    strcat(buf, sleep_state);
2197	}
2198    }
2199    error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2200    return (error);
2201}
2202
2203static int
2204acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2205{
2206    char sleep_state[10];
2207    int error;
2208    u_int new_state, old_state;
2209
2210    old_state = *(u_int *)oidp->oid_arg1;
2211    if (old_state > ACPI_S_STATES_MAX+1) {
2212	strcpy(sleep_state, "unknown");
2213    } else {
2214	bzero(sleep_state, sizeof(sleep_state));
2215	strncpy(sleep_state, sleep_state_names[old_state],
2216		sizeof(sleep_state_names[old_state]));
2217    }
2218    error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
2219    if (error == 0 && req->newptr != NULL) {
2220	new_state = ACPI_STATE_S0;
2221	for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++) {
2222	    if (strncmp(sleep_state, sleep_state_names[new_state],
2223			sizeof(sleep_state)) == 0)
2224		break;
2225	}
2226	if (new_state <= ACPI_S_STATES_MAX + 1) {
2227	    if (new_state != old_state)
2228		*(u_int *)oidp->oid_arg1 = new_state;
2229	} else {
2230	    error = EINVAL;
2231	}
2232    }
2233
2234    return (error);
2235}
2236
2237/* Inform devctl(4) when we receive a Notify. */
2238void
2239acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
2240{
2241    char		notify_buf[16];
2242    ACPI_BUFFER		handle_buf;
2243    ACPI_STATUS		status;
2244
2245    if (subsystem == NULL)
2246	return;
2247
2248    handle_buf.Pointer = NULL;
2249    handle_buf.Length = ACPI_ALLOCATE_BUFFER;
2250    status = AcpiNsHandleToPathname(h, &handle_buf);
2251    if (ACPI_FAILURE(status))
2252	return;
2253    snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
2254    devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
2255    AcpiOsFree(handle_buf.Pointer);
2256}
2257
2258#ifdef ACPI_DEBUG
2259/*
2260 * Support for parsing debug options from the kernel environment.
2261 *
2262 * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
2263 * by specifying the names of the bits in the debug.acpi.layer and
2264 * debug.acpi.level environment variables.  Bits may be unset by
2265 * prefixing the bit name with !.
2266 */
2267struct debugtag
2268{
2269    char	*name;
2270    UINT32	value;
2271};
2272
2273static struct debugtag	dbg_layer[] = {
2274    {"ACPI_UTILITIES",		ACPI_UTILITIES},
2275    {"ACPI_HARDWARE",		ACPI_HARDWARE},
2276    {"ACPI_EVENTS",		ACPI_EVENTS},
2277    {"ACPI_TABLES",		ACPI_TABLES},
2278    {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
2279    {"ACPI_PARSER",		ACPI_PARSER},
2280    {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
2281    {"ACPI_EXECUTER",		ACPI_EXECUTER},
2282    {"ACPI_RESOURCES",		ACPI_RESOURCES},
2283    {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
2284    {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
2285    {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
2286    {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
2287
2288    {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
2289    {"ACPI_BATTERY",		ACPI_BATTERY},
2290    {"ACPI_BUS",		ACPI_BUS},
2291    {"ACPI_BUTTON",		ACPI_BUTTON},
2292    {"ACPI_EC", 		ACPI_EC},
2293    {"ACPI_FAN",		ACPI_FAN},
2294    {"ACPI_POWERRES",		ACPI_POWERRES},
2295    {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
2296    {"ACPI_THERMAL",		ACPI_THERMAL},
2297    {"ACPI_TIMER",		ACPI_TIMER},
2298    {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
2299    {NULL, 0}
2300};
2301
2302static struct debugtag dbg_level[] = {
2303    {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
2304    {"ACPI_LV_WARN",		ACPI_LV_WARN},
2305    {"ACPI_LV_INIT",		ACPI_LV_INIT},
2306    {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
2307    {"ACPI_LV_INFO",		ACPI_LV_INFO},
2308    {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
2309
2310    /* Trace verbosity level 1 [Standard Trace Level] */
2311    {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
2312    {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
2313    {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
2314    {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
2315    {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
2316    {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
2317    {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
2318    {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
2319    {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
2320    {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
2321    {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
2322    {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
2323    {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
2324    {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
2325    {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
2326
2327    /* Trace verbosity level 2 [Function tracing and memory allocation] */
2328    {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
2329    {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
2330    {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
2331    {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
2332    {"ACPI_LV_ALL",		ACPI_LV_ALL},
2333
2334    /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2335    {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
2336    {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
2337    {"ACPI_LV_IO",		ACPI_LV_IO},
2338    {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
2339    {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
2340
2341    /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2342    {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
2343    {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
2344    {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
2345    {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
2346    {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
2347    {NULL, 0}
2348};
2349
2350static void
2351acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2352{
2353    char	*ep;
2354    int		i, l;
2355    int		set;
2356
2357    while (*cp) {
2358	if (isspace(*cp)) {
2359	    cp++;
2360	    continue;
2361	}
2362	ep = cp;
2363	while (*ep && !isspace(*ep))
2364	    ep++;
2365	if (*cp == '!') {
2366	    set = 0;
2367	    cp++;
2368	    if (cp == ep)
2369		continue;
2370	} else {
2371	    set = 1;
2372	}
2373	l = ep - cp;
2374	for (i = 0; tag[i].name != NULL; i++) {
2375	    if (!strncmp(cp, tag[i].name, l)) {
2376		if (set)
2377		    *flag |= tag[i].value;
2378		else
2379		    *flag &= ~tag[i].value;
2380		printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
2381	    }
2382	}
2383	cp = ep;
2384    }
2385}
2386
2387static void
2388acpi_set_debugging(void *junk)
2389{
2390    char	*cp;
2391
2392    if (cold) {
2393	AcpiDbgLayer = 0;
2394	AcpiDbgLevel = 0;
2395    }
2396
2397    if ((cp = getenv("debug.acpi.layer")) != NULL) {
2398	acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
2399	freeenv(cp);
2400    }
2401    if ((cp = getenv("debug.acpi.level")) != NULL) {
2402	acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
2403	freeenv(cp);
2404    }
2405
2406    if (cold) {
2407	printf("ACPI debug layer 0x%x debug level 0x%x\n",
2408	       AcpiDbgLayer, AcpiDbgLevel);
2409    }
2410}
2411SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
2412	NULL);
2413
2414static int
2415acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
2416{
2417    int		 error, *dbg;
2418    struct	 debugtag *tag;
2419    struct	 sbuf sb;
2420
2421    if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
2422	return (ENOMEM);
2423    if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
2424	tag = &dbg_layer[0];
2425	dbg = &AcpiDbgLayer;
2426    } else {
2427	tag = &dbg_level[0];
2428	dbg = &AcpiDbgLevel;
2429    }
2430
2431    /* Get old values if this is a get request. */
2432    if (*dbg == 0) {
2433	sbuf_cpy(&sb, "NONE");
2434    } else if (req->newptr == NULL) {
2435	for (; tag->name != NULL; tag++) {
2436	    if ((*dbg & tag->value) == tag->value)
2437		sbuf_printf(&sb, "%s ", tag->name);
2438	}
2439    }
2440    sbuf_trim(&sb);
2441    sbuf_finish(&sb);
2442
2443    error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
2444    sbuf_delete(&sb);
2445
2446    /* If the user is setting a string, parse it. */
2447    if (error == 0 && req->newptr != NULL) {
2448	*dbg = 0;
2449	setenv((char *)oidp->oid_arg1, (char *)req->newptr);
2450	acpi_set_debugging(NULL);
2451    }
2452
2453    return (error);
2454}
2455SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
2456	    "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
2457SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
2458	    "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
2459#endif
2460
2461static int
2462acpi_pm_func(u_long cmd, void *arg, ...)
2463{
2464	int	state, acpi_state;
2465	int	error;
2466	struct	acpi_softc *sc;
2467	va_list	ap;
2468
2469	error = 0;
2470	switch (cmd) {
2471	case POWER_CMD_SUSPEND:
2472		sc = (struct acpi_softc *)arg;
2473		if (sc == NULL) {
2474			error = EINVAL;
2475			goto out;
2476		}
2477
2478		va_start(ap, arg);
2479		state = va_arg(ap, int);
2480		va_end(ap);
2481
2482		switch (state) {
2483		case POWER_SLEEP_STATE_STANDBY:
2484			acpi_state = sc->acpi_standby_sx;
2485			break;
2486		case POWER_SLEEP_STATE_SUSPEND:
2487			acpi_state = sc->acpi_suspend_sx;
2488			break;
2489		case POWER_SLEEP_STATE_HIBERNATE:
2490			acpi_state = ACPI_STATE_S4;
2491			break;
2492		default:
2493			error = EINVAL;
2494			goto out;
2495		}
2496
2497		acpi_SetSleepState(sc, acpi_state);
2498		break;
2499	default:
2500		error = EINVAL;
2501		goto out;
2502	}
2503
2504out:
2505	return (error);
2506}
2507
2508static void
2509acpi_pm_register(void *arg)
2510{
2511    if (!cold || resource_disabled("acpi", 0))
2512	return;
2513
2514    power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2515}
2516
2517SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
2518