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