xref: /freebsd/sys/dev/acpica/acpi_ec.c (revision f8335e3a97801ebb49d091a7e09a33711d56a76c)
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$
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 "opt_acpi.h"
140 #include <sys/param.h>
141 #include <sys/kernel.h>
142 #include <sys/bus.h>
143 
144 #include <machine/bus.h>
145 #include <machine/resource.h>
146 #include <sys/rman.h>
147 
148 #include "acpi.h"
149 
150 #include <dev/acpica/acpivar.h>
151 
152 /*
153  * Hooks for the ACPI CA debugging infrastructure
154  */
155 #define _COMPONENT	ACPI_EC
156 ACPI_MODULE_NAME("EC")
157 
158 /*
159  * EC_COMMAND:
160  * -----------
161  */
162 typedef UINT8				EC_COMMAND;
163 
164 #define EC_COMMAND_UNKNOWN		((EC_COMMAND) 0x00)
165 #define EC_COMMAND_READ			((EC_COMMAND) 0x80)
166 #define EC_COMMAND_WRITE		((EC_COMMAND) 0x81)
167 #define EC_COMMAND_BURST_ENABLE		((EC_COMMAND) 0x82)
168 #define EC_COMMAND_BURST_DISABLE	((EC_COMMAND) 0x83)
169 #define EC_COMMAND_QUERY		((EC_COMMAND) 0x84)
170 
171 /*
172  * EC_STATUS:
173  * ----------
174  * The encoding of the EC status register is illustrated below.
175  * Note that a set bit (1) indicates the property is TRUE
176  * (e.g. if bit 0 is set then the output buffer is full).
177  * +-+-+-+-+-+-+-+-+
178  * |7|6|5|4|3|2|1|0|
179  * +-+-+-+-+-+-+-+-+
180  *  | | | | | | | |
181  *  | | | | | | | +- Output Buffer Full?
182  *  | | | | | | +--- Input Buffer Full?
183  *  | | | | | +----- <reserved>
184  *  | | | | +------- Data Register is Command Byte?
185  *  | | | +--------- Burst Mode Enabled?
186  *  | | +----------- SCI Event?
187  *  | +------------- SMI Event?
188  *  +--------------- <Reserved>
189  *
190  */
191 typedef UINT8				EC_STATUS;
192 
193 #define EC_FLAG_OUTPUT_BUFFER		((EC_STATUS) 0x01)
194 #define EC_FLAG_INPUT_BUFFER		((EC_STATUS) 0x02)
195 #define EC_FLAG_BURST_MODE		((EC_STATUS) 0x10)
196 #define EC_FLAG_SCI			((EC_STATUS) 0x20)
197 
198 /*
199  * EC_EVENT:
200  * ---------
201  */
202 typedef UINT8				EC_EVENT;
203 
204 #define EC_EVENT_UNKNOWN		((EC_EVENT) 0x00)
205 #define EC_EVENT_OUTPUT_BUFFER_FULL	((EC_EVENT) 0x01)
206 #define EC_EVENT_INPUT_BUFFER_EMPTY	((EC_EVENT) 0x02)
207 #define EC_EVENT_SCI			((EC_EVENT) 0x20)
208 
209 /*
210  * Register access primitives
211  */
212 #define EC_GET_DATA(sc)							\
213 	bus_space_read_1((sc)->ec_data_tag, (sc)->ec_data_handle, 0)
214 
215 #define EC_SET_DATA(sc, v)						\
216 	bus_space_write_1((sc)->ec_data_tag, (sc)->ec_data_handle, 0, (v))
217 
218 #define EC_GET_CSR(sc)							\
219 	bus_space_read_1((sc)->ec_csr_tag, (sc)->ec_csr_handle, 0)
220 
221 #define EC_SET_CSR(sc, v)						\
222 	bus_space_write_1((sc)->ec_csr_tag, (sc)->ec_csr_handle, 0, (v))
223 
224 /* Embedded Controller Boot Resources Table (ECDT) */
225 typedef struct {
226     ACPI_TABLE_HEADER		header;
227     ACPI_GENERIC_ADDRESS	control;
228     ACPI_GENERIC_ADDRESS	data;
229     UINT32			uid;
230     UINT8			gpe_bit;
231     char			ec_id[0];
232 } ACPI_TABLE_ECDT;
233 
234 /* Indicate that this device has already been probed via ECDT. */
235 #define DEV_ECDT_FLAG		0x80000000
236 
237 /* Indicate that this device should use the global lock. */
238 #define DEV_GLK_FLAG		0x40000000
239 
240 /* Get/set GPE bit value in the magic ivar. */
241 #define DEV_GET_GPEBIT(x)	((x) & 0xff)
242 #define DEV_SET_GPEBIT(x, y)	((x) = ((x) & ~0xff) | ((y) & 0xff))
243 
244 /*
245  * Driver softc.
246  */
247 struct acpi_ec_softc {
248     device_t		ec_dev;
249     ACPI_HANDLE		ec_handle;
250     UINT32		ec_gpebit;
251 
252     int			ec_data_rid;
253     struct resource	*ec_data_res;
254     bus_space_tag_t	ec_data_tag;
255     bus_space_handle_t	ec_data_handle;
256 
257     int			ec_csr_rid;
258     struct resource	*ec_csr_res;
259     bus_space_tag_t	ec_csr_tag;
260     bus_space_handle_t	ec_csr_handle;
261 
262     int			ec_glk;
263     int			ec_glkhandle;
264     struct mtx		ec_mtx;
265     UINT32		ec_polldelay;
266 };
267 
268 /*
269  * XXX
270  * I couldn't find it in the spec but other implementations also use a
271  * value of 1 ms for the time to acquire global lock.
272  */
273 #define EC_LOCK_TIMEOUT	1000
274 
275 /*
276  * Start with an interval of 1 us for status poll loop.  This delay
277  * will be dynamically adjusted based on the actual time waited.
278  */
279 #define EC_POLL_DELAY	1
280 
281 /* Total time in ms spent in the poll loop waiting for a response. */
282 #define EC_POLL_TIMEOUT	50
283 
284 #define EVENT_READY(event, status)			\
285 	(((event) == EC_EVENT_OUTPUT_BUFFER_FULL &&	\
286 	 ((status) & EC_FLAG_OUTPUT_BUFFER) != 0) ||	\
287 	 ((event) == EC_EVENT_INPUT_BUFFER_EMPTY && 	\
288 	 ((status) & EC_FLAG_INPUT_BUFFER) == 0))
289 
290 static __inline ACPI_STATUS
291 EcLock(struct acpi_ec_softc *sc)
292 {
293     ACPI_STATUS	status = AE_OK;
294 
295     /* Always acquire this EC's mutex. */
296     mtx_lock(&sc->ec_mtx);
297 
298     /* If _GLK is non-zero, also acquire the global lock. */
299     if (sc->ec_glk) {
300 	status = AcpiAcquireGlobalLock(EC_LOCK_TIMEOUT, &sc->ec_glkhandle);
301 	if (ACPI_FAILURE(status))
302 	    mtx_unlock(&sc->ec_mtx);
303     }
304 
305     return (status);
306 }
307 
308 static __inline void
309 EcUnlock(struct acpi_ec_softc *sc)
310 {
311     if (sc->ec_glk)
312 	AcpiReleaseGlobalLock(sc->ec_glkhandle);
313     mtx_unlock(&sc->ec_mtx);
314 }
315 
316 static void		EcGpeHandler(void *Context);
317 static ACPI_STATUS	EcSpaceSetup(ACPI_HANDLE Region, UINT32 Function,
318 				void *Context, void **return_Context);
319 static ACPI_STATUS	EcSpaceHandler(UINT32 Function,
320 				ACPI_PHYSICAL_ADDRESS Address,
321 				UINT32 width, ACPI_INTEGER *Value,
322 				void *Context, void *RegionContext);
323 static ACPI_STATUS	EcWaitEvent(struct acpi_ec_softc *sc, EC_EVENT Event);
324 static ACPI_STATUS	EcQuery(struct acpi_ec_softc *sc, UINT8 *Data);
325 static ACPI_STATUS	EcCommand(struct acpi_ec_softc *sc, EC_COMMAND cmd);
326 static ACPI_STATUS	EcRead(struct acpi_ec_softc *sc, UINT8 Address,
327 				UINT8 *Data);
328 static ACPI_STATUS	EcWrite(struct acpi_ec_softc *sc, UINT8 Address,
329 				UINT8 *Data);
330 static int		acpi_ec_probe(device_t dev);
331 static int		acpi_ec_attach(device_t dev);
332 
333 static device_method_t acpi_ec_methods[] = {
334     /* Device interface */
335     DEVMETHOD(device_probe,	acpi_ec_probe),
336     DEVMETHOD(device_attach,	acpi_ec_attach),
337 
338     {0, 0}
339 };
340 
341 static driver_t acpi_ec_driver = {
342     "acpi_ec",
343     acpi_ec_methods,
344     sizeof(struct acpi_ec_softc),
345 };
346 
347 static devclass_t acpi_ec_devclass;
348 DRIVER_MODULE(acpi_ec, acpi, acpi_ec_driver, acpi_ec_devclass, 0, 0);
349 
350 /*
351  * Look for an ECDT and if we find one, set up default GPE and
352  * space handlers to catch attempts to access EC space before
353  * we have a real driver instance in place.
354  * TODO: if people report invalid ECDTs, add a tunable to disable them.
355  */
356 void
357 acpi_ec_ecdt_probe(device_t parent)
358 {
359     ACPI_TABLE_ECDT *ecdt;
360     ACPI_STATUS	     status;
361     device_t	     child;
362     ACPI_HANDLE	     h;
363     int		     magic;
364 
365     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
366 
367     /* Find and validate the ECDT. */
368     status = AcpiGetFirmwareTable("ECDT", 1, ACPI_LOGICAL_ADDRESSING,
369 		(ACPI_TABLE_HEADER **)&ecdt);
370     if (ACPI_FAILURE(status) ||
371 	ecdt->control.RegisterBitWidth != 8 ||
372 	ecdt->data.RegisterBitWidth != 8) {
373 	return;
374     }
375 
376     /* Create the child device with the given unit number. */
377     child = BUS_ADD_CHILD(parent, 0, "acpi_ec", ecdt->uid);
378     if (child == NULL) {
379 	printf("acpi_ec_ecdt_probe: can't add child\n");
380 	return;
381     }
382 
383     /* Find and save the ACPI handle for this device. */
384     status = AcpiGetHandle(NULL, ecdt->ec_id, &h);
385     if (ACPI_FAILURE(status)) {
386 	device_delete_child(parent, child);
387 	printf("acpi_ec_ecdt_probe: can't get handle\n");
388 	return;
389     }
390     acpi_set_handle(child, h);
391 
392     /* Set the data and CSR register addresses. */
393     bus_set_resource(child, SYS_RES_IOPORT, 0, ecdt->data.Address,
394 	/*count*/1);
395     bus_set_resource(child, SYS_RES_IOPORT, 1, ecdt->control.Address,
396 	/*count*/1);
397 
398     /*
399      * Store values for the probe/attach routines to use.  Store the
400      * ECDT GPE bit and set the global lock flag (just to be safe).
401      * We'll determine whether we really want to use the global lock
402      * in a later call to attach.
403      */
404     magic = DEV_ECDT_FLAG | DEV_GLK_FLAG;
405     DEV_SET_GPEBIT(magic, ecdt->gpe_bit);
406     acpi_set_magic(child, magic);
407 
408     /* Finish the attach process. */
409     if (device_probe_and_attach(child) != 0)
410 	device_delete_child(parent, child);
411 }
412 
413 static int
414 acpi_ec_probe(device_t dev)
415 {
416     ACPI_HANDLE h;
417     ACPI_STATUS status;
418     device_t	peer;
419     char	desc[64];
420     int		magic, uid, glk, gpebit, ret = ENXIO;
421 
422     /* Check that this is an EC device and it's not disabled. */
423     if (acpi_get_type(dev) != ACPI_TYPE_DEVICE || acpi_disabled("ec") ||
424 	!acpi_MatchHid(dev, "PNP0C09")) {
425 	return (ENXIO);
426     }
427 
428     /*
429      * If probed via ECDT, set description and continue.  Otherwise,
430      * we can access the namespace and make sure this is not a
431      * duplicate probe.
432      */
433     magic = acpi_get_magic(dev);
434     if ((magic & DEV_ECDT_FLAG) != 0) {
435 	snprintf(desc, sizeof(desc), "embedded controller: ECDT, GPE %#x, GLK",
436 		 DEV_GET_GPEBIT(magic));
437 	device_set_desc_copy(dev, desc);
438 	ret = 0;
439     } else {
440 	h = acpi_get_handle(dev);
441 
442 	/*
443 	 * Read the unit ID to check for duplicate attach and the
444 	 * global lock value to see if we should acquire it when
445 	 * accessing the EC.
446 	 */
447 	status = acpi_EvaluateInteger(h, "_UID", &uid);
448 	if (ACPI_FAILURE(status))
449 	    uid = 0;
450 	status = acpi_EvaluateInteger(h, "_GLK", &glk);
451 	if (ACPI_FAILURE(status))
452 	    glk = 0;
453 
454 	/*
455 	 * Evaluate the _GPE method to find the GPE bit used by the EC to
456 	 * signal status (SCI).  Note that we don't handle the case where
457 	 * it can return a package instead of an int.
458 	 */
459 	status = acpi_EvaluateInteger(h, "_GPE", &gpebit);
460 	if (ACPI_FAILURE(status)) {
461 	    device_printf(dev, "can't evaluate _GPE - %s\n",
462 			  AcpiFormatException(status));
463 	    return (ENXIO);
464 	}
465 
466 	/* Store the values we got from the namespace for attach. */
467 	magic = glk != 0 ? DEV_GLK_FLAG : 0;
468 	DEV_SET_GPEBIT(magic, gpebit);
469 	acpi_set_magic(dev, magic);
470 
471 	/*
472 	 * Check for a duplicate probe.  This can happen when a probe
473 	 * via ECDT succeeded already.  If there is a duplicate, override
474 	 * its value for GLK in the peer's softc since the ECDT case
475 	 * always enables the global lock to be safe.  Otherwise, just
476 	 * continue on to attach.
477 	 */
478 	peer = devclass_get_device(acpi_ec_devclass, uid);
479 	if (peer == NULL || !device_is_alive(peer)) {
480 	    snprintf(desc, sizeof(desc), "embedded controller: GPE %#x%s",
481 		     gpebit, glk != 0 ? ", GLK" : "");
482 	    device_set_desc_copy(dev, desc);
483 	    ret = 0;
484 	} else {
485 	    struct acpi_ec_softc *sc;
486 
487 	    /*
488 	     * Set the peer's sc->ec_glk with locks held so we won't
489 	     * override it between another thread's lock/unlock calls.
490 	     */
491 	    sc = device_get_softc(peer);
492 	    if (sc->ec_glk != glk) {
493 		ACPI_VPRINT(peer, acpi_device_get_parent_softc(peer),
494 		    "Changing GLK from %d to %d\n", sc->ec_glk, glk);
495 		mtx_lock(&sc->ec_mtx);
496 		sc->ec_glk = glk != 0 ? 1 : 0;
497 		mtx_unlock(&sc->ec_mtx);
498 	    }
499 	}
500     }
501 
502     return (ret);
503 }
504 
505 static int
506 acpi_ec_attach(device_t dev)
507 {
508     struct acpi_ec_softc	*sc;
509     ACPI_STATUS			Status;
510     int				magic, errval = 0;
511 
512     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
513 
514     /* Fetch/initialize softc (assumes softc is pre-zeroed). */
515     sc = device_get_softc(dev);
516     sc->ec_dev = dev;
517     sc->ec_handle = acpi_get_handle(dev);
518     sc->ec_polldelay = EC_POLL_DELAY;
519     mtx_init(&sc->ec_mtx, "ACPI embedded controller", NULL, MTX_DEF);
520 
521     /* Retrieve previously probed values via device ivars. */
522     magic = acpi_get_magic(dev);
523     sc->ec_glk = (magic & DEV_GLK_FLAG) != 0 ? 1 : 0;
524     sc->ec_gpebit = DEV_GET_GPEBIT(magic);
525 
526     /* Attach bus resources for data and command/status ports. */
527     sc->ec_data_rid = 0;
528     sc->ec_data_res = bus_alloc_resource(sc->ec_dev, SYS_RES_IOPORT,
529 			&sc->ec_data_rid, 0, ~0, 1, RF_ACTIVE);
530     if (sc->ec_data_res == NULL) {
531 	device_printf(dev, "can't allocate data port\n");
532 	errval = ENXIO;
533 	goto out;
534     }
535     sc->ec_data_tag = rman_get_bustag(sc->ec_data_res);
536     sc->ec_data_handle = rman_get_bushandle(sc->ec_data_res);
537 
538     sc->ec_csr_rid = 1;
539     sc->ec_csr_res = bus_alloc_resource(sc->ec_dev, SYS_RES_IOPORT,
540 			&sc->ec_csr_rid, 0, ~0, 1, RF_ACTIVE);
541     if (sc->ec_csr_res == NULL) {
542 	device_printf(dev, "can't allocate command/status port\n");
543 	errval = ENXIO;
544 	goto out;
545     }
546     sc->ec_csr_tag = rman_get_bustag(sc->ec_csr_res);
547     sc->ec_csr_handle = rman_get_bushandle(sc->ec_csr_res);
548 
549     /*
550      * Install a handler for this EC's GPE bit.  We want edge-triggered
551      * behavior.
552      */
553     ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, "attaching GPE handler\n"));
554     Status = AcpiInstallGpeHandler(NULL, sc->ec_gpebit,
555 		ACPI_EVENT_EDGE_TRIGGERED, &EcGpeHandler, sc);
556     if (ACPI_FAILURE(Status)) {
557 	device_printf(dev, "can't install GPE handler for %s - %s\n",
558 		      acpi_name(sc->ec_handle), AcpiFormatException(Status));
559 	errval = ENXIO;
560 	goto out;
561     }
562 
563     /*
564      * Install address space handler
565      */
566     ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, "attaching address space handler\n"));
567     Status = AcpiInstallAddressSpaceHandler(sc->ec_handle, ACPI_ADR_SPACE_EC,
568 		&EcSpaceHandler, &EcSpaceSetup, sc);
569     if (ACPI_FAILURE(Status)) {
570 	device_printf(dev, "can't install address space handler for %s - %s\n",
571 		      acpi_name(sc->ec_handle), AcpiFormatException(Status));
572 	Status = AcpiRemoveGpeHandler(NULL, sc->ec_gpebit, &EcGpeHandler);
573 	if (ACPI_FAILURE(Status))
574 	    panic("Added GPE handler but can't remove it");
575 	errval = ENXIO;
576 	goto out;
577     }
578 
579     ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, "acpi_ec_attach complete\n"));
580     return (0);
581 
582  out:
583     if (sc->ec_csr_res)
584 	bus_release_resource(sc->ec_dev, SYS_RES_IOPORT, sc->ec_csr_rid,
585 			     sc->ec_csr_res);
586     if (sc->ec_data_res)
587 	bus_release_resource(sc->ec_dev, SYS_RES_IOPORT, sc->ec_data_rid,
588 			     sc->ec_data_res);
589     mtx_destroy(&sc->ec_mtx);
590     return (errval);
591 }
592 
593 static ACPI_STATUS
594 EcQuery(struct acpi_ec_softc *sc, UINT8 *Data)
595 {
596     ACPI_STATUS	Status;
597 
598     Status = EcLock(sc);
599     if (ACPI_FAILURE(Status))
600 	return (Status);
601 
602     /*
603      * Send a query command to the EC to find out which _Qxx call it
604      * wants to make.  This command clears the SCI bit and also the
605      * interrupt source since we are edge-triggered.
606      */
607     Status = EcCommand(sc, EC_COMMAND_QUERY);
608     if (ACPI_SUCCESS(Status))
609 	*Data = EC_GET_DATA(sc);
610 
611     EcUnlock(sc);
612 
613     return (Status);
614 }
615 
616 static void
617 EcGpeQueryHandler(void *Context)
618 {
619     struct acpi_ec_softc	*sc = (struct acpi_ec_softc *)Context;
620     UINT8			Data;
621     ACPI_STATUS			Status;
622     EC_STATUS			EcStatus;
623     char			qxx[5];
624 
625     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
626     KASSERT(Context != NULL, ("EcGpeQueryHandler called with NULL"));
627 
628     /*
629      * Check status for EC_SCI.
630      *
631      * Bail out if the EC_SCI bit of the status register is not set.
632      * Note that this function should only be called when
633      * this bit is set (polling is used to detect IBE/OBF events).
634      *
635      * We don't acquire the global lock here but do protect against other
636      * running commands (read/write/query) by grabbing ec_mtx.
637      */
638     mtx_lock(&sc->ec_mtx);
639     EcStatus = EC_GET_CSR(sc);
640     mtx_unlock(&sc->ec_mtx);
641     if ((EcStatus & EC_EVENT_SCI) == 0) {
642 	/* If it's not an SCI, wakeup the EcWaitEvent sleep. */
643 	wakeup(&sc->ec_polldelay);
644 	goto re_enable;
645     }
646 
647     /* Find out why the EC is signaling us. */
648     Status = EcQuery(sc, &Data);
649     if (ACPI_FAILURE(Status)) {
650 	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
651 		    "GPE query failed - %s\n", AcpiFormatException(Status));
652 	goto re_enable;
653     }
654 
655     /* Ignore the value for "no outstanding event". (13.3.5) */
656     if (Data == 0)
657 	goto re_enable;
658 
659     /* Evaluate _Qxx to respond to the controller. */
660     sprintf(qxx, "_Q%02x", Data);
661     strupr(qxx);
662     Status = AcpiEvaluateObject(sc->ec_handle, qxx, NULL, NULL);
663     if (ACPI_FAILURE(Status) && Status != AE_NOT_FOUND) {
664 	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
665 		    "evaluation of GPE query method %s failed - %s\n",
666 		    qxx, AcpiFormatException(Status));
667     }
668 
669 re_enable:
670     /* Re-enable the GPE event so we'll get future requests. */
671     Status = AcpiEnableGpe(NULL, sc->ec_gpebit, ACPI_NOT_ISR);
672     if (ACPI_FAILURE(Status))
673 	printf("EcGpeQueryHandler: AcpiEnableEvent failed\n");
674 }
675 
676 /*
677  * Handle a GPE.  Currently we only handle SCI events as others must
678  * be handled by polling in EcWaitEvent().  This is because some ECs
679  * treat events as level when they should be edge-triggered.
680  */
681 static void
682 EcGpeHandler(void *Context)
683 {
684     struct acpi_ec_softc *sc = Context;
685     ACPI_STATUS		       Status;
686 
687     KASSERT(Context != NULL, ("EcGpeHandler called with NULL"));
688 
689     /* Disable further GPEs while we handle this one. */
690     AcpiDisableGpe(NULL, sc->ec_gpebit, ACPI_ISR);
691 
692     /* Schedule the GPE query handler. */
693     Status = AcpiOsQueueForExecution(OSD_PRIORITY_GPE, EcGpeQueryHandler,
694 		Context);
695     if (ACPI_FAILURE(Status)) {
696 	printf("Queuing GPE query handler failed.\n");
697 	Status = AcpiEnableGpe(NULL, sc->ec_gpebit, ACPI_ISR);
698 	if (ACPI_FAILURE(Status))
699 	    printf("EcGpeHandler: AcpiEnableEvent failed\n");
700     }
701 }
702 
703 static ACPI_STATUS
704 EcSpaceSetup(ACPI_HANDLE Region, UINT32 Function, void *Context,
705 	     void **RegionContext)
706 {
707 
708     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
709 
710     /*
711      * Just pass the context through, there's nothing to do here.
712      */
713     *RegionContext = Context;
714 
715     return_ACPI_STATUS (AE_OK);
716 }
717 
718 static ACPI_STATUS
719 EcSpaceHandler(UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 width,
720 	       ACPI_INTEGER *Value, void *Context, void *RegionContext)
721 {
722     struct acpi_ec_softc	*sc = (struct acpi_ec_softc *)Context;
723     ACPI_STATUS			Status = AE_OK;
724     UINT8			EcAddr, EcData;
725     int				i;
726 
727     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, (UINT32)Address);
728 
729     if (Address > 0xFF || width % 8 != 0 || Value == NULL || Context == NULL)
730 	return_ACPI_STATUS (AE_BAD_PARAMETER);
731 
732     /*
733      * Perform the transaction.
734      */
735     EcAddr = Address;
736     for (i = 0; i < width; i += 8) {
737 	Status = EcLock(sc);
738 	if (ACPI_FAILURE(Status))
739 	    return (Status);
740 
741 	switch (Function) {
742 	case ACPI_READ:
743 	    EcData = 0;
744 	    Status = EcRead(sc, EcAddr, &EcData);
745 	    break;
746 	case ACPI_WRITE:
747 	    EcData = (UINT8)((*Value) >> i);
748 	    Status = EcWrite(sc, EcAddr, &EcData);
749 	    break;
750 	default:
751 	    device_printf(sc->ec_dev, "invalid EcSpaceHandler function %d\n",
752 			  Function);
753 	    Status = AE_BAD_PARAMETER;
754 	    break;
755 	}
756 
757 	EcUnlock(sc);
758 	if (ACPI_FAILURE(Status))
759 	    return (Status);
760 
761 	*Value |= (ACPI_INTEGER)EcData << i;
762 	if (++EcAddr == 0)
763 	    return_ACPI_STATUS (AE_BAD_PARAMETER);
764     }
765     return_ACPI_STATUS (Status);
766 }
767 
768 static ACPI_STATUS
769 EcWaitEvent(struct acpi_ec_softc *sc, EC_EVENT Event)
770 {
771     EC_STATUS	EcStatus;
772     ACPI_STATUS	Status;
773     UINT32	i, period;
774 
775     mtx_assert(&sc->ec_mtx, MA_OWNED);
776     Status = AE_NO_HARDWARE_RESPONSE;
777 
778     /*
779      * Wait for 1 us before checking the CSR.  Testing shows about
780      * 50% of requests complete in 1 us and 90% of them complete
781      * in 5 us or less.
782      */
783     AcpiOsStall(1);
784 
785     /*
786      * Poll the EC status register to detect completion of the last
787      * command.  First, wait up to 1 ms in chunks of sc->ec_polldelay
788      * microseconds.
789      */
790     for (i = 0; i < 1000 / sc->ec_polldelay; i++) {
791 	EcStatus = EC_GET_CSR(sc);
792 	if (EVENT_READY(Event, EcStatus)) {
793 	    Status = AE_OK;
794 	    break;
795 	}
796 	AcpiOsStall(sc->ec_polldelay);
797     }
798 
799     /* Scale poll delay by the amount of time actually waited. */
800     period = i * sc->ec_polldelay;
801     if (period <= 5)
802 	sc->ec_polldelay = 1;
803     else if (period <= 20)
804 	sc->ec_polldelay = 5;
805     else if (period <= 100)
806 	sc->ec_polldelay = 10;
807     else
808 	sc->ec_polldelay = 100;
809 
810     /*
811      * If we still don't have a response, wait up to EC_POLL_TIMEOUT ms
812      * for completion, sleeping for chunks of 10 ms.
813      */
814     if (Status != AE_OK) {
815 	for (i = 0; i < EC_POLL_TIMEOUT / 10; i++) {
816 	    EcStatus = EC_GET_CSR(sc);
817 	    if (EVENT_READY(Event, EcStatus)) {
818 		Status = AE_OK;
819 		break;
820 	    }
821 	    msleep(&sc->ec_polldelay, &sc->ec_mtx, PZERO, "ecpoll", 10/*ms*/);
822 	}
823     }
824 
825     return (Status);
826 }
827 
828 static ACPI_STATUS
829 EcCommand(struct acpi_ec_softc *sc, EC_COMMAND cmd)
830 {
831     ACPI_STATUS	Status;
832     EC_EVENT	Event;
833 
834     mtx_assert(&sc->ec_mtx, MA_OWNED);
835 
836     /* Decide what to wait for based on command type. */
837     switch (cmd) {
838     case EC_COMMAND_READ:
839     case EC_COMMAND_WRITE:
840     case EC_COMMAND_BURST_DISABLE:
841 	Event = EC_EVENT_INPUT_BUFFER_EMPTY;
842 	break;
843     case EC_COMMAND_QUERY:
844     case EC_COMMAND_BURST_ENABLE:
845 	Event = EC_EVENT_OUTPUT_BUFFER_FULL;
846 	break;
847     default:
848 	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
849 		    "EcCommand: Invalid command %#x\n", cmd);
850 	return (AE_BAD_PARAMETER);
851     }
852 
853     /* Run the command and wait for the chosen event. */
854     EC_SET_CSR(sc, cmd);
855     Status = EcWaitEvent(sc, Event);
856     if (ACPI_FAILURE(Status)) {
857 	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
858 		    "EcCommand: no response to %#x\n", cmd);
859     }
860 
861     return (Status);
862 }
863 
864 static ACPI_STATUS
865 EcRead(struct acpi_ec_softc *sc, UINT8 Address, UINT8 *Data)
866 {
867     ACPI_STATUS	Status;
868 
869     mtx_assert(&sc->ec_mtx, MA_OWNED);
870 
871 #ifdef notyet
872     /* If we can't start burst mode, continue anyway. */
873     EcCommand(sc, EC_COMMAND_BURST_ENABLE);
874 #endif
875 
876     Status = EcCommand(sc, EC_COMMAND_READ);
877     if (ACPI_FAILURE(Status))
878 	return (Status);
879 
880     EC_SET_DATA(sc, Address);
881     Status = EcWaitEvent(sc, EC_EVENT_OUTPUT_BUFFER_FULL);
882     if (ACPI_FAILURE(Status)) {
883 	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
884 		    "EcRead: Failed waiting for EC to send data.\n");
885 	return (Status);
886     }
887 
888     *Data = EC_GET_DATA(sc);
889 
890 #ifdef notyet
891     if (sc->ec_burstactive) {
892 	Status = EcCommand(sc, EC_COMMAND_BURST_DISABLE);
893 	if (ACPI_FAILURE(Status))
894 	    return (Status);
895     }
896 #endif
897 
898     return (AE_OK);
899 }
900 
901 static ACPI_STATUS
902 EcWrite(struct acpi_ec_softc *sc, UINT8 Address, UINT8 *Data)
903 {
904     ACPI_STATUS	Status;
905 
906     mtx_assert(&sc->ec_mtx, MA_OWNED);
907 
908 #ifdef notyet
909     /* If we can't start burst mode, continue anyway. */
910     EcCommand(sc, EC_COMMAND_BURST_ENABLE);
911 #endif
912 
913     Status = EcCommand(sc, EC_COMMAND_WRITE);
914     if (ACPI_FAILURE(Status))
915 	return (Status);
916 
917     EC_SET_DATA(sc, Address);
918     Status = EcWaitEvent(sc, EC_EVENT_INPUT_BUFFER_EMPTY);
919     if (ACPI_FAILURE(Status)) {
920 	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
921 		    "EcRead: Failed waiting for EC to process address\n");
922 	return (Status);
923     }
924 
925     EC_SET_DATA(sc, *Data);
926     Status = EcWaitEvent(sc, EC_EVENT_INPUT_BUFFER_EMPTY);
927     if (ACPI_FAILURE(Status)) {
928 	ACPI_VPRINT(sc->ec_dev, acpi_device_get_parent_softc(sc->ec_dev),
929 		    "EcWrite: Failed waiting for EC to process data\n");
930 	return (Status);
931     }
932 
933 #ifdef notyet
934     if (sc->ec_burstactive) {
935 	Status = EcCommand(sc, EC_COMMAND_BURST_DISABLE);
936 	if (ACPI_FAILURE(Status))
937 	    return (Status);
938     }
939 #endif
940 
941     return (AE_OK);
942 }
943