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