]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/atkbdc/atkbdc.c
allwinner: Add a new clock aw_clk_m
[FreeBSD/FreeBSD.git] / sys / dev / atkbdc / atkbdc.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1996-1999
5  * Kazutaka YOKOTA (yokota@zodiac.mech.utsunomiya-u.ac.jp)
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote 
17  *    products derived from this software without specific prior written 
18  *    permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * from kbdio.c,v 1.13 1998/09/25 11:55:46 yokota Exp
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include "opt_kbd.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/bus.h>
43 #include <sys/malloc.h>
44 #include <sys/syslog.h>
45 #include <machine/bus.h>
46 #include <machine/resource.h>
47 #include <sys/rman.h>
48
49 #if defined(__amd64__)
50 #include <machine/clock.h>
51 #endif
52
53 #include <dev/atkbdc/atkbdcreg.h>
54
55 #ifdef __sparc64__
56 #include <dev/ofw/openfirm.h>
57 #include <machine/bus_private.h>
58 #include <machine/ofw_machdep.h>
59 #else
60 #include <isa/isareg.h>
61 #endif
62
63 /* constants */
64
65 #define MAXKBDC         1               /* XXX */
66
67 /* macros */
68
69 #ifndef MAX
70 #define MAX(x, y)       ((x) > (y) ? (x) : (y))
71 #endif
72
73 #define kbdcp(p)        ((atkbdc_softc_t *)(p))
74 #define nextq(i)        (((i) + 1) % KBDQ_BUFSIZE)
75 #define availq(q)       ((q)->head != (q)->tail)
76 #if KBDIO_DEBUG >= 2
77 #define emptyq(q)       ((q)->tail = (q)->head = (q)->qcount = 0)
78 #else
79 #define emptyq(q)       ((q)->tail = (q)->head = 0)
80 #endif
81
82 #define read_data(k)    (bus_space_read_1((k)->iot, (k)->ioh0, 0))
83 #define read_status(k)  (bus_space_read_1((k)->iot, (k)->ioh1, 0))
84 #define write_data(k, d)        \
85                         (bus_space_write_1((k)->iot, (k)->ioh0, 0, (d)))
86 #define write_command(k, d)     \
87                         (bus_space_write_1((k)->iot, (k)->ioh1, 0, (d)))
88
89 /* local variables */
90
91 /*
92  * We always need at least one copy of the kbdc_softc struct for the
93  * low-level console.  As the low-level console accesses the keyboard
94  * controller before kbdc, and all other devices, is probed, we
95  * statically allocate one entry. XXX
96  */
97 static atkbdc_softc_t default_kbdc;
98 static atkbdc_softc_t *atkbdc_softc[MAXKBDC] = { &default_kbdc };
99
100 static int verbose = KBDIO_DEBUG;
101
102 #ifdef __sparc64__
103 static struct bus_space_tag atkbdc_bst_store[MAXKBDC];
104 #endif
105
106 /* function prototypes */
107
108 static int atkbdc_setup(atkbdc_softc_t *sc, bus_space_tag_t tag,
109                         bus_space_handle_t h0, bus_space_handle_t h1);
110 static int addq(kqueue *q, int c);
111 static int removeq(kqueue *q);
112 static int wait_while_controller_busy(atkbdc_softc_t *kbdc);
113 static int wait_for_data(atkbdc_softc_t *kbdc);
114 static int wait_for_kbd_data(atkbdc_softc_t *kbdc);
115 static int wait_for_kbd_ack(atkbdc_softc_t *kbdc);
116 static int wait_for_aux_data(atkbdc_softc_t *kbdc);
117 static int wait_for_aux_ack(atkbdc_softc_t *kbdc);
118
119 struct atkbdc_quirks {
120     const char* bios_vendor;
121     const char* maker;
122     const char* product;
123     int         quirk;
124 };
125
126 static struct atkbdc_quirks quirks[] = {
127     {"coreboot", NULL, NULL,
128         KBDC_QUIRK_KEEP_ACTIVATED | KBDC_QUIRK_IGNORE_PROBE_RESULT |
129         KBDC_QUIRK_RESET_AFTER_PROBE | KBDC_QUIRK_SETLEDS_ON_INIT},
130
131     {NULL, NULL, NULL, 0}
132 };
133
134 #define QUIRK_STR_MATCH(s1, s2) (s1 == NULL || \
135     (s2 != NULL && !strcmp(s1, s2)))
136
137 static int
138 atkbdc_getquirks(void)
139 {
140     int i;
141     char* bios_vendor = kern_getenv("smbios.bios.vendor");
142     char* maker = kern_getenv("smbios.system.maker");
143     char* product = kern_getenv("smbios.system.product");
144
145     for (i=0; quirks[i].quirk != 0; ++i)
146         if (QUIRK_STR_MATCH(quirks[i].bios_vendor, bios_vendor) &&
147             QUIRK_STR_MATCH(quirks[i].maker, maker) &&
148             QUIRK_STR_MATCH(quirks[i].product, product))
149                 return (quirks[i].quirk);
150
151     return (0);
152 }
153
154 atkbdc_softc_t
155 *atkbdc_get_softc(int unit)
156 {
157         atkbdc_softc_t *sc;
158
159         if (unit >= nitems(atkbdc_softc))
160                 return NULL;
161         sc = atkbdc_softc[unit];
162         if (sc == NULL) {
163                 sc = atkbdc_softc[unit]
164                    = malloc(sizeof(*sc), M_DEVBUF, M_NOWAIT | M_ZERO);
165                 if (sc == NULL)
166                         return NULL;
167         }
168         return sc;
169 }
170
171 int
172 atkbdc_probe_unit(int unit, struct resource *port0, struct resource *port1)
173 {
174         if (rman_get_start(port0) <= 0)
175                 return ENXIO;
176         if (rman_get_start(port1) <= 0)
177                 return ENXIO;
178         return 0;
179 }
180
181 int
182 atkbdc_attach_unit(int unit, atkbdc_softc_t *sc, struct resource *port0,
183                    struct resource *port1)
184 {
185         return atkbdc_setup(sc, rman_get_bustag(port0),
186                             rman_get_bushandle(port0),
187                             rman_get_bushandle(port1));
188 }
189
190 /* the backdoor to the keyboard controller! XXX */
191 int
192 atkbdc_configure(void)
193 {
194         bus_space_tag_t tag;
195         bus_space_handle_t h0;
196         bus_space_handle_t h1;
197 #if defined(__i386__) || defined(__amd64__)
198         volatile int i;
199         register_t flags;
200 #endif
201 #ifdef __sparc64__
202         char name[32];
203         phandle_t chosen, node;
204         ihandle_t stdin;
205         bus_addr_t port0;
206         bus_addr_t port1;
207         int space;
208 #else
209         int port0;
210         int port1;
211 #endif
212
213         /* XXX: tag should be passed from the caller */
214 #if defined(__amd64__) || defined(__i386__)
215         tag = X86_BUS_SPACE_IO;
216 #elif defined(__sparc64__)
217         tag = &atkbdc_bst_store[0];
218 #else
219 #error "define tag!"
220 #endif
221
222 #ifdef __sparc64__
223         if ((chosen = OF_finddevice("/chosen")) == -1)
224                 return 0;
225         if (OF_getprop(chosen, "stdin", &stdin, sizeof(stdin)) == -1)
226                 return 0;
227         if ((node = OF_instance_to_package(stdin)) == -1)
228                 return 0;
229         if (OF_getprop(node, "name", name, sizeof(name)) == -1)
230                 return 0;
231         name[sizeof(name) - 1] = '\0';
232         if (strcmp(name, "kb_ps2") != 0)
233                 return 0;
234         /*
235          * The stdin handle points to an instance of a PS/2 keyboard
236          * package but we want the 8042 controller, which is the parent
237          * of that keyboard node.
238          */
239         if ((node = OF_parent(node)) == 0)
240                 return 0;
241         if (OF_decode_addr(node, 0, &space, &port0) != 0)
242                 return 0;
243         h0 = sparc64_fake_bustag(space, port0, tag);
244         bus_space_subregion(tag, h0, KBD_DATA_PORT, 1, &h0);
245         if (OF_decode_addr(node, 1, &space, &port1) != 0)
246                 return 0;
247         h1 = sparc64_fake_bustag(space, port1, tag);
248         bus_space_subregion(tag, h1, KBD_STATUS_PORT, 1, &h1);
249 #else
250         port0 = IO_KBD;
251         resource_int_value("atkbdc", 0, "port", &port0);
252         port1 = IO_KBD + KBD_STATUS_PORT;
253 #ifdef notyet
254         bus_space_map(tag, port0, IO_KBDSIZE, 0, &h0);
255         bus_space_map(tag, port1, IO_KBDSIZE, 0, &h1);
256 #else
257         h0 = (bus_space_handle_t)port0;
258         h1 = (bus_space_handle_t)port1;
259 #endif
260 #endif
261
262 #if defined(__i386__) || defined(__amd64__)
263         /*
264          * Check if we really have AT keyboard controller. Poll status
265          * register until we get "all clear" indication. If no such
266          * indication comes, it probably means that there is no AT
267          * keyboard controller present. Give up in such case. Check relies
268          * on the fact that reading from non-existing in/out port returns
269          * 0xff on i386. May or may not be true on other platforms.
270          */
271         flags = intr_disable();
272         for (i = 0; i != 65535; i++) {
273                 if ((bus_space_read_1(tag, h1, 0) & 0x2) == 0)
274                         break;
275         }
276         intr_restore(flags);
277         if (i == 65535)
278                 return ENXIO;
279 #endif
280
281         return atkbdc_setup(atkbdc_softc[0], tag, h0, h1);
282 }
283
284 static int
285 atkbdc_setup(atkbdc_softc_t *sc, bus_space_tag_t tag, bus_space_handle_t h0,
286              bus_space_handle_t h1)
287 {
288 #if defined(__amd64__)
289         u_int64_t tscval[3], read_delay;
290         register_t flags;
291 #endif
292
293         if (sc->ioh0 == 0) {    /* XXX */
294             sc->command_byte = -1;
295             sc->command_mask = 0;
296             sc->lock = FALSE;
297             sc->kbd.head = sc->kbd.tail = 0;
298             sc->aux.head = sc->aux.tail = 0;
299             sc->aux_mux_enabled = FALSE;
300 #if KBDIO_DEBUG >= 2
301             sc->kbd.call_count = 0;
302             sc->kbd.qcount = sc->kbd.max_qcount = 0;
303             sc->aux.call_count = 0;
304             sc->aux.qcount = sc->aux.max_qcount = 0;
305 #endif
306         }
307         sc->iot = tag;
308         sc->ioh0 = h0;
309         sc->ioh1 = h1;
310
311 #if defined(__amd64__)
312         /*
313          * On certain chipsets AT keyboard controller isn't present and is
314          * emulated by BIOS using SMI interrupt. On those chipsets reading
315          * from the status port may be thousand times slower than usually.
316          * Sometimes this emilation is not working properly resulting in
317          * commands timing our and since we assume that inb() operation 
318          * takes very little time to complete we need to adjust number of
319          * retries to keep waiting time within a designed limits (100ms).
320          * Measure time it takes to make read_status() call and adjust
321          * number of retries accordingly.
322          */
323         flags = intr_disable();
324         tscval[0] = rdtsc();
325         read_status(sc);
326         tscval[1] = rdtsc();
327         DELAY(1000);
328         tscval[2] = rdtsc();
329         intr_restore(flags);
330         read_delay = tscval[1] - tscval[0];
331         read_delay /= (tscval[2] - tscval[1]) / 1000;
332         sc->retry = 100000 / ((KBDD_DELAYTIME * 2) + read_delay);
333 #else
334         sc->retry = 5000;
335 #endif
336         sc->quirks = atkbdc_getquirks();
337
338         return 0;
339 }
340
341 /* open a keyboard controller */
342 KBDC 
343 atkbdc_open(int unit)
344 {
345     if (unit <= 0)
346         unit = 0;
347     if (unit >= MAXKBDC)
348         return NULL;
349     if ((atkbdc_softc[unit]->port0 != NULL)
350         || (atkbdc_softc[unit]->ioh0 != 0))             /* XXX */
351         return (KBDC)atkbdc_softc[unit];
352     return NULL;
353 }
354
355 /*
356  * I/O access arbitration in `kbdio'
357  *
358  * The `kbdio' module uses a simplistic convention to arbitrate
359  * I/O access to the controller/keyboard/mouse. The convention requires
360  * close cooperation of the calling device driver.
361  *
362  * The device drivers which utilize the `kbdio' module are assumed to
363  * have the following set of routines.
364  *    a. An interrupt handler (the bottom half of the driver).
365  *    b. Timeout routines which may briefly poll the keyboard controller.
366  *    c. Routines outside interrupt context (the top half of the driver).
367  * They should follow the rules below:
368  *    1. The interrupt handler may assume that it always has full access 
369  *       to the controller/keyboard/mouse.
370  *    2. The other routines must issue `spltty()' if they wish to 
371  *       prevent the interrupt handler from accessing 
372  *       the controller/keyboard/mouse.
373  *    3. The timeout routines and the top half routines of the device driver
374  *       arbitrate I/O access by observing the lock flag in `kbdio'.
375  *       The flag is manipulated via `kbdc_lock()'; when one wants to
376  *       perform I/O, call `kbdc_lock(kbdc, TRUE)' and proceed only if
377  *       the call returns with TRUE. Otherwise the caller must back off.
378  *       Call `kbdc_lock(kbdc, FALSE)' when necessary I/O operaion
379  *       is finished. This mechanism does not prevent the interrupt 
380  *       handler from being invoked at any time and carrying out I/O.
381  *       Therefore, `spltty()' must be strategically placed in the device
382  *       driver code. Also note that the timeout routine may interrupt
383  *       `kbdc_lock()' called by the top half of the driver, but this
384  *       interruption is OK so long as the timeout routine observes
385  *       rule 4 below.
386  *    4. The interrupt and timeout routines should not extend I/O operation
387  *       across more than one interrupt or timeout; they must complete any
388  *       necessary I/O operation within one invocation of the routine.
389  *       This means that if the timeout routine acquires the lock flag,
390  *       it must reset the flag to FALSE before it returns.
391  */
392
393 /* set/reset polling lock */
394 int 
395 kbdc_lock(KBDC p, int lock)
396 {
397     int prevlock;
398
399     prevlock = kbdcp(p)->lock;
400     kbdcp(p)->lock = lock;
401
402     return (prevlock != lock);
403 }
404
405 /* check if any data is waiting to be processed */
406 int
407 kbdc_data_ready(KBDC p)
408 {
409     return (availq(&kbdcp(p)->kbd) || availq(&kbdcp(p)->aux) 
410         || (read_status(kbdcp(p)) & KBDS_ANY_BUFFER_FULL));
411 }
412
413 /* queuing functions */
414
415 static int
416 addq(kqueue *q, int c)
417 {
418     if (nextq(q->tail) != q->head) {
419         q->q[q->tail] = c;
420         q->tail = nextq(q->tail);
421 #if KBDIO_DEBUG >= 2
422         ++q->call_count;
423         ++q->qcount;
424         if (q->qcount > q->max_qcount)
425             q->max_qcount = q->qcount;
426 #endif
427         return TRUE;
428     }
429     return FALSE;
430 }
431
432 static int
433 removeq(kqueue *q)
434 {
435     int c;
436
437     if (q->tail != q->head) {
438         c = q->q[q->head];
439         q->head = nextq(q->head);
440 #if KBDIO_DEBUG >= 2
441         --q->qcount;
442 #endif
443         return c;
444     }
445     return -1;
446 }
447
448 /* 
449  * device I/O routines
450  */
451 static int
452 wait_while_controller_busy(struct atkbdc_softc *kbdc)
453 {
454     int retry;
455     int f;
456
457     /* CPU will stay inside the loop for 100msec at most */
458     retry = kbdc->retry;
459
460     while ((f = read_status(kbdc)) & KBDS_INPUT_BUFFER_FULL) {
461         if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) {
462             DELAY(KBDD_DELAYTIME);
463             addq(&kbdc->kbd, read_data(kbdc));
464         } else if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) {
465             DELAY(KBDD_DELAYTIME);
466             addq(&kbdc->aux, read_data(kbdc));
467         }
468         DELAY(KBDC_DELAYTIME);
469         if (--retry < 0)
470             return FALSE;
471     }
472     return TRUE;
473 }
474
475 /*
476  * wait for any data; whether it's from the controller, 
477  * the keyboard, or the aux device.
478  */
479 static int
480 wait_for_data(struct atkbdc_softc *kbdc)
481 {
482     int retry;
483     int f;
484
485     /* CPU will stay inside the loop for 200msec at most */
486     retry = kbdc->retry * 2;
487
488     while ((f = read_status(kbdc) & KBDS_ANY_BUFFER_FULL) == 0) {
489         DELAY(KBDC_DELAYTIME);
490         if (--retry < 0)
491             return 0;
492     }
493     DELAY(KBDD_DELAYTIME);
494     return f;
495 }
496
497 /* wait for data from the keyboard */
498 static int
499 wait_for_kbd_data(struct atkbdc_softc *kbdc)
500 {
501     int retry;
502     int f;
503
504     /* CPU will stay inside the loop for 200msec at most */
505     retry = kbdc->retry * 2;
506
507     while ((f = read_status(kbdc) & KBDS_BUFFER_FULL)
508             != KBDS_KBD_BUFFER_FULL) {
509         if (f == KBDS_AUX_BUFFER_FULL) {
510             DELAY(KBDD_DELAYTIME);
511             addq(&kbdc->aux, read_data(kbdc));
512         }
513         DELAY(KBDC_DELAYTIME);
514         if (--retry < 0)
515             return 0;
516     }
517     DELAY(KBDD_DELAYTIME);
518     return f;
519 }
520
521 /* 
522  * wait for an ACK(FAh), RESEND(FEh), or RESET_FAIL(FCh) from the keyboard.
523  * queue anything else.
524  */
525 static int
526 wait_for_kbd_ack(struct atkbdc_softc *kbdc)
527 {
528     int retry;
529     int f;
530     int b;
531
532     /* CPU will stay inside the loop for 200msec at most */
533     retry = kbdc->retry * 2;
534
535     while (retry-- > 0) {
536         if ((f = read_status(kbdc)) & KBDS_ANY_BUFFER_FULL) {
537             DELAY(KBDD_DELAYTIME);
538             b = read_data(kbdc);
539             if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) {
540                 if ((b == KBD_ACK) || (b == KBD_RESEND) 
541                     || (b == KBD_RESET_FAIL))
542                     return b;
543                 addq(&kbdc->kbd, b);
544             } else if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) {
545                 addq(&kbdc->aux, b);
546             }
547         }
548         DELAY(KBDC_DELAYTIME);
549     }
550     return -1;
551 }
552
553 /* wait for data from the aux device */
554 static int
555 wait_for_aux_data(struct atkbdc_softc *kbdc)
556 {
557     int retry;
558     int f;
559
560     /* CPU will stay inside the loop for 200msec at most */
561     retry = kbdc->retry * 2;
562
563     while ((f = read_status(kbdc) & KBDS_BUFFER_FULL)
564             != KBDS_AUX_BUFFER_FULL) {
565         if (f == KBDS_KBD_BUFFER_FULL) {
566             DELAY(KBDD_DELAYTIME);
567             addq(&kbdc->kbd, read_data(kbdc));
568         }
569         DELAY(KBDC_DELAYTIME);
570         if (--retry < 0)
571             return 0;
572     }
573     DELAY(KBDD_DELAYTIME);
574     return f;
575 }
576
577 /* 
578  * wait for an ACK(FAh), RESEND(FEh), or RESET_FAIL(FCh) from the aux device.
579  * queue anything else.
580  */
581 static int
582 wait_for_aux_ack(struct atkbdc_softc *kbdc)
583 {
584     int retry;
585     int f;
586     int b;
587
588     /* CPU will stay inside the loop for 200msec at most */
589     retry = kbdc->retry * 2;
590
591     while (retry-- > 0) {
592         if ((f = read_status(kbdc)) & KBDS_ANY_BUFFER_FULL) {
593             DELAY(KBDD_DELAYTIME);
594             b = read_data(kbdc);
595             if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) {
596                 if ((b == PSM_ACK) || (b == PSM_RESEND) 
597                     || (b == PSM_RESET_FAIL))
598                     return b;
599                 addq(&kbdc->aux, b);
600             } else if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) {
601                 addq(&kbdc->kbd, b);
602             }
603         }
604         DELAY(KBDC_DELAYTIME);
605     }
606     return -1;
607 }
608
609 /* write a one byte command to the controller */
610 int
611 write_controller_command(KBDC p, int c)
612 {
613     if (!wait_while_controller_busy(kbdcp(p)))
614         return FALSE;
615     write_command(kbdcp(p), c);
616     return TRUE;
617 }
618
619 /* write a one byte data to the controller */
620 int
621 write_controller_data(KBDC p, int c)
622 {
623     if (!wait_while_controller_busy(kbdcp(p)))
624         return FALSE;
625     write_data(kbdcp(p), c);
626     return TRUE;
627 }
628
629 /* write a one byte keyboard command */
630 int
631 write_kbd_command(KBDC p, int c)
632 {
633     if (!wait_while_controller_busy(kbdcp(p)))
634         return FALSE;
635     write_data(kbdcp(p), c);
636     return TRUE;
637 }
638
639 /* write a one byte auxiliary device command */
640 int
641 write_aux_command(KBDC p, int c)
642 {
643     int f;
644
645     f = aux_mux_is_enabled(p) ?
646         KBDC_WRITE_TO_AUX_MUX + kbdcp(p)->aux_mux_port : KBDC_WRITE_TO_AUX;
647
648     if (!write_controller_command(p, f))
649         return FALSE;
650     return write_controller_data(p, c);
651 }
652
653 /* send a command to the keyboard and wait for ACK */
654 int
655 send_kbd_command(KBDC p, int c)
656 {
657     int retry = KBD_MAXRETRY;
658     int res = -1;
659
660     while (retry-- > 0) {
661         if (!write_kbd_command(p, c))
662             continue;
663         res = wait_for_kbd_ack(kbdcp(p));
664         if (res == KBD_ACK)
665             break;
666     }
667     return res;
668 }
669
670 /* send a command to the auxiliary device and wait for ACK */
671 int
672 send_aux_command(KBDC p, int c)
673 {
674     int retry = KBD_MAXRETRY;
675     int res = -1;
676
677     while (retry-- > 0) {
678         if (!write_aux_command(p, c))
679             continue;
680         /*
681          * FIXME: XXX
682          * The aux device may have already sent one or two bytes of 
683          * status data, when a command is received. It will immediately 
684          * stop data transmission, thus, leaving an incomplete data 
685          * packet in our buffer. We have to discard any unprocessed
686          * data in order to remove such packets. Well, we may remove 
687          * unprocessed, but necessary data byte as well... 
688          */
689         emptyq(&kbdcp(p)->aux);
690         res = wait_for_aux_ack(kbdcp(p));
691         if (res == PSM_ACK)
692             break;
693     }
694     return res;
695 }
696
697 /* send a command and a data to the keyboard, wait for ACKs */
698 int
699 send_kbd_command_and_data(KBDC p, int c, int d)
700 {
701     int retry;
702     int res = -1;
703
704     for (retry = KBD_MAXRETRY; retry > 0; --retry) {
705         if (!write_kbd_command(p, c))
706             continue;
707         res = wait_for_kbd_ack(kbdcp(p));
708         if (res == KBD_ACK)
709             break;
710         else if (res != KBD_RESEND)
711             return res;
712     }
713     if (retry <= 0)
714         return res;
715
716     for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) {
717         if (!write_kbd_command(p, d))
718             continue;
719         res = wait_for_kbd_ack(kbdcp(p));
720         if (res != KBD_RESEND)
721             break;
722     }
723     return res;
724 }
725
726 /* send a command and a data to the auxiliary device, wait for ACKs */
727 int
728 send_aux_command_and_data(KBDC p, int c, int d)
729 {
730     int retry;
731     int res = -1;
732
733     for (retry = KBD_MAXRETRY; retry > 0; --retry) {
734         if (!write_aux_command(p, c))
735             continue;
736         emptyq(&kbdcp(p)->aux);
737         res = wait_for_aux_ack(kbdcp(p));
738         if (res == PSM_ACK)
739             break;
740         else if (res != PSM_RESEND)
741             return res;
742     }
743     if (retry <= 0)
744         return res;
745
746     for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) {
747         if (!write_aux_command(p, d))
748             continue;
749         res = wait_for_aux_ack(kbdcp(p));
750         if (res != PSM_RESEND)
751             break;
752     }
753     return res;
754 }
755
756 /* 
757  * read one byte from any source; whether from the controller,
758  * the keyboard, or the aux device
759  */
760 int
761 read_controller_data(KBDC p)
762 {
763     if (availq(&kbdcp(p)->kbd)) 
764         return removeq(&kbdcp(p)->kbd);
765     if (availq(&kbdcp(p)->aux)) 
766         return removeq(&kbdcp(p)->aux);
767     if (!wait_for_data(kbdcp(p)))
768         return -1;              /* timeout */
769     return read_data(kbdcp(p));
770 }
771
772 #if KBDIO_DEBUG >= 2
773 static int call = 0;
774 #endif
775
776 /* read one byte from the keyboard */
777 int
778 read_kbd_data(KBDC p)
779 {
780 #if KBDIO_DEBUG >= 2
781     if (++call > 2000) {
782         call = 0;
783         log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, "
784                              "aux q: %d calls, max %d chars\n",
785                        kbdcp(p)->kbd.call_count, kbdcp(p)->kbd.max_qcount,
786                        kbdcp(p)->aux.call_count, kbdcp(p)->aux.max_qcount);
787     }
788 #endif
789
790     if (availq(&kbdcp(p)->kbd)) 
791         return removeq(&kbdcp(p)->kbd);
792     if (!wait_for_kbd_data(kbdcp(p)))
793         return -1;              /* timeout */
794     return read_data(kbdcp(p));
795 }
796
797 /* read one byte from the keyboard, but return immediately if 
798  * no data is waiting
799  */
800 int
801 read_kbd_data_no_wait(KBDC p)
802 {
803     int f;
804
805 #if KBDIO_DEBUG >= 2
806     if (++call > 2000) {
807         call = 0;
808         log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, "
809                              "aux q: %d calls, max %d chars\n",
810                        kbdcp(p)->kbd.call_count, kbdcp(p)->kbd.max_qcount,
811                        kbdcp(p)->aux.call_count, kbdcp(p)->aux.max_qcount);
812     }
813 #endif
814
815     if (availq(&kbdcp(p)->kbd)) 
816         return removeq(&kbdcp(p)->kbd);
817     f = read_status(kbdcp(p)) & KBDS_BUFFER_FULL;
818     if (f == KBDS_AUX_BUFFER_FULL) {
819         DELAY(KBDD_DELAYTIME);
820         addq(&kbdcp(p)->aux, read_data(kbdcp(p)));
821         f = read_status(kbdcp(p)) & KBDS_BUFFER_FULL;
822     }
823     if (f == KBDS_KBD_BUFFER_FULL) {
824         DELAY(KBDD_DELAYTIME);
825         return read_data(kbdcp(p));
826     }
827     return -1;          /* no data */
828 }
829
830 /* read one byte from the aux device */
831 int
832 read_aux_data(KBDC p)
833 {
834     if (availq(&kbdcp(p)->aux)) 
835         return removeq(&kbdcp(p)->aux);
836     if (!wait_for_aux_data(kbdcp(p)))
837         return -1;              /* timeout */
838     return read_data(kbdcp(p));
839 }
840
841 /* read one byte from the aux device, but return immediately if 
842  * no data is waiting
843  */
844 int
845 read_aux_data_no_wait(KBDC p)
846 {
847     int f;
848
849     if (availq(&kbdcp(p)->aux)) 
850         return removeq(&kbdcp(p)->aux);
851     f = read_status(kbdcp(p)) & KBDS_BUFFER_FULL;
852     if (f == KBDS_KBD_BUFFER_FULL) {
853         DELAY(KBDD_DELAYTIME);
854         addq(&kbdcp(p)->kbd, read_data(kbdcp(p)));
855         f = read_status(kbdcp(p)) & KBDS_BUFFER_FULL;
856     }
857     if (f == KBDS_AUX_BUFFER_FULL) {
858         DELAY(KBDD_DELAYTIME);
859         return read_data(kbdcp(p));
860     }
861     return -1;          /* no data */
862 }
863
864 /* discard data from the keyboard */
865 void
866 empty_kbd_buffer(KBDC p, int wait)
867 {
868     int t;
869     int b;
870     int f;
871 #if KBDIO_DEBUG >= 2
872     int c1 = 0;
873     int c2 = 0;
874 #endif
875     int delta = 2;
876
877     for (t = wait; t > 0; ) { 
878         if ((f = read_status(kbdcp(p))) & KBDS_ANY_BUFFER_FULL) {
879             DELAY(KBDD_DELAYTIME);
880             b = read_data(kbdcp(p));
881             if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) {
882                 addq(&kbdcp(p)->aux, b);
883 #if KBDIO_DEBUG >= 2
884                 ++c2;
885             } else {
886                 ++c1;
887 #endif
888             }
889             t = wait;
890         } else {
891             t -= delta;
892         }
893         DELAY(delta*1000);
894     }
895 #if KBDIO_DEBUG >= 2
896     if ((c1 > 0) || (c2 > 0))
897         log(LOG_DEBUG, "kbdc: %d:%d char read (empty_kbd_buffer)\n", c1, c2);
898 #endif
899
900     emptyq(&kbdcp(p)->kbd);
901 }
902
903 /* discard data from the aux device */
904 void
905 empty_aux_buffer(KBDC p, int wait)
906 {
907     int t;
908     int b;
909     int f;
910 #if KBDIO_DEBUG >= 2
911     int c1 = 0;
912     int c2 = 0;
913 #endif
914     int delta = 2;
915
916     for (t = wait; t > 0; ) { 
917         if ((f = read_status(kbdcp(p))) & KBDS_ANY_BUFFER_FULL) {
918             DELAY(KBDD_DELAYTIME);
919             b = read_data(kbdcp(p));
920             if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) {
921                 addq(&kbdcp(p)->kbd, b);
922 #if KBDIO_DEBUG >= 2
923                 ++c1;
924             } else {
925                 ++c2;
926 #endif
927             }
928             t = wait;
929         } else {
930             t -= delta;
931         }
932         DELAY(delta*1000);
933     }
934 #if KBDIO_DEBUG >= 2
935     if ((c1 > 0) || (c2 > 0))
936         log(LOG_DEBUG, "kbdc: %d:%d char read (empty_aux_buffer)\n", c1, c2);
937 #endif
938
939     emptyq(&kbdcp(p)->aux);
940 }
941
942 /* discard any data from the keyboard or the aux device */
943 void
944 empty_both_buffers(KBDC p, int wait)
945 {
946     int t;
947     int f;
948     int waited = 0;
949 #if KBDIO_DEBUG >= 2
950     int c1 = 0;
951     int c2 = 0;
952 #endif
953     int delta = 2;
954
955     for (t = wait; t > 0; ) { 
956         if ((f = read_status(kbdcp(p))) & KBDS_ANY_BUFFER_FULL) {
957             DELAY(KBDD_DELAYTIME);
958             (void)read_data(kbdcp(p));
959 #if KBDIO_DEBUG >= 2
960             if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL)
961                 ++c1;
962             else
963                 ++c2;
964 #endif
965             t = wait;
966         } else {
967             t -= delta;
968         }
969
970         /*
971          * Some systems (Intel/IBM blades) do not have keyboard devices and
972          * will thus hang in this procedure. Time out after delta seconds to
973          * avoid this hang -- the keyboard attach will fail later on.
974          */
975         waited += (delta * 1000);
976         if (waited == (delta * 1000000))
977             return;
978
979         DELAY(delta*1000);
980     }
981 #if KBDIO_DEBUG >= 2
982     if ((c1 > 0) || (c2 > 0))
983         log(LOG_DEBUG, "kbdc: %d:%d char read (empty_both_buffers)\n", c1, c2);
984 #endif
985
986     emptyq(&kbdcp(p)->kbd);
987     emptyq(&kbdcp(p)->aux);
988 }
989
990 /* keyboard and mouse device control */
991
992 /* NOTE: enable the keyboard port but disable the keyboard 
993  * interrupt before calling "reset_kbd()".
994  */
995 int
996 reset_kbd(KBDC p)
997 {
998     int retry = KBD_MAXRETRY;
999     int again = KBD_MAXWAIT;
1000     int c = KBD_RESEND;         /* keep the compiler happy */
1001
1002     while (retry-- > 0) {
1003         empty_both_buffers(p, 10);
1004         if (!write_kbd_command(p, KBDC_RESET_KBD))
1005             continue;
1006         emptyq(&kbdcp(p)->kbd);
1007         c = read_controller_data(p);
1008         if (verbose || bootverbose)
1009             log(LOG_DEBUG, "kbdc: RESET_KBD return code:%04x\n", c);
1010         if (c == KBD_ACK)       /* keyboard has agreed to reset itself... */
1011             break;
1012     }
1013     if (retry < 0)
1014         return FALSE;
1015
1016     while (again-- > 0) {
1017         /* wait awhile, well, in fact we must wait quite loooooooooooong */
1018         DELAY(KBD_RESETDELAY*1000);
1019         c = read_controller_data(p);    /* RESET_DONE/RESET_FAIL */
1020         if (c != -1)    /* wait again if the controller is not ready */
1021             break;
1022     }
1023     if (verbose || bootverbose)
1024         log(LOG_DEBUG, "kbdc: RESET_KBD status:%04x\n", c);
1025     if (c != KBD_RESET_DONE)
1026         return FALSE;
1027     return TRUE;
1028 }
1029
1030 /* NOTE: enable the aux port but disable the aux interrupt
1031  * before calling `reset_aux_dev()'.
1032  */
1033 int
1034 reset_aux_dev(KBDC p)
1035 {
1036     int retry = KBD_MAXRETRY;
1037     int again = KBD_MAXWAIT;
1038     int c = PSM_RESEND;         /* keep the compiler happy */
1039
1040     while (retry-- > 0) {
1041         empty_both_buffers(p, 10);
1042         if (!write_aux_command(p, PSMC_RESET_DEV))
1043             continue;
1044         emptyq(&kbdcp(p)->aux);
1045         /* NOTE: Compaq Armada laptops require extra delay here. XXX */
1046         for (again = KBD_MAXWAIT; again > 0; --again) {
1047             DELAY(KBD_RESETDELAY*1000);
1048             c = read_aux_data_no_wait(p);
1049             if (c != -1)
1050                 break;
1051         }
1052         if (verbose || bootverbose)
1053             log(LOG_DEBUG, "kbdc: RESET_AUX return code:%04x\n", c);
1054         if (c == PSM_ACK)       /* aux dev is about to reset... */
1055             break;
1056     }
1057     if (retry < 0)
1058         return FALSE;
1059
1060     for (again = KBD_MAXWAIT; again > 0; --again) {
1061         /* wait awhile, well, quite looooooooooooong */
1062         DELAY(KBD_RESETDELAY*1000);
1063         c = read_aux_data_no_wait(p);   /* RESET_DONE/RESET_FAIL */
1064         if (c != -1)    /* wait again if the controller is not ready */
1065             break;
1066     }
1067     if (verbose || bootverbose)
1068         log(LOG_DEBUG, "kbdc: RESET_AUX status:%04x\n", c);
1069     if (c != PSM_RESET_DONE)    /* reset status */
1070         return FALSE;
1071
1072     c = read_aux_data(p);       /* device ID */
1073     if (verbose || bootverbose)
1074         log(LOG_DEBUG, "kbdc: RESET_AUX ID:%04x\n", c);
1075     /* NOTE: we could check the device ID now, but leave it later... */
1076     return TRUE;
1077 }
1078
1079 /* controller diagnostics and setup */
1080
1081 int
1082 test_controller(KBDC p)
1083 {
1084     int retry = KBD_MAXRETRY;
1085     int again = KBD_MAXWAIT;
1086     int c = KBD_DIAG_FAIL;
1087
1088     while (retry-- > 0) {
1089         empty_both_buffers(p, 10);
1090         if (write_controller_command(p, KBDC_DIAGNOSE))
1091             break;
1092     }
1093     if (retry < 0)
1094         return FALSE;
1095
1096     emptyq(&kbdcp(p)->kbd);
1097     while (again-- > 0) {
1098         /* wait awhile */
1099         DELAY(KBD_RESETDELAY*1000);
1100         c = read_controller_data(p);    /* DIAG_DONE/DIAG_FAIL */
1101         if (c != -1)    /* wait again if the controller is not ready */
1102             break;
1103     }
1104     if (verbose || bootverbose)
1105         log(LOG_DEBUG, "kbdc: DIAGNOSE status:%04x\n", c);
1106     return (c == KBD_DIAG_DONE);
1107 }
1108
1109 int
1110 test_kbd_port(KBDC p)
1111 {
1112     int retry = KBD_MAXRETRY;
1113     int again = KBD_MAXWAIT;
1114     int c = -1;
1115
1116     while (retry-- > 0) {
1117         empty_both_buffers(p, 10);
1118         if (write_controller_command(p, KBDC_TEST_KBD_PORT))
1119             break;
1120     }
1121     if (retry < 0)
1122         return FALSE;
1123
1124     emptyq(&kbdcp(p)->kbd);
1125     while (again-- > 0) {
1126         c = read_controller_data(p);
1127         if (c != -1)    /* try again if the controller is not ready */
1128             break;
1129     }
1130     if (verbose || bootverbose)
1131         log(LOG_DEBUG, "kbdc: TEST_KBD_PORT status:%04x\n", c);
1132     return c;
1133 }
1134
1135 int
1136 test_aux_port(KBDC p)
1137 {
1138     int retry = KBD_MAXRETRY;
1139     int again = KBD_MAXWAIT;
1140     int c = -1;
1141
1142     while (retry-- > 0) {
1143         empty_both_buffers(p, 10);
1144         if (write_controller_command(p, KBDC_TEST_AUX_PORT))
1145             break;
1146     }
1147     if (retry < 0)
1148         return FALSE;
1149
1150     emptyq(&kbdcp(p)->kbd);
1151     while (again-- > 0) {
1152         c = read_controller_data(p);
1153         if (c != -1)    /* try again if the controller is not ready */
1154             break;
1155     }
1156     if (verbose || bootverbose)
1157         log(LOG_DEBUG, "kbdc: TEST_AUX_PORT status:%04x\n", c);
1158     return c;
1159 }
1160
1161 int
1162 kbdc_get_device_mask(KBDC p)
1163 {
1164     return kbdcp(p)->command_mask;
1165 }
1166
1167 void
1168 kbdc_set_device_mask(KBDC p, int mask)
1169 {
1170     kbdcp(p)->command_mask = 
1171         mask & (((kbdcp(p)->quirks & KBDC_QUIRK_KEEP_ACTIVATED)
1172             ? 0 : KBD_KBD_CONTROL_BITS) | KBD_AUX_CONTROL_BITS);
1173 }
1174
1175 int
1176 get_controller_command_byte(KBDC p)
1177 {
1178     if (kbdcp(p)->command_byte != -1)
1179         return kbdcp(p)->command_byte;
1180     if (!write_controller_command(p, KBDC_GET_COMMAND_BYTE))
1181         return -1;
1182     emptyq(&kbdcp(p)->kbd);
1183     kbdcp(p)->command_byte = read_controller_data(p);
1184     return kbdcp(p)->command_byte;
1185 }
1186
1187 int
1188 set_controller_command_byte(KBDC p, int mask, int command)
1189 {
1190     if (get_controller_command_byte(p) == -1)
1191         return FALSE;
1192
1193     command = (kbdcp(p)->command_byte & ~mask) | (command & mask);
1194     if (command & KBD_DISABLE_KBD_PORT) {
1195         if (!write_controller_command(p, KBDC_DISABLE_KBD_PORT))
1196             return FALSE;
1197     }
1198     if (!write_controller_command(p, KBDC_SET_COMMAND_BYTE))
1199         return FALSE;
1200     if (!write_controller_data(p, command))
1201         return FALSE;
1202     kbdcp(p)->command_byte = command;
1203
1204     if (verbose)
1205         log(LOG_DEBUG, "kbdc: new command byte:%04x (set_controller...)\n",
1206             command);
1207
1208     return TRUE;
1209 }
1210
1211 /*
1212  * Rudimentary support for active PS/2 AUX port multiplexing.
1213  * Only write commands can be routed to a selected AUX port.
1214  * Source port of data processed by read commands is totally ignored.
1215  */
1216 static int
1217 set_aux_mux_state(KBDC p, int enabled)
1218 {
1219         int command, version;
1220
1221         if (write_controller_command(p, KBDC_FORCE_AUX_OUTPUT) == 0 ||
1222             write_controller_data(p, 0xF0) == 0 ||
1223             read_controller_data(p) != 0xF0)
1224                 return (-1);
1225
1226         if (write_controller_command(p, KBDC_FORCE_AUX_OUTPUT) == 0 ||
1227             write_controller_data(p, 0x56) == 0 ||
1228             read_controller_data(p) != 0x56)
1229                 return (-1);
1230
1231         command = enabled ? 0xa4 : 0xa5;
1232         if (write_controller_command(p, KBDC_FORCE_AUX_OUTPUT) == 0 ||
1233             write_controller_data(p, command) == 0 ||
1234             (version = read_controller_data(p)) == command)
1235                 return (-1);
1236
1237         return (version);
1238 }
1239
1240 int
1241 set_active_aux_mux_port(KBDC p, int port)
1242 {
1243
1244         if (!aux_mux_is_enabled(p))
1245                 return (FALSE);
1246
1247         if (port < 0 || port >= KBDC_AUX_MUX_NUM_PORTS)
1248                 return (FALSE);
1249
1250         kbdcp(p)->aux_mux_port = port;
1251
1252         return (TRUE);
1253 }
1254
1255 /* Checks for active multiplexing support and enables it */
1256 int
1257 enable_aux_mux(KBDC p)
1258 {
1259         int version;
1260
1261         version = set_aux_mux_state(p, TRUE);
1262         if (version >= 0) {
1263                 kbdcp(p)->aux_mux_enabled = TRUE;
1264                 set_active_aux_mux_port(p, 0);
1265         }
1266
1267         return (version);
1268 }
1269
1270 int
1271 disable_aux_mux(KBDC p)
1272 {
1273
1274         kbdcp(p)->aux_mux_enabled = FALSE;
1275
1276         return (set_aux_mux_state(p, FALSE));
1277 }
1278
1279 int
1280 aux_mux_is_enabled(KBDC p)
1281 {
1282
1283         return (kbdcp(p)->aux_mux_enabled);
1284 }