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