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