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