xref: /dragonfly/sys/dev/acpica/acpi_ec.c (revision 8d411d7d)
1 /*-
2  * Copyright (c) 2003-2007 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 246128 2013-01-30 18:01:20Z sbz $
29  */
30 
31 #include "opt_acpi.h"
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/bus.h>
35 #include <sys/lock.h>
36 #include <sys/malloc.h>
37 #include <sys/module.h>
38 #include <sys/rman.h>
39 #include <sys/ktr.h>
40 
41 #include "acpi.h"
42 #include "accommon.h"
43 
44 #include <dev/acpica/acpivar.h>
45 
46 /* Hooks for the ACPICA debugging infrastructure */
47 #define _COMPONENT	ACPI_EC
48 ACPI_MODULE_NAME("EC")
49 
50 #define rebooting 0
51 
52 /*
53  * EC_COMMAND:
54  * -----------
55  */
56 typedef UINT8				EC_COMMAND;
57 
58 #define EC_COMMAND_UNKNOWN		((EC_COMMAND) 0x00)
59 #define EC_COMMAND_READ			((EC_COMMAND) 0x80)
60 #define EC_COMMAND_WRITE		((EC_COMMAND) 0x81)
61 #define EC_COMMAND_BURST_ENABLE		((EC_COMMAND) 0x82)
62 #define EC_COMMAND_BURST_DISABLE	((EC_COMMAND) 0x83)
63 #define EC_COMMAND_QUERY		((EC_COMMAND) 0x84)
64 
65 /*
66  * EC_STATUS:
67  * ----------
68  * The encoding of the EC status register is illustrated below.
69  * Note that a set bit (1) indicates the property is TRUE
70  * (e.g. if bit 0 is set then the output buffer is full).
71  * +-+-+-+-+-+-+-+-+
72  * |7|6|5|4|3|2|1|0|
73  * +-+-+-+-+-+-+-+-+
74  *  | | | | | | | |
75  *  | | | | | | | +- Output Buffer Full?
76  *  | | | | | | +--- Input Buffer Full?
77  *  | | | | | +----- <reserved>
78  *  | | | | +------- Data Register is Command Byte?
79  *  | | | +--------- Burst Mode Enabled?
80  *  | | +----------- SCI Event?
81  *  | +------------- SMI Event?
82  *  +--------------- <reserved>
83  *
84  */
85 typedef UINT8				EC_STATUS;
86 
87 #define EC_FLAG_OUTPUT_BUFFER		((EC_STATUS) 0x01)
88 #define EC_FLAG_INPUT_BUFFER		((EC_STATUS) 0x02)
89 #define EC_FLAG_DATA_IS_CMD		((EC_STATUS) 0x08)
90 #define EC_FLAG_BURST_MODE		((EC_STATUS) 0x10)
91 
92 /*
93  * EC_EVENT:
94  * ---------
95  */
96 typedef UINT8				EC_EVENT;
97 
98 #define EC_EVENT_UNKNOWN		((EC_EVENT) 0x00)
99 #define EC_EVENT_OUTPUT_BUFFER_FULL	((EC_EVENT) 0x01)
100 #define EC_EVENT_INPUT_BUFFER_EMPTY	((EC_EVENT) 0x02)
101 #define EC_EVENT_SCI			((EC_EVENT) 0x20)
102 #define EC_EVENT_SMI			((EC_EVENT) 0x40)
103 
104 /* Data byte returned after burst enable indicating it was successful. */
105 #define EC_BURST_ACK			0x90
106 
107 /*
108  * Register access primitives
109  */
110 #define EC_GET_DATA(sc)							\
111 	bus_space_read_1((sc)->ec_data_tag, (sc)->ec_data_handle, 0)
112 
113 #define EC_SET_DATA(sc, v)						\
114 	bus_space_write_1((sc)->ec_data_tag, (sc)->ec_data_handle, 0, (v))
115 
116 #define EC_GET_CSR(sc)							\
117 	bus_space_read_1((sc)->ec_csr_tag, (sc)->ec_csr_handle, 0)
118 
119 #define EC_SET_CSR(sc, v)						\
120 	bus_space_write_1((sc)->ec_csr_tag, (sc)->ec_csr_handle, 0, (v))
121 
122 /* Additional params to pass from the probe routine */
123 struct acpi_ec_params {
124     int		glk;
125     int		gpe_bit;
126     ACPI_HANDLE	gpe_handle;
127     int		uid;
128 };
129 
130 /*
131  * Driver softc.
132  */
133 struct acpi_ec_softc {
134     device_t		ec_dev;
135     ACPI_HANDLE		ec_handle;
136     int			ec_uid;
137     ACPI_HANDLE		ec_gpehandle;
138     UINT8		ec_gpebit;
139 
140     int			ec_data_rid;
141     struct resource	*ec_data_res;
142     bus_space_tag_t	ec_data_tag;
143     bus_space_handle_t	ec_data_handle;
144 
145     int			ec_csr_rid;
146     struct resource	*ec_csr_res;
147     bus_space_tag_t	ec_csr_tag;
148     bus_space_handle_t	ec_csr_handle;
149 
150     int			ec_glk;
151     int			ec_glkhandle;
152     int			ec_burstactive;
153     int			ec_sci_pend;
154     volatile u_int	ec_gencount;
155     int			ec_suspending;
156 };
157 
158 /*
159  * XXX njl
160  * I couldn't find it in the spec but other implementations also use a
161  * value of 1 ms for the time to acquire global lock.
162  */
163 #define EC_LOCK_TIMEOUT	1000
164 
165 /* Default delay in microseconds between each run of the status polling loop. */
166 #define EC_POLL_DELAY	50
167 
168 /* Total time in ms spent waiting for a response from EC. */
169 #define EC_TIMEOUT	750
170 
171 #define EVENT_READY(event, status)			\
172 	(((event) == EC_EVENT_OUTPUT_BUFFER_FULL &&	\
173 	 ((status) & EC_FLAG_OUTPUT_BUFFER) != 0) ||	\
174 	 ((event) == EC_EVENT_INPUT_BUFFER_EMPTY && 	\
175 	 ((status) & EC_FLAG_INPUT_BUFFER) == 0))
176 
177 ACPI_SERIAL_DECL(ec, "ACPI embedded controller");
178 
179 static SYSCTL_NODE(_debug_acpi, OID_AUTO, ec, CTLFLAG_RD, NULL, "EC debugging");
180 
181 static int	ec_burst_mode;
182 TUNABLE_INT("debug.acpi.ec.burst", &ec_burst_mode);
183 SYSCTL_INT(_debug_acpi_ec, OID_AUTO, burst, CTLFLAG_RW, &ec_burst_mode, 0,
184     "Enable use of burst mode (faster for nearly all systems)");
185 static int	ec_polled_mode;
186 TUNABLE_INT("debug.acpi.ec.polled", &ec_polled_mode);
187 SYSCTL_INT(_debug_acpi_ec, OID_AUTO, polled, CTLFLAG_RW, &ec_polled_mode, 0,
188     "Force use of polled mode (only if interrupt mode doesn't work)");
189 static int	ec_timeout = EC_TIMEOUT;
190 TUNABLE_INT("debug.acpi.ec.timeout", &ec_timeout);
191 SYSCTL_INT(_debug_acpi_ec, OID_AUTO, timeout, CTLFLAG_RW, &ec_timeout,
192     EC_TIMEOUT, "Total time spent waiting for a response (poll+sleep)");
193 
194 #ifndef KTR_ACPI_EC
195 #define	KTR_ACPI_EC	KTR_ALL
196 #endif
197 
198 KTR_INFO_MASTER(acpi_ec);
199 KTR_INFO(KTR_ACPI_EC, acpi_ec, burstdis, 0,
200     "ec burst disabled in waitevent (%s)", const char *msg);
201 KTR_INFO(KTR_ACPI_EC, acpi_ec, burstdisok, 1,
202     "ec disabled burst ok");
203 KTR_INFO(KTR_ACPI_EC, acpi_ec, burstenl, 2,
204     "ec burst enabled");
205 KTR_INFO(KTR_ACPI_EC, acpi_ec, cmdrun, 3,
206     "ec running command %#hhx", EC_COMMAND cmd);
207 KTR_INFO(KTR_ACPI_EC, acpi_ec, gpehdlstart, 4,
208     "ec gpe handler start");
209 KTR_INFO(KTR_ACPI_EC, acpi_ec, gpequeuehdl, 5,
210     "ec gpe queueing query handler");
211 KTR_INFO(KTR_ACPI_EC, acpi_ec, gperun, 6,
212     "ec running gpe handler directly");
213 KTR_INFO(KTR_ACPI_EC, acpi_ec, qryoknotrun, 7,
214     "ec query ok, not running _Q%02hhX", uint8_t Data);
215 KTR_INFO(KTR_ACPI_EC, acpi_ec, qryokrun, 8,
216     "ec query ok, running _Q%02hhX", uint8_t Data);
217 KTR_INFO(KTR_ACPI_EC, acpi_ec, readaddr, 9,
218     "ec read from %#hhx", UINT8 Address);
219 KTR_INFO(KTR_ACPI_EC, acpi_ec, timeout, 10,
220     "error: ec wait timed out");
221 KTR_INFO(KTR_ACPI_EC, acpi_ec, waitrdy, 11,
222     "ec %s wait ready, status %#hhx", const char *msg, EC_STATUS ec_status);
223 KTR_INFO(KTR_ACPI_EC, acpi_ec, writeaddr, 12,
224     "ec write to %#hhx, data %#hhx", UINT8 Address, UINT8 Data);
225 
226 static ACPI_STATUS
227 EcLock(struct acpi_ec_softc *sc)
228 {
229     ACPI_STATUS	status;
230 
231     /* If _GLK is non-zero, acquire the global lock. */
232     status = AE_OK;
233     if (sc->ec_glk) {
234 	status = AcpiAcquireGlobalLock(EC_LOCK_TIMEOUT, &sc->ec_glkhandle);
235 	if (ACPI_FAILURE(status))
236 	    return (status);
237     }
238     ACPI_SERIAL_BEGIN(ec);
239     return (status);
240 }
241 
242 static void
243 EcUnlock(struct acpi_ec_softc *sc)
244 {
245     ACPI_SERIAL_END(ec);
246     if (sc->ec_glk)
247 	AcpiReleaseGlobalLock(sc->ec_glkhandle);
248 }
249 
250 static UINT32		EcGpeHandler(ACPI_HANDLE GpeDevice,
251 				UINT32 GpeNumber, void *Context);
252 static ACPI_STATUS	EcSpaceSetup(ACPI_HANDLE Region, UINT32 Function,
253 				void *Context, void **return_Context);
254 static ACPI_STATUS	EcSpaceHandler(UINT32 Function,
255 				ACPI_PHYSICAL_ADDRESS Address,
256 				UINT32 Width, UINT64 *Value,
257 				void *Context, void *RegionContext);
258 static ACPI_STATUS	EcWaitEvent(struct acpi_ec_softc *sc, EC_EVENT Event,
259 				u_int gen_count);
260 static ACPI_STATUS	EcCommand(struct acpi_ec_softc *sc, EC_COMMAND cmd);
261 static ACPI_STATUS	EcRead(struct acpi_ec_softc *sc, UINT8 Address,
262 				UINT8 *Data);
263 static ACPI_STATUS	EcWrite(struct acpi_ec_softc *sc, UINT8 Address,
264 				UINT8 Data);
265 static int		acpi_ec_probe(device_t dev);
266 static int		acpi_ec_attach(device_t dev);
267 static int		acpi_ec_suspend(device_t dev);
268 static int		acpi_ec_resume(device_t dev);
269 static int		acpi_ec_shutdown(device_t dev);
270 static int		acpi_ec_read_method(device_t dev, u_int addr,
271 				UINT64 *val, int width);
272 static int		acpi_ec_write_method(device_t dev, u_int addr,
273 				UINT64 val, int width);
274 
275 static device_method_t acpi_ec_methods[] = {
276     /* Device interface */
277     DEVMETHOD(device_probe,	acpi_ec_probe),
278     DEVMETHOD(device_attach,	acpi_ec_attach),
279     DEVMETHOD(device_suspend,	acpi_ec_suspend),
280     DEVMETHOD(device_resume,	acpi_ec_resume),
281     DEVMETHOD(device_shutdown,	acpi_ec_shutdown),
282 
283     /* Embedded controller interface */
284     DEVMETHOD(acpi_ec_read,	acpi_ec_read_method),
285     DEVMETHOD(acpi_ec_write,	acpi_ec_write_method),
286 
287     DEVMETHOD_END
288 };
289 
290 static driver_t acpi_ec_driver = {
291     "acpi_ec",
292     acpi_ec_methods,
293     sizeof(struct acpi_ec_softc),
294     .gpri = KOBJ_GPRI_ACPI
295 };
296 
297 static devclass_t acpi_ec_devclass;
298 DRIVER_MODULE(acpi_ec, acpi, acpi_ec_driver, acpi_ec_devclass, NULL, NULL);
299 MODULE_DEPEND(acpi_ec, acpi, 1, 1, 1);
300 
301 /*
302  * Look for an ECDT and if we find one, set up default GPE and
303  * space handlers to catch attempts to access EC space before
304  * we have a real driver instance in place.
305  *
306  * TODO: Some old Gateway laptops need us to fake up an ECDT or
307  * otherwise attach early so that _REG methods can run.
308  */
309 void
310 acpi_ec_ecdt_probe(device_t parent)
311 {
312     ACPI_TABLE_ECDT *ecdt;
313     ACPI_STATUS	     status;
314     device_t	     child;
315     ACPI_HANDLE	     h;
316     struct acpi_ec_params *params;
317 
318     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
319 
320     /* Find and validate the ECDT. */
321     status = AcpiGetTable(ACPI_SIG_ECDT, 1, (ACPI_TABLE_HEADER **)&ecdt);
322     if (ACPI_FAILURE(status) ||
323 	ecdt->Control.BitWidth != 8 ||
324 	ecdt->Data.BitWidth != 8) {
325 	return;
326     }
327 
328     /* Create the child device with the given unit number. */
329     child = BUS_ADD_CHILD(parent, parent, 0, "acpi_ec", ecdt->Uid);
330     if (child == NULL) {
331 	kprintf("%s: can't add child\n", __func__);
332 	return;
333     }
334 
335     /* Find and save the ACPI handle for this device. */
336     status = AcpiGetHandle(NULL, ecdt->Id, &h);
337     if (ACPI_FAILURE(status)) {
338 	device_delete_child(parent, child);
339 	kprintf("%s: can't get handle\n", __func__);
340 	return;
341     }
342     acpi_set_handle(child, h);
343 
344     /* Set the data and CSR register addresses. */
345     bus_set_resource(child, SYS_RES_IOPORT, 0, ecdt->Data.Address,
346 	/*count*/1, -1);
347     bus_set_resource(child, SYS_RES_IOPORT, 1, ecdt->Control.Address,
348 	/*count*/1, -1);
349 
350     /*
351      * Store values for the probe/attach routines to use.  Store the
352      * ECDT GPE bit and set the global lock flag according to _GLK.
353      * Note that it is not perfectly correct to be evaluating a method
354      * before initializing devices, but in practice this function
355      * should be safe to call at this point.
356      */
357     params = kmalloc(sizeof(struct acpi_ec_params), M_TEMP, M_WAITOK | M_ZERO);
358     params->gpe_handle = NULL;
359     params->gpe_bit = ecdt->Gpe;
360     params->uid = ecdt->Uid;
361     acpi_GetInteger(h, "_GLK", &params->glk);
362     acpi_set_private(child, params);
363 
364     /* Finish the attach process. */
365     if (device_probe_and_attach(child) != 0)
366 	device_delete_child(parent, child);
367 }
368 
369 static int
370 acpi_ec_probe(device_t dev)
371 {
372     ACPI_BUFFER buf;
373     ACPI_HANDLE h;
374     ACPI_OBJECT *obj;
375     ACPI_STATUS status;
376     device_t	peer;
377     char	desc[64];
378     int		ecdt;
379     int		ret;
380     struct acpi_ec_params *params;
381     static char *ec_ids[] = { "PNP0C09", NULL };
382 
383     /* Check that this is a device and that EC is not disabled. */
384     if (acpi_get_type(dev) != ACPI_TYPE_DEVICE || acpi_disabled("ec"))
385 	return (ENXIO);
386 
387     /*
388      * If probed via ECDT, set description and continue.  Otherwise,
389      * we can access the namespace and make sure this is not a
390      * duplicate probe.
391      */
392     ret = ENXIO;
393     ecdt = 0;
394     buf.Pointer = NULL;
395     buf.Length = ACPI_ALLOCATE_BUFFER;
396     params = acpi_get_private(dev);
397     if (params != NULL) {
398 	ecdt = 1;
399 	ret = 0;
400     } else if (ACPI_ID_PROBE(device_get_parent(dev), dev, ec_ids)) {
401 	params = kmalloc(sizeof(struct acpi_ec_params), M_TEMP,
402 			M_WAITOK | M_ZERO);
403 	h = acpi_get_handle(dev);
404 
405 	/*
406 	 * Read the unit ID to check for duplicate attach and the
407 	 * global lock value to see if we should acquire it when
408 	 * accessing the EC.
409 	 */
410 	status = acpi_GetInteger(h, "_UID", &params->uid);
411 	if (ACPI_FAILURE(status))
412 	    params->uid = 0;
413 	status = acpi_GetInteger(h, "_GLK", &params->glk);
414 	if (ACPI_FAILURE(status))
415 	    params->glk = 0;
416 
417 	/*
418 	 * Evaluate the _GPE method to find the GPE bit used by the EC to
419 	 * signal status (SCI).  If it's a package, it contains a reference
420 	 * and GPE bit, similar to _PRW.
421 	 */
422 	status = AcpiEvaluateObject(h, "_GPE", NULL, &buf);
423 	if (ACPI_FAILURE(status)) {
424 	    device_printf(dev, "can't evaluate _GPE - %s\n",
425 			  AcpiFormatException(status));
426 	    goto out;
427 	}
428 	obj = (ACPI_OBJECT *)buf.Pointer;
429 	if (obj == NULL)
430 	    goto out;
431 
432 	switch (obj->Type) {
433 	case ACPI_TYPE_INTEGER:
434 	    params->gpe_handle = NULL;
435 	    params->gpe_bit = obj->Integer.Value;
436 	    break;
437 	case ACPI_TYPE_PACKAGE:
438 	    if (!ACPI_PKG_VALID(obj, 2))
439 		goto out;
440 	    params->gpe_handle =
441 		acpi_GetReference(NULL, &obj->Package.Elements[0]);
442 	    if (params->gpe_handle == NULL ||
443 		acpi_PkgInt32(obj, 1, &params->gpe_bit) != 0)
444 		goto out;
445 	    break;
446 	default:
447 	    device_printf(dev, "_GPE has invalid type %d\n", obj->Type);
448 	    goto out;
449 	}
450 
451 	/* Store the values we got from the namespace for attach. */
452 	acpi_set_private(dev, params);
453 
454 	/*
455 	 * Check for a duplicate probe.  This can happen when a probe
456 	 * via ECDT succeeded already.  If this is a duplicate, disable
457 	 * this device.
458 	 */
459 	peer = devclass_get_device(acpi_ec_devclass, params->uid);
460 	if (peer == NULL || !device_is_alive(peer))
461 	    ret = 0;
462 	else
463 	    device_disable(dev);
464     }
465 
466 out:
467     if (ret == 0) {
468 	ksnprintf(desc, sizeof(desc), "Embedded Controller: GPE %#x%s%s",
469 		 params->gpe_bit, (params->glk) ? ", GLK" : "",
470 		 ecdt ? ", ECDT" : "");
471 	device_set_desc_copy(dev, desc);
472     }
473 
474     if (ret > 0 && params)
475 	kfree(params, M_TEMP);
476     if (buf.Pointer)
477 	AcpiOsFree(buf.Pointer);
478     return (ret);
479 }
480 
481 static int
482 acpi_ec_attach(device_t dev)
483 {
484     struct acpi_ec_softc	*sc;
485     struct acpi_ec_params	*params;
486     ACPI_STATUS			Status;
487 
488     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
489 
490     /* Fetch/initialize softc (assumes softc is pre-zeroed). */
491     sc = device_get_softc(dev);
492     params = acpi_get_private(dev);
493     sc->ec_dev = dev;
494     sc->ec_handle = acpi_get_handle(dev);
495     ACPI_SERIAL_INIT(ec);
496 
497     /* Retrieve previously probed values via device ivars. */
498     sc->ec_glk = params->glk;
499     sc->ec_gpebit = params->gpe_bit;
500     sc->ec_gpehandle = params->gpe_handle;
501     sc->ec_uid = params->uid;
502     sc->ec_suspending = FALSE;
503     acpi_set_private(dev, NULL);
504     kfree(params, M_TEMP);
505 
506     /* Attach bus resources for data and command/status ports. */
507     sc->ec_data_rid = 0;
508     sc->ec_data_res = bus_alloc_resource_any(sc->ec_dev, SYS_RES_IOPORT,
509 			&sc->ec_data_rid, RF_ACTIVE);
510     if (sc->ec_data_res == NULL) {
511 	device_printf(dev, "can't allocate data port\n");
512 	goto error;
513     }
514     sc->ec_data_tag = rman_get_bustag(sc->ec_data_res);
515     sc->ec_data_handle = rman_get_bushandle(sc->ec_data_res);
516 
517     sc->ec_csr_rid = 1;
518     sc->ec_csr_res = bus_alloc_resource_any(sc->ec_dev, SYS_RES_IOPORT,
519 			&sc->ec_csr_rid, RF_ACTIVE);
520     if (sc->ec_csr_res == NULL) {
521 	device_printf(dev, "can't allocate command/status port\n");
522 	goto error;
523     }
524     sc->ec_csr_tag = rman_get_bustag(sc->ec_csr_res);
525     sc->ec_csr_handle = rman_get_bushandle(sc->ec_csr_res);
526 
527     /*
528      * Install a handler for this EC's GPE bit.  We want edge-triggered
529      * behavior.
530      */
531     ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, "attaching GPE handler\n"));
532     Status = AcpiInstallGpeHandler(sc->ec_gpehandle, sc->ec_gpebit,
533 		ACPI_GPE_EDGE_TRIGGERED, EcGpeHandler, sc);
534     if (ACPI_FAILURE(Status)) {
535 	device_printf(dev, "can't install GPE handler for %s - %s\n",
536 		      acpi_name(sc->ec_handle), AcpiFormatException(Status));
537 	goto error;
538     }
539 
540     /*
541      * Install address space handler
542      */
543     ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, "attaching address space handler\n"));
544     Status = AcpiInstallAddressSpaceHandler(sc->ec_handle, ACPI_ADR_SPACE_EC,
545 		&EcSpaceHandler, &EcSpaceSetup, sc);
546     if (ACPI_FAILURE(Status)) {
547 	device_printf(dev, "can't install address space handler for %s - %s\n",
548 		      acpi_name(sc->ec_handle), AcpiFormatException(Status));
549 	goto error;
550     }
551 
552     /* Enable runtime GPEs for the handler. */
553     Status = AcpiEnableGpe(sc->ec_gpehandle, sc->ec_gpebit);
554     if (ACPI_FAILURE(Status)) {
555 	device_printf(dev, "AcpiEnableGpe failed: %s\n",
556 		      AcpiFormatException(Status));
557 	goto error;
558     }
559 
560     ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, "acpi_ec_attach complete\n"));
561     return (0);
562 
563 error:
564     AcpiRemoveGpeHandler(sc->ec_gpehandle, sc->ec_gpebit, EcGpeHandler);
565     AcpiRemoveAddressSpaceHandler(sc->ec_handle, ACPI_ADR_SPACE_EC,
566 	EcSpaceHandler);
567     if (sc->ec_csr_res)
568 	bus_release_resource(sc->ec_dev, SYS_RES_IOPORT, sc->ec_csr_rid,
569 			     sc->ec_csr_res);
570     if (sc->ec_data_res)
571 	bus_release_resource(sc->ec_dev, SYS_RES_IOPORT, sc->ec_data_rid,
572 			     sc->ec_data_res);
573     return (ENXIO);
574 }
575 
576 static int
577 acpi_ec_suspend(device_t dev)
578 {
579     struct acpi_ec_softc	*sc;
580 
581     sc = device_get_softc(dev);
582     sc->ec_suspending = TRUE;
583     return (0);
584 }
585 
586 static int
587 acpi_ec_resume(device_t dev)
588 {
589     struct acpi_ec_softc	*sc;
590 
591     sc = device_get_softc(dev);
592     sc->ec_suspending = FALSE;
593     return (0);
594 }
595 
596 static int
597 acpi_ec_shutdown(device_t dev)
598 {
599     struct acpi_ec_softc	*sc;
600 
601     /* Disable the GPE so we don't get EC events during shutdown. */
602     sc = device_get_softc(dev);
603     AcpiDisableGpe(sc->ec_gpehandle, sc->ec_gpebit);
604     return (0);
605 }
606 
607 /* Methods to allow other devices (e.g., smbat) to read/write EC space. */
608 static int
609 acpi_ec_read_method(device_t dev, u_int addr, UINT64 *val, int width)
610 {
611     struct acpi_ec_softc *sc;
612     ACPI_STATUS status;
613 
614     sc = device_get_softc(dev);
615     status = EcSpaceHandler(ACPI_READ, addr, width * 8, val, sc, NULL);
616     if (ACPI_FAILURE(status))
617 	return (ENXIO);
618     return (0);
619 }
620 
621 static int
622 acpi_ec_write_method(device_t dev, u_int addr, UINT64 val, int width)
623 {
624     struct acpi_ec_softc *sc;
625     ACPI_STATUS status;
626 
627     sc = device_get_softc(dev);
628     status = EcSpaceHandler(ACPI_WRITE, addr, width * 8, &val, sc, NULL);
629     if (ACPI_FAILURE(status))
630 	return (ENXIO);
631     return (0);
632 }
633 
634 static ACPI_STATUS
635 EcCheckStatus(struct acpi_ec_softc *sc, const char *msg, EC_EVENT event)
636 {
637     ACPI_STATUS status;
638     EC_STATUS ec_status;
639 
640     status = AE_NO_HARDWARE_RESPONSE;
641     ec_status = EC_GET_CSR(sc);
642     if (sc->ec_burstactive && !(ec_status & EC_FLAG_BURST_MODE)) {
643 	KTR_LOG(acpi_ec_burstdis, msg);
644 	sc->ec_burstactive = FALSE;
645     }
646     if (EVENT_READY(event, ec_status)) {
647 	KTR_LOG(acpi_ec_waitrdy, msg, ec_status);
648 	status = AE_OK;
649     }
650     return (status);
651 }
652 
653 static void
654 EcGpeQueryHandler(void *Context)
655 {
656     struct acpi_ec_softc	*sc = (struct acpi_ec_softc *)Context;
657     UINT8			Data;
658     ACPI_STATUS			Status;
659     int				retry, sci_enqueued;
660     char			qxx[5];
661 
662     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
663     KASSERT(Context != NULL, ("EcGpeQueryHandler called with NULL"));
664 
665     /* Serialize user access with EcSpaceHandler(). */
666     Status = EcLock(sc);
667     if (ACPI_FAILURE(Status)) {
668 	device_printf(sc->ec_dev, "GpeQuery lock error: %s\n",
669 	    AcpiFormatException(Status));
670 	return;
671     }
672 
673     /*
674      * Send a query command to the EC to find out which _Qxx call it
675      * wants to make.  This command clears the SCI bit and also the
676      * interrupt source since we are edge-triggered.  To prevent the GPE
677      * that may arise from running the query from causing another query
678      * to be queued, we clear the pending flag only after running it.
679      */
680     sci_enqueued = sc->ec_sci_pend;
681     for (retry = 0; retry < 2; retry++) {
682 	Status = EcCommand(sc, EC_COMMAND_QUERY);
683 	if (ACPI_SUCCESS(Status))
684 	    break;
685 	if (ACPI_SUCCESS(EcCheckStatus(sc, "retr_check",
686 	    EC_EVENT_INPUT_BUFFER_EMPTY)))
687 	    continue;
688 	else
689 	    break;
690     }
691     sc->ec_sci_pend = FALSE;
692     if (ACPI_FAILURE(Status)) {
693 	EcUnlock(sc);
694 	device_printf(sc->ec_dev, "GPE query failed: %s\n",
695 	    AcpiFormatException(Status));
696 	return;
697     }
698     Data = EC_GET_DATA(sc);
699 
700     /*
701      * We have to unlock before running the _Qxx method below since that
702      * method may attempt to read/write from EC address space, causing
703      * recursive acquisition of the lock.
704      */
705     EcUnlock(sc);
706 
707     /* Ignore the value for "no outstanding event". (13.3.5) */
708     if (Data == 0) {
709 	KTR_LOG(acpi_ec_qryoknotrun, Data);
710 	return;
711     } else {
712 	KTR_LOG(acpi_ec_qryokrun, Data);
713     }
714 
715     /* Evaluate _Qxx to respond to the controller. */
716     ksnprintf(qxx, sizeof(qxx), "_Q%02X", Data);
717     AcpiUtStrupr(qxx);
718     Status = AcpiEvaluateObject(sc->ec_handle, qxx, NULL, NULL);
719     if (ACPI_FAILURE(Status) && Status != AE_NOT_FOUND) {
720 	device_printf(sc->ec_dev, "evaluation of query method %s failed: %s\n",
721 	    qxx, AcpiFormatException(Status));
722     }
723 
724     /* Reenable runtime GPE if its execution was deferred. */
725     if (sci_enqueued) {
726 	Status = AcpiFinishGpe(sc->ec_gpehandle, sc->ec_gpebit);
727 	if (ACPI_FAILURE(Status))
728 	    device_printf(sc->ec_dev, "reenabling runtime GPE failed: %s\n",
729 		AcpiFormatException(Status));
730     }
731 }
732 
733 /*
734  * The GPE handler is called when IBE/OBF or SCI events occur.  We are
735  * called from an unknown lock context.
736  */
737 static UINT32
738 EcGpeHandler(ACPI_HANDLE GpeDevice, UINT32 GpeNumber, void *Context)
739 {
740     struct acpi_ec_softc *sc = Context;
741     ACPI_STATUS		       Status;
742     EC_STATUS		       EcStatus;
743 
744     KASSERT(Context != NULL, ("EcGpeHandler called with NULL"));
745     KTR_LOG(acpi_ec_gpehdlstart);
746     /*
747      * Notify EcWaitEvent() that the status register is now fresh.  If we
748      * didn't do this, it wouldn't be possible to distinguish an old IBE
749      * from a new one, for example when doing a write transaction (writing
750      * address and then data values.)
751      */
752     atomic_add_int(&sc->ec_gencount, 1);
753     wakeup(sc);
754 
755     /*
756      * If the EC_SCI bit of the status register is set, queue a query handler.
757      * It will run the query and _Qxx method later, under the lock.
758      */
759     EcStatus = EC_GET_CSR(sc);
760     if ((EcStatus & EC_EVENT_SCI) && !sc->ec_sci_pend) {
761 	KTR_LOG(acpi_ec_gpequeuehdl);
762 	Status = AcpiOsExecute(OSL_GPE_HANDLER, EcGpeQueryHandler, Context);
763 	if (ACPI_SUCCESS(Status)) {
764 	    sc->ec_sci_pend = TRUE;
765 	    return (0);
766 	} else {
767 	    kprintf("EcGpeHandler: queuing GPE query handler failed\n");
768     	}
769     }
770     return (ACPI_REENABLE_GPE);
771 }
772 
773 static ACPI_STATUS
774 EcSpaceSetup(ACPI_HANDLE Region, UINT32 Function, void *Context,
775 	     void **RegionContext)
776 {
777 
778     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
779 
780     /*
781      * If deactivating a region, always set the output to NULL.  Otherwise,
782      * just pass the context through.
783      */
784     if (Function == ACPI_REGION_DEACTIVATE)
785 	*RegionContext = NULL;
786     else
787 	*RegionContext = Context;
788 
789     return_ACPI_STATUS (AE_OK);
790 }
791 
792 static ACPI_STATUS
793 EcSpaceHandler(UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 Width,
794 	       UINT64 *Value, void *Context, void *RegionContext)
795 {
796     struct acpi_ec_softc	*sc = (struct acpi_ec_softc *)Context;
797     ACPI_PHYSICAL_ADDRESS	EcAddr;
798     UINT8			*EcData;
799     ACPI_STATUS			Status;
800 
801     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, (UINT32)Address);
802 
803     if (Function != ACPI_READ && Function != ACPI_WRITE)
804 	return_ACPI_STATUS (AE_BAD_PARAMETER);
805     if (Width % 8 != 0 || Value == NULL || Context == NULL)
806 	return_ACPI_STATUS (AE_BAD_PARAMETER);
807     if (Address + Width / 8 > 256)
808 	return_ACPI_STATUS (AE_BAD_ADDRESS);
809 
810     /*
811      * If booting, check if we need to run the query handler.  If so, we
812      * we call it directly here since our thread taskq is not active yet.
813      */
814     if (cold || rebooting || sc->ec_suspending) {
815 	if ((EC_GET_CSR(sc) & EC_EVENT_SCI)) {
816 	    KTR_LOG(acpi_ec_gperun);
817 	    EcGpeQueryHandler(sc);
818 	}
819     }
820 
821     /* Serialize with EcGpeQueryHandler() at transaction granularity. */
822     Status = EcLock(sc);
823     if (ACPI_FAILURE(Status))
824 	return_ACPI_STATUS (Status);
825 
826     /* If we can't start burst mode, continue anyway. */
827     Status = EcCommand(sc, EC_COMMAND_BURST_ENABLE);
828     if (ACPI_SUCCESS(Status)) {
829 	if (EC_GET_DATA(sc) == EC_BURST_ACK) {
830 	    KTR_LOG(acpi_ec_burstenl);
831 	    sc->ec_burstactive = TRUE;
832 	}
833     }
834 
835     /* Perform the transaction(s), based on Width. */
836     EcAddr = Address;
837     EcData = (UINT8 *)Value;
838     if (Function == ACPI_READ)
839 	*Value = 0;
840     do {
841 	switch (Function) {
842 	case ACPI_READ:
843 	    Status = EcRead(sc, EcAddr, EcData);
844 	    break;
845 	case ACPI_WRITE:
846 	    Status = EcWrite(sc, EcAddr, *EcData);
847 	    break;
848 	}
849 	if (ACPI_FAILURE(Status))
850 	    break;
851 	EcAddr++;
852 	EcData++;
853     } while (EcAddr < Address + Width / 8);
854 
855     if (sc->ec_burstactive) {
856 	sc->ec_burstactive = FALSE;
857 	if (ACPI_SUCCESS(EcCommand(sc, EC_COMMAND_BURST_DISABLE)))
858 	    KTR_LOG(acpi_ec_burstdisok);
859     }
860 
861     EcUnlock(sc);
862     return_ACPI_STATUS (Status);
863 }
864 
865 static ACPI_STATUS
866 EcWaitEvent(struct acpi_ec_softc *sc, EC_EVENT Event, u_int gen_count)
867 {
868     static int	no_intr = 0;
869     ACPI_STATUS	Status;
870     int		count, i, need_poll, slp_ival;
871 
872     ACPI_SERIAL_ASSERT(ec);
873     Status = AE_NO_HARDWARE_RESPONSE;
874     need_poll = cold || rebooting || ec_polled_mode || sc->ec_suspending;
875 
876     /* Wait for event by polling or GPE (interrupt). */
877     if (need_poll) {
878 	count = (ec_timeout * 1000) / EC_POLL_DELAY;
879 	if (count == 0)
880 	    count = 1;
881 	DELAY(10);
882 	for (i = 0; i < count; i++) {
883 	    Status = EcCheckStatus(sc, "poll", Event);
884 	    if (ACPI_SUCCESS(Status))
885 		break;
886 	    DELAY(EC_POLL_DELAY);
887 	}
888     } else {
889 	slp_ival = hz / 1000;
890 	if (slp_ival != 0) {
891 	    count = ec_timeout;
892 	} else {
893 	    /* hz has less than 1 ms resolution so scale timeout. */
894 	    slp_ival = 1;
895 	    count = ec_timeout / (1000 / hz);
896 	}
897 
898 	/*
899 	 * Wait for the GPE to signal the status changed, checking the
900 	 * status register each time we get one.  It's possible to get a
901 	 * GPE for an event we're not interested in here (i.e., SCI for
902 	 * EC query).
903 	 */
904 	for (i = 0; i < count; i++) {
905 	    if (gen_count == sc->ec_gencount)
906 		tsleep(sc, 0, "ecgpe", slp_ival);
907 	    /*
908 	     * Record new generation count.  It's possible the GPE was
909 	     * just to notify us that a query is needed and we need to
910 	     * wait for a second GPE to signal the completion of the
911 	     * event we are actually waiting for.
912 	     */
913 	    Status = EcCheckStatus(sc, "sleep", Event);
914 	    if (ACPI_SUCCESS(Status)) {
915 		if (gen_count == sc->ec_gencount)
916 		    no_intr++;
917 		else
918 		    no_intr = 0;
919 		break;
920 	    }
921 	    gen_count = sc->ec_gencount;
922 	}
923 
924 	/*
925 	 * We finished waiting for the GPE and it never arrived.  Try to
926 	 * read the register once and trust whatever value we got.  This is
927 	 * the best we can do at this point.
928 	 */
929 	if (ACPI_FAILURE(Status))
930 	    Status = EcCheckStatus(sc, "sleep_end", Event);
931     }
932     if (!need_poll && no_intr > 10) {
933 	device_printf(sc->ec_dev,
934 	    "not getting interrupts, switched to polled mode\n");
935 	ec_polled_mode = 1;
936     }
937     if (ACPI_FAILURE(Status))
938 	KTR_LOG(acpi_ec_timeout);
939     return (Status);
940 }
941 
942 static ACPI_STATUS
943 EcCommand(struct acpi_ec_softc *sc, EC_COMMAND cmd)
944 {
945     ACPI_STATUS	status;
946     EC_EVENT	event;
947     EC_STATUS	ec_status;
948     u_int	gen_count;
949 
950     ACPI_SERIAL_ASSERT(ec);
951 
952     /* Don't use burst mode if user disabled it. */
953     if (!ec_burst_mode && cmd == EC_COMMAND_BURST_ENABLE)
954 	return (AE_ERROR);
955 
956     /* Decide what to wait for based on command type. */
957     switch (cmd) {
958     case EC_COMMAND_READ:
959     case EC_COMMAND_WRITE:
960     case EC_COMMAND_BURST_DISABLE:
961 	event = EC_EVENT_INPUT_BUFFER_EMPTY;
962 	break;
963     case EC_COMMAND_QUERY:
964     case EC_COMMAND_BURST_ENABLE:
965 	event = EC_EVENT_OUTPUT_BUFFER_FULL;
966 	break;
967     default:
968 	device_printf(sc->ec_dev, "EcCommand: invalid command %#x\n", cmd);
969 	return (AE_BAD_PARAMETER);
970     }
971 
972     /*
973      * Ensure empty input buffer before issuing command.
974      * Use generation count of zero to force a quick check.
975      */
976     status = EcWaitEvent(sc, EC_EVENT_INPUT_BUFFER_EMPTY, 0);
977     if (ACPI_FAILURE(status))
978 	return (status);
979 
980     /* Run the command and wait for the chosen event. */
981     KTR_LOG(acpi_ec_cmdrun, cmd);
982     gen_count = sc->ec_gencount;
983     EC_SET_CSR(sc, cmd);
984     status = EcWaitEvent(sc, event, gen_count);
985     if (ACPI_SUCCESS(status)) {
986 	/* If we succeeded, burst flag should now be present. */
987 	if (cmd == EC_COMMAND_BURST_ENABLE) {
988 	    ec_status = EC_GET_CSR(sc);
989 	    if ((ec_status & EC_FLAG_BURST_MODE) == 0)
990 		status = AE_ERROR;
991 	}
992     } else
993 	device_printf(sc->ec_dev, "EcCommand: no response to %#x\n", cmd);
994     return (status);
995 }
996 
997 static ACPI_STATUS
998 EcRead(struct acpi_ec_softc *sc, UINT8 Address, UINT8 *Data)
999 {
1000     ACPI_STATUS	status;
1001     u_int gen_count;
1002     int retry;
1003 
1004     ACPI_SERIAL_ASSERT(ec);
1005     KTR_LOG(acpi_ec_readaddr, Address);
1006 
1007     for (retry = 0; retry < 2; retry++) {
1008 	status = EcCommand(sc, EC_COMMAND_READ);
1009 	if (ACPI_FAILURE(status))
1010 	    return (status);
1011 
1012 	gen_count = sc->ec_gencount;
1013 	EC_SET_DATA(sc, Address);
1014 	status = EcWaitEvent(sc, EC_EVENT_OUTPUT_BUFFER_FULL, gen_count);
1015 	if (ACPI_FAILURE(status)) {
1016 	    if (ACPI_SUCCESS(EcCheckStatus(sc, "retr_check",
1017 		EC_EVENT_INPUT_BUFFER_EMPTY)))
1018 		continue;
1019 	    else
1020 		break;
1021 	}
1022 	*Data = EC_GET_DATA(sc);
1023 	return (AE_OK);
1024     }
1025     device_printf(sc->ec_dev, "EcRead: failed waiting to get data\n");
1026     return (status);
1027 }
1028 
1029 static ACPI_STATUS
1030 EcWrite(struct acpi_ec_softc *sc, UINT8 Address, UINT8 Data)
1031 {
1032     ACPI_STATUS	status;
1033     u_int gen_count;
1034 
1035     ACPI_SERIAL_ASSERT(ec);
1036     KTR_LOG(acpi_ec_writeaddr, Address, Data);
1037 
1038     status = EcCommand(sc, EC_COMMAND_WRITE);
1039     if (ACPI_FAILURE(status))
1040 	return (status);
1041 
1042     gen_count = sc->ec_gencount;
1043     EC_SET_DATA(sc, Address);
1044     status = EcWaitEvent(sc, EC_EVENT_INPUT_BUFFER_EMPTY, gen_count);
1045     if (ACPI_FAILURE(status)) {
1046 	device_printf(sc->ec_dev, "EcWrite: failed waiting for sent address\n");
1047 	return (status);
1048     }
1049 
1050     gen_count = sc->ec_gencount;
1051     EC_SET_DATA(sc, Data);
1052     status = EcWaitEvent(sc, EC_EVENT_INPUT_BUFFER_EMPTY, gen_count);
1053     if (ACPI_FAILURE(status)) {
1054 	device_printf(sc->ec_dev, "EcWrite: failed waiting for sent data\n");
1055 	return (status);
1056     }
1057 
1058     return (AE_OK);
1059 }
1060