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