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