1/*-
2 * Copyright (c) 1999 Kazutaka YOKOTA <yokota@zodiac.mech.utsunomiya-u.ac.jp>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer as
10 *    the first lines of this file unmodified.
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 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 *
26 */
27
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD$");
30
31#include "opt_compat.h"
32#include "opt_kbd.h"
33#include "opt_atkbd.h"
34
35#include <sys/param.h>
36#include <sys/systm.h>
37#include <sys/kernel.h>
38#include <sys/bus.h>
39#include <sys/eventhandler.h>
40#include <sys/proc.h>
41#include <sys/limits.h>
42#include <sys/malloc.h>
43
44#include <machine/bus.h>
45#include <machine/resource.h>
46
47#if defined(__i386__) || defined(__amd64__)
48#include <machine/md_var.h>
49#include <machine/psl.h>
50#include <compat/x86bios/x86bios.h>
51#include <machine/pc/bios.h>
52
53#include <vm/vm.h>
54#include <vm/pmap.h>
55#include <vm/vm_param.h>
56
57#include <isa/isareg.h>
58#endif /* __i386__ || __amd64__ */
59
60#include <sys/kbio.h>
61#include <dev/kbd/kbdreg.h>
62#include <dev/atkbdc/atkbdreg.h>
63#include <dev/atkbdc/atkbdcreg.h>
64
65static timeout_t	atkbd_timeout;
66static void		atkbd_shutdown_final(void *v);
67
68int
69atkbd_probe_unit(device_t dev, int irq, int flags)
70{
71	keyboard_switch_t *sw;
72	int args[2];
73	int error;
74
75	sw = kbd_get_switch(ATKBD_DRIVER_NAME);
76	if (sw == NULL)
77		return ENXIO;
78
79	args[0] = device_get_unit(device_get_parent(dev));
80	args[1] = irq;
81	error = (*sw->probe)(device_get_unit(dev), args, flags);
82	if (error)
83		return error;
84	return 0;
85}
86
87int
88atkbd_attach_unit(device_t dev, keyboard_t **kbd, int irq, int flags)
89{
90	keyboard_switch_t *sw;
91	int args[2];
92	int error;
93	int unit;
94
95	sw = kbd_get_switch(ATKBD_DRIVER_NAME);
96	if (sw == NULL)
97		return ENXIO;
98
99	/* reset, initialize and enable the device */
100	unit = device_get_unit(dev);
101	args[0] = device_get_unit(device_get_parent(dev));
102	args[1] = irq;
103	*kbd = NULL;
104	error = (*sw->probe)(unit, args, flags);
105	if (error)
106		return error;
107	error = (*sw->init)(unit, kbd, args, flags);
108	if (error)
109		return error;
110	(*sw->enable)(*kbd);
111
112#ifdef KBD_INSTALL_CDEV
113	/* attach a virtual keyboard cdev */
114	error = kbd_attach(*kbd);
115	if (error)
116		return error;
117#endif
118
119	/*
120	 * This is a kludge to compensate for lost keyboard interrupts.
121	 * A similar code used to be in syscons. See below. XXX
122	 */
123	atkbd_timeout(*kbd);
124
125	if (bootverbose)
126		(*sw->diag)(*kbd, bootverbose);
127
128	EVENTHANDLER_REGISTER(shutdown_final, atkbd_shutdown_final, *kbd,
129	    SHUTDOWN_PRI_DEFAULT);
130
131	return 0;
132}
133
134static void
135atkbd_timeout(void *arg)
136{
137	keyboard_t *kbd;
138	int s;
139
140	/*
141	 * The original text of the following comments are extracted
142	 * from syscons.c (1.287)
143	 *
144	 * With release 2.1 of the Xaccel server, the keyboard is left
145	 * hanging pretty often. Apparently an interrupt from the
146	 * keyboard is lost, and I don't know why (yet).
147	 * This ugly hack calls the low-level interrupt routine if input
148	 * is ready for the keyboard and conveniently hides the problem. XXX
149	 *
150	 * Try removing anything stuck in the keyboard controller; whether
151	 * it's a keyboard scan code or mouse data. The low-level
152	 * interrupt routine doesn't read the mouse data directly,
153	 * but the keyboard controller driver will, as a side effect.
154	 */
155	/*
156	 * And here is bde's original comment about this:
157	 *
158	 * This is necessary to handle edge triggered interrupts - if we
159	 * returned when our IRQ is high due to unserviced input, then there
160	 * would be no more keyboard IRQs until the keyboard is reset by
161	 * external powers.
162	 *
163	 * The keyboard apparently unwedges the irq in most cases.
164	 */
165	s = spltty();
166	kbd = (keyboard_t *)arg;
167	if (kbdd_lock(kbd, TRUE)) {
168		/*
169		 * We have seen the lock flag is not set. Let's reset
170		 * the flag early, otherwise the LED update routine fails
171		 * which may want the lock during the interrupt routine.
172		 */
173		kbdd_lock(kbd, FALSE);
174		if (kbdd_check_char(kbd))
175			kbdd_intr(kbd, NULL);
176	}
177	splx(s);
178	timeout(atkbd_timeout, arg, hz/10);
179}
180
181/* LOW-LEVEL */
182
183#define ATKBD_DEFAULT	0
184
185typedef struct atkbd_state {
186	KBDC		kbdc;		/* keyboard controller */
187	int		ks_mode;	/* input mode (K_XLATE,K_RAW,K_CODE) */
188	int		ks_flags;	/* flags */
189#define COMPOSE		(1 << 0)
190	int		ks_polling;
191	int		ks_state;	/* shift/lock key state */
192	int		ks_accents;	/* accent key index (> 0) */
193	u_int		ks_composed_char; /* composed char code (> 0) */
194	u_char		ks_prefix;	/* AT scan code prefix */
195} atkbd_state_t;
196
197/* keyboard driver declaration */
198static int		atkbd_configure(int flags);
199static kbd_probe_t	atkbd_probe;
200static kbd_init_t	atkbd_init;
201static kbd_term_t	atkbd_term;
202static kbd_intr_t	atkbd_intr;
203static kbd_test_if_t	atkbd_test_if;
204static kbd_enable_t	atkbd_enable;
205static kbd_disable_t	atkbd_disable;
206static kbd_read_t	atkbd_read;
207static kbd_check_t	atkbd_check;
208static kbd_read_char_t	atkbd_read_char;
209static kbd_check_char_t	atkbd_check_char;
210static kbd_ioctl_t	atkbd_ioctl;
211static kbd_lock_t	atkbd_lock;
212static kbd_clear_state_t atkbd_clear_state;
213static kbd_get_state_t	atkbd_get_state;
214static kbd_set_state_t	atkbd_set_state;
215static kbd_poll_mode_t	atkbd_poll;
216
217static keyboard_switch_t atkbdsw = {
218	atkbd_probe,
219	atkbd_init,
220	atkbd_term,
221	atkbd_intr,
222	atkbd_test_if,
223	atkbd_enable,
224	atkbd_disable,
225	atkbd_read,
226	atkbd_check,
227	atkbd_read_char,
228	atkbd_check_char,
229	atkbd_ioctl,
230	atkbd_lock,
231	atkbd_clear_state,
232	atkbd_get_state,
233	atkbd_set_state,
234	genkbd_get_fkeystr,
235	atkbd_poll,
236	genkbd_diag,
237};
238
239KEYBOARD_DRIVER(atkbd, atkbdsw, atkbd_configure);
240
241/* local functions */
242static int		get_typematic(keyboard_t *kbd);
243static int		setup_kbd_port(KBDC kbdc, int port, int intr);
244static int		get_kbd_echo(KBDC kbdc);
245static int		probe_keyboard(KBDC kbdc, int flags);
246static int		init_keyboard(KBDC kbdc, int *type, int flags);
247static int		write_kbd(KBDC kbdc, int command, int data);
248static int		get_kbd_id(KBDC kbdc);
249static int		typematic(int delay, int rate);
250static int		typematic_delay(int delay);
251static int		typematic_rate(int rate);
252
253/* local variables */
254
255/* the initial key map, accent map and fkey strings */
256#ifdef ATKBD_DFLT_KEYMAP
257#define KBD_DFLT_KEYMAP
258#include "atkbdmap.h"
259#endif
260#include <dev/kbd/kbdtables.h>
261
262/* structures for the default keyboard */
263static keyboard_t	default_kbd;
264static atkbd_state_t	default_kbd_state;
265static keymap_t		default_keymap;
266static accentmap_t	default_accentmap;
267static fkeytab_t	default_fkeytab[NUM_FKEYS];
268
269/*
270 * The back door to the keyboard driver!
271 * This function is called by the console driver, via the kbdio module,
272 * to tickle keyboard drivers when the low-level console is being initialized.
273 * Almost nothing in the kernel has been initialied yet.  Try to probe
274 * keyboards if possible.
275 * NOTE: because of the way the low-level console is initialized, this routine
276 * may be called more than once!!
277 */
278static int
279atkbd_configure(int flags)
280{
281	keyboard_t *kbd;
282	int arg[2];
283	int i;
284
285	/*
286	 * Probe the keyboard controller, if not present or if the driver
287	 * is disabled, unregister the keyboard if any.
288	 */
289	if (atkbdc_configure() != 0 ||
290	    resource_disabled("atkbd", ATKBD_DEFAULT)) {
291		i = kbd_find_keyboard(ATKBD_DRIVER_NAME, ATKBD_DEFAULT);
292		if (i >= 0) {
293			kbd = kbd_get_keyboard(i);
294			kbd_unregister(kbd);
295			kbd->kb_flags &= ~KB_REGISTERED;
296		}
297		return 0;
298	}
299
300	/* XXX: a kludge to obtain the device configuration flags */
301	if (resource_int_value("atkbd", ATKBD_DEFAULT, "flags", &i) == 0)
302		flags |= i;
303
304	/* probe the default keyboard */
305	arg[0] = -1;
306	arg[1] = -1;
307	kbd = NULL;
308	if (atkbd_probe(ATKBD_DEFAULT, arg, flags))
309		return 0;
310	if (atkbd_init(ATKBD_DEFAULT, &kbd, arg, flags))
311		return 0;
312
313	/* return the number of found keyboards */
314	return 1;
315}
316
317/* low-level functions */
318
319/* detect a keyboard */
320static int
321atkbd_probe(int unit, void *arg, int flags)
322{
323	KBDC kbdc;
324	int *data = (int *)arg;	/* data[0]: controller, data[1]: irq */
325
326	/* XXX */
327	if (unit == ATKBD_DEFAULT) {
328		if (KBD_IS_PROBED(&default_kbd))
329			return 0;
330	}
331
332	kbdc = atkbdc_open(data[0]);
333	if (kbdc == NULL)
334		return ENXIO;
335	if (probe_keyboard(kbdc, flags)) {
336		if (flags & KB_CONF_FAIL_IF_NO_KBD)
337			return ENXIO;
338	}
339	return 0;
340}
341
342/* reset and initialize the device */
343static int
344atkbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
345{
346	keyboard_t *kbd;
347	atkbd_state_t *state;
348	keymap_t *keymap;
349	accentmap_t *accmap;
350	fkeytab_t *fkeymap;
351	int fkeymap_size;
352	int delay[2];
353	int *data = (int *)arg;	/* data[0]: controller, data[1]: irq */
354	int error, needfree;
355
356	/* XXX */
357	if (unit == ATKBD_DEFAULT) {
358		*kbdp = kbd = &default_kbd;
359		if (KBD_IS_INITIALIZED(kbd) && KBD_IS_CONFIGURED(kbd))
360			return 0;
361		state = &default_kbd_state;
362		keymap = &default_keymap;
363		accmap = &default_accentmap;
364		fkeymap = default_fkeytab;
365		fkeymap_size =
366			sizeof(default_fkeytab)/sizeof(default_fkeytab[0]);
367		needfree = 0;
368	} else if (*kbdp == NULL) {
369		*kbdp = kbd = malloc(sizeof(*kbd), M_DEVBUF, M_NOWAIT | M_ZERO);
370		state = malloc(sizeof(*state), M_DEVBUF, M_NOWAIT | M_ZERO);
371		/* NB: these will always be initialized 'cuz !KBD_IS_PROBED */
372		keymap = malloc(sizeof(key_map), M_DEVBUF, M_NOWAIT);
373		accmap = malloc(sizeof(accent_map), M_DEVBUF, M_NOWAIT);
374		fkeymap = malloc(sizeof(fkey_tab), M_DEVBUF, M_NOWAIT);
375		fkeymap_size = sizeof(fkey_tab)/sizeof(fkey_tab[0]);
376		needfree = 1;
377		if ((kbd == NULL) || (state == NULL) || (keymap == NULL)
378		     || (accmap == NULL) || (fkeymap == NULL)) {
379			error = ENOMEM;
380			goto bad;
381		}
382	} else if (KBD_IS_INITIALIZED(*kbdp) && KBD_IS_CONFIGURED(*kbdp)) {
383		return 0;
384	} else {
385		kbd = *kbdp;
386		state = (atkbd_state_t *)kbd->kb_data;
387		bzero(state, sizeof(*state));
388		keymap = kbd->kb_keymap;
389		accmap = kbd->kb_accentmap;
390		fkeymap = kbd->kb_fkeytab;
391		fkeymap_size = kbd->kb_fkeytab_size;
392		needfree = 0;
393	}
394
395	if (!KBD_IS_PROBED(kbd)) {
396		state->kbdc = atkbdc_open(data[0]);
397		if (state->kbdc == NULL) {
398			error = ENXIO;
399			goto bad;
400		}
401		kbd_init_struct(kbd, ATKBD_DRIVER_NAME, KB_OTHER, unit, flags,
402				0, 0);
403		bcopy(&key_map, keymap, sizeof(key_map));
404		bcopy(&accent_map, accmap, sizeof(accent_map));
405		bcopy(fkey_tab, fkeymap,
406		    imin(fkeymap_size * sizeof(fkeymap[0]), sizeof(fkey_tab)));
407		kbd_set_maps(kbd, keymap, accmap, fkeymap, fkeymap_size);
408		kbd->kb_data = (void *)state;
409
410		if (probe_keyboard(state->kbdc, flags)) { /* shouldn't happen */
411			if (flags & KB_CONF_FAIL_IF_NO_KBD) {
412				error = ENXIO;
413				goto bad;
414			}
415		} else {
416			KBD_FOUND_DEVICE(kbd);
417		}
418		atkbd_clear_state(kbd);
419		state->ks_mode = K_XLATE;
420		/*
421		 * FIXME: set the initial value for lock keys in ks_state
422		 * according to the BIOS data?
423		 */
424		KBD_PROBE_DONE(kbd);
425	}
426	if (!KBD_IS_INITIALIZED(kbd) && !(flags & KB_CONF_PROBE_ONLY)) {
427		kbd->kb_config = flags & ~KB_CONF_PROBE_ONLY;
428		if (KBD_HAS_DEVICE(kbd)
429		    && init_keyboard(state->kbdc, &kbd->kb_type, kbd->kb_config)
430		    && (kbd->kb_config & KB_CONF_FAIL_IF_NO_KBD)) {
431			kbd_unregister(kbd);
432			error = ENXIO;
433			goto bad;
434		}
435		atkbd_ioctl(kbd, KDSETLED, (caddr_t)&state->ks_state);
436		get_typematic(kbd);
437		delay[0] = kbd->kb_delay1;
438		delay[1] = kbd->kb_delay2;
439		atkbd_ioctl(kbd, KDSETREPEAT, (caddr_t)delay);
440		KBD_INIT_DONE(kbd);
441	}
442	if (!KBD_IS_CONFIGURED(kbd)) {
443		if (kbd_register(kbd) < 0) {
444			error = ENXIO;
445			goto bad;
446		}
447		KBD_CONFIG_DONE(kbd);
448	}
449
450	return 0;
451bad:
452	if (needfree) {
453		if (state != NULL)
454			free(state, M_DEVBUF);
455		if (keymap != NULL)
456			free(keymap, M_DEVBUF);
457		if (accmap != NULL)
458			free(accmap, M_DEVBUF);
459		if (fkeymap != NULL)
460			free(fkeymap, M_DEVBUF);
461		if (kbd != NULL) {
462			free(kbd, M_DEVBUF);
463			*kbdp = NULL;	/* insure ref doesn't leak to caller */
464		}
465	}
466	return error;
467}
468
469/* finish using this keyboard */
470static int
471atkbd_term(keyboard_t *kbd)
472{
473	kbd_unregister(kbd);
474	return 0;
475}
476
477/* keyboard interrupt routine */
478static int
479atkbd_intr(keyboard_t *kbd, void *arg)
480{
481	atkbd_state_t *state = (atkbd_state_t *)kbd->kb_data;
482	int delay[2];
483	int c;
484
485	if (!KBD_HAS_DEVICE(kbd)) {
486		/*
487		 * The keyboard was not detected before;
488		 * it must have been reconnected!
489		 */
490		init_keyboard(state->kbdc, &kbd->kb_type, kbd->kb_config);
491		KBD_FOUND_DEVICE(kbd);
492		atkbd_ioctl(kbd, KDSETLED, (caddr_t)&state->ks_state);
493		get_typematic(kbd);
494		delay[0] = kbd->kb_delay1;
495		delay[1] = kbd->kb_delay2;
496		atkbd_ioctl(kbd, KDSETREPEAT, (caddr_t)delay);
497	}
498
499	if (state->ks_polling)
500		return 0;
501
502	if (KBD_IS_ACTIVE(kbd) && KBD_IS_BUSY(kbd)) {
503		/* let the callback function to process the input */
504		(*kbd->kb_callback.kc_func)(kbd, KBDIO_KEYINPUT,
505					    kbd->kb_callback.kc_arg);
506	} else {
507		/* read and discard the input; no one is waiting for input */
508		do {
509			c = atkbd_read_char(kbd, FALSE);
510		} while (c != NOKEY);
511	}
512	return 0;
513}
514
515/* test the interface to the device */
516static int
517atkbd_test_if(keyboard_t *kbd)
518{
519	int error;
520	int s;
521
522	error = 0;
523	empty_both_buffers(((atkbd_state_t *)kbd->kb_data)->kbdc, 10);
524	s = spltty();
525	if (!test_controller(((atkbd_state_t *)kbd->kb_data)->kbdc))
526		error = EIO;
527	else if (test_kbd_port(((atkbd_state_t *)kbd->kb_data)->kbdc) != 0)
528		error = EIO;
529	splx(s);
530
531	return error;
532}
533
534/*
535 * Enable the access to the device; until this function is called,
536 * the client cannot read from the keyboard.
537 */
538static int
539atkbd_enable(keyboard_t *kbd)
540{
541	int s;
542
543	s = spltty();
544	KBD_ACTIVATE(kbd);
545	splx(s);
546	return 0;
547}
548
549/* disallow the access to the device */
550static int
551atkbd_disable(keyboard_t *kbd)
552{
553	int s;
554
555	s = spltty();
556	KBD_DEACTIVATE(kbd);
557	splx(s);
558	return 0;
559}
560
561/* read one byte from the keyboard if it's allowed */
562static int
563atkbd_read(keyboard_t *kbd, int wait)
564{
565	int c;
566
567	if (wait)
568		c = read_kbd_data(((atkbd_state_t *)kbd->kb_data)->kbdc);
569	else
570		c = read_kbd_data_no_wait(((atkbd_state_t *)kbd->kb_data)->kbdc);
571	if (c != -1)
572		++kbd->kb_count;
573	return (KBD_IS_ACTIVE(kbd) ? c : -1);
574}
575
576/* check if data is waiting */
577static int
578atkbd_check(keyboard_t *kbd)
579{
580	if (!KBD_IS_ACTIVE(kbd))
581		return FALSE;
582	return kbdc_data_ready(((atkbd_state_t *)kbd->kb_data)->kbdc);
583}
584
585/* read char from the keyboard */
586static u_int
587atkbd_read_char(keyboard_t *kbd, int wait)
588{
589	atkbd_state_t *state;
590	u_int action;
591	int scancode;
592	int keycode;
593
594	state = (atkbd_state_t *)kbd->kb_data;
595next_code:
596	/* do we have a composed char to return? */
597	if (!(state->ks_flags & COMPOSE) && (state->ks_composed_char > 0)) {
598		action = state->ks_composed_char;
599		state->ks_composed_char = 0;
600		if (action > UCHAR_MAX)
601			return ERRKEY;
602		return action;
603	}
604
605	/* see if there is something in the keyboard port */
606	if (wait) {
607		do {
608			scancode = read_kbd_data(state->kbdc);
609		} while (scancode == -1);
610	} else {
611		scancode = read_kbd_data_no_wait(state->kbdc);
612		if (scancode == -1)
613			return NOKEY;
614	}
615	++kbd->kb_count;
616
617#if KBDIO_DEBUG >= 10
618	printf("atkbd_read_char(): scancode:0x%x\n", scancode);
619#endif
620
621	/* return the byte as is for the K_RAW mode */
622	if (state->ks_mode == K_RAW)
623		return scancode;
624
625	/* translate the scan code into a keycode */
626	keycode = scancode & 0x7F;
627	switch (state->ks_prefix) {
628	case 0x00:	/* normal scancode */
629		switch(scancode) {
630		case 0xB8:	/* left alt (compose key) released */
631			if (state->ks_flags & COMPOSE) {
632				state->ks_flags &= ~COMPOSE;
633				if (state->ks_composed_char > UCHAR_MAX)
634					state->ks_composed_char = 0;
635			}
636			break;
637		case 0x38:	/* left alt (compose key) pressed */
638			if (!(state->ks_flags & COMPOSE)) {
639				state->ks_flags |= COMPOSE;
640				state->ks_composed_char = 0;
641			}
642			break;
643		case 0xE0:
644		case 0xE1:
645			state->ks_prefix = scancode;
646			goto next_code;
647		}
648		break;
649	case 0xE0:		/* 0xE0 prefix */
650		state->ks_prefix = 0;
651		switch (keycode) {
652		case 0x1C:	/* right enter key */
653			keycode = 0x59;
654			break;
655		case 0x1D:	/* right ctrl key */
656			keycode = 0x5A;
657			break;
658		case 0x35:	/* keypad divide key */
659			keycode = 0x5B;
660			break;
661		case 0x37:	/* print scrn key */
662			keycode = 0x5C;
663			break;
664		case 0x38:	/* right alt key (alt gr) */
665			keycode = 0x5D;
666			break;
667		case 0x46:	/* ctrl-pause/break on AT 101 (see below) */
668			keycode = 0x68;
669			break;
670		case 0x47:	/* grey home key */
671			keycode = 0x5E;
672			break;
673		case 0x48:	/* grey up arrow key */
674			keycode = 0x5F;
675			break;
676		case 0x49:	/* grey page up key */
677			keycode = 0x60;
678			break;
679		case 0x4B:	/* grey left arrow key */
680			keycode = 0x61;
681			break;
682		case 0x4D:	/* grey right arrow key */
683			keycode = 0x62;
684			break;
685		case 0x4F:	/* grey end key */
686			keycode = 0x63;
687			break;
688		case 0x50:	/* grey down arrow key */
689			keycode = 0x64;
690			break;
691		case 0x51:	/* grey page down key */
692			keycode = 0x65;
693			break;
694		case 0x52:	/* grey insert key */
695			keycode = 0x66;
696			break;
697		case 0x53:	/* grey delete key */
698			keycode = 0x67;
699			break;
700			/* the following 3 are only used on the MS "Natural" keyboard */
701		case 0x5b:	/* left Window key */
702			keycode = 0x69;
703			break;
704		case 0x5c:	/* right Window key */
705			keycode = 0x6a;
706			break;
707		case 0x5d:	/* menu key */
708			keycode = 0x6b;
709			break;
710		case 0x5e:	/* power key */
711			keycode = 0x6d;
712			break;
713		case 0x5f:	/* sleep key */
714			keycode = 0x6e;
715			break;
716		case 0x63:	/* wake key */
717			keycode = 0x6f;
718			break;
719		default:	/* ignore everything else */
720			goto next_code;
721		}
722		break;
723   	case 0xE1:	/* 0xE1 prefix */
724		/*
725		 * The pause/break key on the 101 keyboard produces:
726		 * E1-1D-45 E1-9D-C5
727		 * Ctrl-pause/break produces:
728		 * E0-46 E0-C6 (See above.)
729		 */
730		state->ks_prefix = 0;
731		if (keycode == 0x1D)
732			state->ks_prefix = 0x1D;
733		goto next_code;
734		/* NOT REACHED */
735   	case 0x1D:	/* pause / break */
736		state->ks_prefix = 0;
737		if (keycode != 0x45)
738			goto next_code;
739		keycode = 0x68;
740		break;
741	}
742
743	if (kbd->kb_type == KB_84) {
744		switch (keycode) {
745		case 0x37:	/* *(numpad)/print screen */
746			if (state->ks_flags & SHIFTS)
747				keycode = 0x5c;	/* print screen */
748			break;
749		case 0x45:	/* num lock/pause */
750			if (state->ks_flags & CTLS)
751				keycode = 0x68;	/* pause */
752			break;
753		case 0x46:	/* scroll lock/break */
754			if (state->ks_flags & CTLS)
755				keycode = 0x6c;	/* break */
756			break;
757		}
758	} else if (kbd->kb_type == KB_101) {
759		switch (keycode) {
760		case 0x5c:	/* print screen */
761			if (state->ks_flags & ALTS)
762				keycode = 0x54;	/* sysrq */
763			break;
764		case 0x68:	/* pause/break */
765			if (state->ks_flags & CTLS)
766				keycode = 0x6c;	/* break */
767			break;
768		}
769	}
770
771	/* return the key code in the K_CODE mode */
772	if (state->ks_mode == K_CODE)
773		return (keycode | (scancode & 0x80));
774
775	/* compose a character code */
776	if (state->ks_flags & COMPOSE) {
777		switch (keycode | (scancode & 0x80)) {
778		/* key pressed, process it */
779		case 0x47: case 0x48: case 0x49:	/* keypad 7,8,9 */
780			state->ks_composed_char *= 10;
781			state->ks_composed_char += keycode - 0x40;
782			if (state->ks_composed_char > UCHAR_MAX)
783				return ERRKEY;
784			goto next_code;
785		case 0x4B: case 0x4C: case 0x4D:	/* keypad 4,5,6 */
786			state->ks_composed_char *= 10;
787			state->ks_composed_char += keycode - 0x47;
788			if (state->ks_composed_char > UCHAR_MAX)
789				return ERRKEY;
790			goto next_code;
791		case 0x4F: case 0x50: case 0x51:	/* keypad 1,2,3 */
792			state->ks_composed_char *= 10;
793			state->ks_composed_char += keycode - 0x4E;
794			if (state->ks_composed_char > UCHAR_MAX)
795				return ERRKEY;
796			goto next_code;
797		case 0x52:				/* keypad 0 */
798			state->ks_composed_char *= 10;
799			if (state->ks_composed_char > UCHAR_MAX)
800				return ERRKEY;
801			goto next_code;
802
803		/* key released, no interest here */
804		case 0xC7: case 0xC8: case 0xC9:	/* keypad 7,8,9 */
805		case 0xCB: case 0xCC: case 0xCD:	/* keypad 4,5,6 */
806		case 0xCF: case 0xD0: case 0xD1:	/* keypad 1,2,3 */
807		case 0xD2:				/* keypad 0 */
808			goto next_code;
809
810		case 0x38:				/* left alt key */
811			break;
812
813		default:
814			if (state->ks_composed_char > 0) {
815				state->ks_flags &= ~COMPOSE;
816				state->ks_composed_char = 0;
817				return ERRKEY;
818			}
819			break;
820		}
821	}
822
823	/* keycode to key action */
824	action = genkbd_keyaction(kbd, keycode, scancode & 0x80,
825				  &state->ks_state, &state->ks_accents);
826	if (action == NOKEY)
827		goto next_code;
828	else
829		return action;
830}
831
832/* check if char is waiting */
833static int
834atkbd_check_char(keyboard_t *kbd)
835{
836	atkbd_state_t *state;
837
838	if (!KBD_IS_ACTIVE(kbd))
839		return FALSE;
840	state = (atkbd_state_t *)kbd->kb_data;
841	if (!(state->ks_flags & COMPOSE) && (state->ks_composed_char > 0))
842		return TRUE;
843	return kbdc_data_ready(state->kbdc);
844}
845
846/* some useful control functions */
847static int
848atkbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
849{
850	/* translate LED_XXX bits into the device specific bits */
851	static u_char ledmap[8] = {
852		0, 4, 2, 6, 1, 5, 3, 7,
853	};
854	atkbd_state_t *state = kbd->kb_data;
855	int error;
856	int s;
857	int i;
858#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
859    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
860	int ival;
861#endif
862
863	s = spltty();
864	switch (cmd) {
865
866	case KDGKBMODE:		/* get keyboard mode */
867		*(int *)arg = state->ks_mode;
868		break;
869#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
870    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
871	case _IO('K', 7):
872		ival = IOCPARM_IVAL(arg);
873		arg = (caddr_t)&ival;
874		/* FALLTHROUGH */
875#endif
876	case KDSKBMODE:		/* set keyboard mode */
877		switch (*(int *)arg) {
878		case K_XLATE:
879			if (state->ks_mode != K_XLATE) {
880				/* make lock key state and LED state match */
881				state->ks_state &= ~LOCK_MASK;
882				state->ks_state |= KBD_LED_VAL(kbd);
883			}
884			/* FALLTHROUGH */
885		case K_RAW:
886		case K_CODE:
887			if (state->ks_mode != *(int *)arg) {
888				atkbd_clear_state(kbd);
889				state->ks_mode = *(int *)arg;
890			}
891			break;
892		default:
893			splx(s);
894			return EINVAL;
895		}
896		break;
897
898	case KDGETLED:		/* get keyboard LED */
899		*(int *)arg = KBD_LED_VAL(kbd);
900		break;
901#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
902    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
903	case _IO('K', 66):
904		ival = IOCPARM_IVAL(arg);
905		arg = (caddr_t)&ival;
906		/* FALLTHROUGH */
907#endif
908	case KDSETLED:		/* set keyboard LED */
909		/* NOTE: lock key state in ks_state won't be changed */
910		if (*(int *)arg & ~LOCK_MASK) {
911			splx(s);
912			return EINVAL;
913		}
914		i = *(int *)arg;
915		/* replace CAPS LED with ALTGR LED for ALTGR keyboards */
916		if (state->ks_mode == K_XLATE &&
917		    kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
918			if (i & ALKED)
919				i |= CLKED;
920			else
921				i &= ~CLKED;
922		}
923		if (KBD_HAS_DEVICE(kbd)) {
924			error = write_kbd(state->kbdc, KBDC_SET_LEDS,
925					  ledmap[i & LED_MASK]);
926			if (error) {
927				splx(s);
928				return error;
929			}
930		}
931		KBD_LED_VAL(kbd) = *(int *)arg;
932		break;
933
934	case KDGKBSTATE:	/* get lock key state */
935		*(int *)arg = state->ks_state & LOCK_MASK;
936		break;
937#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
938    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
939	case _IO('K', 20):
940		ival = IOCPARM_IVAL(arg);
941		arg = (caddr_t)&ival;
942		/* FALLTHROUGH */
943#endif
944	case KDSKBSTATE:	/* set lock key state */
945		if (*(int *)arg & ~LOCK_MASK) {
946			splx(s);
947			return EINVAL;
948		}
949		state->ks_state &= ~LOCK_MASK;
950		state->ks_state |= *(int *)arg;
951		splx(s);
952		/* set LEDs and quit */
953		return atkbd_ioctl(kbd, KDSETLED, arg);
954
955	case KDSETREPEAT:	/* set keyboard repeat rate (new interface) */
956		splx(s);
957		if (!KBD_HAS_DEVICE(kbd))
958			return 0;
959		i = typematic(((int *)arg)[0], ((int *)arg)[1]);
960		error = write_kbd(state->kbdc, KBDC_SET_TYPEMATIC, i);
961		if (error == 0) {
962			kbd->kb_delay1 = typematic_delay(i);
963			kbd->kb_delay2 = typematic_rate(i);
964		}
965		return error;
966
967#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
968    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
969	case _IO('K', 67):
970		ival = IOCPARM_IVAL(arg);
971		arg = (caddr_t)&ival;
972		/* FALLTHROUGH */
973#endif
974	case KDSETRAD:		/* set keyboard repeat rate (old interface) */
975		splx(s);
976		if (!KBD_HAS_DEVICE(kbd))
977			return 0;
978		error = write_kbd(state->kbdc, KBDC_SET_TYPEMATIC, *(int *)arg);
979		if (error == 0) {
980			kbd->kb_delay1 = typematic_delay(*(int *)arg);
981			kbd->kb_delay2 = typematic_rate(*(int *)arg);
982		}
983		return error;
984
985	case PIO_KEYMAP:	/* set keyboard translation table */
986	case OPIO_KEYMAP:	/* set keyboard translation table (compat) */
987	case PIO_KEYMAPENT:	/* set keyboard translation table entry */
988	case PIO_DEADKEYMAP:	/* set accent key translation table */
989		state->ks_accents = 0;
990		/* FALLTHROUGH */
991	default:
992		splx(s);
993		return genkbd_commonioctl(kbd, cmd, arg);
994	}
995
996	splx(s);
997	return 0;
998}
999
1000/* lock the access to the keyboard */
1001static int
1002atkbd_lock(keyboard_t *kbd, int lock)
1003{
1004	return kbdc_lock(((atkbd_state_t *)kbd->kb_data)->kbdc, lock);
1005}
1006
1007/* clear the internal state of the keyboard */
1008static void
1009atkbd_clear_state(keyboard_t *kbd)
1010{
1011	atkbd_state_t *state;
1012
1013	state = (atkbd_state_t *)kbd->kb_data;
1014	state->ks_flags = 0;
1015	state->ks_polling = 0;
1016	state->ks_state &= LOCK_MASK;	/* preserve locking key state */
1017	state->ks_accents = 0;
1018	state->ks_composed_char = 0;
1019#if 0
1020	state->ks_prefix = 0; /* XXX */
1021#endif
1022}
1023
1024/* save the internal state */
1025static int
1026atkbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1027{
1028	if (len == 0)
1029		return sizeof(atkbd_state_t);
1030	if (len < sizeof(atkbd_state_t))
1031		return -1;
1032	bcopy(kbd->kb_data, buf, sizeof(atkbd_state_t));
1033	return 0;
1034}
1035
1036/* set the internal state */
1037static int
1038atkbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1039{
1040	if (len < sizeof(atkbd_state_t))
1041		return ENOMEM;
1042	if (((atkbd_state_t *)kbd->kb_data)->kbdc
1043		!= ((atkbd_state_t *)buf)->kbdc)
1044		return ENOMEM;
1045	bcopy(buf, kbd->kb_data, sizeof(atkbd_state_t));
1046	return 0;
1047}
1048
1049static int
1050atkbd_poll(keyboard_t *kbd, int on)
1051{
1052	atkbd_state_t *state;
1053	int s;
1054
1055	state = (atkbd_state_t *)kbd->kb_data;
1056	s = spltty();
1057	if (on)
1058		++state->ks_polling;
1059	else
1060		--state->ks_polling;
1061	splx(s);
1062	return 0;
1063}
1064
1065static void
1066atkbd_shutdown_final(void *v)
1067{
1068#ifdef __sparc64__
1069	keyboard_t *kbd = v;
1070	KBDC kbdc = ((atkbd_state_t *)kbd->kb_data)->kbdc;
1071
1072	/*
1073	 * Turn off the translation in preparation for handing the keyboard
1074	 * over to the OFW as the OBP driver doesn't use translation and
1075	 * also doesn't disable it itself resulting in a broken keymap at
1076	 * the boot prompt. Also disable the aux port and the interrupts as
1077	 * the OBP driver doesn't use them, i.e. polls the keyboard. Not
1078	 * disabling the interrupts doesn't cause real problems but the
1079	 * responsiveness is a bit better when they are turned off.
1080	 */
1081	send_kbd_command(kbdc, KBDC_DISABLE_KBD);
1082	set_controller_command_byte(kbdc,
1083	    KBD_AUX_CONTROL_BITS | KBD_KBD_CONTROL_BITS | KBD_TRANSLATION,
1084	    KBD_DISABLE_AUX_PORT | KBD_DISABLE_KBD_INT | KBD_ENABLE_KBD_PORT);
1085	send_kbd_command(kbdc, KBDC_ENABLE_KBD);
1086#endif
1087}
1088
1089/* local functions */
1090
1091static int
1092get_typematic(keyboard_t *kbd)
1093{
1094#if defined(__i386__) || defined(__amd64__)
1095	/*
1096	 * Only some systems allow us to retrieve the keyboard repeat
1097	 * rate previously set via the BIOS...
1098	 */
1099	x86regs_t regs;
1100	uint8_t *p;
1101
1102	/*
1103	 * Traditional entry points of int 0x15 and 0x16 are fixed
1104	 * and later BIOSes follow them.  (U)EFI CSM specification
1105	 * also mandates these fixed entry points.
1106	 *
1107	 * Validate the entry points here before we proceed further.
1108	 * It's known that some recent laptops does not have the
1109	 * same entry point and hang on boot if we call it.
1110	 */
1111	if (x86bios_get_intr(0x15) != 0xf000f859 ||
1112	    x86bios_get_intr(0x16) != 0xf000e82e)
1113		return (ENODEV);
1114
1115	/* Is BIOS system configuration table supported? */
1116	x86bios_init_regs(&regs);
1117	regs.R_AH = 0xc0;
1118	x86bios_intr(&regs, 0x15);
1119	if ((regs.R_FLG & PSL_C) != 0 || regs.R_AH != 0)
1120		return (ENODEV);
1121
1122	/* Is int 0x16, function 0x09 supported? */
1123	p = x86bios_offset((regs.R_ES << 4) + regs.R_BX);
1124	if (readw(p) < 5 || (readb(p + 6) & 0x40) == 0)
1125		return (ENODEV);
1126
1127	/* Is int 0x16, function 0x0306 supported? */
1128	x86bios_init_regs(&regs);
1129	regs.R_AH = 0x09;
1130	x86bios_intr(&regs, 0x16);
1131	if ((regs.R_AL & 0x08) == 0)
1132		return (ENODEV);
1133
1134	x86bios_init_regs(&regs);
1135	regs.R_AX = 0x0306;
1136	x86bios_intr(&regs, 0x16);
1137	kbd->kb_delay1 = typematic_delay(regs.R_BH << 5);
1138	kbd->kb_delay2 = typematic_rate(regs.R_BL);
1139	return (0);
1140#else
1141	return (ENODEV);
1142#endif /* __i386__ || __amd64__ */
1143}
1144
1145static int
1146setup_kbd_port(KBDC kbdc, int port, int intr)
1147{
1148	if (!set_controller_command_byte(kbdc,
1149		KBD_KBD_CONTROL_BITS,
1150		((port) ? KBD_ENABLE_KBD_PORT : KBD_DISABLE_KBD_PORT)
1151		    | ((intr) ? KBD_ENABLE_KBD_INT : KBD_DISABLE_KBD_INT)))
1152		return 1;
1153	return 0;
1154}
1155
1156static int
1157get_kbd_echo(KBDC kbdc)
1158{
1159	/* enable the keyboard port, but disable the keyboard intr. */
1160	if (setup_kbd_port(kbdc, TRUE, FALSE))
1161		/* CONTROLLER ERROR: there is very little we can do... */
1162		return ENXIO;
1163
1164	/* see if something is present */
1165	write_kbd_command(kbdc, KBDC_ECHO);
1166	if (read_kbd_data(kbdc) != KBD_ECHO) {
1167		empty_both_buffers(kbdc, 10);
1168		test_controller(kbdc);
1169		test_kbd_port(kbdc);
1170		return ENXIO;
1171	}
1172
1173	/* enable the keyboard port and intr. */
1174	if (setup_kbd_port(kbdc, TRUE, TRUE)) {
1175		/*
1176		 * CONTROLLER ERROR
1177		 * This is serious; the keyboard intr is left disabled!
1178		 */
1179		return ENXIO;
1180	}
1181
1182	return 0;
1183}
1184
1185static int
1186probe_keyboard(KBDC kbdc, int flags)
1187{
1188	/*
1189	 * Don't try to print anything in this function.  The low-level
1190	 * console may not have been initialized yet...
1191	 */
1192	int err;
1193	int c;
1194	int m;
1195
1196	if (!kbdc_lock(kbdc, TRUE)) {
1197		/* driver error? */
1198		return ENXIO;
1199	}
1200
1201	/* temporarily block data transmission from the keyboard */
1202	write_controller_command(kbdc, KBDC_DISABLE_KBD_PORT);
1203
1204	/* flush any noise in the buffer */
1205	empty_both_buffers(kbdc, 100);
1206
1207	/* save the current keyboard controller command byte */
1208	m = kbdc_get_device_mask(kbdc) & ~KBD_KBD_CONTROL_BITS;
1209	c = get_controller_command_byte(kbdc);
1210	if (c == -1) {
1211		/* CONTROLLER ERROR */
1212		kbdc_set_device_mask(kbdc, m);
1213		kbdc_lock(kbdc, FALSE);
1214		return ENXIO;
1215	}
1216
1217	/*
1218	 * The keyboard may have been screwed up by the boot block.
1219	 * We may just be able to recover from error by testing the controller
1220	 * and the keyboard port. The controller command byte needs to be
1221	 * saved before this recovery operation, as some controllers seem
1222	 * to set the command byte to particular values.
1223	 */
1224	test_controller(kbdc);
1225	if (!(flags & KB_CONF_NO_PROBE_TEST))
1226		test_kbd_port(kbdc);
1227
1228	err = get_kbd_echo(kbdc);
1229
1230	/*
1231	 * Even if the keyboard doesn't seem to be present (err != 0),
1232	 * we shall enable the keyboard port and interrupt so that
1233	 * the driver will be operable when the keyboard is attached
1234	 * to the system later.  It is NOT recommended to hot-plug
1235	 * the AT keyboard, but many people do so...
1236	 */
1237	kbdc_set_device_mask(kbdc, m | KBD_KBD_CONTROL_BITS);
1238	setup_kbd_port(kbdc, TRUE, TRUE);
1239#if 0
1240	if (err == 0) {
1241		kbdc_set_device_mask(kbdc, m | KBD_KBD_CONTROL_BITS);
1242	} else {
1243		/* try to restore the command byte as before */
1244		set_controller_command_byte(kbdc, 0xff, c);
1245		kbdc_set_device_mask(kbdc, m);
1246	}
1247#endif
1248
1249	kbdc_lock(kbdc, FALSE);
1250	return err;
1251}
1252
1253static int
1254init_keyboard(KBDC kbdc, int *type, int flags)
1255{
1256	int codeset;
1257	int id;
1258	int c;
1259
1260	if (!kbdc_lock(kbdc, TRUE)) {
1261		/* driver error? */
1262		return EIO;
1263	}
1264
1265	/* temporarily block data transmission from the keyboard */
1266	write_controller_command(kbdc, KBDC_DISABLE_KBD_PORT);
1267
1268	/* save the current controller command byte */
1269	empty_both_buffers(kbdc, 200);
1270	c = get_controller_command_byte(kbdc);
1271	if (c == -1) {
1272		/* CONTROLLER ERROR */
1273		kbdc_lock(kbdc, FALSE);
1274		printf("atkbd: unable to get the current command byte value.\n");
1275		return EIO;
1276	}
1277	if (bootverbose)
1278		printf("atkbd: the current kbd controller command byte %04x\n",
1279		   c);
1280#if 0
1281	/* override the keyboard lock switch */
1282	c |= KBD_OVERRIDE_KBD_LOCK;
1283#endif
1284
1285	/* enable the keyboard port, but disable the keyboard intr. */
1286	if (setup_kbd_port(kbdc, TRUE, FALSE)) {
1287		/* CONTROLLER ERROR: there is very little we can do... */
1288		printf("atkbd: unable to set the command byte.\n");
1289		kbdc_lock(kbdc, FALSE);
1290		return EIO;
1291	}
1292
1293	/*
1294	 * Check if we have an XT keyboard before we attempt to reset it.
1295	 * The procedure assumes that the keyboard and the controller have
1296	 * been set up properly by BIOS and have not been messed up
1297	 * during the boot process.
1298	 */
1299	codeset = -1;
1300	if (flags & KB_CONF_ALT_SCANCODESET)
1301		/* the user says there is a XT keyboard */
1302		codeset = 1;
1303#ifdef KBD_DETECT_XT_KEYBOARD
1304	else if ((c & KBD_TRANSLATION) == 0) {
1305		/* SET_SCANCODE_SET is not always supported; ignore error */
1306		if (send_kbd_command_and_data(kbdc, KBDC_SET_SCANCODE_SET, 0)
1307			== KBD_ACK)
1308			codeset = read_kbd_data(kbdc);
1309	}
1310	if (bootverbose)
1311		printf("atkbd: scancode set %d\n", codeset);
1312#endif /* KBD_DETECT_XT_KEYBOARD */
1313
1314	*type = KB_OTHER;
1315	id = get_kbd_id(kbdc);
1316	switch(id) {
1317	case 0x41ab:	/* 101/102/... Enhanced */
1318	case 0x83ab:	/* ditto */
1319	case 0x54ab:	/* SpaceSaver */
1320	case 0x84ab:	/* ditto */
1321#if 0
1322	case 0x90ab:	/* 'G' */
1323	case 0x91ab:	/* 'P' */
1324	case 0x92ab:	/* 'A' */
1325#endif
1326		*type = KB_101;
1327		break;
1328	case -1:	/* AT 84 keyboard doesn't return ID */
1329		*type = KB_84;
1330		break;
1331	default:
1332		break;
1333	}
1334	if (bootverbose)
1335		printf("atkbd: keyboard ID 0x%x (%d)\n", id, *type);
1336
1337	/* reset keyboard hardware */
1338	if (!(flags & KB_CONF_NO_RESET) && !reset_kbd(kbdc)) {
1339		/*
1340		 * KEYBOARD ERROR
1341		 * Keyboard reset may fail either because the keyboard
1342		 * doen't exist, or because the keyboard doesn't pass
1343		 * the self-test, or the keyboard controller on the
1344		 * motherboard and the keyboard somehow fail to shake hands.
1345		 * It is just possible, particularly in the last case,
1346		 * that the keyboard controller may be left in a hung state.
1347		 * test_controller() and test_kbd_port() appear to bring
1348		 * the keyboard controller back (I don't know why and how,
1349		 * though.)
1350		 */
1351		empty_both_buffers(kbdc, 10);
1352		test_controller(kbdc);
1353		test_kbd_port(kbdc);
1354		/*
1355		 * We could disable the keyboard port and interrupt... but,
1356		 * the keyboard may still exist (see above).
1357		 */
1358		set_controller_command_byte(kbdc, 0xff, c);
1359		kbdc_lock(kbdc, FALSE);
1360		if (bootverbose)
1361			printf("atkbd: failed to reset the keyboard.\n");
1362		return EIO;
1363	}
1364
1365	/*
1366	 * Allow us to set the XT_KEYBD flag so that keyboards
1367	 * such as those on the IBM ThinkPad laptop computers can be used
1368	 * with the standard console driver.
1369	 */
1370	if (codeset == 1) {
1371		if (send_kbd_command_and_data(kbdc,
1372			KBDC_SET_SCANCODE_SET, codeset) == KBD_ACK) {
1373			/* XT kbd doesn't need scan code translation */
1374			c &= ~KBD_TRANSLATION;
1375		} else {
1376			/*
1377			 * KEYBOARD ERROR
1378			 * The XT kbd isn't usable unless the proper scan
1379			 * code set is selected.
1380			 */
1381			set_controller_command_byte(kbdc, 0xff, c);
1382			kbdc_lock(kbdc, FALSE);
1383			printf("atkbd: unable to set the XT keyboard mode.\n");
1384			return EIO;
1385		}
1386	}
1387
1388#if defined(__sparc64__)
1389	if (send_kbd_command_and_data(
1390		kbdc, KBDC_SET_SCANCODE_SET, 2) != KBD_ACK) {
1391		printf("atkbd: can't set translation.\n");
1392	}
1393	c |= KBD_TRANSLATION;
1394#endif
1395
1396	/* enable the keyboard port and intr. */
1397	if (!set_controller_command_byte(kbdc,
1398		KBD_KBD_CONTROL_BITS | KBD_TRANSLATION | KBD_OVERRIDE_KBD_LOCK,
1399		(c & (KBD_TRANSLATION | KBD_OVERRIDE_KBD_LOCK))
1400		    | KBD_ENABLE_KBD_PORT | KBD_ENABLE_KBD_INT)) {
1401		/*
1402		 * CONTROLLER ERROR
1403		 * This is serious; we are left with the disabled
1404		 * keyboard intr.
1405		 */
1406		set_controller_command_byte(kbdc, 0xff, c);
1407		kbdc_lock(kbdc, FALSE);
1408		printf("atkbd: unable to enable the keyboard port and intr.\n");
1409		return EIO;
1410	}
1411
1412	kbdc_lock(kbdc, FALSE);
1413	return 0;
1414}
1415
1416static int
1417write_kbd(KBDC kbdc, int command, int data)
1418{
1419	int s;
1420
1421	/* prevent the timeout routine from polling the keyboard */
1422	if (!kbdc_lock(kbdc, TRUE))
1423		return EBUSY;
1424
1425	/* disable the keyboard and mouse interrupt */
1426	s = spltty();
1427#if 0
1428	c = get_controller_command_byte(kbdc);
1429	if ((c == -1)
1430	    || !set_controller_command_byte(kbdc,
1431		kbdc_get_device_mask(kbdc),
1432		KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1433		| KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1434		/* CONTROLLER ERROR */
1435		kbdc_lock(kbdc, FALSE);
1436		splx(s);
1437		return EIO;
1438	}
1439	/*
1440	 * Now that the keyboard controller is told not to generate
1441	 * the keyboard and mouse interrupts, call `splx()' to allow
1442	 * the other tty interrupts. The clock interrupt may also occur,
1443	 * but the timeout routine (`scrn_timer()') will be blocked
1444	 * by the lock flag set via `kbdc_lock()'
1445	 */
1446	splx(s);
1447#endif
1448	if (send_kbd_command_and_data(kbdc, command, data) != KBD_ACK)
1449		send_kbd_command(kbdc, KBDC_ENABLE_KBD);
1450#if 0
1451	/* restore the interrupts */
1452	if (!set_controller_command_byte(kbdc, kbdc_get_device_mask(kbdc),
1453	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1454		/* CONTROLLER ERROR */
1455	}
1456#else
1457	splx(s);
1458#endif
1459	kbdc_lock(kbdc, FALSE);
1460
1461	return 0;
1462}
1463
1464static int
1465get_kbd_id(KBDC kbdc)
1466{
1467	int id1, id2;
1468
1469	empty_both_buffers(kbdc, 10);
1470	id1 = id2 = -1;
1471	if (send_kbd_command(kbdc, KBDC_SEND_DEV_ID) != KBD_ACK)
1472		return -1;
1473
1474	DELAY(10000); 	/* 10 msec delay */
1475	id1 = read_kbd_data(kbdc);
1476	if (id1 != -1)
1477		id2 = read_kbd_data(kbdc);
1478
1479	if ((id1 == -1) || (id2 == -1)) {
1480		empty_both_buffers(kbdc, 10);
1481		test_controller(kbdc);
1482		test_kbd_port(kbdc);
1483		return -1;
1484	}
1485	return ((id2 << 8) | id1);
1486}
1487
1488static int delays[] = { 250, 500, 750, 1000 };
1489static int rates[] = {  34,  38,  42,  46,  50,  55,  59,  63,
1490			68,  76,  84,  92, 100, 110, 118, 126,
1491		       136, 152, 168, 184, 200, 220, 236, 252,
1492		       272, 304, 336, 368, 400, 440, 472, 504 };
1493
1494static int
1495typematic_delay(int i)
1496{
1497	return delays[(i >> 5) & 3];
1498}
1499
1500static int
1501typematic_rate(int i)
1502{
1503	return rates[i & 0x1f];
1504}
1505
1506static int
1507typematic(int delay, int rate)
1508{
1509	int value;
1510	int i;
1511
1512	for (i = sizeof(delays)/sizeof(delays[0]) - 1; i > 0; --i) {
1513		if (delay >= delays[i])
1514			break;
1515	}
1516	value = i << 5;
1517	for (i = sizeof(rates)/sizeof(rates[0]) - 1; i > 0; --i) {
1518		if (rate >= rates[i])
1519			break;
1520	}
1521	value |= i;
1522	return value;
1523}
1524