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