xref: /freebsd/sys/dev/atkbdc/atkbdc.c (revision a7dea1671b87c07d2d266f836bfa8b58efc7c134)
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 nextq(i)	(((i) + 1) % KBDQ_BUFSIZE)
74 #define availq(q)	((q)->head != (q)->tail)
75 #if KBDIO_DEBUG >= 2
76 #define emptyq(q)	((q)->tail = (q)->head = (q)->qcount = 0)
77 #else
78 #define emptyq(q)	((q)->tail = (q)->head = 0)
79 #endif
80 
81 #define read_data(k)	(bus_space_read_1((k)->iot, (k)->ioh0, 0))
82 #define read_status(k)	(bus_space_read_1((k)->iot, (k)->ioh1, 0))
83 #define write_data(k, d)	\
84 			(bus_space_write_1((k)->iot, (k)->ioh0, 0, (d)))
85 #define write_command(k, d)	\
86 			(bus_space_write_1((k)->iot, (k)->ioh1, 0, (d)))
87 
88 /* local variables */
89 
90 /*
91  * We always need at least one copy of the kbdc_softc struct for the
92  * low-level console.  As the low-level console accesses the keyboard
93  * controller before kbdc, and all other devices, is probed, we
94  * statically allocate one entry. XXX
95  */
96 static atkbdc_softc_t default_kbdc;
97 static atkbdc_softc_t *atkbdc_softc[MAXKBDC] = { &default_kbdc };
98 
99 static int verbose = KBDIO_DEBUG;
100 
101 #ifdef __sparc64__
102 static struct bus_space_tag atkbdc_bst_store[MAXKBDC];
103 #endif
104 
105 /* function prototypes */
106 
107 static int atkbdc_setup(atkbdc_softc_t *sc, bus_space_tag_t tag,
108 			bus_space_handle_t h0, bus_space_handle_t h1);
109 static int addq(kqueue *q, int c);
110 static int removeq(kqueue *q);
111 static int wait_while_controller_busy(atkbdc_softc_t *kbdc);
112 static int wait_for_data(atkbdc_softc_t *kbdc);
113 static int wait_for_kbd_data(atkbdc_softc_t *kbdc);
114 static int wait_for_kbd_ack(atkbdc_softc_t *kbdc);
115 static int wait_for_aux_data(atkbdc_softc_t *kbdc);
116 static int wait_for_aux_ack(atkbdc_softc_t *kbdc);
117 
118 struct atkbdc_quirks {
119     const char* bios_vendor;
120     const char*	maker;
121     const char*	product;
122     int		quirk;
123 };
124 
125 static struct atkbdc_quirks quirks[] = {
126     {"coreboot", NULL, NULL,
127 	KBDC_QUIRK_KEEP_ACTIVATED | KBDC_QUIRK_IGNORE_PROBE_RESULT |
128 	KBDC_QUIRK_RESET_AFTER_PROBE | KBDC_QUIRK_SETLEDS_ON_INIT},
129 
130     {NULL, NULL, NULL, 0}
131 };
132 
133 #define QUIRK_STR_MATCH(s1, s2) (s1 == NULL || \
134     (s2 != NULL && !strcmp(s1, s2)))
135 
136 static int
137 atkbdc_getquirks(void)
138 {
139     int i;
140     char* bios_vendor = kern_getenv("smbios.bios.vendor");
141     char* maker = kern_getenv("smbios.system.maker");
142     char* product = kern_getenv("smbios.system.product");
143 
144     for (i=0; quirks[i].quirk != 0; ++i)
145 	if (QUIRK_STR_MATCH(quirks[i].bios_vendor, bios_vendor) &&
146 	    QUIRK_STR_MATCH(quirks[i].maker, maker) &&
147 	    QUIRK_STR_MATCH(quirks[i].product, product))
148 		return (quirks[i].quirk);
149 
150     return (0);
151 }
152 
153 atkbdc_softc_t
154 *atkbdc_get_softc(int unit)
155 {
156 	atkbdc_softc_t *sc;
157 
158 	if (unit >= nitems(atkbdc_softc))
159 		return NULL;
160 	sc = atkbdc_softc[unit];
161 	if (sc == NULL) {
162 		sc = atkbdc_softc[unit]
163 		   = malloc(sizeof(*sc), M_DEVBUF, M_NOWAIT | M_ZERO);
164 		if (sc == NULL)
165 			return NULL;
166 	}
167 	return sc;
168 }
169 
170 int
171 atkbdc_probe_unit(int unit, struct resource *port0, struct resource *port1)
172 {
173 	if (rman_get_start(port0) <= 0)
174 		return ENXIO;
175 	if (rman_get_start(port1) <= 0)
176 		return ENXIO;
177 	return 0;
178 }
179 
180 int
181 atkbdc_attach_unit(int unit, atkbdc_softc_t *sc, struct resource *port0,
182 		   struct resource *port1)
183 {
184 	return atkbdc_setup(sc, rman_get_bustag(port0),
185 			    rman_get_bushandle(port0),
186 			    rman_get_bushandle(port1));
187 }
188 
189 /* the backdoor to the keyboard controller! XXX */
190 int
191 atkbdc_configure(void)
192 {
193 	bus_space_tag_t tag;
194 	bus_space_handle_t h0;
195 	bus_space_handle_t h1;
196 #if defined(__i386__) || defined(__amd64__)
197 	volatile int i;
198 	register_t flags;
199 #endif
200 #ifdef __sparc64__
201 	char name[32];
202 	phandle_t chosen, node;
203 	ihandle_t stdin;
204 	bus_addr_t port0;
205 	bus_addr_t port1;
206 	int space;
207 #else
208 	int port0;
209 	int port1;
210 #endif
211 
212 	/* XXX: tag should be passed from the caller */
213 #if defined(__amd64__) || defined(__i386__)
214 	tag = X86_BUS_SPACE_IO;
215 #elif defined(__sparc64__)
216 	tag = &atkbdc_bst_store[0];
217 #else
218 #error "define tag!"
219 #endif
220 
221 #ifdef __sparc64__
222 	if ((chosen = OF_finddevice("/chosen")) == -1)
223 		return 0;
224 	if (OF_getprop(chosen, "stdin", &stdin, sizeof(stdin)) == -1)
225 		return 0;
226 	if ((node = OF_instance_to_package(stdin)) == -1)
227 		return 0;
228 	if (OF_getprop(node, "name", name, sizeof(name)) == -1)
229 		return 0;
230 	name[sizeof(name) - 1] = '\0';
231 	if (strcmp(name, "kb_ps2") != 0)
232 		return 0;
233 	/*
234 	 * The stdin handle points to an instance of a PS/2 keyboard
235 	 * package but we want the 8042 controller, which is the parent
236 	 * of that keyboard node.
237 	 */
238 	if ((node = OF_parent(node)) == 0)
239 		return 0;
240 	if (OF_decode_addr(node, 0, &space, &port0) != 0)
241 		return 0;
242 	h0 = sparc64_fake_bustag(space, port0, tag);
243 	bus_space_subregion(tag, h0, KBD_DATA_PORT, 1, &h0);
244 	if (OF_decode_addr(node, 1, &space, &port1) != 0)
245 		return 0;
246 	h1 = sparc64_fake_bustag(space, port1, tag);
247 	bus_space_subregion(tag, h1, KBD_STATUS_PORT, 1, &h1);
248 #else
249 	port0 = IO_KBD;
250 	resource_int_value("atkbdc", 0, "port", &port0);
251 	port1 = IO_KBD + KBD_STATUS_PORT;
252 #ifdef notyet
253 	bus_space_map(tag, port0, IO_KBDSIZE, 0, &h0);
254 	bus_space_map(tag, port1, IO_KBDSIZE, 0, &h1);
255 #else
256 	h0 = (bus_space_handle_t)port0;
257 	h1 = (bus_space_handle_t)port1;
258 #endif
259 #endif
260 
261 #if defined(__i386__) || defined(__amd64__)
262 	/*
263 	 * Check if we really have AT keyboard controller. Poll status
264 	 * register until we get "all clear" indication. If no such
265 	 * indication comes, it probably means that there is no AT
266 	 * keyboard controller present. Give up in such case. Check relies
267 	 * on the fact that reading from non-existing in/out port returns
268 	 * 0xff on i386. May or may not be true on other platforms.
269 	 */
270 	flags = intr_disable();
271 	for (i = 0; i != 65535; i++) {
272 		if ((bus_space_read_1(tag, h1, 0) & 0x2) == 0)
273 			break;
274 	}
275 	intr_restore(flags);
276 	if (i == 65535)
277                 return ENXIO;
278 #endif
279 
280 	return atkbdc_setup(atkbdc_softc[0], tag, h0, h1);
281 }
282 
283 static int
284 atkbdc_setup(atkbdc_softc_t *sc, bus_space_tag_t tag, bus_space_handle_t h0,
285 	     bus_space_handle_t h1)
286 {
287 #if defined(__amd64__)
288 	u_int64_t tscval[3], read_delay;
289 	register_t flags;
290 #endif
291 
292 	if (sc->ioh0 == 0) {	/* XXX */
293 	    sc->command_byte = -1;
294 	    sc->command_mask = 0;
295 	    sc->lock = FALSE;
296 	    sc->kbd.head = sc->kbd.tail = 0;
297 	    sc->aux.head = sc->aux.tail = 0;
298 	    sc->aux_mux_enabled = FALSE;
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 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 = p->lock;
399     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(&p->kbd) || availq(&p->aux)
409 	|| (read_status(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(p))
613 	return FALSE;
614     write_command(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(p))
623 	return FALSE;
624     write_data(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(p))
633 	return FALSE;
634     write_data(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     int f;
643 
644     f = aux_mux_is_enabled(p) ?
645         KBDC_WRITE_TO_AUX_MUX + p->aux_mux_port : KBDC_WRITE_TO_AUX;
646 
647     if (!write_controller_command(p, f))
648 	return FALSE;
649     return write_controller_data(p, c);
650 }
651 
652 /* send a command to the keyboard and wait for ACK */
653 int
654 send_kbd_command(KBDC p, int c)
655 {
656     int retry = KBD_MAXRETRY;
657     int res = -1;
658 
659     while (retry-- > 0) {
660 	if (!write_kbd_command(p, c))
661 	    continue;
662         res = wait_for_kbd_ack(p);
663         if (res == KBD_ACK)
664     	    break;
665     }
666     return res;
667 }
668 
669 /* send a command to the auxiliary device and wait for ACK */
670 int
671 send_aux_command(KBDC p, int c)
672 {
673     int retry = KBD_MAXRETRY;
674     int res = -1;
675 
676     while (retry-- > 0) {
677 	if (!write_aux_command(p, c))
678 	    continue;
679 	/*
680 	 * FIXME: XXX
681 	 * The aux device may have already sent one or two bytes of
682 	 * status data, when a command is received. It will immediately
683 	 * stop data transmission, thus, leaving an incomplete data
684 	 * packet in our buffer. We have to discard any unprocessed
685 	 * data in order to remove such packets. Well, we may remove
686 	 * unprocessed, but necessary data byte as well...
687 	 */
688 	emptyq(&p->aux);
689         res = wait_for_aux_ack(p);
690         if (res == PSM_ACK)
691     	    break;
692     }
693     return res;
694 }
695 
696 /* send a command and a data to the keyboard, wait for ACKs */
697 int
698 send_kbd_command_and_data(KBDC p, int c, int d)
699 {
700     int retry;
701     int res = -1;
702 
703     for (retry = KBD_MAXRETRY; retry > 0; --retry) {
704 	if (!write_kbd_command(p, c))
705 	    continue;
706         res = wait_for_kbd_ack(p);
707         if (res == KBD_ACK)
708     	    break;
709         else if (res != KBD_RESEND)
710     	    return res;
711     }
712     if (retry <= 0)
713 	return res;
714 
715     for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) {
716 	if (!write_kbd_command(p, d))
717 	    continue;
718         res = wait_for_kbd_ack(p);
719         if (res != KBD_RESEND)
720     	    break;
721     }
722     return res;
723 }
724 
725 /* send a command and a data to the auxiliary device, wait for ACKs */
726 int
727 send_aux_command_and_data(KBDC p, int c, int d)
728 {
729     int retry;
730     int res = -1;
731 
732     for (retry = KBD_MAXRETRY; retry > 0; --retry) {
733 	if (!write_aux_command(p, c))
734 	    continue;
735 	emptyq(&p->aux);
736         res = wait_for_aux_ack(p);
737         if (res == PSM_ACK)
738     	    break;
739         else if (res != PSM_RESEND)
740     	    return res;
741     }
742     if (retry <= 0)
743 	return res;
744 
745     for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) {
746 	if (!write_aux_command(p, d))
747 	    continue;
748         res = wait_for_aux_ack(p);
749         if (res != PSM_RESEND)
750     	    break;
751     }
752     return res;
753 }
754 
755 /*
756  * read one byte from any source; whether from the controller,
757  * the keyboard, or the aux device
758  */
759 int
760 read_controller_data(KBDC p)
761 {
762     if (availq(&p->kbd))
763         return removeq(&p->kbd);
764     if (availq(&p->aux))
765         return removeq(&p->aux);
766     if (!wait_for_data(p))
767         return -1;		/* timeout */
768     return read_data(p);
769 }
770 
771 #if KBDIO_DEBUG >= 2
772 static int call = 0;
773 #endif
774 
775 /* read one byte from the keyboard */
776 int
777 read_kbd_data(KBDC p)
778 {
779 #if KBDIO_DEBUG >= 2
780     if (++call > 2000) {
781 	call = 0;
782 	log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, "
783 			     "aux q: %d calls, max %d chars\n",
784 		       p->kbd.call_count, p->kbd.max_qcount,
785 		       p->aux.call_count, p->aux.max_qcount);
786     }
787 #endif
788 
789     if (availq(&p->kbd))
790         return removeq(&p->kbd);
791     if (!wait_for_kbd_data(p))
792         return -1;		/* timeout */
793     return read_data(p);
794 }
795 
796 /* read one byte from the keyboard, but return immediately if
797  * no data is waiting
798  */
799 int
800 read_kbd_data_no_wait(KBDC p)
801 {
802     int f;
803 
804 #if KBDIO_DEBUG >= 2
805     if (++call > 2000) {
806 	call = 0;
807 	log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, "
808 			     "aux q: %d calls, max %d chars\n",
809 		       p->kbd.call_count, p->kbd.max_qcount,
810 		       p->aux.call_count, p->aux.max_qcount);
811     }
812 #endif
813 
814     if (availq(&p->kbd))
815         return removeq(&p->kbd);
816     f = read_status(p) & KBDS_BUFFER_FULL;
817     if (f == KBDS_AUX_BUFFER_FULL) {
818         DELAY(KBDD_DELAYTIME);
819         addq(&p->aux, read_data(p));
820         f = read_status(p) & KBDS_BUFFER_FULL;
821     }
822     if (f == KBDS_KBD_BUFFER_FULL) {
823         DELAY(KBDD_DELAYTIME);
824         return read_data(p);
825     }
826     return -1;		/* no data */
827 }
828 
829 /* read one byte from the aux device */
830 int
831 read_aux_data(KBDC p)
832 {
833     if (availq(&p->aux))
834         return removeq(&p->aux);
835     if (!wait_for_aux_data(p))
836         return -1;		/* timeout */
837     return read_data(p);
838 }
839 
840 /* read one byte from the aux device, but return immediately if
841  * no data is waiting
842  */
843 int
844 read_aux_data_no_wait(KBDC p)
845 {
846     int f;
847 
848     if (availq(&p->aux))
849         return removeq(&p->aux);
850     f = read_status(p) & KBDS_BUFFER_FULL;
851     if (f == KBDS_KBD_BUFFER_FULL) {
852         DELAY(KBDD_DELAYTIME);
853         addq(&p->kbd, read_data(p));
854         f = read_status(p) & KBDS_BUFFER_FULL;
855     }
856     if (f == KBDS_AUX_BUFFER_FULL) {
857         DELAY(KBDD_DELAYTIME);
858         return read_data(p);
859     }
860     return -1;		/* no data */
861 }
862 
863 /* discard data from the keyboard */
864 void
865 empty_kbd_buffer(KBDC p, int wait)
866 {
867     int t;
868     int b;
869     int f;
870 #if KBDIO_DEBUG >= 2
871     int c1 = 0;
872     int c2 = 0;
873 #endif
874     int delta = 2;
875 
876     for (t = wait; t > 0; ) {
877         if ((f = read_status(p)) & KBDS_ANY_BUFFER_FULL) {
878 	    DELAY(KBDD_DELAYTIME);
879             b = read_data(p);
880 	    if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) {
881 		addq(&p->aux, b);
882 #if KBDIO_DEBUG >= 2
883 		++c2;
884             } else {
885 		++c1;
886 #endif
887 	    }
888 	    t = wait;
889 	} else {
890 	    t -= delta;
891 	}
892         DELAY(delta*1000);
893     }
894 #if KBDIO_DEBUG >= 2
895     if ((c1 > 0) || (c2 > 0))
896         log(LOG_DEBUG, "kbdc: %d:%d char read (empty_kbd_buffer)\n", c1, c2);
897 #endif
898 
899     emptyq(&p->kbd);
900 }
901 
902 /* discard data from the aux device */
903 void
904 empty_aux_buffer(KBDC p, int wait)
905 {
906     int t;
907     int b;
908     int f;
909 #if KBDIO_DEBUG >= 2
910     int c1 = 0;
911     int c2 = 0;
912 #endif
913     int delta = 2;
914 
915     for (t = wait; t > 0; ) {
916         if ((f = read_status(p)) & KBDS_ANY_BUFFER_FULL) {
917 	    DELAY(KBDD_DELAYTIME);
918             b = read_data(p);
919 	    if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) {
920 		addq(&p->kbd, b);
921 #if KBDIO_DEBUG >= 2
922 		++c1;
923             } else {
924 		++c2;
925 #endif
926 	    }
927 	    t = wait;
928 	} else {
929 	    t -= delta;
930 	}
931 	DELAY(delta*1000);
932     }
933 #if KBDIO_DEBUG >= 2
934     if ((c1 > 0) || (c2 > 0))
935         log(LOG_DEBUG, "kbdc: %d:%d char read (empty_aux_buffer)\n", c1, c2);
936 #endif
937 
938     emptyq(&p->aux);
939 }
940 
941 /* discard any data from the keyboard or the aux device */
942 void
943 empty_both_buffers(KBDC p, int wait)
944 {
945     int t;
946     int f;
947     int waited = 0;
948 #if KBDIO_DEBUG >= 2
949     int c1 = 0;
950     int c2 = 0;
951 #endif
952     int delta = 2;
953 
954     for (t = wait; t > 0; ) {
955         if ((f = read_status(p)) & KBDS_ANY_BUFFER_FULL) {
956 	    DELAY(KBDD_DELAYTIME);
957             (void)read_data(p);
958 #if KBDIO_DEBUG >= 2
959 	    if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL)
960 		++c1;
961             else
962 		++c2;
963 #endif
964 	    t = wait;
965 	} else {
966 	    t -= delta;
967 	}
968 
969 	/*
970 	 * Some systems (Intel/IBM blades) do not have keyboard devices and
971 	 * will thus hang in this procedure. Time out after delta seconds to
972 	 * avoid this hang -- the keyboard attach will fail later on.
973 	 */
974         waited += (delta * 1000);
975         if (waited == (delta * 1000000))
976 	    return;
977 
978 	DELAY(delta*1000);
979     }
980 #if KBDIO_DEBUG >= 2
981     if ((c1 > 0) || (c2 > 0))
982         log(LOG_DEBUG, "kbdc: %d:%d char read (empty_both_buffers)\n", c1, c2);
983 #endif
984 
985     emptyq(&p->kbd);
986     emptyq(&p->aux);
987 }
988 
989 /* keyboard and mouse device control */
990 
991 /* NOTE: enable the keyboard port but disable the keyboard
992  * interrupt before calling "reset_kbd()".
993  */
994 int
995 reset_kbd(KBDC p)
996 {
997     int retry = KBD_MAXRETRY;
998     int again = KBD_MAXWAIT;
999     int c = KBD_RESEND;		/* keep the compiler happy */
1000 
1001     while (retry-- > 0) {
1002         empty_both_buffers(p, 10);
1003         if (!write_kbd_command(p, KBDC_RESET_KBD))
1004 	    continue;
1005 	emptyq(&p->kbd);
1006         c = read_controller_data(p);
1007 	if (verbose || bootverbose)
1008             log(LOG_DEBUG, "kbdc: RESET_KBD return code:%04x\n", c);
1009         if (c == KBD_ACK)	/* keyboard has agreed to reset itself... */
1010     	    break;
1011     }
1012     if (retry < 0)
1013         return FALSE;
1014 
1015     while (again-- > 0) {
1016         /* wait awhile, well, in fact we must wait quite loooooooooooong */
1017         DELAY(KBD_RESETDELAY*1000);
1018         c = read_controller_data(p);	/* RESET_DONE/RESET_FAIL */
1019         if (c != -1) 	/* wait again if the controller is not ready */
1020     	    break;
1021     }
1022     if (verbose || bootverbose)
1023         log(LOG_DEBUG, "kbdc: RESET_KBD status:%04x\n", c);
1024     if (c != KBD_RESET_DONE)
1025         return FALSE;
1026     return TRUE;
1027 }
1028 
1029 /* NOTE: enable the aux port but disable the aux interrupt
1030  * before calling `reset_aux_dev()'.
1031  */
1032 int
1033 reset_aux_dev(KBDC p)
1034 {
1035     int retry = KBD_MAXRETRY;
1036     int again = KBD_MAXWAIT;
1037     int c = PSM_RESEND;		/* keep the compiler happy */
1038 
1039     while (retry-- > 0) {
1040         empty_both_buffers(p, 10);
1041         if (!write_aux_command(p, PSMC_RESET_DEV))
1042 	    continue;
1043 	emptyq(&p->aux);
1044 	/* NOTE: Compaq Armada laptops require extra delay here. XXX */
1045 	for (again = KBD_MAXWAIT; again > 0; --again) {
1046             DELAY(KBD_RESETDELAY*1000);
1047             c = read_aux_data_no_wait(p);
1048 	    if (c != -1)
1049 		break;
1050 	}
1051         if (verbose || bootverbose)
1052             log(LOG_DEBUG, "kbdc: RESET_AUX return code:%04x\n", c);
1053         if (c == PSM_ACK)	/* aux dev is about to reset... */
1054     	    break;
1055     }
1056     if (retry < 0)
1057         return FALSE;
1058 
1059     for (again = KBD_MAXWAIT; again > 0; --again) {
1060         /* wait awhile, well, quite looooooooooooong */
1061         DELAY(KBD_RESETDELAY*1000);
1062         c = read_aux_data_no_wait(p);	/* RESET_DONE/RESET_FAIL */
1063         if (c != -1) 	/* wait again if the controller is not ready */
1064     	    break;
1065     }
1066     if (verbose || bootverbose)
1067         log(LOG_DEBUG, "kbdc: RESET_AUX status:%04x\n", c);
1068     if (c != PSM_RESET_DONE)	/* reset status */
1069         return FALSE;
1070 
1071     c = read_aux_data(p);	/* device ID */
1072     if (verbose || bootverbose)
1073         log(LOG_DEBUG, "kbdc: RESET_AUX ID:%04x\n", c);
1074     /* NOTE: we could check the device ID now, but leave it later... */
1075     return TRUE;
1076 }
1077 
1078 /* controller diagnostics and setup */
1079 
1080 int
1081 test_controller(KBDC p)
1082 {
1083     int retry = KBD_MAXRETRY;
1084     int again = KBD_MAXWAIT;
1085     int c = KBD_DIAG_FAIL;
1086 
1087     while (retry-- > 0) {
1088         empty_both_buffers(p, 10);
1089         if (write_controller_command(p, KBDC_DIAGNOSE))
1090     	    break;
1091     }
1092     if (retry < 0)
1093         return FALSE;
1094 
1095     emptyq(&p->kbd);
1096     while (again-- > 0) {
1097         /* wait awhile */
1098         DELAY(KBD_RESETDELAY*1000);
1099         c = read_controller_data(p);	/* DIAG_DONE/DIAG_FAIL */
1100         if (c != -1) 	/* wait again if the controller is not ready */
1101     	    break;
1102     }
1103     if (verbose || bootverbose)
1104         log(LOG_DEBUG, "kbdc: DIAGNOSE status:%04x\n", c);
1105     return (c == KBD_DIAG_DONE);
1106 }
1107 
1108 int
1109 test_kbd_port(KBDC p)
1110 {
1111     int retry = KBD_MAXRETRY;
1112     int again = KBD_MAXWAIT;
1113     int c = -1;
1114 
1115     while (retry-- > 0) {
1116         empty_both_buffers(p, 10);
1117         if (write_controller_command(p, KBDC_TEST_KBD_PORT))
1118     	    break;
1119     }
1120     if (retry < 0)
1121         return FALSE;
1122 
1123     emptyq(&p->kbd);
1124     while (again-- > 0) {
1125         c = read_controller_data(p);
1126         if (c != -1) 	/* try again if the controller is not ready */
1127     	    break;
1128     }
1129     if (verbose || bootverbose)
1130         log(LOG_DEBUG, "kbdc: TEST_KBD_PORT status:%04x\n", c);
1131     return c;
1132 }
1133 
1134 int
1135 test_aux_port(KBDC p)
1136 {
1137     int retry = KBD_MAXRETRY;
1138     int again = KBD_MAXWAIT;
1139     int c = -1;
1140 
1141     while (retry-- > 0) {
1142         empty_both_buffers(p, 10);
1143         if (write_controller_command(p, KBDC_TEST_AUX_PORT))
1144     	    break;
1145     }
1146     if (retry < 0)
1147         return FALSE;
1148 
1149     emptyq(&p->kbd);
1150     while (again-- > 0) {
1151         c = read_controller_data(p);
1152         if (c != -1) 	/* try again if the controller is not ready */
1153     	    break;
1154     }
1155     if (verbose || bootverbose)
1156         log(LOG_DEBUG, "kbdc: TEST_AUX_PORT status:%04x\n", c);
1157     return c;
1158 }
1159 
1160 int
1161 kbdc_get_device_mask(KBDC p)
1162 {
1163     return p->command_mask;
1164 }
1165 
1166 void
1167 kbdc_set_device_mask(KBDC p, int mask)
1168 {
1169     p->command_mask =
1170 	mask & (((p->quirks & KBDC_QUIRK_KEEP_ACTIVATED)
1171 	    ? 0 : KBD_KBD_CONTROL_BITS) | KBD_AUX_CONTROL_BITS);
1172 }
1173 
1174 int
1175 get_controller_command_byte(KBDC p)
1176 {
1177     if (p->command_byte != -1)
1178 	return p->command_byte;
1179     if (!write_controller_command(p, KBDC_GET_COMMAND_BYTE))
1180 	return -1;
1181     emptyq(&p->kbd);
1182     p->command_byte = read_controller_data(p);
1183     return p->command_byte;
1184 }
1185 
1186 int
1187 set_controller_command_byte(KBDC p, int mask, int command)
1188 {
1189     if (get_controller_command_byte(p) == -1)
1190 	return FALSE;
1191 
1192     command = (p->command_byte & ~mask) | (command & mask);
1193     if (command & KBD_DISABLE_KBD_PORT) {
1194 	if (!write_controller_command(p, KBDC_DISABLE_KBD_PORT))
1195 	    return FALSE;
1196     }
1197     if (!write_controller_command(p, KBDC_SET_COMMAND_BYTE))
1198 	return FALSE;
1199     if (!write_controller_data(p, command))
1200 	return FALSE;
1201     p->command_byte = command;
1202 
1203     if (verbose)
1204         log(LOG_DEBUG, "kbdc: new command byte:%04x (set_controller...)\n",
1205 	    command);
1206 
1207     return TRUE;
1208 }
1209 
1210 /*
1211  * Rudimentary support for active PS/2 AUX port multiplexing.
1212  * Only write commands can be routed to a selected AUX port.
1213  * Source port of data processed by read commands is totally ignored.
1214  */
1215 static int
1216 set_aux_mux_state(KBDC p, int enabled)
1217 {
1218 	int command, version;
1219 
1220 	if (write_controller_command(p, KBDC_FORCE_AUX_OUTPUT) == 0 ||
1221 	    write_controller_data(p, 0xF0) == 0 ||
1222 	    read_controller_data(p) != 0xF0)
1223 		return (-1);
1224 
1225 	if (write_controller_command(p, KBDC_FORCE_AUX_OUTPUT) == 0 ||
1226 	    write_controller_data(p, 0x56) == 0 ||
1227 	    read_controller_data(p) != 0x56)
1228 		return (-1);
1229 
1230 	command = enabled ? 0xa4 : 0xa5;
1231 	if (write_controller_command(p, KBDC_FORCE_AUX_OUTPUT) == 0 ||
1232 	    write_controller_data(p, command) == 0 ||
1233 	    (version = read_controller_data(p)) == command)
1234 		return (-1);
1235 
1236 	return (version);
1237 }
1238 
1239 int
1240 set_active_aux_mux_port(KBDC p, int port)
1241 {
1242 
1243 	if (!aux_mux_is_enabled(p))
1244 		return (FALSE);
1245 
1246 	if (port < 0 || port >= KBDC_AUX_MUX_NUM_PORTS)
1247 		return (FALSE);
1248 
1249 	p->aux_mux_port = port;
1250 
1251 	return (TRUE);
1252 }
1253 
1254 /* Checks for active multiplexing support and enables it */
1255 int
1256 enable_aux_mux(KBDC p)
1257 {
1258 	int version;
1259 
1260 	version = set_aux_mux_state(p, TRUE);
1261 	if (version >= 0) {
1262 		p->aux_mux_enabled = TRUE;
1263 		set_active_aux_mux_port(p, 0);
1264 	}
1265 
1266 	return (version);
1267 }
1268 
1269 int
1270 disable_aux_mux(KBDC p)
1271 {
1272 
1273 	p->aux_mux_enabled = FALSE;
1274 
1275 	return (set_aux_mux_state(p, FALSE));
1276 }
1277 
1278 int
1279 aux_mux_is_enabled(KBDC p)
1280 {
1281 
1282 	return (p->aux_mux_enabled);
1283 }
1284