acpi_ec.c revision 131474
1/*-
2 * Copyright (c) 2003 Nate Lawson
3 * Copyright (c) 2000 Michael Smith
4 * Copyright (c) 2000 BSDi
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 *
28 *	$FreeBSD: head/sys/dev/acpica/acpi_ec.c 131474 2004-07-02 19:17:27Z njl $
29 */
30/******************************************************************************
31 *
32 * 1. Copyright Notice
33 *
34 * Some or all of this work - Copyright (c) 1999, Intel Corp.  All rights
35 * reserved.
36 *
37 * 2. License
38 *
39 * 2.1. This is your license from Intel Corp. under its intellectual property
40 * rights.  You may have additional license terms from the party that provided
41 * you this software, covering your right to use that party's intellectual
42 * property rights.
43 *
44 * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
45 * copy of the source code appearing in this file ("Covered Code") an
46 * irrevocable, perpetual, worldwide license under Intel's copyrights in the
47 * base code distributed originally by Intel ("Original Intel Code") to copy,
48 * make derivatives, distribute, use and display any portion of the Covered
49 * Code in any form, with the right to sublicense such rights; and
50 *
51 * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
52 * license (with the right to sublicense), under only those claims of Intel
53 * patents that are infringed by the Original Intel Code, to make, use, sell,
54 * offer to sell, and import the Covered Code and derivative works thereof
55 * solely to the minimum extent necessary to exercise the above copyright
56 * license, and in no event shall the patent license extend to any additions
57 * to or modifications of the Original Intel Code.  No other license or right
58 * is granted directly or by implication, estoppel or otherwise;
59 *
60 * The above copyright and patent license is granted only if the following
61 * conditions are met:
62 *
63 * 3. Conditions
64 *
65 * 3.1. Redistribution of Source with Rights to Further Distribute Source.
66 * Redistribution of source code of any substantial portion of the Covered
67 * Code or modification with rights to further distribute source must include
68 * the above Copyright Notice, the above License, this list of Conditions,
69 * and the following Disclaimer and Export Compliance provision.  In addition,
70 * Licensee must cause all Covered Code to which Licensee contributes to
71 * contain a file documenting the changes Licensee made to create that Covered
72 * Code and the date of any change.  Licensee must include in that file the
73 * documentation of any changes made by any predecessor Licensee.  Licensee
74 * must include a prominent statement that the modification is derived,
75 * directly or indirectly, from Original Intel Code.
76 *
77 * 3.2. Redistribution of Source with no Rights to Further Distribute Source.
78 * Redistribution of source code of any substantial portion of the Covered
79 * Code or modification without rights to further distribute source must
80 * include the following Disclaimer and Export Compliance provision in the
81 * documentation and/or other materials provided with distribution.  In
82 * addition, Licensee may not authorize further sublicense of source of any
83 * portion of the Covered Code, and must include terms to the effect that the
84 * license from Licensee to its licensee is limited to the intellectual
85 * property embodied in the software Licensee provides to its licensee, and
86 * not to intellectual property embodied in modifications its licensee may
87 * make.
88 *
89 * 3.3. Redistribution of Executable. Redistribution in executable form of any
90 * substantial portion of the Covered Code or modification must reproduce the
91 * above Copyright Notice, and the following Disclaimer and Export Compliance
92 * provision in the documentation and/or other materials provided with the
93 * distribution.
94 *
95 * 3.4. Intel retains all right, title, and interest in and to the Original
96 * Intel Code.
97 *
98 * 3.5. Neither the name Intel nor any other trademark owned or controlled by
99 * Intel shall be used in advertising or otherwise to promote the sale, use or
100 * other dealings in products derived from or relating to the Covered Code
101 * without prior written authorization from Intel.
102 *
103 * 4. Disclaimer and Export Compliance
104 *
105 * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
106 * HERE.  ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
107 * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT,  ASSISTANCE,
108 * INSTALLATION, TRAINING OR OTHER SERVICES.  INTEL WILL NOT PROVIDE ANY
109 * UPDATES, ENHANCEMENTS OR EXTENSIONS.  INTEL SPECIFICALLY DISCLAIMS ANY
110 * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
111 * PARTICULAR PURPOSE.
112 *
113 * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
114 * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
115 * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
116 * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
117 * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
118 * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.  THESE LIMITATIONS
119 * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
120 * LIMITED REMEDY.
121 *
122 * 4.3. Licensee shall not export, either directly or indirectly, any of this
123 * software or system incorporating such software without first obtaining any
124 * required license or other approval from the U. S. Department of Commerce or
125 * any other agency or department of the United States Government.  In the
126 * event Licensee exports any such software from the United States or
127 * re-exports any such software from a foreign destination, Licensee shall
128 * ensure that the distribution and export/re-export of the software is in
129 * compliance with all laws, regulations, orders, or other restrictions of the
130 * U.S. Export Administration Regulations. Licensee agrees that neither it nor
131 * any of its subsidiaries will export/re-export any technical data, process,
132 * software, or service, directly or indirectly, to any country for which the
133 * United States government or any agency thereof requires an export license,
134 * other governmental approval, or letter of assurance, without first obtaining
135 * such license, approval or letter.
136 *
137 *****************************************************************************/
138
139#include <sys/cdefs.h>
140__FBSDID("$FreeBSD: head/sys/dev/acpica/acpi_ec.c 131474 2004-07-02 19:17:27Z njl $");
141
142#include "opt_acpi.h"
143#include <sys/param.h>
144#include <sys/kernel.h>
145#include <sys/bus.h>
146#include <sys/malloc.h>
147#include <sys/module.h>
148#include <sys/sx.h>
149
150#include <machine/bus.h>
151#include <machine/resource.h>
152#include <sys/rman.h>
153
154#include "acpi.h"
155#include <dev/acpica/acpivar.h>
156
157/*
158 * Hooks for the ACPI CA debugging infrastructure
159 */
160#define _COMPONENT	ACPI_EC
161ACPI_MODULE_NAME("EC")
162
163/*
164 * EC_COMMAND:
165 * -----------
166 */
167typedef UINT8				EC_COMMAND;
168
169#define EC_COMMAND_UNKNOWN		((EC_COMMAND) 0x00)
170#define EC_COMMAND_READ			((EC_COMMAND) 0x80)
171#define EC_COMMAND_WRITE		((EC_COMMAND) 0x81)
172#define EC_COMMAND_BURST_ENABLE		((EC_COMMAND) 0x82)
173#define EC_COMMAND_BURST_DISABLE	((EC_COMMAND) 0x83)
174#define EC_COMMAND_QUERY		((EC_COMMAND) 0x84)
175
176/*
177 * EC_STATUS:
178 * ----------
179 * The encoding of the EC status register is illustrated below.
180 * Note that a set bit (1) indicates the property is TRUE
181 * (e.g. if bit 0 is set then the output buffer is full).
182 * +-+-+-+-+-+-+-+-+
183 * |7|6|5|4|3|2|1|0|
184 * +-+-+-+-+-+-+-+-+
185 *  | | | | | | | |
186 *  | | | | | | | +- Output Buffer Full?
187 *  | | | | | | +--- Input Buffer Full?
188 *  | | | | | +----- <reserved>
189 *  | | | | +------- Data Register is Command Byte?
190 *  | | | +--------- Burst Mode Enabled?
191 *  | | +----------- SCI Event?
192 *  | +------------- SMI Event?
193 *  +--------------- <Reserved>
194 *
195 */
196typedef UINT8				EC_STATUS;
197
198#define EC_FLAG_OUTPUT_BUFFER		((EC_STATUS) 0x01)
199#define EC_FLAG_INPUT_BUFFER		((EC_STATUS) 0x02)
200#define EC_FLAG_BURST_MODE		((EC_STATUS) 0x10)
201#define EC_FLAG_SCI			((EC_STATUS) 0x20)
202
203/*
204 * EC_EVENT:
205 * ---------
206 */
207typedef UINT8				EC_EVENT;
208
209#define EC_EVENT_UNKNOWN		((EC_EVENT) 0x00)
210#define EC_EVENT_OUTPUT_BUFFER_FULL	((EC_EVENT) 0x01)
211#define EC_EVENT_INPUT_BUFFER_EMPTY	((EC_EVENT) 0x02)
212#define EC_EVENT_SCI			((EC_EVENT) 0x20)
213
214/*
215 * Register access primitives
216 */
217#define EC_GET_DATA(sc)							\
218	bus_space_read_1((sc)->ec_data_tag, (sc)->ec_data_handle, 0)
219
220#define EC_SET_DATA(sc, v)						\
221	bus_space_write_1((sc)->ec_data_tag, (sc)->ec_data_handle, 0, (v))
222
223#define EC_GET_CSR(sc)							\
224	bus_space_read_1((sc)->ec_csr_tag, (sc)->ec_csr_handle, 0)
225
226#define EC_SET_CSR(sc, v)						\
227	bus_space_write_1((sc)->ec_csr_tag, (sc)->ec_csr_handle, 0, (v))
228
229/* Embedded Controller Boot Resources Table (ECDT) */
230typedef struct {
231    ACPI_TABLE_HEADER		header;
232    ACPI_GENERIC_ADDRESS	control;
233    ACPI_GENERIC_ADDRESS	data;
234    UINT32			uid;
235    UINT8			gpe_bit;
236    char			ec_id[0];
237} ACPI_TABLE_ECDT;
238
239/* Additional params to pass from the probe routine */
240struct acpi_ec_params {
241    int		glk;
242    int		gpe_bit;
243    ACPI_HANDLE	gpe_handle;
244    int		uid;
245};
246
247/* Indicate that this device has already been probed via ECDT. */
248#define DEV_ECDT(x)		(acpi_get_magic(x) == (int)&acpi_ec_devclass)
249
250/*
251 * Driver softc.
252 */
253struct acpi_ec_softc {
254    device_t		ec_dev;
255    ACPI_HANDLE		ec_handle;
256    int			ec_uid;
257    ACPI_HANDLE		ec_gpehandle;
258    UINT8		ec_gpebit;
259    UINT8		ec_csrvalue;
260
261    int			ec_data_rid;
262    struct resource	*ec_data_res;
263    bus_space_tag_t	ec_data_tag;
264    bus_space_handle_t	ec_data_handle;
265
266    int			ec_csr_rid;
267    struct resource	*ec_csr_res;
268    bus_space_tag_t	ec_csr_tag;
269    bus_space_handle_t	ec_csr_handle;
270
271    int			ec_glk;
272    int			ec_glkhandle;
273    struct sx		ec_sxlock;
274};
275
276/*
277 * XXX
278 * I couldn't find it in the spec but other implementations also use a
279 * value of 1 ms for the time to acquire global lock.
280 */
281#define EC_LOCK_TIMEOUT	1000
282
283/* Default interval in microseconds for the status polling loop. */
284#define EC_POLL_DELAY	10
285
286/* Total time in ms spent in the poll loop waiting for a response. */
287#define EC_POLL_TIMEOUT	100
288
289#define EVENT_READY(event, status)			\
290	(((event) == EC_EVENT_OUTPUT_BUFFER_FULL &&	\
291	 ((status) & EC_FLAG_OUTPUT_BUFFER) != 0) ||	\
292	 ((event) == EC_EVENT_INPUT_BUFFER_EMPTY && 	\
293	 ((status) & EC_FLAG_INPUT_BUFFER) == 0))
294
295static int	ec_poll_timeout = EC_POLL_TIMEOUT;
296TUNABLE_INT("hw.acpi.ec.poll_timeout", &ec_poll_timeout);
297
298static __inline ACPI_STATUS
299EcLock(struct acpi_ec_softc *sc)
300{
301    ACPI_STATUS	status = AE_OK;
302
303    /* Always acquire this EC's mutex. */
304    sx_xlock(&sc->ec_sxlock);
305
306    /* If _GLK is non-zero, also acquire the global lock. */
307    if (sc->ec_glk) {
308	status = AcpiAcquireGlobalLock(EC_LOCK_TIMEOUT, &sc->ec_glkhandle);
309	if (ACPI_FAILURE(status))
310	    sx_xunlock(&sc->ec_sxlock);
311    }
312
313    return (status);
314}
315
316static __inline void
317EcUnlock(struct acpi_ec_softc *sc)
318{
319    if (sc->ec_glk)
320	AcpiReleaseGlobalLock(sc->ec_glkhandle);
321    sx_xunlock(&sc->ec_sxlock);
322}
323
324static uint32_t		EcGpeHandler(void *Context);
325static ACPI_STATUS	EcSpaceSetup(ACPI_HANDLE Region, UINT32 Function,
326				void *Context, void **return_Context);
327static ACPI_STATUS	EcSpaceHandler(UINT32 Function,
328				ACPI_PHYSICAL_ADDRESS Address,
329				UINT32 width, ACPI_INTEGER *Value,
330				void *Context, void *RegionContext);
331static ACPI_STATUS	EcWaitEvent(struct acpi_ec_softc *sc, EC_EVENT Event);
332static ACPI_STATUS	EcCommand(struct acpi_ec_softc *sc, EC_COMMAND cmd);
333static ACPI_STATUS	EcRead(struct acpi_ec_softc *sc, UINT8 Address,
334				UINT8 *Data);
335static ACPI_STATUS	EcWrite(struct acpi_ec_softc *sc, UINT8 Address,
336				UINT8 *Data);
337static int		acpi_ec_probe(device_t dev);
338static int		acpi_ec_attach(device_t dev);
339static int		acpi_ec_shutdown(device_t dev);
340
341static device_method_t acpi_ec_methods[] = {
342    /* Device interface */
343    DEVMETHOD(device_probe,	acpi_ec_probe),
344    DEVMETHOD(device_attach,	acpi_ec_attach),
345    DEVMETHOD(device_shutdown,	acpi_ec_shutdown),
346
347    {0, 0}
348};
349
350static driver_t acpi_ec_driver = {
351    "acpi_ec",
352    acpi_ec_methods,
353    sizeof(struct acpi_ec_softc),
354};
355
356static devclass_t acpi_ec_devclass;
357DRIVER_MODULE(acpi_ec, acpi, acpi_ec_driver, acpi_ec_devclass, 0, 0);
358MODULE_DEPEND(acpi_ec, acpi, 1, 1, 1);
359
360/*
361 * Look for an ECDT and if we find one, set up default GPE and
362 * space handlers to catch attempts to access EC space before
363 * we have a real driver instance in place.
364 * TODO: if people report invalid ECDTs, add a tunable to disable them.
365 */
366void
367acpi_ec_ecdt_probe(device_t parent)
368{
369    ACPI_TABLE_ECDT *ecdt;
370    ACPI_TABLE_HEADER *hdr;
371    ACPI_STATUS	     status;
372    device_t	     child;
373    ACPI_HANDLE	     h;
374    struct acpi_ec_params *params;
375
376    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
377
378    /* Find and validate the ECDT. */
379    status = AcpiGetFirmwareTable("ECDT", 1, ACPI_LOGICAL_ADDRESSING, &hdr);
380    ecdt = (ACPI_TABLE_ECDT *)hdr;
381    if (ACPI_FAILURE(status) ||
382	ecdt->control.RegisterBitWidth != 8 ||
383	ecdt->data.RegisterBitWidth != 8) {
384	return;
385    }
386
387    /* Create the child device with the given unit number. */
388    child = BUS_ADD_CHILD(parent, 0, "acpi_ec", ecdt->uid);
389    if (child == NULL) {
390	printf("%s: can't add child\n", __func__);
391	return;
392    }
393
394    /* Find and save the ACPI handle for this device. */
395    status = AcpiGetHandle(NULL, ecdt->ec_id, &h);
396    if (ACPI_FAILURE(status)) {
397	device_delete_child(parent, child);
398	printf("%s: can't get handle\n", __func__);
399	return;
400    }
401    acpi_set_handle(child, h);
402
403    /* Set the data and CSR register addresses. */
404    bus_set_resource(child, SYS_RES_IOPORT, 0, ecdt->data.Address,
405	/*count*/1);
406    bus_set_resource(child, SYS_RES_IOPORT, 1, ecdt->control.Address,
407	/*count*/1);
408
409    /*
410     * Store values for the probe/attach routines to use.  Store the
411     * ECDT GPE bit and set the global lock flag according to _GLK.
412     * Note that it is not perfectly correct to be evaluating a method
413     * before initializing devices, but in practice this function
414     * should be safe to call at this point.
415     */
416    params = malloc(sizeof(struct acpi_ec_params), M_TEMP, M_WAITOK | M_ZERO);
417    params->gpe_handle = NULL;
418    params->gpe_bit = ecdt->gpe_bit;
419    params->uid = ecdt->uid;
420    acpi_GetInteger(h, "_GLK", &params->glk);
421    acpi_set_private(child, params);
422    acpi_set_magic(child, (int)&acpi_ec_devclass);
423
424    /* Finish the attach process. */
425    if (device_probe_and_attach(child) != 0)
426	device_delete_child(parent, child);
427}
428
429static int
430acpi_ec_probe(device_t dev)
431{
432    ACPI_BUFFER buf;
433    ACPI_HANDLE h;
434    ACPI_OBJECT *obj;
435    ACPI_STATUS status;
436    device_t	peer;
437    char	desc[64];
438    int		ret;
439    struct acpi_ec_params *params;
440    static char *ec_ids[] = { "PNP0C09", NULL };
441
442    /* Check that this is a device and that EC is not disabled. */
443    if (acpi_get_type(dev) != ACPI_TYPE_DEVICE || acpi_disabled("ec"))
444	return (ENXIO);
445
446    /*
447     * If probed via ECDT, set description and continue.  Otherwise,
448     * we can access the namespace and make sure this is not a
449     * duplicate probe.
450     */
451    ret = ENXIO;
452    params = NULL;
453    buf.Pointer = NULL;
454    buf.Length = ACPI_ALLOCATE_BUFFER;
455    if (DEV_ECDT(dev)) {
456	params = acpi_get_private(dev);
457	ret = 0;
458    } else if (!acpi_disabled("ec") &&
459	ACPI_ID_PROBE(device_get_parent(dev), dev, ec_ids)) {
460	params = malloc(sizeof(struct acpi_ec_params), M_TEMP,
461			M_WAITOK | M_ZERO);
462	h = acpi_get_handle(dev);
463
464	/*
465	 * Read the unit ID to check for duplicate attach and the
466	 * global lock value to see if we should acquire it when
467	 * accessing the EC.
468	 */
469	status = acpi_GetInteger(h, "_UID", &params->uid);
470	if (ACPI_FAILURE(status))
471	    params->uid = 0;
472	status = acpi_GetInteger(h, "_GLK", &params->glk);
473	if (ACPI_FAILURE(status))
474	    params->glk = 0;
475
476	/*
477	 * Evaluate the _GPE method to find the GPE bit used by the EC to
478	 * signal status (SCI).  If it's a package, it contains a reference
479	 * and GPE bit, similar to _PRW.
480	 */
481	status = AcpiEvaluateObject(h, "_GPE", NULL, &buf);
482	if (ACPI_FAILURE(status)) {
483	    device_printf(dev, "can't evaluate _GPE - %s\n",
484			  AcpiFormatException(status));
485	    return (ENXIO);
486	}
487	obj = (ACPI_OBJECT *)buf.Pointer;
488	if (obj == NULL)
489	    return (ENXIO);
490
491	switch (obj->Type) {
492	case ACPI_TYPE_INTEGER:
493	    params->gpe_handle = NULL;
494	    params->gpe_bit = obj->Integer.Value;
495	    break;
496	case ACPI_TYPE_PACKAGE:
497	    if (!ACPI_PKG_VALID(obj, 2))
498		goto out;
499	    params->gpe_handle =
500		acpi_GetReference(NULL, &obj->Package.Elements[0]);
501	    if (params->gpe_handle == NULL ||
502		acpi_PkgInt32(obj, 1, &params->gpe_bit) != 0)
503		goto out;
504	    break;
505	default:
506	    device_printf(dev, "_GPE has invalid type %d\n", obj->Type);
507	    goto out;
508	}
509
510	/* Store the values we got from the namespace for attach. */
511	acpi_set_private(dev, params);
512
513	/*
514	 * Check for a duplicate probe.  This can happen when a probe
515	 * via ECDT succeeded already.  If this is a duplicate, disable
516	 * this device.
517	 */
518	peer = devclass_get_device(acpi_ec_devclass, params->uid);
519	if (peer == NULL || !device_is_alive(peer))
520	    ret = 0;
521	else
522	    device_disable(dev);
523    }
524
525out:
526    if (ret == 0) {
527	snprintf(desc, sizeof(desc), "Embedded Controller: GPE %#x%s%s",
528		 params->gpe_bit, (params->glk) ? ", GLK" : "",
529		 DEV_ECDT(dev) ? ", ECDT" : "");
530	device_set_desc_copy(dev, desc);
531    }
532
533    if (ret > 0 && params)
534	free(params, M_TEMP);
535    if (buf.Pointer)
536	AcpiOsFree(buf.Pointer);
537    return (ret);
538}
539
540static int
541acpi_ec_attach(device_t dev)
542{
543    struct acpi_ec_softc	*sc;
544    struct acpi_ec_params	*params;
545    ACPI_STATUS			Status;
546
547    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
548
549    /* Fetch/initialize softc (assumes softc is pre-zeroed). */
550    sc = device_get_softc(dev);
551    params = acpi_get_private(dev);
552    sc->ec_dev = dev;
553    sc->ec_handle = acpi_get_handle(dev);
554    sx_init(&sc->ec_sxlock, "ACPI embedded controller");
555
556    /* Retrieve previously probed values via device ivars. */
557    sc->ec_glk = params->glk;
558    sc->ec_gpebit = params->gpe_bit;
559    sc->ec_gpehandle = params->gpe_handle;
560    sc->ec_uid = params->uid;
561    free(params, M_TEMP);
562
563    /* Attach bus resources for data and command/status ports. */
564    sc->ec_data_rid = 0;
565    sc->ec_data_res = bus_alloc_resource_any(sc->ec_dev, SYS_RES_IOPORT,
566			&sc->ec_data_rid, RF_ACTIVE);
567    if (sc->ec_data_res == NULL) {
568	device_printf(dev, "can't allocate data port\n");
569	goto error;
570    }
571    sc->ec_data_tag = rman_get_bustag(sc->ec_data_res);
572    sc->ec_data_handle = rman_get_bushandle(sc->ec_data_res);
573
574    sc->ec_csr_rid = 1;
575    sc->ec_csr_res = bus_alloc_resource_any(sc->ec_dev, SYS_RES_IOPORT,
576			&sc->ec_csr_rid, RF_ACTIVE);
577    if (sc->ec_csr_res == NULL) {
578	device_printf(dev, "can't allocate command/status port\n");
579	goto error;
580    }
581    sc->ec_csr_tag = rman_get_bustag(sc->ec_csr_res);
582    sc->ec_csr_handle = rman_get_bushandle(sc->ec_csr_res);
583
584    /*
585     * Install a handler for this EC's GPE bit.  We want edge-triggered
586     * behavior.
587     */
588    ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, "attaching GPE handler\n"));
589    Status = AcpiInstallGpeHandler(sc->ec_gpehandle, sc->ec_gpebit,
590		ACPI_GPE_EDGE_TRIGGERED, &EcGpeHandler, sc);
591    if (ACPI_FAILURE(Status)) {
592	device_printf(dev, "can't install GPE handler for %s - %s\n",
593		      acpi_name(sc->ec_handle), AcpiFormatException(Status));
594	goto error;
595    }
596
597    /*
598     * Install address space handler
599     */
600    ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, "attaching address space handler\n"));
601    Status = AcpiInstallAddressSpaceHandler(sc->ec_handle, ACPI_ADR_SPACE_EC,
602		&EcSpaceHandler, &EcSpaceSetup, sc);
603    if (ACPI_FAILURE(Status)) {
604	device_printf(dev, "can't install address space handler for %s - %s\n",
605		      acpi_name(sc->ec_handle), AcpiFormatException(Status));
606	goto error;
607    }
608
609    /* Enable runtime GPEs for the handler. */
610    Status = AcpiSetGpeType(sc->ec_gpehandle, sc->ec_gpebit,
611			    ACPI_GPE_TYPE_RUNTIME);
612    if (ACPI_FAILURE(Status)) {
613	device_printf(dev, "AcpiSetGpeType failed: %s\n",
614		      AcpiFormatException(Status));
615	goto error;
616    }
617    Status = AcpiEnableGpe(sc->ec_gpehandle, sc->ec_gpebit, ACPI_NOT_ISR);
618    if (ACPI_FAILURE(Status)) {
619	device_printf(dev, "AcpiEnableGpe failed: %s\n",
620		      AcpiFormatException(Status));
621	goto error;
622    }
623
624    ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, "acpi_ec_attach complete\n"));
625    return (0);
626
627error:
628    AcpiRemoveGpeHandler(sc->ec_gpehandle, sc->ec_gpebit, &EcGpeHandler);
629    AcpiRemoveAddressSpaceHandler(sc->ec_handle, ACPI_ADR_SPACE_EC,
630	EcSpaceHandler);
631    if (sc->ec_csr_res)
632	bus_release_resource(sc->ec_dev, SYS_RES_IOPORT, sc->ec_csr_rid,
633			     sc->ec_csr_res);
634    if (sc->ec_data_res)
635	bus_release_resource(sc->ec_dev, SYS_RES_IOPORT, sc->ec_data_rid,
636			     sc->ec_data_res);
637    sx_destroy(&sc->ec_sxlock);
638    return (ENXIO);
639}
640
641static int
642acpi_ec_shutdown(device_t dev)
643{
644    struct acpi_ec_softc	*sc;
645
646    /* Disable the GPE so we don't get EC events during shutdown. */
647    sc = device_get_softc(dev);
648    AcpiDisableGpe(sc->ec_gpehandle, sc->ec_gpebit, ACPI_NOT_ISR);
649    return (0);
650}
651
652static void
653EcGpeQueryHandler(void *Context)
654{
655    struct acpi_ec_softc	*sc = (struct acpi_ec_softc *)Context;
656    UINT8			Data;
657    ACPI_STATUS			Status;
658    EC_STATUS			EcStatus;
659    char			qxx[5];
660
661    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
662    KASSERT(Context != NULL, ("EcGpeQueryHandler called with NULL"));
663
664    Status = EcLock(sc);
665    if (ACPI_FAILURE(Status)) {
666	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
667		    "GpeQuery lock error: %s\n", AcpiFormatException(Status));
668	return;
669    }
670
671    /*
672     * If the EC_SCI bit of the status register is not set, then pass
673     * it along to any potential waiters as it may be an IBE/OBF event.
674     */
675    EcStatus = EC_GET_CSR(sc);
676    if ((EcStatus & EC_EVENT_SCI) == 0) {
677	sc->ec_csrvalue = EcStatus;
678	wakeup(&sc->ec_csrvalue);
679	EcUnlock(sc);
680	goto re_enable;
681    }
682
683    /*
684     * Send a query command to the EC to find out which _Qxx call it
685     * wants to make.  This command clears the SCI bit and also the
686     * interrupt source since we are edge-triggered.
687     */
688    Status = EcCommand(sc, EC_COMMAND_QUERY);
689    if (ACPI_FAILURE(Status)) {
690	EcUnlock(sc);
691	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
692		    "GPE query failed - %s\n", AcpiFormatException(Status));
693	goto re_enable;
694    }
695    Data = EC_GET_DATA(sc);
696    EcUnlock(sc);
697
698    /* Ignore the value for "no outstanding event". (13.3.5) */
699    if (Data == 0)
700	goto re_enable;
701
702    /* Evaluate _Qxx to respond to the controller. */
703    sprintf(qxx, "_Q%02x", Data);
704    strupr(qxx);
705    Status = AcpiEvaluateObject(sc->ec_handle, qxx, NULL, NULL);
706    if (ACPI_FAILURE(Status) && Status != AE_NOT_FOUND) {
707	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
708		    "evaluation of GPE query method %s failed - %s\n",
709		    qxx, AcpiFormatException(Status));
710    }
711
712re_enable:
713    /* Re-enable the GPE event so we'll get future requests. */
714    Status = AcpiEnableGpe(sc->ec_gpehandle, sc->ec_gpebit, ACPI_NOT_ISR);
715    if (ACPI_FAILURE(Status))
716	printf("EcGpeQueryHandler: AcpiEnableEvent failed\n");
717}
718
719/*
720 * Handle a GPE.  Currently we only handle SCI events as others must
721 * be handled by polling in EcWaitEvent().  This is because some ECs
722 * treat events as level when they should be edge-triggered.
723 */
724static uint32_t
725EcGpeHandler(void *Context)
726{
727    struct acpi_ec_softc *sc = Context;
728    ACPI_STATUS		       Status;
729
730    KASSERT(Context != NULL, ("EcGpeHandler called with NULL"));
731
732    /* Disable further GPEs while we handle this one. */
733    AcpiDisableGpe(sc->ec_gpehandle, sc->ec_gpebit, ACPI_NOT_ISR);
734
735    /* Schedule the GPE query handler. */
736    Status = AcpiOsQueueForExecution(OSD_PRIORITY_GPE, EcGpeQueryHandler,
737		Context);
738    if (ACPI_FAILURE(Status)) {
739	printf("Queuing GPE query handler failed.\n");
740	Status = AcpiEnableGpe(sc->ec_gpehandle, sc->ec_gpebit, ACPI_NOT_ISR);
741	if (ACPI_FAILURE(Status))
742	    printf("EcGpeHandler: AcpiEnableEvent failed\n");
743    }
744
745    return (0);
746}
747
748static ACPI_STATUS
749EcSpaceSetup(ACPI_HANDLE Region, UINT32 Function, void *Context,
750	     void **RegionContext)
751{
752
753    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
754
755    /*
756     * If deactivating a region, always set the output to NULL.  Otherwise,
757     * just pass the context through.
758     */
759    if (Function == ACPI_REGION_DEACTIVATE)
760	*RegionContext = NULL;
761    else
762	*RegionContext = Context;
763
764    return_ACPI_STATUS (AE_OK);
765}
766
767static ACPI_STATUS
768EcSpaceHandler(UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 width,
769	       ACPI_INTEGER *Value, void *Context, void *RegionContext)
770{
771    struct acpi_ec_softc	*sc = (struct acpi_ec_softc *)Context;
772    ACPI_STATUS			Status;
773    UINT8			EcAddr, EcData;
774    int				i;
775
776    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, (UINT32)Address);
777
778    if (width % 8 != 0 || Value == NULL || Context == NULL)
779	return_ACPI_STATUS (AE_BAD_PARAMETER);
780    if (Address + (width / 8) - 1 > 0xFF)
781	return_ACPI_STATUS (AE_BAD_ADDRESS);
782
783    if (Function == ACPI_READ)
784	*Value = 0;
785    EcAddr = Address;
786    Status = AE_ERROR;
787
788    /* Perform the transaction(s), based on width. */
789    for (i = 0; i < width; i += 8, EcAddr++) {
790	Status = EcLock(sc);
791	if (ACPI_FAILURE(Status))
792	    break;
793
794	switch (Function) {
795	case ACPI_READ:
796	    Status = EcRead(sc, EcAddr, &EcData);
797	    if (ACPI_SUCCESS(Status))
798		*Value |= ((ACPI_INTEGER)EcData) << i;
799	    break;
800	case ACPI_WRITE:
801	    EcData = (UINT8)((*Value) >> i);
802	    Status = EcWrite(sc, EcAddr, &EcData);
803	    break;
804	default:
805	    device_printf(sc->ec_dev, "invalid EcSpaceHandler function %d\n",
806			  Function);
807	    Status = AE_BAD_PARAMETER;
808	    break;
809	}
810	EcUnlock(sc);
811	if (ACPI_FAILURE(Status))
812	    break;
813    }
814
815    return_ACPI_STATUS (Status);
816}
817
818static ACPI_STATUS
819EcWaitEvent(struct acpi_ec_softc *sc, EC_EVENT Event)
820{
821    EC_STATUS	EcStatus;
822    ACPI_STATUS	Status;
823    int		count, i, period, retval, slp_ival;
824    static int	EcDbgMaxDelay;
825
826    sx_assert(&sc->ec_sxlock, SX_XLOCKED);
827    Status = AE_NO_HARDWARE_RESPONSE;
828
829    /*
830     * Wait for 1 us before checking the CSR.  Testing shows about
831     * 50% of requests complete in 1 us and 90% of them complete
832     * in 5 us or less.
833     */
834    AcpiOsStall(1);
835
836    /*
837     * Poll the EC status register for up to 1 ms in chunks of 10 us
838     * to detect completion of the last command.
839     */
840    for (i = 0; i < 1000 / EC_POLL_DELAY; i++) {
841	EcStatus = EC_GET_CSR(sc);
842	if (EVENT_READY(Event, EcStatus)) {
843	    Status = AE_OK;
844	    break;
845	}
846	AcpiOsStall(EC_POLL_DELAY);
847    }
848    period = i * EC_POLL_DELAY;
849
850    /*
851     * If we still don't have a response and we're up and running, wait up
852     * to ec_poll_timeout ms for completion, sleeping for chunks of 10 ms.
853     */
854    slp_ival = 0;
855    if (Status != AE_OK) {
856	retval = ENXIO;
857	count = ec_poll_timeout / 10;
858	if (count == 0)
859	    count = 1;
860	slp_ival = hz / 100;
861	if (slp_ival == 0)
862	    slp_ival = 1;
863	for (i = 0; i < count; i++) {
864	    if (retval != 0)
865		EcStatus = EC_GET_CSR(sc);
866	    else
867		EcStatus = sc->ec_csrvalue;
868	    if (EVENT_READY(Event, EcStatus)) {
869		Status = AE_OK;
870		break;
871	    }
872	    if (!cold)
873		retval = tsleep(&sc->ec_csrvalue, PZERO, "ecpoll", slp_ival);
874	    else
875		AcpiOsStall(10000);
876	}
877    }
878
879    /* Calculate new delay and print it if it exceeds the max. */
880    if (slp_ival > 0)
881	period += i * 10000;
882    if (period > EcDbgMaxDelay) {
883	EcDbgMaxDelay = period;
884	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
885		    "info: new max delay is %d us\n", period);
886    }
887
888    return (Status);
889}
890
891static ACPI_STATUS
892EcCommand(struct acpi_ec_softc *sc, EC_COMMAND cmd)
893{
894    ACPI_STATUS	Status;
895    EC_EVENT	Event;
896
897    sx_assert(&sc->ec_sxlock, SX_XLOCKED);
898
899    /* Decide what to wait for based on command type. */
900    switch (cmd) {
901    case EC_COMMAND_READ:
902    case EC_COMMAND_WRITE:
903    case EC_COMMAND_BURST_DISABLE:
904	Event = EC_EVENT_INPUT_BUFFER_EMPTY;
905	break;
906    case EC_COMMAND_QUERY:
907    case EC_COMMAND_BURST_ENABLE:
908	Event = EC_EVENT_OUTPUT_BUFFER_FULL;
909	break;
910    default:
911	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
912		    "EcCommand: Invalid command %#x\n", cmd);
913	return (AE_BAD_PARAMETER);
914    }
915
916    /* Run the command and wait for the chosen event. */
917    EC_SET_CSR(sc, cmd);
918    Status = EcWaitEvent(sc, Event);
919    if (ACPI_FAILURE(Status)) {
920	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
921		    "EcCommand: no response to %#x\n", cmd);
922    }
923
924    return (Status);
925}
926
927static ACPI_STATUS
928EcRead(struct acpi_ec_softc *sc, UINT8 Address, UINT8 *Data)
929{
930    ACPI_STATUS	Status;
931
932    sx_assert(&sc->ec_sxlock, SX_XLOCKED);
933
934#ifdef notyet
935    /* If we can't start burst mode, continue anyway. */
936    EcCommand(sc, EC_COMMAND_BURST_ENABLE);
937#endif
938
939    Status = EcCommand(sc, EC_COMMAND_READ);
940    if (ACPI_FAILURE(Status))
941	return (Status);
942
943    EC_SET_DATA(sc, Address);
944    Status = EcWaitEvent(sc, EC_EVENT_OUTPUT_BUFFER_FULL);
945    if (ACPI_FAILURE(Status)) {
946	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
947		    "EcRead: Failed waiting for EC to send data.\n");
948	return (Status);
949    }
950
951    *Data = EC_GET_DATA(sc);
952
953#ifdef notyet
954    if (sc->ec_burstactive) {
955	Status = EcCommand(sc, EC_COMMAND_BURST_DISABLE);
956	if (ACPI_FAILURE(Status))
957	    return (Status);
958    }
959#endif
960
961    return (AE_OK);
962}
963
964static ACPI_STATUS
965EcWrite(struct acpi_ec_softc *sc, UINT8 Address, UINT8 *Data)
966{
967    ACPI_STATUS	Status;
968
969    sx_assert(&sc->ec_sxlock, SX_XLOCKED);
970
971#ifdef notyet
972    /* If we can't start burst mode, continue anyway. */
973    EcCommand(sc, EC_COMMAND_BURST_ENABLE);
974#endif
975
976    Status = EcCommand(sc, EC_COMMAND_WRITE);
977    if (ACPI_FAILURE(Status))
978	return (Status);
979
980    EC_SET_DATA(sc, Address);
981    Status = EcWaitEvent(sc, EC_EVENT_INPUT_BUFFER_EMPTY);
982    if (ACPI_FAILURE(Status)) {
983	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
984		    "EcRead: Failed waiting for EC to process address\n");
985	return (Status);
986    }
987
988    EC_SET_DATA(sc, *Data);
989    Status = EcWaitEvent(sc, EC_EVENT_INPUT_BUFFER_EMPTY);
990    if (ACPI_FAILURE(Status)) {
991	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
992		    "EcWrite: Failed waiting for EC to process data\n");
993	return (Status);
994    }
995
996#ifdef notyet
997    if (sc->ec_burstactive) {
998	Status = EcCommand(sc, EC_COMMAND_BURST_DISABLE);
999	if (ACPI_FAILURE(Status))
1000	    return (Status);
1001    }
1002#endif
1003
1004    return (AE_OK);
1005}
1006