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