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