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