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