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