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: stable/11/sys/dev/atkbdc/atkbdc.c 343158 2019-01-18 21:12:00Z wulf $");
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 */
95static atkbdc_softc_t default_kbdc;
96static atkbdc_softc_t *atkbdc_softc[MAXKBDC] = { &default_kbdc };
97
98static int verbose = KBDIO_DEBUG;
99
100#ifdef __sparc64__
101static struct bus_space_tag atkbdc_bst_store[MAXKBDC];
102#endif
103
104/* function prototypes */
105
106static int atkbdc_setup(atkbdc_softc_t *sc, bus_space_tag_t tag,
107			bus_space_handle_t h0, bus_space_handle_t h1);
108static int addq(kqueue *q, int c);
109static int removeq(kqueue *q);
110static int wait_while_controller_busy(atkbdc_softc_t *kbdc);
111static int wait_for_data(atkbdc_softc_t *kbdc);
112static int wait_for_kbd_data(atkbdc_softc_t *kbdc);
113static int wait_for_kbd_ack(atkbdc_softc_t *kbdc);
114static int wait_for_aux_data(atkbdc_softc_t *kbdc);
115static int wait_for_aux_ack(atkbdc_softc_t *kbdc);
116
117struct atkbdc_quirks {
118    const char* bios_vendor;
119    const char*	maker;
120    const char*	product;
121    int		quirk;
122};
123
124static 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
135static int
136atkbdc_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
152atkbdc_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
169int
170atkbdc_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
179int
180atkbdc_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 */
189int
190atkbdc_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
282static int
283atkbdc_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	    sc->aux_mux_enabled = FALSE;
298#if KBDIO_DEBUG >= 2
299	    sc->kbd.call_count = 0;
300	    sc->kbd.qcount = sc->kbd.max_qcount = 0;
301	    sc->aux.call_count = 0;
302	    sc->aux.qcount = sc->aux.max_qcount = 0;
303#endif
304	}
305	sc->iot = tag;
306	sc->ioh0 = h0;
307	sc->ioh1 = h1;
308
309#if defined(__amd64__)
310	/*
311	 * On certain chipsets AT keyboard controller isn't present and is
312	 * emulated by BIOS using SMI interrupt. On those chipsets reading
313	 * from the status port may be thousand times slower than usually.
314	 * Sometimes this emilation is not working properly resulting in
315	 * commands timing our and since we assume that inb() operation
316	 * takes very little time to complete we need to adjust number of
317	 * retries to keep waiting time within a designed limits (100ms).
318	 * Measure time it takes to make read_status() call and adjust
319	 * number of retries accordingly.
320	 */
321	flags = intr_disable();
322	tscval[0] = rdtsc();
323	read_status(sc);
324	tscval[1] = rdtsc();
325	DELAY(1000);
326	tscval[2] = rdtsc();
327	intr_restore(flags);
328	read_delay = tscval[1] - tscval[0];
329	read_delay /= (tscval[2] - tscval[1]) / 1000;
330	sc->retry = 100000 / ((KBDD_DELAYTIME * 2) + read_delay);
331#else
332	sc->retry = 5000;
333#endif
334	sc->quirks = atkbdc_getquirks();
335
336	return 0;
337}
338
339/* open a keyboard controller */
340KBDC
341atkbdc_open(int unit)
342{
343    if (unit <= 0)
344	unit = 0;
345    if (unit >= MAXKBDC)
346	return NULL;
347    if ((atkbdc_softc[unit]->port0 != NULL)
348	|| (atkbdc_softc[unit]->ioh0 != 0))		/* XXX */
349	return (KBDC)atkbdc_softc[unit];
350    return NULL;
351}
352
353/*
354 * I/O access arbitration in `kbdio'
355 *
356 * The `kbdio' module uses a simplistic convention to arbitrate
357 * I/O access to the controller/keyboard/mouse. The convention requires
358 * close cooperation of the calling device driver.
359 *
360 * The device drivers which utilize the `kbdio' module are assumed to
361 * have the following set of routines.
362 *    a. An interrupt handler (the bottom half of the driver).
363 *    b. Timeout routines which may briefly poll the keyboard controller.
364 *    c. Routines outside interrupt context (the top half of the driver).
365 * They should follow the rules below:
366 *    1. The interrupt handler may assume that it always has full access
367 *       to the controller/keyboard/mouse.
368 *    2. The other routines must issue `spltty()' if they wish to
369 *       prevent the interrupt handler from accessing
370 *       the controller/keyboard/mouse.
371 *    3. The timeout routines and the top half routines of the device driver
372 *       arbitrate I/O access by observing the lock flag in `kbdio'.
373 *       The flag is manipulated via `kbdc_lock()'; when one wants to
374 *       perform I/O, call `kbdc_lock(kbdc, TRUE)' and proceed only if
375 *       the call returns with TRUE. Otherwise the caller must back off.
376 *       Call `kbdc_lock(kbdc, FALSE)' when necessary I/O operaion
377 *       is finished. This mechanism does not prevent the interrupt
378 *       handler from being invoked at any time and carrying out I/O.
379 *       Therefore, `spltty()' must be strategically placed in the device
380 *       driver code. Also note that the timeout routine may interrupt
381 *       `kbdc_lock()' called by the top half of the driver, but this
382 *       interruption is OK so long as the timeout routine observes
383 *       rule 4 below.
384 *    4. The interrupt and timeout routines should not extend I/O operation
385 *       across more than one interrupt or timeout; they must complete any
386 *       necessary I/O operation within one invocation of the routine.
387 *       This means that if the timeout routine acquires the lock flag,
388 *       it must reset the flag to FALSE before it returns.
389 */
390
391/* set/reset polling lock */
392int
393kbdc_lock(KBDC p, int lock)
394{
395    int prevlock;
396
397    prevlock = kbdcp(p)->lock;
398    kbdcp(p)->lock = lock;
399
400    return (prevlock != lock);
401}
402
403/* check if any data is waiting to be processed */
404int
405kbdc_data_ready(KBDC p)
406{
407    return (availq(&kbdcp(p)->kbd) || availq(&kbdcp(p)->aux)
408	|| (read_status(kbdcp(p)) & KBDS_ANY_BUFFER_FULL));
409}
410
411/* queuing functions */
412
413static int
414addq(kqueue *q, int c)
415{
416    if (nextq(q->tail) != q->head) {
417	q->q[q->tail] = c;
418	q->tail = nextq(q->tail);
419#if KBDIO_DEBUG >= 2
420        ++q->call_count;
421        ++q->qcount;
422	if (q->qcount > q->max_qcount)
423            q->max_qcount = q->qcount;
424#endif
425	return TRUE;
426    }
427    return FALSE;
428}
429
430static int
431removeq(kqueue *q)
432{
433    int c;
434
435    if (q->tail != q->head) {
436	c = q->q[q->head];
437	q->head = nextq(q->head);
438#if KBDIO_DEBUG >= 2
439        --q->qcount;
440#endif
441	return c;
442    }
443    return -1;
444}
445
446/*
447 * device I/O routines
448 */
449static int
450wait_while_controller_busy(struct atkbdc_softc *kbdc)
451{
452    int retry;
453    int f;
454
455    /* CPU will stay inside the loop for 100msec at most */
456    retry = kbdc->retry;
457
458    while ((f = read_status(kbdc)) & KBDS_INPUT_BUFFER_FULL) {
459	if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) {
460	    DELAY(KBDD_DELAYTIME);
461	    addq(&kbdc->kbd, read_data(kbdc));
462	} else if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) {
463	    DELAY(KBDD_DELAYTIME);
464	    addq(&kbdc->aux, read_data(kbdc));
465	}
466        DELAY(KBDC_DELAYTIME);
467        if (--retry < 0)
468    	    return FALSE;
469    }
470    return TRUE;
471}
472
473/*
474 * wait for any data; whether it's from the controller,
475 * the keyboard, or the aux device.
476 */
477static int
478wait_for_data(struct atkbdc_softc *kbdc)
479{
480    int retry;
481    int f;
482
483    /* CPU will stay inside the loop for 200msec at most */
484    retry = kbdc->retry * 2;
485
486    while ((f = read_status(kbdc) & KBDS_ANY_BUFFER_FULL) == 0) {
487        DELAY(KBDC_DELAYTIME);
488        if (--retry < 0)
489    	    return 0;
490    }
491    DELAY(KBDD_DELAYTIME);
492    return f;
493}
494
495/* wait for data from the keyboard */
496static int
497wait_for_kbd_data(struct atkbdc_softc *kbdc)
498{
499    int retry;
500    int f;
501
502    /* CPU will stay inside the loop for 200msec at most */
503    retry = kbdc->retry * 2;
504
505    while ((f = read_status(kbdc) & KBDS_BUFFER_FULL)
506	    != KBDS_KBD_BUFFER_FULL) {
507        if (f == KBDS_AUX_BUFFER_FULL) {
508	    DELAY(KBDD_DELAYTIME);
509	    addq(&kbdc->aux, read_data(kbdc));
510	}
511        DELAY(KBDC_DELAYTIME);
512        if (--retry < 0)
513    	    return 0;
514    }
515    DELAY(KBDD_DELAYTIME);
516    return f;
517}
518
519/*
520 * wait for an ACK(FAh), RESEND(FEh), or RESET_FAIL(FCh) from the keyboard.
521 * queue anything else.
522 */
523static int
524wait_for_kbd_ack(struct atkbdc_softc *kbdc)
525{
526    int retry;
527    int f;
528    int b;
529
530    /* CPU will stay inside the loop for 200msec at most */
531    retry = kbdc->retry * 2;
532
533    while (retry-- > 0) {
534        if ((f = read_status(kbdc)) & KBDS_ANY_BUFFER_FULL) {
535	    DELAY(KBDD_DELAYTIME);
536            b = read_data(kbdc);
537	    if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) {
538		if ((b == KBD_ACK) || (b == KBD_RESEND)
539		    || (b == KBD_RESET_FAIL))
540		    return b;
541		addq(&kbdc->kbd, b);
542	    } else if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) {
543		addq(&kbdc->aux, b);
544	    }
545	}
546        DELAY(KBDC_DELAYTIME);
547    }
548    return -1;
549}
550
551/* wait for data from the aux device */
552static int
553wait_for_aux_data(struct atkbdc_softc *kbdc)
554{
555    int retry;
556    int f;
557
558    /* CPU will stay inside the loop for 200msec at most */
559    retry = kbdc->retry * 2;
560
561    while ((f = read_status(kbdc) & KBDS_BUFFER_FULL)
562	    != KBDS_AUX_BUFFER_FULL) {
563        if (f == KBDS_KBD_BUFFER_FULL) {
564	    DELAY(KBDD_DELAYTIME);
565	    addq(&kbdc->kbd, read_data(kbdc));
566	}
567        DELAY(KBDC_DELAYTIME);
568        if (--retry < 0)
569    	    return 0;
570    }
571    DELAY(KBDD_DELAYTIME);
572    return f;
573}
574
575/*
576 * wait for an ACK(FAh), RESEND(FEh), or RESET_FAIL(FCh) from the aux device.
577 * queue anything else.
578 */
579static int
580wait_for_aux_ack(struct atkbdc_softc *kbdc)
581{
582    int retry;
583    int f;
584    int b;
585
586    /* CPU will stay inside the loop for 200msec at most */
587    retry = kbdc->retry * 2;
588
589    while (retry-- > 0) {
590        if ((f = read_status(kbdc)) & KBDS_ANY_BUFFER_FULL) {
591	    DELAY(KBDD_DELAYTIME);
592            b = read_data(kbdc);
593	    if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) {
594		if ((b == PSM_ACK) || (b == PSM_RESEND)
595		    || (b == PSM_RESET_FAIL))
596		    return b;
597		addq(&kbdc->aux, b);
598	    } else if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) {
599		addq(&kbdc->kbd, b);
600	    }
601	}
602        DELAY(KBDC_DELAYTIME);
603    }
604    return -1;
605}
606
607/* write a one byte command to the controller */
608int
609write_controller_command(KBDC p, int c)
610{
611    if (!wait_while_controller_busy(kbdcp(p)))
612	return FALSE;
613    write_command(kbdcp(p), c);
614    return TRUE;
615}
616
617/* write a one byte data to the controller */
618int
619write_controller_data(KBDC p, int c)
620{
621    if (!wait_while_controller_busy(kbdcp(p)))
622	return FALSE;
623    write_data(kbdcp(p), c);
624    return TRUE;
625}
626
627/* write a one byte keyboard command */
628int
629write_kbd_command(KBDC p, int c)
630{
631    if (!wait_while_controller_busy(kbdcp(p)))
632	return FALSE;
633    write_data(kbdcp(p), c);
634    return TRUE;
635}
636
637/* write a one byte auxiliary device command */
638int
639write_aux_command(KBDC p, int c)
640{
641    int f;
642
643    f = aux_mux_is_enabled(p) ?
644        KBDC_WRITE_TO_AUX_MUX + kbdcp(p)->aux_mux_port : KBDC_WRITE_TO_AUX;
645
646    if (!write_controller_command(p, f))
647	return FALSE;
648    return write_controller_data(p, c);
649}
650
651/* send a command to the keyboard and wait for ACK */
652int
653send_kbd_command(KBDC p, int c)
654{
655    int retry = KBD_MAXRETRY;
656    int res = -1;
657
658    while (retry-- > 0) {
659	if (!write_kbd_command(p, c))
660	    continue;
661        res = wait_for_kbd_ack(kbdcp(p));
662        if (res == KBD_ACK)
663    	    break;
664    }
665    return res;
666}
667
668/* send a command to the auxiliary device and wait for ACK */
669int
670send_aux_command(KBDC p, int c)
671{
672    int retry = KBD_MAXRETRY;
673    int res = -1;
674
675    while (retry-- > 0) {
676	if (!write_aux_command(p, c))
677	    continue;
678	/*
679	 * FIXME: XXX
680	 * The aux device may have already sent one or two bytes of
681	 * status data, when a command is received. It will immediately
682	 * stop data transmission, thus, leaving an incomplete data
683	 * packet in our buffer. We have to discard any unprocessed
684	 * data in order to remove such packets. Well, we may remove
685	 * unprocessed, but necessary data byte as well...
686	 */
687	emptyq(&kbdcp(p)->aux);
688        res = wait_for_aux_ack(kbdcp(p));
689        if (res == PSM_ACK)
690    	    break;
691    }
692    return res;
693}
694
695/* send a command and a data to the keyboard, wait for ACKs */
696int
697send_kbd_command_and_data(KBDC p, int c, int d)
698{
699    int retry;
700    int res = -1;
701
702    for (retry = KBD_MAXRETRY; retry > 0; --retry) {
703	if (!write_kbd_command(p, c))
704	    continue;
705        res = wait_for_kbd_ack(kbdcp(p));
706        if (res == KBD_ACK)
707    	    break;
708        else if (res != KBD_RESEND)
709    	    return res;
710    }
711    if (retry <= 0)
712	return res;
713
714    for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) {
715	if (!write_kbd_command(p, d))
716	    continue;
717        res = wait_for_kbd_ack(kbdcp(p));
718        if (res != KBD_RESEND)
719    	    break;
720    }
721    return res;
722}
723
724/* send a command and a data to the auxiliary device, wait for ACKs */
725int
726send_aux_command_and_data(KBDC p, int c, int d)
727{
728    int retry;
729    int res = -1;
730
731    for (retry = KBD_MAXRETRY; retry > 0; --retry) {
732	if (!write_aux_command(p, c))
733	    continue;
734	emptyq(&kbdcp(p)->aux);
735        res = wait_for_aux_ack(kbdcp(p));
736        if (res == PSM_ACK)
737    	    break;
738        else if (res != PSM_RESEND)
739    	    return res;
740    }
741    if (retry <= 0)
742	return res;
743
744    for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) {
745	if (!write_aux_command(p, d))
746	    continue;
747        res = wait_for_aux_ack(kbdcp(p));
748        if (res != PSM_RESEND)
749    	    break;
750    }
751    return res;
752}
753
754/*
755 * read one byte from any source; whether from the controller,
756 * the keyboard, or the aux device
757 */
758int
759read_controller_data(KBDC p)
760{
761    if (availq(&kbdcp(p)->kbd))
762        return removeq(&kbdcp(p)->kbd);
763    if (availq(&kbdcp(p)->aux))
764        return removeq(&kbdcp(p)->aux);
765    if (!wait_for_data(kbdcp(p)))
766        return -1;		/* timeout */
767    return read_data(kbdcp(p));
768}
769
770#if KBDIO_DEBUG >= 2
771static int call = 0;
772#endif
773
774/* read one byte from the keyboard */
775int
776read_kbd_data(KBDC p)
777{
778#if KBDIO_DEBUG >= 2
779    if (++call > 2000) {
780	call = 0;
781	log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, "
782			     "aux q: %d calls, max %d chars\n",
783		       kbdcp(p)->kbd.call_count, kbdcp(p)->kbd.max_qcount,
784		       kbdcp(p)->aux.call_count, kbdcp(p)->aux.max_qcount);
785    }
786#endif
787
788    if (availq(&kbdcp(p)->kbd))
789        return removeq(&kbdcp(p)->kbd);
790    if (!wait_for_kbd_data(kbdcp(p)))
791        return -1;		/* timeout */
792    return read_data(kbdcp(p));
793}
794
795/* read one byte from the keyboard, but return immediately if
796 * no data is waiting
797 */
798int
799read_kbd_data_no_wait(KBDC p)
800{
801    int f;
802
803#if KBDIO_DEBUG >= 2
804    if (++call > 2000) {
805	call = 0;
806	log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, "
807			     "aux q: %d calls, max %d chars\n",
808		       kbdcp(p)->kbd.call_count, kbdcp(p)->kbd.max_qcount,
809		       kbdcp(p)->aux.call_count, kbdcp(p)->aux.max_qcount);
810    }
811#endif
812
813    if (availq(&kbdcp(p)->kbd))
814        return removeq(&kbdcp(p)->kbd);
815    f = read_status(kbdcp(p)) & KBDS_BUFFER_FULL;
816    if (f == KBDS_AUX_BUFFER_FULL) {
817        DELAY(KBDD_DELAYTIME);
818        addq(&kbdcp(p)->aux, read_data(kbdcp(p)));
819        f = read_status(kbdcp(p)) & KBDS_BUFFER_FULL;
820    }
821    if (f == KBDS_KBD_BUFFER_FULL) {
822        DELAY(KBDD_DELAYTIME);
823        return read_data(kbdcp(p));
824    }
825    return -1;		/* no data */
826}
827
828/* read one byte from the aux device */
829int
830read_aux_data(KBDC p)
831{
832    if (availq(&kbdcp(p)->aux))
833        return removeq(&kbdcp(p)->aux);
834    if (!wait_for_aux_data(kbdcp(p)))
835        return -1;		/* timeout */
836    return read_data(kbdcp(p));
837}
838
839/* read one byte from the aux device, but return immediately if
840 * no data is waiting
841 */
842int
843read_aux_data_no_wait(KBDC p)
844{
845    int f;
846
847    if (availq(&kbdcp(p)->aux))
848        return removeq(&kbdcp(p)->aux);
849    f = read_status(kbdcp(p)) & KBDS_BUFFER_FULL;
850    if (f == KBDS_KBD_BUFFER_FULL) {
851        DELAY(KBDD_DELAYTIME);
852        addq(&kbdcp(p)->kbd, read_data(kbdcp(p)));
853        f = read_status(kbdcp(p)) & KBDS_BUFFER_FULL;
854    }
855    if (f == KBDS_AUX_BUFFER_FULL) {
856        DELAY(KBDD_DELAYTIME);
857        return read_data(kbdcp(p));
858    }
859    return -1;		/* no data */
860}
861
862/* discard data from the keyboard */
863void
864empty_kbd_buffer(KBDC p, int wait)
865{
866    int t;
867    int b;
868    int f;
869#if KBDIO_DEBUG >= 2
870    int c1 = 0;
871    int c2 = 0;
872#endif
873    int delta = 2;
874
875    for (t = wait; t > 0; ) {
876        if ((f = read_status(kbdcp(p))) & KBDS_ANY_BUFFER_FULL) {
877	    DELAY(KBDD_DELAYTIME);
878            b = read_data(kbdcp(p));
879	    if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) {
880		addq(&kbdcp(p)->aux, b);
881#if KBDIO_DEBUG >= 2
882		++c2;
883            } else {
884		++c1;
885#endif
886	    }
887	    t = wait;
888	} else {
889	    t -= delta;
890	}
891        DELAY(delta*1000);
892    }
893#if KBDIO_DEBUG >= 2
894    if ((c1 > 0) || (c2 > 0))
895        log(LOG_DEBUG, "kbdc: %d:%d char read (empty_kbd_buffer)\n", c1, c2);
896#endif
897
898    emptyq(&kbdcp(p)->kbd);
899}
900
901/* discard data from the aux device */
902void
903empty_aux_buffer(KBDC p, int wait)
904{
905    int t;
906    int b;
907    int f;
908#if KBDIO_DEBUG >= 2
909    int c1 = 0;
910    int c2 = 0;
911#endif
912    int delta = 2;
913
914    for (t = wait; t > 0; ) {
915        if ((f = read_status(kbdcp(p))) & KBDS_ANY_BUFFER_FULL) {
916	    DELAY(KBDD_DELAYTIME);
917            b = read_data(kbdcp(p));
918	    if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) {
919		addq(&kbdcp(p)->kbd, b);
920#if KBDIO_DEBUG >= 2
921		++c1;
922            } else {
923		++c2;
924#endif
925	    }
926	    t = wait;
927	} else {
928	    t -= delta;
929	}
930	DELAY(delta*1000);
931    }
932#if KBDIO_DEBUG >= 2
933    if ((c1 > 0) || (c2 > 0))
934        log(LOG_DEBUG, "kbdc: %d:%d char read (empty_aux_buffer)\n", c1, c2);
935#endif
936
937    emptyq(&kbdcp(p)->aux);
938}
939
940/* discard any data from the keyboard or the aux device */
941void
942empty_both_buffers(KBDC p, int wait)
943{
944    int t;
945    int f;
946    int waited = 0;
947#if KBDIO_DEBUG >= 2
948    int c1 = 0;
949    int c2 = 0;
950#endif
951    int delta = 2;
952
953    for (t = wait; t > 0; ) {
954        if ((f = read_status(kbdcp(p))) & KBDS_ANY_BUFFER_FULL) {
955	    DELAY(KBDD_DELAYTIME);
956            (void)read_data(kbdcp(p));
957#if KBDIO_DEBUG >= 2
958	    if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL)
959		++c1;
960            else
961		++c2;
962#endif
963	    t = wait;
964	} else {
965	    t -= delta;
966	}
967
968	/*
969	 * Some systems (Intel/IBM blades) do not have keyboard devices and
970	 * will thus hang in this procedure. Time out after delta seconds to
971	 * avoid this hang -- the keyboard attach will fail later on.
972	 */
973        waited += (delta * 1000);
974        if (waited == (delta * 1000000))
975	    return;
976
977	DELAY(delta*1000);
978    }
979#if KBDIO_DEBUG >= 2
980    if ((c1 > 0) || (c2 > 0))
981        log(LOG_DEBUG, "kbdc: %d:%d char read (empty_both_buffers)\n", c1, c2);
982#endif
983
984    emptyq(&kbdcp(p)->kbd);
985    emptyq(&kbdcp(p)->aux);
986}
987
988/* keyboard and mouse device control */
989
990/* NOTE: enable the keyboard port but disable the keyboard
991 * interrupt before calling "reset_kbd()".
992 */
993int
994reset_kbd(KBDC p)
995{
996    int retry = KBD_MAXRETRY;
997    int again = KBD_MAXWAIT;
998    int c = KBD_RESEND;		/* keep the compiler happy */
999
1000    while (retry-- > 0) {
1001        empty_both_buffers(p, 10);
1002        if (!write_kbd_command(p, KBDC_RESET_KBD))
1003	    continue;
1004	emptyq(&kbdcp(p)->kbd);
1005        c = read_controller_data(p);
1006	if (verbose || bootverbose)
1007            log(LOG_DEBUG, "kbdc: RESET_KBD return code:%04x\n", c);
1008        if (c == KBD_ACK)	/* keyboard has agreed to reset itself... */
1009    	    break;
1010    }
1011    if (retry < 0)
1012        return FALSE;
1013
1014    while (again-- > 0) {
1015        /* wait awhile, well, in fact we must wait quite loooooooooooong */
1016        DELAY(KBD_RESETDELAY*1000);
1017        c = read_controller_data(p);	/* RESET_DONE/RESET_FAIL */
1018        if (c != -1) 	/* wait again if the controller is not ready */
1019    	    break;
1020    }
1021    if (verbose || bootverbose)
1022        log(LOG_DEBUG, "kbdc: RESET_KBD status:%04x\n", c);
1023    if (c != KBD_RESET_DONE)
1024        return FALSE;
1025    return TRUE;
1026}
1027
1028/* NOTE: enable the aux port but disable the aux interrupt
1029 * before calling `reset_aux_dev()'.
1030 */
1031int
1032reset_aux_dev(KBDC p)
1033{
1034    int retry = KBD_MAXRETRY;
1035    int again = KBD_MAXWAIT;
1036    int c = PSM_RESEND;		/* keep the compiler happy */
1037
1038    while (retry-- > 0) {
1039        empty_both_buffers(p, 10);
1040        if (!write_aux_command(p, PSMC_RESET_DEV))
1041	    continue;
1042	emptyq(&kbdcp(p)->aux);
1043	/* NOTE: Compaq Armada laptops require extra delay here. XXX */
1044	for (again = KBD_MAXWAIT; again > 0; --again) {
1045            DELAY(KBD_RESETDELAY*1000);
1046            c = read_aux_data_no_wait(p);
1047	    if (c != -1)
1048		break;
1049	}
1050        if (verbose || bootverbose)
1051            log(LOG_DEBUG, "kbdc: RESET_AUX return code:%04x\n", c);
1052        if (c == PSM_ACK)	/* aux dev is about to reset... */
1053    	    break;
1054    }
1055    if (retry < 0)
1056        return FALSE;
1057
1058    for (again = KBD_MAXWAIT; again > 0; --again) {
1059        /* wait awhile, well, quite looooooooooooong */
1060        DELAY(KBD_RESETDELAY*1000);
1061        c = read_aux_data_no_wait(p);	/* RESET_DONE/RESET_FAIL */
1062        if (c != -1) 	/* wait again if the controller is not ready */
1063    	    break;
1064    }
1065    if (verbose || bootverbose)
1066        log(LOG_DEBUG, "kbdc: RESET_AUX status:%04x\n", c);
1067    if (c != PSM_RESET_DONE)	/* reset status */
1068        return FALSE;
1069
1070    c = read_aux_data(p);	/* device ID */
1071    if (verbose || bootverbose)
1072        log(LOG_DEBUG, "kbdc: RESET_AUX ID:%04x\n", c);
1073    /* NOTE: we could check the device ID now, but leave it later... */
1074    return TRUE;
1075}
1076
1077/* controller diagnostics and setup */
1078
1079int
1080test_controller(KBDC p)
1081{
1082    int retry = KBD_MAXRETRY;
1083    int again = KBD_MAXWAIT;
1084    int c = KBD_DIAG_FAIL;
1085
1086    while (retry-- > 0) {
1087        empty_both_buffers(p, 10);
1088        if (write_controller_command(p, KBDC_DIAGNOSE))
1089    	    break;
1090    }
1091    if (retry < 0)
1092        return FALSE;
1093
1094    emptyq(&kbdcp(p)->kbd);
1095    while (again-- > 0) {
1096        /* wait awhile */
1097        DELAY(KBD_RESETDELAY*1000);
1098        c = read_controller_data(p);	/* DIAG_DONE/DIAG_FAIL */
1099        if (c != -1) 	/* wait again if the controller is not ready */
1100    	    break;
1101    }
1102    if (verbose || bootverbose)
1103        log(LOG_DEBUG, "kbdc: DIAGNOSE status:%04x\n", c);
1104    return (c == KBD_DIAG_DONE);
1105}
1106
1107int
1108test_kbd_port(KBDC p)
1109{
1110    int retry = KBD_MAXRETRY;
1111    int again = KBD_MAXWAIT;
1112    int c = -1;
1113
1114    while (retry-- > 0) {
1115        empty_both_buffers(p, 10);
1116        if (write_controller_command(p, KBDC_TEST_KBD_PORT))
1117    	    break;
1118    }
1119    if (retry < 0)
1120        return FALSE;
1121
1122    emptyq(&kbdcp(p)->kbd);
1123    while (again-- > 0) {
1124        c = read_controller_data(p);
1125        if (c != -1) 	/* try again if the controller is not ready */
1126    	    break;
1127    }
1128    if (verbose || bootverbose)
1129        log(LOG_DEBUG, "kbdc: TEST_KBD_PORT status:%04x\n", c);
1130    return c;
1131}
1132
1133int
1134test_aux_port(KBDC p)
1135{
1136    int retry = KBD_MAXRETRY;
1137    int again = KBD_MAXWAIT;
1138    int c = -1;
1139
1140    while (retry-- > 0) {
1141        empty_both_buffers(p, 10);
1142        if (write_controller_command(p, KBDC_TEST_AUX_PORT))
1143    	    break;
1144    }
1145    if (retry < 0)
1146        return FALSE;
1147
1148    emptyq(&kbdcp(p)->kbd);
1149    while (again-- > 0) {
1150        c = read_controller_data(p);
1151        if (c != -1) 	/* try again if the controller is not ready */
1152    	    break;
1153    }
1154    if (verbose || bootverbose)
1155        log(LOG_DEBUG, "kbdc: TEST_AUX_PORT status:%04x\n", c);
1156    return c;
1157}
1158
1159int
1160kbdc_get_device_mask(KBDC p)
1161{
1162    return kbdcp(p)->command_mask;
1163}
1164
1165void
1166kbdc_set_device_mask(KBDC p, int mask)
1167{
1168    kbdcp(p)->command_mask =
1169	mask & (((kbdcp(p)->quirks & KBDC_QUIRK_KEEP_ACTIVATED)
1170	    ? 0 : KBD_KBD_CONTROL_BITS) | KBD_AUX_CONTROL_BITS);
1171}
1172
1173int
1174get_controller_command_byte(KBDC p)
1175{
1176    if (kbdcp(p)->command_byte != -1)
1177	return kbdcp(p)->command_byte;
1178    if (!write_controller_command(p, KBDC_GET_COMMAND_BYTE))
1179	return -1;
1180    emptyq(&kbdcp(p)->kbd);
1181    kbdcp(p)->command_byte = read_controller_data(p);
1182    return kbdcp(p)->command_byte;
1183}
1184
1185int
1186set_controller_command_byte(KBDC p, int mask, int command)
1187{
1188    if (get_controller_command_byte(p) == -1)
1189	return FALSE;
1190
1191    command = (kbdcp(p)->command_byte & ~mask) | (command & mask);
1192    if (command & KBD_DISABLE_KBD_PORT) {
1193	if (!write_controller_command(p, KBDC_DISABLE_KBD_PORT))
1194	    return FALSE;
1195    }
1196    if (!write_controller_command(p, KBDC_SET_COMMAND_BYTE))
1197	return FALSE;
1198    if (!write_controller_data(p, command))
1199	return FALSE;
1200    kbdcp(p)->command_byte = command;
1201
1202    if (verbose)
1203        log(LOG_DEBUG, "kbdc: new command byte:%04x (set_controller...)\n",
1204	    command);
1205
1206    return TRUE;
1207}
1208
1209/*
1210 * Rudimentary support for active PS/2 AUX port multiplexing.
1211 * Only write commands can be routed to a selected AUX port.
1212 * Source port of data processed by read commands is totally ignored.
1213 */
1214static int
1215set_aux_mux_state(KBDC p, int enabled)
1216{
1217	int command, version;
1218
1219	if (write_controller_command(p, KBDC_FORCE_AUX_OUTPUT) == 0 ||
1220	    write_controller_data(p, 0xF0) == 0 ||
1221	    read_controller_data(p) != 0xF0)
1222		return (-1);
1223
1224	if (write_controller_command(p, KBDC_FORCE_AUX_OUTPUT) == 0 ||
1225	    write_controller_data(p, 0x56) == 0 ||
1226	    read_controller_data(p) != 0x56)
1227		return (-1);
1228
1229	command = enabled ? 0xa4 : 0xa5;
1230	if (write_controller_command(p, KBDC_FORCE_AUX_OUTPUT) == 0 ||
1231	    write_controller_data(p, command) == 0 ||
1232	    (version = read_controller_data(p)) == command)
1233		return (-1);
1234
1235	return (version);
1236}
1237
1238int
1239set_active_aux_mux_port(KBDC p, int port)
1240{
1241
1242	if (!aux_mux_is_enabled(p))
1243		return (FALSE);
1244
1245	if (port < 0 || port >= KBDC_AUX_MUX_NUM_PORTS)
1246		return (FALSE);
1247
1248	kbdcp(p)->aux_mux_port = port;
1249
1250	return (TRUE);
1251}
1252
1253/* Checks for active multiplexing support and enables it */
1254int
1255enable_aux_mux(KBDC p)
1256{
1257	int version;
1258
1259	version = set_aux_mux_state(p, TRUE);
1260	if (version >= 0) {
1261		kbdcp(p)->aux_mux_enabled = TRUE;
1262		set_active_aux_mux_port(p, 0);
1263	}
1264
1265	return (version);
1266}
1267
1268int
1269disable_aux_mux(KBDC p)
1270{
1271
1272	kbdcp(p)->aux_mux_enabled = FALSE;
1273
1274	return (set_aux_mux_state(p, FALSE));
1275}
1276
1277int
1278aux_mux_is_enabled(KBDC p)
1279{
1280
1281	return (kbdcp(p)->aux_mux_enabled);
1282}
1283