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