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