acpi.c revision 67761
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 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 67761 2000-10-28 06:59:48Z msmith $
30 */
31
32#include "opt_acpi.h"
33#include <sys/param.h>
34#include <sys/kernel.h>
35#include <sys/malloc.h>
36#include <sys/bus.h>
37#include <sys/conf.h>
38#include <sys/ioccom.h>
39#include <sys/reboot.h>
40#include <sys/sysctl.h>
41#include <sys/ctype.h>
42
43#include <machine/clock.h>
44
45#include <machine/resource.h>
46
47#include "acpi.h"
48
49#include <dev/acpica/acpivar.h>
50#include <dev/acpica/acpiio.h>
51
52#include <pci/pcivar.h>
53#include "pcib_if.h"
54
55MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
56
57/*
58 * Character device
59 */
60
61static d_open_t		acpiopen;
62static d_close_t	acpiclose;
63static d_ioctl_t	acpiioctl;
64
65#define CDEV_MAJOR 152
66static struct cdevsw acpi_cdevsw = {
67    acpiopen,
68    acpiclose,
69    noread,
70    nowrite,
71    acpiioctl,
72    nopoll,
73    nommap,
74    nostrategy,
75    "acpi",
76    CDEV_MAJOR,
77    nodump,
78    nopsize,
79    0,
80    -1
81};
82
83static void	acpi_identify(driver_t *driver, device_t parent);
84static int	acpi_probe(device_t dev);
85static int	acpi_attach(device_t dev);
86static device_t	acpi_add_child(device_t bus, int order, const char *name, int unit);
87static int	acpi_print_resources(struct resource_list *rl, const char *name, int type,
88				     const char *format);
89static int	acpi_print_child(device_t bus, device_t child);
90static int	acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result);
91static int	acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value);
92static int	acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start,
93				  u_long count);
94static int	acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp,
95				  u_long *countp);
96static struct resource *acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
97					    u_long start, u_long end, u_long count, u_int flags);
98static int	acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r);
99
100static void	acpi_probe_children(device_t bus);
101static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status);
102
103static void	acpi_shutdown_pre_sync(void *arg, int howto);
104static void	acpi_shutdown_final(void *arg, int howto);
105
106#ifdef ACPI_DEBUG
107static void	acpi_set_debugging(void);
108#endif
109
110static void	acpi_system_eventhandler_sleep(void *arg, int state);
111static void	acpi_system_eventhandler_wakeup(void *arg, int state);
112
113static device_method_t acpi_methods[] = {
114    /* Device interface */
115    DEVMETHOD(device_identify,		acpi_identify),
116    DEVMETHOD(device_probe,		acpi_probe),
117    DEVMETHOD(device_attach,		acpi_attach),
118    DEVMETHOD(device_shutdown,		bus_generic_shutdown),
119    DEVMETHOD(device_suspend,		bus_generic_suspend),
120    DEVMETHOD(device_resume,		bus_generic_resume),
121
122    /* Bus interface */
123    DEVMETHOD(bus_add_child,		acpi_add_child),
124    DEVMETHOD(bus_print_child,		acpi_print_child),
125    DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
126    DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
127    DEVMETHOD(bus_set_resource,		acpi_set_resource),
128    DEVMETHOD(bus_get_resource,		acpi_get_resource),
129    DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
130    DEVMETHOD(bus_release_resource,	acpi_release_resource),
131    DEVMETHOD(bus_driver_added,		bus_generic_driver_added),
132    DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
133    DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
134    DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
135    DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
136
137    {0, 0}
138};
139
140static driver_t acpi_driver = {
141    "acpi",
142    acpi_methods,
143    sizeof(struct acpi_softc),
144};
145
146devclass_t acpi_devclass;
147DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, 0, 0);
148
149SYSCTL_INT(_debug, OID_AUTO, acpi_debug_layer, CTLFLAG_RW, &AcpiDbgLayer, 0, "");
150SYSCTL_INT(_debug, OID_AUTO, acpi_debug_level, CTLFLAG_RW, &AcpiDbgLevel, 0, "");
151
152/*
153 * Detect ACPI, perform early initialisation
154 */
155static void
156acpi_identify(driver_t *driver, device_t parent)
157{
158    device_t	child;
159    void	*rsdp;
160    int		error;
161#ifdef ENABLE_DEBUGGER
162    char		*debugpoint = getenv("debug.acpi.debugger");
163#endif
164
165    /*
166     * Make sure we're not being doubly invoked.
167     */
168    if (device_find_child(parent, "acpi", 0) != NULL)
169	return;
170
171#ifdef ACPI_DEBUG
172    acpi_set_debugging();
173#endif
174
175    /*
176     * Start up ACPICA
177     */
178#ifdef ENABLE_DEBUGGER
179    if (debugpoint && !strcmp(debugpoint, "init"))
180	acpi_EnterDebugger();
181#endif
182    if ((error = AcpiInitializeSubsystem()) != AE_OK) {
183	printf("ACPI: initialisation failed: %s\n", acpi_strerror(error));
184	return;
185    }
186#ifdef ENABLE_DEBUGGER
187    if (debugpoint && !strcmp(debugpoint, "tables"))
188	acpi_EnterDebugger();
189#endif
190    if (((error = AcpiFindRootPointer(&rsdp)) != AE_OK) ||
191	((error = AcpiLoadTables(rsdp)) != AE_OK)) {
192	printf("ACPI: table load failed: %s\n", acpi_strerror(error));
193	return;
194    }
195
196    /*
197     * Attach the actual ACPI device.
198     */
199    if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
200	    device_printf(parent, "ACPI: could not attach\n");
201	    return;
202    }
203}
204
205/*
206 * Fetch some descriptive data from ACPI to put in our attach message
207 */
208static int
209acpi_probe(device_t dev)
210{
211    ACPI_TABLE_HEADER	th;
212    char		buf[20];
213    int			error;
214
215    if ((error = AcpiGetTableHeader(ACPI_TABLE_RSDT, 1, &th)) != AE_OK) {
216	device_printf(dev, "couldn't get RSDT header: %s\n", acpi_strerror(error));
217	return(ENXIO);
218    }
219    sprintf(buf, "%.6s %.8s", th.OemId, th.OemTableId);
220    device_set_desc_copy(dev, buf);
221
222    return(0);
223}
224
225static int
226acpi_attach(device_t dev)
227{
228    struct acpi_softc	*sc;
229    int			error;
230#ifdef ENABLE_DEBUGGER
231    char		*debugpoint = getenv("debug.acpi.debugger");
232#endif
233
234
235    sc = device_get_softc(dev);
236    bzero(sc, sizeof(*sc));
237    sc->acpi_dev = dev;
238
239#ifdef ENABLE_DEBUGGER
240    if (debugpoint && !strcmp(debugpoint, "spaces"))
241	acpi_EnterDebugger();
242#endif
243
244    /*
245     * Install the default address space handlers.
246     */
247    if ((error = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
248						ADDRESS_SPACE_SYSTEM_MEMORY,
249						ACPI_DEFAULT_HANDLER,
250						NULL, NULL)) != AE_OK) {
251	device_printf(dev, "could not initialise SystemMemory handler: %s\n", acpi_strerror(error));
252	return(ENXIO);
253    }
254    if ((error = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
255						ADDRESS_SPACE_SYSTEM_IO,
256						ACPI_DEFAULT_HANDLER,
257						NULL, NULL)) != AE_OK) {
258	device_printf(dev, "could not initialise SystemIO handler: %s\n", acpi_strerror(error));
259	return(ENXIO);
260    }
261    if ((error = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
262						ADDRESS_SPACE_PCI_CONFIG,
263						ACPI_DEFAULT_HANDLER,
264						NULL, NULL)) != AE_OK) {
265	device_printf(dev, "could not initialise PciConfig handler: %s\n", acpi_strerror(error));
266	return(ENXIO);
267    }
268
269    /*
270     * Bring ACPI fully online.
271     *
272     * Note that we request that device _STA and _INI methods not be run (ACPI_NO_DEVICE_INIT)
273     * and the final object initialisation pass be skipped (ACPI_NO_OBJECT_INIT).
274     *
275     * XXX We need to arrange for the object init pass after we have attached all our
276     *     child devices.
277     */
278#ifdef ENABLE_DEBUGGER
279    if (debugpoint && !strcmp(debugpoint, "enable"))
280	acpi_EnterDebugger();
281#endif
282    if ((error = AcpiEnableSubsystem(ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT)) != AE_OK) {
283	device_printf(dev, "could not enable ACPI: %s\n", acpi_strerror(error));
284	return(ENXIO);
285    }
286
287    /*
288     * Dispatch the default sleep state to devices.
289     * TBD: should be configured from userland policy manager.
290     */
291    sc->acpi_power_button_sx = ACPI_POWER_BUTTON_DEFAULT_SX;
292    sc->acpi_sleep_button_sx = ACPI_SLEEP_BUTTON_DEFAULT_SX;
293    sc->acpi_lid_switch_sx = ACPI_LID_SWITCH_DEFAULT_SX;
294
295    /* Enable and clear fixed events and install handlers. */
296    if (AcpiGbl_FACP != NULL && AcpiGbl_FACP->PwrButton == 0) {
297	AcpiEnableEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
298	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
299	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON, acpi_eventhandler_power_button_for_sleep, sc);
300	device_printf(dev, "power button is handled as a fixed feature programming model.\n");
301    }
302    if (AcpiGbl_FACP != NULL && AcpiGbl_FACP->SleepButton == 0) {
303	AcpiEnableEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
304	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
305	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON, acpi_eventhandler_sleep_button_for_sleep, sc);
306	device_printf(dev, "sleep button is handled as a fixed feature programming model.\n");
307    }
308
309    /*
310     * Scan the namespace and attach/initialise children.
311     */
312#ifdef ENABLE_DEBUGGER
313    if (debugpoint && !strcmp(debugpoint, "probe"))
314	acpi_EnterDebugger();
315#endif
316    acpi_probe_children(dev);
317
318    /*
319     * Register our shutdown handlers
320     */
321    EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc, SHUTDOWN_PRI_LAST);
322    EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc, SHUTDOWN_PRI_LAST);
323
324    /*
325     * Register our acpi event handlers.
326     * XXX should be configurable eg. via userland policy manager.
327     */
328    EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep, sc, ACPI_EVENT_PRI_LAST);
329    EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup, sc, ACPI_EVENT_PRI_LAST);
330
331    /*
332     * Flag our initial states.
333     */
334    sc->acpi_enabled = 1;
335    sc->acpi_sstate = ACPI_STATE_S0;
336
337    /*
338     * Create the control device
339     */
340    sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, 0, 5, 0660, "acpi");
341    sc->acpi_dev_t->si_drv1 = sc;
342
343#ifdef ENABLE_DEBUGGER
344    if (debugpoint && !strcmp(debugpoint, "running"))
345	acpi_EnterDebugger();
346#endif
347    return(0);
348}
349
350/*
351 * Handle a new device being added
352 */
353static device_t
354acpi_add_child(device_t bus, int order, const char *name, int unit)
355{
356    struct acpi_device	*ad;
357    device_t		child;
358
359    if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT)) == NULL)
360	return(NULL);
361    bzero(ad, sizeof(*ad));
362
363    resource_list_init(&ad->ad_rl);
364
365    child = device_add_child_ordered(bus, order, name, unit);
366    if (child != NULL)
367	device_set_ivars(child, ad);
368    return(child);
369}
370
371/*
372 * Print child device resource usage
373 */
374static int
375acpi_print_resources(struct resource_list *rl, const char *name, int type, const char *format)
376{
377    struct resource_list_entry	*rle;
378    int				printed, retval;
379
380    printed = 0;
381    retval = 0;
382
383    if (!SLIST_FIRST(rl))
384	return(0);
385
386    /* Yes, this is kinda cheating */
387    SLIST_FOREACH(rle, rl, link) {
388	if (rle->type == type) {
389	    if (printed == 0)
390		retval += printf(" %s ", name);
391	    else if (printed > 0)
392		retval += printf(",");
393	    printed++;
394	    retval += printf(format, rle->start);
395	    if (rle->count > 1) {
396		retval += printf("-");
397		retval += printf(format, rle->start +
398				 rle->count - 1);
399	    }
400	}
401    }
402    return(retval);
403}
404
405static int
406acpi_print_child(device_t bus, device_t child)
407{
408    struct acpi_device		*adev = device_get_ivars(child);
409    struct resource_list	*rl = &adev->ad_rl;
410    int retval = 0;
411
412    retval += bus_print_child_header(bus, child);
413    retval += acpi_print_resources(rl, "port",  SYS_RES_IOPORT, "%#lx");
414    retval += acpi_print_resources(rl, "iomem", SYS_RES_MEMORY, "%#lx");
415    retval += acpi_print_resources(rl, "irq",   SYS_RES_IRQ,    "%ld");
416    retval += bus_print_child_footer(bus, child);
417
418    return(retval);
419}
420
421
422/*
423 * Handle per-device ivars
424 */
425static int
426acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
427{
428    struct acpi_device	*ad;
429
430    if ((ad = device_get_ivars(child)) == NULL) {
431	printf("device has no ivars\n");
432	return(ENOENT);
433    }
434
435    switch(index) {
436	/* ACPI ivars */
437    case ACPI_IVAR_HANDLE:
438	*(ACPI_HANDLE *)result = ad->ad_handle;
439	break;
440    case ACPI_IVAR_MAGIC:
441	*(int *)result = ad->ad_magic;
442	break;
443    case ACPI_IVAR_PRIVATE:
444	*(void **)result = ad->ad_private;
445	break;
446
447    default:
448	panic("bad ivar read request (%d)\n", index);
449	return(ENOENT);
450    }
451    return(0);
452}
453
454static int
455acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
456{
457    struct acpi_device	*ad;
458
459    if ((ad = device_get_ivars(child)) == NULL) {
460	printf("device has no ivars\n");
461	return(ENOENT);
462    }
463
464    switch(index) {
465	/* ACPI ivars */
466    case ACPI_IVAR_HANDLE:
467	ad->ad_handle = (ACPI_HANDLE)value;
468	break;
469    case ACPI_IVAR_MAGIC:
470	ad->ad_magic = (int )value;
471	break;
472    case ACPI_IVAR_PRIVATE:
473	ad->ad_private = (void *)value;
474	break;
475
476    default:
477	panic("bad ivar write request (%d)\n", index);
478	return(ENOENT);
479    }
480    return(0);
481}
482
483/*
484 * Handle child resource allocation/removal
485 */
486static int
487acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start, u_long count)
488{
489    struct acpi_device		*ad = device_get_ivars(child);
490    struct resource_list	*rl = &ad->ad_rl;
491
492    resource_list_add(rl, type, rid, start, start + count -1, count);
493
494    return(0);
495}
496
497static int
498acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp, u_long *countp)
499{
500    struct acpi_device		*ad = device_get_ivars(child);
501    struct resource_list	*rl = &ad->ad_rl;
502    struct resource_list_entry	*rle;
503
504    rle = resource_list_find(rl, type, rid);
505    if (!rle)
506	return(ENOENT);
507
508    if (startp)
509	*startp = rle->start;
510    if (countp)
511	*countp = rle->count;
512
513    return(0);
514}
515
516static struct resource *
517acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
518		    u_long start, u_long end, u_long count, u_int flags)
519{
520    struct acpi_device *ad = device_get_ivars(child);
521    struct resource_list *rl = &ad->ad_rl;
522
523    return(resource_list_alloc(rl, bus, child, type, rid, start, end, count, flags));
524}
525
526static int
527acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
528{
529    struct acpi_device *ad = device_get_ivars(child);
530    struct resource_list *rl = &ad->ad_rl;
531
532    return(resource_list_release(rl, bus, child, type, rid, r));
533}
534
535/*
536 * Scan relevant portions of the ACPI namespace and attach child devices.
537 *
538 * Note that we only expect to find devices in the \_TZ_, \_SI_ and \_SB_ scopes,
539 * and \_TZ_ becomes obsolete in the ACPI 2.0 spec.
540 */
541static void
542acpi_probe_children(device_t bus)
543{
544    ACPI_HANDLE		parent;
545    static char		*scopes[] = {"\\_TZ_", "\\_SI", "\\_SB_", NULL};
546    int			i;
547
548    /*
549     * Create any static children by calling device identify methods.
550     */
551    bus_generic_probe(bus);
552
553    /*
554     * Scan the namespace and insert placeholders for all the devices that
555     * we find.
556     *
557     * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
558     * we want to create nodes for all devices, not just those that are currently
559     * present. (This assumes that we don't want to create/remove devices as they
560     * appear, which might be smarter.)
561     */
562    for (i = 0; scopes[i] != NULL; i++)
563	if ((AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent)) == AE_OK)
564	    AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child, bus, NULL);
565
566    /*
567     * Scan all of the child devices we have created and let them probe/attach.
568     */
569    bus_generic_attach(bus);
570
571    /*
572     * Some of these children may have attached others as part of their attach
573     * process (eg. the root PCI bus driver), so rescan.
574     */
575    bus_generic_attach(bus);
576}
577
578/*
579 * Evaluate a child device and determine whether we might attach a device to
580 * it.
581 */
582static ACPI_STATUS
583acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
584{
585    ACPI_OBJECT_TYPE	type;
586    device_t		child, bus = (device_t)context;
587
588    if (AcpiGetType(handle, &type) == AE_OK) {
589	switch(type) {
590	case ACPI_TYPE_DEVICE:
591	case ACPI_TYPE_PROCESSOR:
592	case ACPI_TYPE_THERMAL:
593	case ACPI_TYPE_POWER:
594	    /*
595	     * Create a placeholder device for this node.  Sort the placeholder
596	     * so that the probe/attach passes will run breadth-first.
597	     */
598	    child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
599	    acpi_set_handle(child, handle);
600	}
601    }
602    return(AE_OK);
603}
604
605static void
606acpi_shutdown_pre_sync(void *arg, int howto)
607{
608    /*
609     * disable all of ACPI events before soft off, otherwise the system
610     * will be turned on again on some laptops.
611     *
612     * XXX this should probably be restricted to masking some events just
613     *     before powering down, since we may still need ACPI during the
614     *     shutdown process.
615     */
616    acpi_Disable((struct acpi_softc *)arg);
617}
618
619static void
620acpi_shutdown_final(void *arg, int howto)
621{
622    ACPI_STATUS	status;
623
624    if (howto == RB_POWEROFF) {
625	printf("Power system off using ACPI...\n");
626	if ((status = AcpiSetSystemSleepState(ACPI_STATE_S5)) != AE_OK) {
627	    printf("ACPI power-off failed - %s\n", acpi_strerror(status));
628	} else {
629	    DELAY(1000000);
630	    printf("ACPI power-off failed - timeout\n");
631	}
632    }
633}
634
635/*
636 * Match a HID string against a device
637 */
638BOOLEAN
639acpi_MatchHid(device_t dev, char *hid)
640{
641    ACPI_HANDLE		h;
642    ACPI_DEVICE_INFO	devinfo;
643    ACPI_STATUS		error;
644
645    if ((hid == NULL) || (strlen(hid) != 7))
646	return(FALSE);
647    if ((h = acpi_get_handle(dev)) == NULL)
648	return(FALSE);
649    if ((error = AcpiGetObjectInfo(h, &devinfo)) != AE_OK)
650	return(FALSE);
651    if ((devinfo.Valid & ACPI_VALID_HID) && !strncmp(hid, devinfo.HardwareId, 7))
652	return(TRUE);
653    return(FALSE);
654}
655
656/*
657 * Perform the tedious double-get procedure required for fetching something into
658 * an ACPI_BUFFER that has not been initialised.
659 */
660ACPI_STATUS
661acpi_GetIntoBuffer(ACPI_HANDLE handle, ACPI_STATUS (*func)(ACPI_HANDLE, ACPI_BUFFER *), ACPI_BUFFER *buf)
662{
663    ACPI_STATUS	status;
664
665    buf->Length = 0;
666    buf->Pointer = NULL;
667
668    if ((status = func(handle, buf)) != AE_BUFFER_OVERFLOW)
669	return(status);
670    if ((buf->Pointer = AcpiOsCallocate(buf->Length)) == NULL)
671	return(AE_NO_MEMORY);
672    return(func(handle, buf));
673}
674
675/*
676 * Allocate a buffer with a preset data size.
677 */
678ACPI_BUFFER *
679acpi_AllocBuffer(int size)
680{
681    ACPI_BUFFER	*buf;
682
683    if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
684	return(NULL);
685    buf->Length = size;
686    buf->Pointer = (void *)(buf + 1);
687    return(buf);
688}
689
690/*
691 * Set the system sleep state
692 *
693 * Currently we only support S1 and S5
694 */
695ACPI_STATUS
696acpi_SetSleepState(struct acpi_softc *sc, int state)
697{
698    ACPI_STATUS	status = AE_OK;
699
700    switch (state) {
701    case ACPI_STATE_S0:	/* XXX only for testing */
702	status = AcpiSetSystemSleepState((UINT8)state);
703	if (status != AE_OK) {
704	    device_printf(sc->acpi_dev, "AcpiSetSystemSleepState failed - %s\n", acpi_strerror(status));
705	}
706	break;
707
708    case ACPI_STATE_S1:
709	/*
710	 * Inform all devices that we are going to sleep.
711	 */
712	if (DEVICE_SUSPEND(root_bus) != 0) {
713	    /*
714	     * Re-wake the system.
715	     *
716	     * XXX note that a better two-pass approach with a 'veto' pass
717	     *     followed by a "real thing" pass would be better, but the
718	     *     current bus interface does not provide for this.
719	     */
720	    DEVICE_RESUME(root_bus);
721	    return(AE_ERROR);
722	}
723	sc->acpi_sstate = state;
724	status = AcpiSetSystemSleepState((UINT8)state);
725	if (status != AE_OK) {
726	    device_printf(sc->acpi_dev, "AcpiSetSystemSleepState failed - %s\n", acpi_strerror(status));
727	}
728	DEVICE_RESUME(root_bus);
729	sc->acpi_sstate = ACPI_STATE_S0;
730	break;
731
732    case ACPI_STATE_S5:
733	/*
734	 * Shut down cleanly and power off.  This will call us back through the
735	 * shutdown handlers.
736	 */
737	shutdown_nice(RB_POWEROFF);
738	break;
739
740    default:
741	status = AE_BAD_PARAMETER;
742	break;
743    }
744    return(status);
745}
746
747/*
748 * Enable/Disable ACPI
749 */
750ACPI_STATUS
751acpi_Enable(struct acpi_softc *sc)
752{
753    ACPI_STATUS	status;
754    u_int32_t	flags;
755
756    flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
757            ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
758    if (!sc->acpi_enabled) {
759	status = AcpiEnableSubsystem(flags);
760    } else {
761	status = AE_OK;
762    }
763    if (status == AE_OK)
764	sc->acpi_enabled = 1;
765    return(status);
766}
767
768ACPI_STATUS
769acpi_Disable(struct acpi_softc *sc)
770{
771    ACPI_STATUS	status;
772
773    if (sc->acpi_enabled) {
774	status = AcpiDisable();
775    } else {
776	status = AE_OK;
777    }
778    if (status == AE_OK)
779	sc->acpi_enabled = 0;
780    return(status);
781}
782
783/*
784 * Returns true if the device is actually present and should
785 * be attached to.  This requires the present, enabled, UI-visible
786 * and diagnostics-passed bits to be set.
787 */
788BOOLEAN
789acpi_DeviceIsPresent(device_t dev)
790{
791    ACPI_HANDLE		h;
792    ACPI_DEVICE_INFO	devinfo;
793    ACPI_STATUS		error;
794
795    if ((h = acpi_get_handle(dev)) == NULL)
796	return(FALSE);
797    if ((error = AcpiGetObjectInfo(h, &devinfo)) != AE_OK)
798	return(FALSE);
799    if ((devinfo.Valid & ACPI_VALID_HID) && (devinfo.CurrentStatus & 0xf))
800	return(TRUE);
801    return(FALSE);
802}
803
804/*
805 * Evaluate a path that should return a number
806 */
807ACPI_STATUS
808acpi_EvaluateNumber(ACPI_HANDLE handle, char *path, int *number)
809{
810    ACPI_STATUS	error;
811    ACPI_BUFFER	buf;
812    int		param[4];
813
814    if (handle == NULL)
815	handle = ACPI_ROOT_OBJECT;
816    buf.Pointer = &param[0];
817    buf.Length = sizeof(param);
818    if ((error = AcpiEvaluateObject(handle, path, NULL, &buf)) == AE_OK) {
819	if (param[0] == ACPI_TYPE_NUMBER) {
820	    *number = param[1];
821	} else {
822	    error = AE_TYPE;
823	}
824    }
825    return(error);
826}
827
828/*
829 * ACPI Event Handlers
830 */
831
832/* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
833
834static void
835acpi_system_eventhandler_sleep(void *arg, int state)
836{
837    if (state < ACPI_STATE_S0 || state > ACPI_STATE_S5) {
838	return;
839    }
840
841    acpi_SetSleepState((struct acpi_softc *)arg, state);
842}
843
844
845static void
846acpi_system_eventhandler_wakeup(void *arg, int state)
847{
848    /* Well, what to do? :-) */
849}
850
851/*
852 * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
853 */
854UINT32
855acpi_eventhandler_power_button_for_sleep(void *context)
856{
857    struct acpi_softc	*sc = (struct acpi_softc *)context;
858
859    EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
860    return(INTERRUPT_HANDLED);
861}
862
863UINT32
864acpi_eventhandler_power_button_for_wakeup(void *context)
865{
866    struct acpi_softc	*sc = (struct acpi_softc *)context;
867
868    EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
869    return(INTERRUPT_HANDLED);
870}
871
872UINT32
873acpi_eventhandler_sleep_button_for_sleep(void *context)
874{
875    struct acpi_softc	*sc = (struct acpi_softc *)context;
876
877    EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
878    return(INTERRUPT_HANDLED);
879}
880
881UINT32
882acpi_eventhandler_sleep_button_for_wakeup(void *context)
883{
884    struct acpi_softc	*sc = (struct acpi_softc *)context;
885
886    EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
887    return(INTERRUPT_HANDLED);
888}
889
890/*
891 * XXX This is kinda ugly, and should not be here.
892 */
893struct acpi_staticbuf {
894    ACPI_BUFFER	buffer;
895    char	data[512];
896};
897
898char *
899acpi_strerror(ACPI_STATUS excep)
900{
901    static struct acpi_staticbuf	buf;
902
903    buf.buffer.Length = 512;
904    buf.buffer.Pointer = &buf.data[0];
905
906    if (AcpiFormatException(excep, &buf.buffer) == AE_OK)
907	return(buf.buffer.Pointer);
908    return("(error formatting exception)");
909}
910
911char *
912acpi_name(ACPI_HANDLE handle)
913{
914    static struct acpi_staticbuf	buf;
915
916    buf.buffer.Length = 512;
917    buf.buffer.Pointer = &buf.data[0];
918
919    if (AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer) == AE_OK)
920	return(buf.buffer.Pointer);
921    return("(unknown path)");
922}
923
924/*
925 * Debugging/bug-avoidance.  Avoid trying to fetch info on various
926 * parts of the namespace.
927 */
928int
929acpi_avoid(ACPI_HANDLE handle)
930{
931    char	*cp, *np;
932    int		len;
933
934    np = acpi_name(handle);
935    if (*np == '\\')
936	np++;
937    if ((cp = getenv("debug.acpi.avoid")) == NULL)
938	return(0);
939
940    /* scan the avoid list checking for a match */
941    for (;;) {
942	while ((*cp != 0) && isspace(*cp))
943	    cp++;
944	if (*cp == 0)
945	    break;
946	len = 0;
947	while ((cp[len] != 0) && !isspace(cp[len]))
948	    len++;
949	if (!strncmp(cp, np, len)) {
950	    printf("avoiding '%s'\n", np);
951	    return(1);
952	}
953	cp += len;
954    }
955    return(0);
956}
957
958/*
959 * Control interface.
960 *
961 * XXX this is provided as a temporary measure for
962 *     backwards compatibility for now.  A better
963 *     interface will probably use sysctl or similar.
964 */
965static int
966acpiopen(dev_t dev, int flag, int fmt, struct proc * p)
967{
968    return(0);
969}
970
971static int
972acpiclose(dev_t dev, int flag, int fmt, struct proc * p)
973{
974    return(0);
975}
976
977static int
978acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc * p)
979{
980    int		error, state;
981    struct acpi_softc	*sc;
982
983    error = state = 0;
984    sc = dev->si_drv1;
985
986    switch (cmd) {
987    case ACPIIO_ENABLE:
988	if (ACPI_FAILURE(acpi_Enable(sc))) {
989	    error = ENXIO;
990	}
991	break;
992
993    case ACPIIO_DISABLE:
994	if (ACPI_FAILURE(acpi_Disable(sc))) {
995	    error = ENXIO;
996	}
997	break;
998
999    case ACPIIO_SETSLPSTATE:
1000	if (!sc->acpi_enabled) {
1001	    error = ENXIO;
1002	    break;
1003	}
1004	state = *(int *)addr;
1005	if (state >= ACPI_STATE_S0  && state <= ACPI_STATE_S5) {
1006	    acpi_SetSleepState(sc, state);
1007	} else {
1008	    error = EINVAL;
1009	}
1010
1011	break;
1012
1013    default:
1014	error = EINVAL;
1015	break;
1016    }
1017
1018    return(error);
1019}
1020
1021#ifdef ACPI_DEBUG
1022struct debugtag
1023{
1024    char	*name;
1025    UINT32	value;
1026};
1027
1028static struct debugtag	dbg_layer[] = {
1029    {"GLOBAL",			0x00000001},
1030    {"COMMON",			0x00000002},
1031    {"PARSER",			0x00000004},
1032    {"DISPATCHER",		0x00000008},
1033    {"INTERPRETER",		0x00000010},
1034    {"NAMESPACE",		0x00000020},
1035    {"RESOURCE_MANAGER",	0x00000040},
1036    {"TABLE_MANAGER",		0x00000080},
1037    {"EVENT_HANDLING",		0x00000100},
1038    {"HARDWARE",		0x00000200},
1039    {"MISCELLANEOUS",		0x00000400},
1040    {"OS_DEPENDENT",		0x00000800},
1041    {"BUS_MANAGER",		0x00001000},
1042    {"PROCESSOR_CONTROL",	0x00002000},
1043    {"SYSTEM_CONTROL",		0x00004000},
1044    {"THERMAL_CONTROL",		0x00008000},
1045    {"POWER_CONTROL",		0x00010000},
1046    {"EMBEDDED_CONTROLLER",	0x00020000},
1047    {"BATTERY",			0x00040000},
1048    {"DEBUGGER",		0x00100000},
1049    {"ALL_COMPONENTS",		0x001FFFFF},
1050    {NULL, 0}
1051};
1052
1053static struct debugtag dbg_level[] = {
1054    {"ACPI_OK",                     0x00000001},
1055    {"ACPI_INFO",                   0x00000002},
1056    {"ACPI_WARN",                   0x00000004},
1057    {"ACPI_ERROR",                  0x00000008},
1058    {"ACPI_FATAL",                  0x00000010},
1059    {"ACPI_DEBUG_OBJECT",           0x00000020},
1060    {"ACPI_ALL",                    0x0000003F},
1061    {"TRACE_PARSE",                 0x00000100},
1062    {"TRACE_DISPATCH",              0x00000200},
1063    {"TRACE_LOAD",                  0x00000400},
1064    {"TRACE_EXEC",                  0x00000800},
1065    {"TRACE_NAMES",                 0x00001000},
1066    {"TRACE_OPREGION",              0x00002000},
1067    {"TRACE_BFIELD",                0x00004000},
1068    {"TRACE_TRASH",                 0x00008000},
1069    {"TRACE_TABLES",                0x00010000},
1070    {"TRACE_FUNCTIONS",             0x00020000},
1071    {"TRACE_VALUES",                0x00040000},
1072    {"TRACE_OBJECTS",               0x00080000},
1073    {"TRACE_ALLOCATIONS",           0x00100000},
1074    {"TRACE_RESOURCES",             0x00200000},
1075    {"TRACE_IO",                    0x00400000},
1076    {"TRACE_INTERRUPTS",            0x00800000},
1077    {"TRACE_USER_REQUESTS",         0x01000000},
1078    {"TRACE_PACKAGE",               0x02000000},
1079    {"TRACE_MUTEX",                 0x04000000},
1080    {"TRACE_ALL",                   0x0FFFFF00},
1081    {"VERBOSE_AML_DISASSEMBLE",     0x10000000},
1082    {"VERBOSE_INFO",                0x20000000},
1083    {"VERBOSE_TABLES",              0x40000000},
1084    {"VERBOSE_EVENTS",              0x80000000},
1085    {"VERBOSE_ALL",                 0xF0000000},
1086    {NULL, 0}
1087};
1088
1089static void
1090acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
1091{
1092    char	*ep;
1093    int		i, l;
1094
1095    while (*cp) {
1096	if (isspace(*cp)) {
1097	    cp++;
1098	    continue;
1099	}
1100	ep = cp;
1101	while (*ep && !isspace(*ep))
1102	    ep++;
1103	l = ep - cp;
1104	for (i = 0; tag[i].name != NULL; i++) {
1105	    if (!strncmp(cp, tag[i].name, l)) {
1106		*flag |= tag[i].value;
1107		printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
1108	    }
1109	}
1110	cp = ep;
1111    }
1112}
1113
1114static void
1115acpi_set_debugging(void)
1116{
1117    char	*cp;
1118
1119    if ((cp = getenv("debug.acpi.layer")) != NULL)
1120	acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
1121    if ((cp = getenv("debug.acpi.level")) != NULL)
1122	acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
1123}
1124#endif
1125