xref: /freebsd/sys/dev/usb/input/ukbd.c (revision c1b2af731bbdd6f37d0f75386acab31b5ad86090)
1 #include <sys/cdefs.h>
2 __FBSDID("$FreeBSD$");
3 
4 
5 /*-
6  * SPDX-License-Identifier: BSD-2-Clause-NetBSD
7  *
8  * Copyright (c) 1998 The NetBSD Foundation, Inc.
9  * All rights reserved.
10  *
11  * This code is derived from software contributed to The NetBSD Foundation
12  * by Lennart Augustsson (lennart@augustsson.net) at
13  * Carlstedt Research & Technology.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
28  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  *
36  */
37 
38 /*
39  * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf
40  */
41 
42 #include "opt_kbd.h"
43 #include "opt_ukbd.h"
44 #include "opt_evdev.h"
45 
46 #include <sys/stdint.h>
47 #include <sys/stddef.h>
48 #include <sys/param.h>
49 #include <sys/queue.h>
50 #include <sys/types.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/bus.h>
54 #include <sys/module.h>
55 #include <sys/lock.h>
56 #include <sys/mutex.h>
57 #include <sys/condvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/sx.h>
60 #include <sys/unistd.h>
61 #include <sys/callout.h>
62 #include <sys/malloc.h>
63 #include <sys/priv.h>
64 #include <sys/proc.h>
65 
66 #include <dev/usb/usb.h>
67 #include <dev/usb/usbdi.h>
68 #include <dev/usb/usbdi_util.h>
69 #include <dev/usb/usbhid.h>
70 
71 #define	USB_DEBUG_VAR ukbd_debug
72 #include <dev/usb/usb_debug.h>
73 
74 #include <dev/usb/quirk/usb_quirk.h>
75 
76 #ifdef EVDEV_SUPPORT
77 #include <dev/evdev/input.h>
78 #include <dev/evdev/evdev.h>
79 #endif
80 
81 #include <sys/ioccom.h>
82 #include <sys/filio.h>
83 #include <sys/kbio.h>
84 
85 #include <dev/kbd/kbdreg.h>
86 
87 /* the initial key map, accent map and fkey strings */
88 #if defined(UKBD_DFLT_KEYMAP) && !defined(KLD_MODULE)
89 #define	KBD_DFLT_KEYMAP
90 #include "ukbdmap.h"
91 #endif
92 
93 /* the following file must be included after "ukbdmap.h" */
94 #include <dev/kbd/kbdtables.h>
95 
96 #ifdef USB_DEBUG
97 static int ukbd_debug = 0;
98 static int ukbd_no_leds = 0;
99 static int ukbd_pollrate = 0;
100 
101 static SYSCTL_NODE(_hw_usb, OID_AUTO, ukbd, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
102     "USB keyboard");
103 SYSCTL_INT(_hw_usb_ukbd, OID_AUTO, debug, CTLFLAG_RWTUN,
104     &ukbd_debug, 0, "Debug level");
105 SYSCTL_INT(_hw_usb_ukbd, OID_AUTO, no_leds, CTLFLAG_RWTUN,
106     &ukbd_no_leds, 0, "Disables setting of keyboard leds");
107 SYSCTL_INT(_hw_usb_ukbd, OID_AUTO, pollrate, CTLFLAG_RWTUN,
108     &ukbd_pollrate, 0, "Force this polling rate, 1-1000Hz");
109 #endif
110 
111 #define	UKBD_EMULATE_ATSCANCODE	       1
112 #define	UKBD_DRIVER_NAME          "ukbd"
113 #define	UKBD_NKEYCODE                 256 /* units */
114 #define	UKBD_IN_BUF_SIZE  (4 * UKBD_NKEYCODE) /* scancodes */
115 #define	UKBD_IN_BUF_FULL  ((UKBD_IN_BUF_SIZE / 2) - 1)	/* scancodes */
116 #define	UKBD_NFKEY        (sizeof(fkey_tab)/sizeof(fkey_tab[0]))	/* units */
117 #define	UKBD_BUFFER_SIZE	      64	/* bytes */
118 #define	UKBD_KEY_PRESSED(map, key) ({ \
119 	CTASSERT((key) >= 0 && (key) < UKBD_NKEYCODE); \
120 	((map)[(key) / 64] & (1ULL << ((key) % 64))); \
121 })
122 
123 #define	MOD_EJECT	0x01
124 #define	MOD_FN		0x02
125 
126 struct ukbd_data {
127 	uint64_t bitmap[howmany(UKBD_NKEYCODE, 64)];
128 };
129 
130 enum {
131 	UKBD_INTR_DT_0,
132 	UKBD_INTR_DT_1,
133 	UKBD_CTRL_LED,
134 	UKBD_N_TRANSFER,
135 };
136 
137 struct ukbd_softc {
138 	keyboard_t sc_kbd;
139 	keymap_t sc_keymap;
140 	accentmap_t sc_accmap;
141 	fkeytab_t sc_fkeymap[UKBD_NFKEY];
142 	uint64_t sc_loc_key_valid[howmany(UKBD_NKEYCODE, 64)];
143 	struct hid_location sc_loc_apple_eject;
144 	struct hid_location sc_loc_apple_fn;
145 	struct hid_location sc_loc_key[UKBD_NKEYCODE];
146 	struct hid_location sc_loc_numlock;
147 	struct hid_location sc_loc_capslock;
148 	struct hid_location sc_loc_scrolllock;
149 	struct usb_callout sc_callout;
150 	struct ukbd_data sc_ndata;
151 	struct ukbd_data sc_odata;
152 
153 	struct thread *sc_poll_thread;
154 	struct usb_device *sc_udev;
155 	struct usb_interface *sc_iface;
156 	struct usb_xfer *sc_xfer[UKBD_N_TRANSFER];
157 #ifdef EVDEV_SUPPORT
158 	struct evdev_dev *sc_evdev;
159 #endif
160 
161 	sbintime_t sc_co_basetime;
162 	int	sc_delay;
163 	uint32_t sc_repeat_time;
164 	uint32_t sc_input[UKBD_IN_BUF_SIZE];	/* input buffer */
165 	uint32_t sc_time_ms;
166 	uint32_t sc_composed_char;	/* composed char code, if non-zero */
167 #ifdef UKBD_EMULATE_ATSCANCODE
168 	uint32_t sc_buffered_char[2];
169 #endif
170 	uint32_t sc_flags;		/* flags */
171 #define	UKBD_FLAG_COMPOSE	0x00000001
172 #define	UKBD_FLAG_POLLING	0x00000002
173 #define	UKBD_FLAG_SET_LEDS	0x00000004
174 #define	UKBD_FLAG_ATTACHED	0x00000010
175 #define	UKBD_FLAG_GONE		0x00000020
176 
177 #define	UKBD_FLAG_HID_MASK	0x003fffc0
178 #define	UKBD_FLAG_APPLE_EJECT	0x00000040
179 #define	UKBD_FLAG_APPLE_FN	0x00000080
180 #define	UKBD_FLAG_APPLE_SWAP	0x00000100
181 #define	UKBD_FLAG_NUMLOCK	0x00080000
182 #define	UKBD_FLAG_CAPSLOCK	0x00100000
183 #define	UKBD_FLAG_SCROLLLOCK 	0x00200000
184 
185 	int	sc_mode;		/* input mode (K_XLATE,K_RAW,K_CODE) */
186 	int	sc_state;		/* shift/lock key state */
187 	int	sc_accents;		/* accent key index (> 0) */
188 	int	sc_polling;		/* polling recursion count */
189 	int	sc_led_size;
190 	int	sc_kbd_size;
191 
192 	uint16_t sc_inputs;
193 	uint16_t sc_inputhead;
194 	uint16_t sc_inputtail;
195 
196 	uint8_t	sc_leds;		/* store for async led requests */
197 	uint8_t	sc_iface_index;
198 	uint8_t	sc_iface_no;
199 	uint8_t sc_id_apple_eject;
200 	uint8_t sc_id_apple_fn;
201 	uint8_t sc_id_loc_key[UKBD_NKEYCODE];
202 	uint8_t sc_id_numlock;
203 	uint8_t sc_id_capslock;
204 	uint8_t sc_id_scrolllock;
205 	uint8_t sc_kbd_id;
206 	uint8_t sc_repeat_key;
207 
208 	uint8_t sc_buffer[UKBD_BUFFER_SIZE];
209 };
210 
211 #define	KEY_NONE	  0x00
212 #define	KEY_ERROR	  0x01
213 
214 #define	KEY_PRESS	  0
215 #define	KEY_RELEASE	  0x400
216 #define	KEY_INDEX(c)	  ((c) & 0xFF)
217 
218 #define	SCAN_PRESS	  0
219 #define	SCAN_RELEASE	  0x80
220 #define	SCAN_PREFIX_E0	  0x100
221 #define	SCAN_PREFIX_E1	  0x200
222 #define	SCAN_PREFIX_CTL	  0x400
223 #define	SCAN_PREFIX_SHIFT 0x800
224 #define	SCAN_PREFIX	(SCAN_PREFIX_E0  | SCAN_PREFIX_E1 | \
225 			 SCAN_PREFIX_CTL | SCAN_PREFIX_SHIFT)
226 #define	SCAN_CHAR(c)	((c) & 0x7f)
227 
228 #define	UKBD_LOCK()	USB_MTX_LOCK(&Giant)
229 #define	UKBD_UNLOCK()	USB_MTX_UNLOCK(&Giant)
230 #define	UKBD_LOCK_ASSERT()	USB_MTX_ASSERT(&Giant, MA_OWNED)
231 
232 #define	NN 0				/* no translation */
233 /*
234  * Translate USB keycodes to AT keyboard scancodes.
235  */
236 /*
237  * FIXME: Mac USB keyboard generates:
238  * 0x53: keypad NumLock/Clear
239  * 0x66: Power
240  * 0x67: keypad =
241  * 0x68: F13
242  * 0x69: F14
243  * 0x6a: F15
244  *
245  * USB Apple Keyboard JIS generates:
246  * 0x90: Kana
247  * 0x91: Eisu
248  */
249 static const uint8_t ukbd_trtab[256] = {
250 	0, 0, 0, 0, 30, 48, 46, 32,	/* 00 - 07 */
251 	18, 33, 34, 35, 23, 36, 37, 38,	/* 08 - 0F */
252 	50, 49, 24, 25, 16, 19, 31, 20,	/* 10 - 17 */
253 	22, 47, 17, 45, 21, 44, 2, 3,	/* 18 - 1F */
254 	4, 5, 6, 7, 8, 9, 10, 11,	/* 20 - 27 */
255 	28, 1, 14, 15, 57, 12, 13, 26,	/* 28 - 2F */
256 	27, 43, 43, 39, 40, 41, 51, 52,	/* 30 - 37 */
257 	53, 58, 59, 60, 61, 62, 63, 64,	/* 38 - 3F */
258 	65, 66, 67, 68, 87, 88, 92, 70,	/* 40 - 47 */
259 	104, 102, 94, 96, 103, 99, 101, 98,	/* 48 - 4F */
260 	97, 100, 95, 69, 91, 55, 74, 78,/* 50 - 57 */
261 	89, 79, 80, 81, 75, 76, 77, 71,	/* 58 - 5F */
262 	72, 73, 82, 83, 86, 107, 122, NN,	/* 60 - 67 */
263 	NN, NN, NN, NN, NN, NN, NN, NN,	/* 68 - 6F */
264 	NN, NN, NN, NN, 115, 108, 111, 113,	/* 70 - 77 */
265 	109, 110, 112, 118, 114, 116, 117, 119,	/* 78 - 7F */
266 	121, 120, NN, NN, NN, NN, NN, 123,	/* 80 - 87 */
267 	124, 125, 126, 127, 128, NN, NN, NN,	/* 88 - 8F */
268 	129, 130, NN, NN, NN, NN, NN, NN,	/* 90 - 97 */
269 	NN, NN, NN, NN, NN, NN, NN, NN,	/* 98 - 9F */
270 	NN, NN, NN, NN, NN, NN, NN, NN,	/* A0 - A7 */
271 	NN, NN, NN, NN, NN, NN, NN, NN,	/* A8 - AF */
272 	NN, NN, NN, NN, NN, NN, NN, NN,	/* B0 - B7 */
273 	NN, NN, NN, NN, NN, NN, NN, NN,	/* B8 - BF */
274 	NN, NN, NN, NN, NN, NN, NN, NN,	/* C0 - C7 */
275 	NN, NN, NN, NN, NN, NN, NN, NN,	/* C8 - CF */
276 	NN, NN, NN, NN, NN, NN, NN, NN,	/* D0 - D7 */
277 	NN, NN, NN, NN, NN, NN, NN, NN,	/* D8 - DF */
278 	29, 42, 56, 105, 90, 54, 93, 106,	/* E0 - E7 */
279 	NN, NN, NN, NN, NN, NN, NN, NN,	/* E8 - EF */
280 	NN, NN, NN, NN, NN, NN, NN, NN,	/* F0 - F7 */
281 	NN, NN, NN, NN, NN, NN, NN, NN,	/* F8 - FF */
282 };
283 
284 static const uint8_t ukbd_boot_desc[] = {
285 	0x05, 0x01, 0x09, 0x06, 0xa1,
286 	0x01, 0x05, 0x07, 0x19, 0xe0,
287 	0x29, 0xe7, 0x15, 0x00, 0x25,
288 	0x01, 0x75, 0x01, 0x95, 0x08,
289 	0x81, 0x02, 0x95, 0x01, 0x75,
290 	0x08, 0x81, 0x01, 0x95, 0x03,
291 	0x75, 0x01, 0x05, 0x08, 0x19,
292 	0x01, 0x29, 0x03, 0x91, 0x02,
293 	0x95, 0x05, 0x75, 0x01, 0x91,
294 	0x01, 0x95, 0x06, 0x75, 0x08,
295 	0x15, 0x00, 0x26, 0xff, 0x00,
296 	0x05, 0x07, 0x19, 0x00, 0x2a,
297 	0xff, 0x00, 0x81, 0x00, 0xc0
298 };
299 
300 /* prototypes */
301 static void	ukbd_timeout(void *);
302 static void	ukbd_set_leds(struct ukbd_softc *, uint8_t);
303 static int	ukbd_set_typematic(keyboard_t *, int);
304 #ifdef UKBD_EMULATE_ATSCANCODE
305 static uint32_t	ukbd_atkeycode(int, const uint64_t *);
306 static int	ukbd_key2scan(struct ukbd_softc *, int, const uint64_t *, int);
307 #endif
308 static uint32_t	ukbd_read_char(keyboard_t *, int);
309 static void	ukbd_clear_state(keyboard_t *);
310 static int	ukbd_ioctl(keyboard_t *, u_long, caddr_t);
311 static int	ukbd_enable(keyboard_t *);
312 static int	ukbd_disable(keyboard_t *);
313 static void	ukbd_interrupt(struct ukbd_softc *);
314 static void	ukbd_event_keyinput(struct ukbd_softc *);
315 
316 static device_probe_t ukbd_probe;
317 static device_attach_t ukbd_attach;
318 static device_detach_t ukbd_detach;
319 static device_resume_t ukbd_resume;
320 
321 #ifdef EVDEV_SUPPORT
322 static evdev_event_t ukbd_ev_event;
323 
324 static const struct evdev_methods ukbd_evdev_methods = {
325 	.ev_event = ukbd_ev_event,
326 };
327 #endif
328 
329 static bool
330 ukbd_any_key_pressed(struct ukbd_softc *sc)
331 {
332 	bool ret = false;
333 	unsigned i;
334 
335 	for (i = 0; i != howmany(UKBD_NKEYCODE, 64); i++)
336 		ret |= (sc->sc_odata.bitmap[i] != 0);
337 	return (ret);
338 }
339 
340 static bool
341 ukbd_any_key_valid(struct ukbd_softc *sc)
342 {
343 	bool ret = false;
344 	unsigned i;
345 
346 	for (i = 0; i != howmany(UKBD_NKEYCODE, 64); i++)
347 		ret |= (sc->sc_loc_key_valid[i] != 0);
348 	return (ret);
349 }
350 
351 static bool
352 ukbd_is_modifier_key(uint32_t key)
353 {
354 
355 	return (key >= 0xe0 && key <= 0xe7);
356 }
357 
358 static void
359 ukbd_start_timer(struct ukbd_softc *sc)
360 {
361 	sbintime_t delay, now, prec;
362 
363 	now = sbinuptime();
364 
365 	/* check if initial delay passed and fallback to key repeat delay */
366 	if (sc->sc_delay == 0)
367 		sc->sc_delay = sc->sc_kbd.kb_delay2;
368 
369 	/* compute timeout */
370 	delay = SBT_1MS * sc->sc_delay;
371 	sc->sc_co_basetime += delay;
372 
373 	/* check if we are running behind */
374 	if (sc->sc_co_basetime < now)
375 		sc->sc_co_basetime = now;
376 
377 	/* This is rarely called, so prefer precision to efficiency. */
378 	prec = qmin(delay >> 7, SBT_1MS * 10);
379 	usb_callout_reset_sbt(&sc->sc_callout, sc->sc_co_basetime, prec,
380 	    ukbd_timeout, sc, C_ABSOLUTE);
381 }
382 
383 static void
384 ukbd_put_key(struct ukbd_softc *sc, uint32_t key)
385 {
386 
387 	UKBD_LOCK_ASSERT();
388 
389 	DPRINTF("0x%02x (%d) %s\n", key, key,
390 	    (key & KEY_RELEASE) ? "released" : "pressed");
391 
392 #ifdef EVDEV_SUPPORT
393 	if (evdev_rcpt_mask & EVDEV_RCPT_HW_KBD && sc->sc_evdev != NULL) {
394 		evdev_push_event(sc->sc_evdev, EV_KEY,
395 		    evdev_hid2key(KEY_INDEX(key)), !(key & KEY_RELEASE));
396 		evdev_sync(sc->sc_evdev);
397 	}
398 #endif
399 
400 	if (sc->sc_inputs < UKBD_IN_BUF_SIZE) {
401 		sc->sc_input[sc->sc_inputtail] = key;
402 		++(sc->sc_inputs);
403 		++(sc->sc_inputtail);
404 		if (sc->sc_inputtail >= UKBD_IN_BUF_SIZE) {
405 			sc->sc_inputtail = 0;
406 		}
407 	} else {
408 		DPRINTF("input buffer is full\n");
409 	}
410 }
411 
412 static void
413 ukbd_do_poll(struct ukbd_softc *sc, uint8_t wait)
414 {
415 
416 	UKBD_LOCK_ASSERT();
417 	KASSERT((sc->sc_flags & UKBD_FLAG_POLLING) != 0,
418 	    ("ukbd_do_poll called when not polling\n"));
419 	DPRINTFN(2, "polling\n");
420 
421 	if (USB_IN_POLLING_MODE_FUNC() == 0) {
422 		/*
423 		 * In this context the kernel is polling for input,
424 		 * but the USB subsystem works in normal interrupt-driven
425 		 * mode, so we just wait on the USB threads to do the job.
426 		 * Note that we currently hold the Giant, but it's also used
427 		 * as the transfer mtx, so we must release it while waiting.
428 		 */
429 		while (sc->sc_inputs == 0) {
430 			/*
431 			 * Give USB threads a chance to run.  Note that
432 			 * kern_yield performs DROP_GIANT + PICKUP_GIANT.
433 			 */
434 			kern_yield(PRI_UNCHANGED);
435 			if (!wait)
436 				break;
437 		}
438 		return;
439 	}
440 
441 	while (sc->sc_inputs == 0) {
442 
443 		usbd_transfer_poll(sc->sc_xfer, UKBD_N_TRANSFER);
444 
445 		/* Delay-optimised support for repetition of keys */
446 		if (ukbd_any_key_pressed(sc)) {
447 			/* a key is pressed - need timekeeping */
448 			DELAY(1000);
449 
450 			/* 1 millisecond has passed */
451 			sc->sc_time_ms += 1;
452 		}
453 
454 		ukbd_interrupt(sc);
455 
456 		if (!wait)
457 			break;
458 	}
459 }
460 
461 static int32_t
462 ukbd_get_key(struct ukbd_softc *sc, uint8_t wait)
463 {
464 	int32_t c;
465 
466 	UKBD_LOCK_ASSERT();
467 	KASSERT((USB_IN_POLLING_MODE_FUNC() == 0) ||
468 	    (sc->sc_flags & UKBD_FLAG_POLLING) != 0,
469 	    ("not polling in kdb or panic\n"));
470 
471 	if (sc->sc_inputs == 0 &&
472 	    (sc->sc_flags & UKBD_FLAG_GONE) == 0) {
473 		/* start transfer, if not already started */
474 		usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_0]);
475 		usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_1]);
476 	}
477 
478 	if (sc->sc_flags & UKBD_FLAG_POLLING)
479 		ukbd_do_poll(sc, wait);
480 
481 	if (sc->sc_inputs == 0) {
482 		c = -1;
483 	} else {
484 		c = sc->sc_input[sc->sc_inputhead];
485 		--(sc->sc_inputs);
486 		++(sc->sc_inputhead);
487 		if (sc->sc_inputhead >= UKBD_IN_BUF_SIZE) {
488 			sc->sc_inputhead = 0;
489 		}
490 	}
491 	return (c);
492 }
493 
494 static void
495 ukbd_interrupt(struct ukbd_softc *sc)
496 {
497 	const uint32_t now = sc->sc_time_ms;
498 	unsigned key;
499 
500 	UKBD_LOCK_ASSERT();
501 
502 	/* Check for key changes */
503 	for (key = 0; key != UKBD_NKEYCODE; key++) {
504 		const uint64_t mask = 1ULL << (key % 64);
505 		const uint64_t delta =
506 		    sc->sc_odata.bitmap[key / 64] ^
507 		    sc->sc_ndata.bitmap[key / 64];
508 
509 		if (mask == 1 && delta == 0) {
510 			key += 63;
511 			continue;	/* skip empty areas */
512 		} else if (delta & mask) {
513 			if (sc->sc_odata.bitmap[key / 64] & mask) {
514 				ukbd_put_key(sc, key | KEY_RELEASE);
515 
516 				/* clear repeating key, if any */
517 				if (sc->sc_repeat_key == key)
518 					sc->sc_repeat_key = 0;
519 			} else {
520 				ukbd_put_key(sc, key | KEY_PRESS);
521 
522 				if (ukbd_is_modifier_key(key))
523 					continue;
524 
525 				sc->sc_co_basetime = sbinuptime();
526 				sc->sc_delay = sc->sc_kbd.kb_delay1;
527 				ukbd_start_timer(sc);
528 
529 				/* set repeat time for last key */
530 				sc->sc_repeat_time = now + sc->sc_kbd.kb_delay1;
531 				sc->sc_repeat_key = key;
532 			}
533 		}
534 	}
535 
536 	/* synchronize old data with new data */
537 	sc->sc_odata = sc->sc_ndata;
538 
539 	/* check if last key is still pressed */
540 	if (sc->sc_repeat_key != 0) {
541 		const int32_t dtime = (sc->sc_repeat_time - now);
542 
543 		/* check if time has elapsed */
544 		if (dtime <= 0) {
545 			ukbd_put_key(sc, sc->sc_repeat_key | KEY_PRESS);
546 			sc->sc_repeat_time = now + sc->sc_kbd.kb_delay2;
547 		}
548 	}
549 
550 	/* wakeup keyboard system */
551 	ukbd_event_keyinput(sc);
552 }
553 
554 static void
555 ukbd_event_keyinput(struct ukbd_softc *sc)
556 {
557 	int c;
558 
559 	UKBD_LOCK_ASSERT();
560 
561 	if ((sc->sc_flags & UKBD_FLAG_POLLING) != 0)
562 		return;
563 
564 	if (sc->sc_inputs == 0)
565 		return;
566 
567 	if (KBD_IS_ACTIVE(&sc->sc_kbd) &&
568 	    KBD_IS_BUSY(&sc->sc_kbd)) {
569 		/* let the callback function process the input */
570 		(sc->sc_kbd.kb_callback.kc_func) (&sc->sc_kbd, KBDIO_KEYINPUT,
571 		    sc->sc_kbd.kb_callback.kc_arg);
572 	} else {
573 		/* read and discard the input, no one is waiting for it */
574 		do {
575 			c = ukbd_read_char(&sc->sc_kbd, 0);
576 		} while (c != NOKEY);
577 	}
578 }
579 
580 static void
581 ukbd_timeout(void *arg)
582 {
583 	struct ukbd_softc *sc = arg;
584 
585 	UKBD_LOCK_ASSERT();
586 
587 	sc->sc_time_ms += sc->sc_delay;
588 	sc->sc_delay = 0;
589 
590 	ukbd_interrupt(sc);
591 
592 	/* Make sure any leftover key events gets read out */
593 	ukbd_event_keyinput(sc);
594 
595 	if (ukbd_any_key_pressed(sc) || (sc->sc_inputs != 0)) {
596 		ukbd_start_timer(sc);
597 	}
598 }
599 
600 static uint32_t
601 ukbd_apple_fn(uint32_t keycode)
602 {
603 	switch (keycode) {
604 	case 0x28: return 0x49; /* RETURN -> INSERT */
605 	case 0x2a: return 0x4c; /* BACKSPACE -> DEL */
606 	case 0x50: return 0x4a; /* LEFT ARROW -> HOME */
607 	case 0x4f: return 0x4d; /* RIGHT ARROW -> END */
608 	case 0x52: return 0x4b; /* UP ARROW -> PGUP */
609 	case 0x51: return 0x4e; /* DOWN ARROW -> PGDN */
610 	default: return keycode;
611 	}
612 }
613 
614 static uint32_t
615 ukbd_apple_swap(uint32_t keycode)
616 {
617 	switch (keycode) {
618 	case 0x35: return 0x64;
619 	case 0x64: return 0x35;
620 	default: return keycode;
621 	}
622 }
623 
624 static void
625 ukbd_intr_callback(struct usb_xfer *xfer, usb_error_t error)
626 {
627 	struct ukbd_softc *sc = usbd_xfer_softc(xfer);
628 	struct usb_page_cache *pc;
629 	uint32_t i;
630 	uint8_t id;
631 	uint8_t modifiers;
632 	int offset;
633 	int len;
634 
635 	UKBD_LOCK_ASSERT();
636 
637 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
638 	pc = usbd_xfer_get_frame(xfer, 0);
639 
640 	switch (USB_GET_STATE(xfer)) {
641 	case USB_ST_TRANSFERRED:
642 		DPRINTF("actlen=%d bytes\n", len);
643 
644 		if (len == 0) {
645 			DPRINTF("zero length data\n");
646 			goto tr_setup;
647 		}
648 
649 		if (sc->sc_kbd_id != 0) {
650 			/* check and remove HID ID byte */
651 			usbd_copy_out(pc, 0, &id, 1);
652 			offset = 1;
653 			len--;
654 			if (len == 0) {
655 				DPRINTF("zero length data\n");
656 				goto tr_setup;
657 			}
658 		} else {
659 			offset = 0;
660 			id = 0;
661 		}
662 
663 		if (len > UKBD_BUFFER_SIZE)
664 			len = UKBD_BUFFER_SIZE;
665 
666 		/* get data */
667 		usbd_copy_out(pc, offset, sc->sc_buffer, len);
668 
669 		/* clear temporary storage */
670 		memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
671 
672 		/* clear modifiers */
673 		modifiers = 0;
674 
675 		/* scan through HID data */
676 		if ((sc->sc_flags & UKBD_FLAG_APPLE_EJECT) &&
677 		    (id == sc->sc_id_apple_eject)) {
678 			if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_apple_eject))
679 				modifiers |= MOD_EJECT;
680 		}
681 		if ((sc->sc_flags & UKBD_FLAG_APPLE_FN) &&
682 		    (id == sc->sc_id_apple_fn)) {
683 			if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_apple_fn))
684 				modifiers |= MOD_FN;
685 		}
686 
687 		for (i = 0; i != UKBD_NKEYCODE; i++) {
688 			const uint64_t valid = sc->sc_loc_key_valid[i / 64];
689 			const uint64_t mask = 1ULL << (i % 64);
690 
691 			if (mask == 1 && valid == 0) {
692 				i += 63;
693 				continue;	/* skip empty areas */
694 			} else if (~valid & mask) {
695 				continue;	/* location is not valid */
696 			} else if (id != sc->sc_id_loc_key[i]) {
697 				continue;	/* invalid HID ID */
698 			} else if (i == 0) {
699 				struct hid_location tmp_loc = sc->sc_loc_key[0];
700 				/* range check array size */
701 				if (tmp_loc.count > UKBD_NKEYCODE)
702 					tmp_loc.count = UKBD_NKEYCODE;
703 				while (tmp_loc.count--) {
704 					uint32_t key =
705 					    hid_get_data_unsigned(sc->sc_buffer, len, &tmp_loc);
706 					/* advance to next location */
707 					tmp_loc.pos += tmp_loc.size;
708 					if (modifiers & MOD_FN)
709 						key = ukbd_apple_fn(key);
710 					if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP)
711 						key = ukbd_apple_swap(key);
712 					if (key == KEY_NONE || key == KEY_ERROR || key >= UKBD_NKEYCODE)
713 						continue;
714 					/* set key in bitmap */
715 					sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
716 				}
717 			} else if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_key[i])) {
718 				uint32_t key = i;
719 
720 				if (modifiers & MOD_FN)
721 					key = ukbd_apple_fn(key);
722 				if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP)
723 					key = ukbd_apple_swap(key);
724 				if (key == KEY_NONE || key == KEY_ERROR || key >= UKBD_NKEYCODE)
725 					continue;
726 				/* set key in bitmap */
727 				sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
728 			}
729 		}
730 #ifdef USB_DEBUG
731 		DPRINTF("modifiers = 0x%04x\n", modifiers);
732 		for (i = 0; i != UKBD_NKEYCODE; i++) {
733 			const uint64_t valid = sc->sc_ndata.bitmap[i / 64];
734 			const uint64_t mask = 1ULL << (i % 64);
735 
736 			if (valid & mask)
737 				DPRINTF("Key 0x%02x pressed\n", i);
738 		}
739 #endif
740 		ukbd_interrupt(sc);
741 
742 	case USB_ST_SETUP:
743 tr_setup:
744 		if (sc->sc_inputs < UKBD_IN_BUF_FULL) {
745 			usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
746 			usbd_transfer_submit(xfer);
747 		} else {
748 			DPRINTF("input queue is full!\n");
749 		}
750 		break;
751 
752 	default:			/* Error */
753 		DPRINTF("error=%s\n", usbd_errstr(error));
754 
755 		if (error != USB_ERR_CANCELLED) {
756 			/* try to clear stall first */
757 			usbd_xfer_set_stall(xfer);
758 			goto tr_setup;
759 		}
760 		break;
761 	}
762 }
763 
764 static void
765 ukbd_set_leds_callback(struct usb_xfer *xfer, usb_error_t error)
766 {
767 	struct ukbd_softc *sc = usbd_xfer_softc(xfer);
768 	struct usb_device_request req;
769 	struct usb_page_cache *pc;
770 	uint8_t id;
771 	uint8_t any;
772 	int len;
773 
774 	UKBD_LOCK_ASSERT();
775 
776 #ifdef USB_DEBUG
777 	if (ukbd_no_leds)
778 		return;
779 #endif
780 
781 	switch (USB_GET_STATE(xfer)) {
782 	case USB_ST_TRANSFERRED:
783 	case USB_ST_SETUP:
784 		if (!(sc->sc_flags & UKBD_FLAG_SET_LEDS))
785 			break;
786 		sc->sc_flags &= ~UKBD_FLAG_SET_LEDS;
787 
788 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
789 		req.bRequest = UR_SET_REPORT;
790 		USETW2(req.wValue, UHID_OUTPUT_REPORT, 0);
791 		req.wIndex[0] = sc->sc_iface_no;
792 		req.wIndex[1] = 0;
793 		req.wLength[1] = 0;
794 
795 		memset(sc->sc_buffer, 0, UKBD_BUFFER_SIZE);
796 
797 		id = 0;
798 		any = 0;
799 
800 		/* Assumption: All led bits must be in the same ID. */
801 
802 		if (sc->sc_flags & UKBD_FLAG_NUMLOCK) {
803 			if (sc->sc_leds & NLKED) {
804 				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
805 				    &sc->sc_loc_numlock, 1);
806 			}
807 			id = sc->sc_id_numlock;
808 			any = 1;
809 		}
810 
811 		if (sc->sc_flags & UKBD_FLAG_SCROLLLOCK) {
812 			if (sc->sc_leds & SLKED) {
813 				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
814 				    &sc->sc_loc_scrolllock, 1);
815 			}
816 			id = sc->sc_id_scrolllock;
817 			any = 1;
818 		}
819 
820 		if (sc->sc_flags & UKBD_FLAG_CAPSLOCK) {
821 			if (sc->sc_leds & CLKED) {
822 				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
823 				    &sc->sc_loc_capslock, 1);
824 			}
825 			id = sc->sc_id_capslock;
826 			any = 1;
827 		}
828 
829 		/* if no leds, nothing to do */
830 		if (!any)
831 			break;
832 
833 #ifdef EVDEV_SUPPORT
834 		if (sc->sc_evdev != NULL)
835 			evdev_push_leds(sc->sc_evdev, sc->sc_leds);
836 #endif
837 
838 		/* range check output report length */
839 		len = sc->sc_led_size;
840 		if (len > (UKBD_BUFFER_SIZE - 1))
841 			len = (UKBD_BUFFER_SIZE - 1);
842 
843 		/* check if we need to prefix an ID byte */
844 		sc->sc_buffer[0] = id;
845 
846 		pc = usbd_xfer_get_frame(xfer, 1);
847 		if (id != 0) {
848 			len++;
849 			usbd_copy_in(pc, 0, sc->sc_buffer, len);
850 		} else {
851 			usbd_copy_in(pc, 0, sc->sc_buffer + 1, len);
852 		}
853 		req.wLength[0] = len;
854 		usbd_xfer_set_frame_len(xfer, 1, len);
855 
856 		DPRINTF("len=%d, id=%d\n", len, id);
857 
858 		/* setup control request last */
859 		pc = usbd_xfer_get_frame(xfer, 0);
860 		usbd_copy_in(pc, 0, &req, sizeof(req));
861 		usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
862 
863 		/* start data transfer */
864 		usbd_xfer_set_frames(xfer, 2);
865 		usbd_transfer_submit(xfer);
866 		break;
867 
868 	default:			/* Error */
869 		DPRINTFN(1, "error=%s\n", usbd_errstr(error));
870 		break;
871 	}
872 }
873 
874 static const struct usb_config ukbd_config[UKBD_N_TRANSFER] = {
875 
876 	[UKBD_INTR_DT_0] = {
877 		.type = UE_INTERRUPT,
878 		.endpoint = UE_ADDR_ANY,
879 		.direction = UE_DIR_IN,
880 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
881 		.bufsize = 0,	/* use wMaxPacketSize */
882 		.callback = &ukbd_intr_callback,
883 	},
884 
885 	[UKBD_INTR_DT_1] = {
886 		.type = UE_INTERRUPT,
887 		.endpoint = UE_ADDR_ANY,
888 		.direction = UE_DIR_IN,
889 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
890 		.bufsize = 0,	/* use wMaxPacketSize */
891 		.callback = &ukbd_intr_callback,
892 	},
893 
894 	[UKBD_CTRL_LED] = {
895 		.type = UE_CONTROL,
896 		.endpoint = 0x00,	/* Control pipe */
897 		.direction = UE_DIR_ANY,
898 		.bufsize = sizeof(struct usb_device_request) + UKBD_BUFFER_SIZE,
899 		.callback = &ukbd_set_leds_callback,
900 		.timeout = 1000,	/* 1 second */
901 	},
902 };
903 
904 /* A match on these entries will load ukbd */
905 static const STRUCT_USB_HOST_ID __used ukbd_devs[] = {
906 	{USB_IFACE_CLASS(UICLASS_HID),
907 	 USB_IFACE_SUBCLASS(UISUBCLASS_BOOT),
908 	 USB_IFACE_PROTOCOL(UIPROTO_BOOT_KEYBOARD),},
909 };
910 
911 static int
912 ukbd_probe(device_t dev)
913 {
914 	keyboard_switch_t *sw = kbd_get_switch(UKBD_DRIVER_NAME);
915 	struct usb_attach_arg *uaa = device_get_ivars(dev);
916 	void *d_ptr;
917 	int error;
918 	uint16_t d_len;
919 
920 	UKBD_LOCK_ASSERT();
921 	DPRINTFN(11, "\n");
922 
923 	if (sw == NULL) {
924 		return (ENXIO);
925 	}
926 	if (uaa->usb_mode != USB_MODE_HOST) {
927 		return (ENXIO);
928 	}
929 
930 	if (uaa->info.bInterfaceClass != UICLASS_HID)
931 		return (ENXIO);
932 
933 	if (usb_test_quirk(uaa, UQ_KBD_IGNORE))
934 		return (ENXIO);
935 
936 	if ((uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) &&
937 	    (uaa->info.bInterfaceProtocol == UIPROTO_BOOT_KEYBOARD))
938 		return (BUS_PROBE_DEFAULT);
939 
940 	error = usbd_req_get_hid_desc(uaa->device, NULL,
941 	    &d_ptr, &d_len, M_TEMP, uaa->info.bIfaceIndex);
942 
943 	if (error)
944 		return (ENXIO);
945 
946 	if (hid_is_keyboard(d_ptr, d_len)) {
947 		if (hid_is_mouse(d_ptr, d_len)) {
948 			/*
949 			 * NOTE: We currently don't support USB mouse
950 			 * and USB keyboard on the same USB endpoint.
951 			 * Let "ums" driver win.
952 			 */
953 			error = ENXIO;
954 		} else {
955 			error = BUS_PROBE_DEFAULT;
956 		}
957 	} else {
958 		error = ENXIO;
959 	}
960 	free(d_ptr, M_TEMP);
961 	return (error);
962 }
963 
964 static void
965 ukbd_parse_hid(struct ukbd_softc *sc, const uint8_t *ptr, uint32_t len)
966 {
967 	uint32_t flags;
968 	uint32_t key;
969 
970 	/* reset detected bits */
971 	sc->sc_flags &= ~UKBD_FLAG_HID_MASK;
972 
973 	/* reset detected keys */
974 	memset(sc->sc_loc_key_valid, 0, sizeof(sc->sc_loc_key_valid));
975 
976 	/* check if there is an ID byte */
977 	sc->sc_kbd_size = hid_report_size(ptr, len,
978 	    hid_input, &sc->sc_kbd_id);
979 
980 	/* investigate if this is an Apple Keyboard */
981 	if (hid_locate(ptr, len,
982 	    HID_USAGE2(HUP_CONSUMER, HUG_APPLE_EJECT),
983 	    hid_input, 0, &sc->sc_loc_apple_eject, &flags,
984 	    &sc->sc_id_apple_eject)) {
985 		if (flags & HIO_VARIABLE)
986 			sc->sc_flags |= UKBD_FLAG_APPLE_EJECT |
987 			    UKBD_FLAG_APPLE_SWAP;
988 		DPRINTFN(1, "Found Apple eject-key\n");
989 	}
990 	if (hid_locate(ptr, len,
991 	    HID_USAGE2(0xFFFF, 0x0003),
992 	    hid_input, 0, &sc->sc_loc_apple_fn, &flags,
993 	    &sc->sc_id_apple_fn)) {
994 		if (flags & HIO_VARIABLE)
995 			sc->sc_flags |= UKBD_FLAG_APPLE_FN;
996 		DPRINTFN(1, "Found Apple FN-key\n");
997 	}
998 
999 	/* figure out event buffer */
1000 	if (hid_locate(ptr, len,
1001 	    HID_USAGE2(HUP_KEYBOARD, 0x00),
1002 	    hid_input, 0, &sc->sc_loc_key[0], &flags,
1003 	    &sc->sc_id_loc_key[0])) {
1004 		if (flags & HIO_VARIABLE) {
1005 			DPRINTFN(1, "Ignoring keyboard event control\n");
1006 		} else {
1007 			sc->sc_loc_key_valid[0] |= 1;
1008 			DPRINTFN(1, "Found keyboard event array\n");
1009 		}
1010 	}
1011 
1012 	/* figure out the keys */
1013 	for (key = 1; key != UKBD_NKEYCODE; key++) {
1014 		if (hid_locate(ptr, len,
1015 		    HID_USAGE2(HUP_KEYBOARD, key),
1016 		    hid_input, 0, &sc->sc_loc_key[key], &flags,
1017 		    &sc->sc_id_loc_key[key])) {
1018 			if (flags & HIO_VARIABLE) {
1019 				sc->sc_loc_key_valid[key / 64] |=
1020 				    1ULL << (key % 64);
1021 				DPRINTFN(1, "Found key 0x%02x\n", key);
1022 			}
1023 		}
1024 	}
1025 
1026 	/* figure out leds on keyboard */
1027 	sc->sc_led_size = hid_report_size(ptr, len,
1028 	    hid_output, NULL);
1029 
1030 	if (hid_locate(ptr, len,
1031 	    HID_USAGE2(HUP_LEDS, 0x01),
1032 	    hid_output, 0, &sc->sc_loc_numlock, &flags,
1033 	    &sc->sc_id_numlock)) {
1034 		if (flags & HIO_VARIABLE)
1035 			sc->sc_flags |= UKBD_FLAG_NUMLOCK;
1036 		DPRINTFN(1, "Found keyboard numlock\n");
1037 	}
1038 	if (hid_locate(ptr, len,
1039 	    HID_USAGE2(HUP_LEDS, 0x02),
1040 	    hid_output, 0, &sc->sc_loc_capslock, &flags,
1041 	    &sc->sc_id_capslock)) {
1042 		if (flags & HIO_VARIABLE)
1043 			sc->sc_flags |= UKBD_FLAG_CAPSLOCK;
1044 		DPRINTFN(1, "Found keyboard capslock\n");
1045 	}
1046 	if (hid_locate(ptr, len,
1047 	    HID_USAGE2(HUP_LEDS, 0x03),
1048 	    hid_output, 0, &sc->sc_loc_scrolllock, &flags,
1049 	    &sc->sc_id_scrolllock)) {
1050 		if (flags & HIO_VARIABLE)
1051 			sc->sc_flags |= UKBD_FLAG_SCROLLLOCK;
1052 		DPRINTFN(1, "Found keyboard scrolllock\n");
1053 	}
1054 }
1055 
1056 static int
1057 ukbd_attach(device_t dev)
1058 {
1059 	struct ukbd_softc *sc = device_get_softc(dev);
1060 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1061 	int unit = device_get_unit(dev);
1062 	keyboard_t *kbd = &sc->sc_kbd;
1063 	void *hid_ptr = NULL;
1064 	usb_error_t err;
1065 	uint16_t n;
1066 	uint16_t hid_len;
1067 #ifdef EVDEV_SUPPORT
1068 	struct evdev_dev *evdev;
1069 	int i;
1070 #endif
1071 #ifdef USB_DEBUG
1072 	int rate;
1073 #endif
1074 	UKBD_LOCK_ASSERT();
1075 
1076 	kbd_init_struct(kbd, UKBD_DRIVER_NAME, KB_OTHER, unit, 0, 0, 0);
1077 
1078 	kbd->kb_data = (void *)sc;
1079 
1080 	device_set_usb_desc(dev);
1081 
1082 	sc->sc_udev = uaa->device;
1083 	sc->sc_iface = uaa->iface;
1084 	sc->sc_iface_index = uaa->info.bIfaceIndex;
1085 	sc->sc_iface_no = uaa->info.bIfaceNum;
1086 	sc->sc_mode = K_XLATE;
1087 
1088 	usb_callout_init_mtx(&sc->sc_callout, &Giant, 0);
1089 
1090 #ifdef UKBD_NO_POLLING
1091 	err = usbd_transfer_setup(uaa->device,
1092 	    &uaa->info.bIfaceIndex, sc->sc_xfer, ukbd_config,
1093 	    UKBD_N_TRANSFER, sc, &Giant);
1094 #else
1095 	/*
1096 	 * Setup the UKBD USB transfers one by one, so they are memory
1097 	 * independent which allows for handling panics triggered by
1098 	 * the keyboard driver itself, typically via CTRL+ALT+ESC
1099 	 * sequences. Or if the USB keyboard driver was processing a
1100 	 * key at the moment of panic.
1101 	 */
1102 	for (n = 0; n != UKBD_N_TRANSFER; n++) {
1103 		err = usbd_transfer_setup(uaa->device,
1104 		    &uaa->info.bIfaceIndex, sc->sc_xfer + n, ukbd_config + n,
1105 		    1, sc, &Giant);
1106 		if (err)
1107 			break;
1108 	}
1109 #endif
1110 
1111 	if (err) {
1112 		DPRINTF("error=%s\n", usbd_errstr(err));
1113 		goto detach;
1114 	}
1115 	/* setup default keyboard maps */
1116 
1117 	sc->sc_keymap = key_map;
1118 	sc->sc_accmap = accent_map;
1119 	for (n = 0; n < UKBD_NFKEY; n++) {
1120 		sc->sc_fkeymap[n] = fkey_tab[n];
1121 	}
1122 
1123 	kbd_set_maps(kbd, &sc->sc_keymap, &sc->sc_accmap,
1124 	    sc->sc_fkeymap, UKBD_NFKEY);
1125 
1126 	KBD_FOUND_DEVICE(kbd);
1127 
1128 	ukbd_clear_state(kbd);
1129 
1130 	/*
1131 	 * FIXME: set the initial value for lock keys in "sc_state"
1132 	 * according to the BIOS data?
1133 	 */
1134 	KBD_PROBE_DONE(kbd);
1135 
1136 	/* get HID descriptor */
1137 	err = usbd_req_get_hid_desc(uaa->device, NULL, &hid_ptr,
1138 	    &hid_len, M_TEMP, uaa->info.bIfaceIndex);
1139 
1140 	if (err == 0) {
1141 		DPRINTF("Parsing HID descriptor of %d bytes\n",
1142 		    (int)hid_len);
1143 
1144 		ukbd_parse_hid(sc, hid_ptr, hid_len);
1145 
1146 		free(hid_ptr, M_TEMP);
1147 	}
1148 
1149 	/* check if we should use the boot protocol */
1150 	if (usb_test_quirk(uaa, UQ_KBD_BOOTPROTO) ||
1151 	    (err != 0) || ukbd_any_key_valid(sc) == false) {
1152 
1153 		DPRINTF("Forcing boot protocol\n");
1154 
1155 		err = usbd_req_set_protocol(sc->sc_udev, NULL,
1156 			sc->sc_iface_index, 0);
1157 
1158 		if (err != 0) {
1159 			DPRINTF("Set protocol error=%s (ignored)\n",
1160 			    usbd_errstr(err));
1161 		}
1162 
1163 		ukbd_parse_hid(sc, ukbd_boot_desc, sizeof(ukbd_boot_desc));
1164 	}
1165 
1166 	/* ignore if SETIDLE fails, hence it is not crucial */
1167 	usbd_req_set_idle(sc->sc_udev, NULL, sc->sc_iface_index, 0, 0);
1168 
1169 	ukbd_ioctl(kbd, KDSETLED, (caddr_t)&sc->sc_state);
1170 
1171 	KBD_INIT_DONE(kbd);
1172 
1173 	if (kbd_register(kbd) < 0) {
1174 		goto detach;
1175 	}
1176 	KBD_CONFIG_DONE(kbd);
1177 
1178 	ukbd_enable(kbd);
1179 
1180 #ifdef KBD_INSTALL_CDEV
1181 	if (kbd_attach(kbd)) {
1182 		goto detach;
1183 	}
1184 #endif
1185 
1186 #ifdef EVDEV_SUPPORT
1187 	evdev = evdev_alloc();
1188 	evdev_set_name(evdev, device_get_desc(dev));
1189 	evdev_set_phys(evdev, device_get_nameunit(dev));
1190 	evdev_set_id(evdev, BUS_USB, uaa->info.idVendor,
1191 	   uaa->info.idProduct, 0);
1192 	evdev_set_serial(evdev, usb_get_serial(uaa->device));
1193 	evdev_set_methods(evdev, kbd, &ukbd_evdev_methods);
1194 	evdev_support_event(evdev, EV_SYN);
1195 	evdev_support_event(evdev, EV_KEY);
1196 	if (sc->sc_flags & (UKBD_FLAG_NUMLOCK | UKBD_FLAG_CAPSLOCK |
1197 			    UKBD_FLAG_SCROLLLOCK))
1198 		evdev_support_event(evdev, EV_LED);
1199 	evdev_support_event(evdev, EV_REP);
1200 
1201 	for (i = 0x00; i <= 0xFF; i++)
1202 		evdev_support_key(evdev, evdev_hid2key(i));
1203 	if (sc->sc_flags & UKBD_FLAG_NUMLOCK)
1204 		evdev_support_led(evdev, LED_NUML);
1205 	if (sc->sc_flags & UKBD_FLAG_CAPSLOCK)
1206 		evdev_support_led(evdev, LED_CAPSL);
1207 	if (sc->sc_flags & UKBD_FLAG_SCROLLLOCK)
1208 		evdev_support_led(evdev, LED_SCROLLL);
1209 
1210 	if (evdev_register_mtx(evdev, &Giant))
1211 		evdev_free(evdev);
1212 	else
1213 		sc->sc_evdev = evdev;
1214 #endif
1215 
1216 	sc->sc_flags |= UKBD_FLAG_ATTACHED;
1217 
1218 	if (bootverbose) {
1219 		kbdd_diag(kbd, bootverbose);
1220 	}
1221 
1222 #ifdef USB_DEBUG
1223 	/* check for polling rate override */
1224 	rate = ukbd_pollrate;
1225 	if (rate > 0) {
1226 		if (rate > 1000)
1227 			rate = 1;
1228 		else
1229 			rate = 1000 / rate;
1230 
1231 		/* set new polling interval in ms */
1232 		usbd_xfer_set_interval(sc->sc_xfer[UKBD_INTR_DT_0], rate);
1233 		usbd_xfer_set_interval(sc->sc_xfer[UKBD_INTR_DT_1], rate);
1234 	}
1235 #endif
1236 	/* start the keyboard */
1237 	usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_0]);
1238 	usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_1]);
1239 
1240 	return (0);			/* success */
1241 
1242 detach:
1243 	ukbd_detach(dev);
1244 	return (ENXIO);			/* error */
1245 }
1246 
1247 static int
1248 ukbd_detach(device_t dev)
1249 {
1250 	struct ukbd_softc *sc = device_get_softc(dev);
1251 	int error;
1252 
1253 	UKBD_LOCK_ASSERT();
1254 
1255 	DPRINTF("\n");
1256 
1257 	sc->sc_flags |= UKBD_FLAG_GONE;
1258 
1259 	usb_callout_stop(&sc->sc_callout);
1260 
1261 	/* kill any stuck keys */
1262 	if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
1263 		/* stop receiving events from the USB keyboard */
1264 		usbd_transfer_stop(sc->sc_xfer[UKBD_INTR_DT_0]);
1265 		usbd_transfer_stop(sc->sc_xfer[UKBD_INTR_DT_1]);
1266 
1267 		/* release all leftover keys, if any */
1268 		memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1269 
1270 		/* process releasing of all keys */
1271 		ukbd_interrupt(sc);
1272 	}
1273 
1274 	ukbd_disable(&sc->sc_kbd);
1275 
1276 #ifdef KBD_INSTALL_CDEV
1277 	if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
1278 		error = kbd_detach(&sc->sc_kbd);
1279 		if (error) {
1280 			/* usb attach cannot return an error */
1281 			device_printf(dev, "WARNING: kbd_detach() "
1282 			    "returned non-zero! (ignored)\n");
1283 		}
1284 	}
1285 #endif
1286 
1287 #ifdef EVDEV_SUPPORT
1288 	evdev_free(sc->sc_evdev);
1289 #endif
1290 
1291 	if (KBD_IS_CONFIGURED(&sc->sc_kbd)) {
1292 		error = kbd_unregister(&sc->sc_kbd);
1293 		if (error) {
1294 			/* usb attach cannot return an error */
1295 			device_printf(dev, "WARNING: kbd_unregister() "
1296 			    "returned non-zero! (ignored)\n");
1297 		}
1298 	}
1299 	sc->sc_kbd.kb_flags = 0;
1300 
1301 	usbd_transfer_unsetup(sc->sc_xfer, UKBD_N_TRANSFER);
1302 
1303 	usb_callout_drain(&sc->sc_callout);
1304 
1305 	DPRINTF("%s: disconnected\n",
1306 	    device_get_nameunit(dev));
1307 
1308 	return (0);
1309 }
1310 
1311 static int
1312 ukbd_resume(device_t dev)
1313 {
1314 	struct ukbd_softc *sc = device_get_softc(dev);
1315 
1316 	UKBD_LOCK_ASSERT();
1317 
1318 	ukbd_clear_state(&sc->sc_kbd);
1319 
1320 	return (0);
1321 }
1322 
1323 #ifdef EVDEV_SUPPORT
1324 static void
1325 ukbd_ev_event(struct evdev_dev *evdev, uint16_t type, uint16_t code,
1326     int32_t value)
1327 {
1328 	keyboard_t *kbd = evdev_get_softc(evdev);
1329 
1330 	if (evdev_rcpt_mask & EVDEV_RCPT_HW_KBD &&
1331 	    (type == EV_LED || type == EV_REP)) {
1332 		mtx_lock(&Giant);
1333 		kbd_ev_event(kbd, type, code, value);
1334 		mtx_unlock(&Giant);
1335 	}
1336 }
1337 #endif
1338 
1339 /* early keyboard probe, not supported */
1340 static int
1341 ukbd_configure(int flags)
1342 {
1343 	return (0);
1344 }
1345 
1346 /* detect a keyboard, not used */
1347 static int
1348 ukbd__probe(int unit, void *arg, int flags)
1349 {
1350 	return (ENXIO);
1351 }
1352 
1353 /* reset and initialize the device, not used */
1354 static int
1355 ukbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
1356 {
1357 	return (ENXIO);
1358 }
1359 
1360 /* test the interface to the device, not used */
1361 static int
1362 ukbd_test_if(keyboard_t *kbd)
1363 {
1364 	return (0);
1365 }
1366 
1367 /* finish using this keyboard, not used */
1368 static int
1369 ukbd_term(keyboard_t *kbd)
1370 {
1371 	return (ENXIO);
1372 }
1373 
1374 /* keyboard interrupt routine, not used */
1375 static int
1376 ukbd_intr(keyboard_t *kbd, void *arg)
1377 {
1378 	return (0);
1379 }
1380 
1381 /* lock the access to the keyboard, not used */
1382 static int
1383 ukbd_lock(keyboard_t *kbd, int lock)
1384 {
1385 	return (1);
1386 }
1387 
1388 /*
1389  * Enable the access to the device; until this function is called,
1390  * the client cannot read from the keyboard.
1391  */
1392 static int
1393 ukbd_enable(keyboard_t *kbd)
1394 {
1395 
1396 	UKBD_LOCK();
1397 	KBD_ACTIVATE(kbd);
1398 	UKBD_UNLOCK();
1399 
1400 	return (0);
1401 }
1402 
1403 /* disallow the access to the device */
1404 static int
1405 ukbd_disable(keyboard_t *kbd)
1406 {
1407 
1408 	UKBD_LOCK();
1409 	KBD_DEACTIVATE(kbd);
1410 	UKBD_UNLOCK();
1411 
1412 	return (0);
1413 }
1414 
1415 /* check if data is waiting */
1416 /* Currently unused. */
1417 static int
1418 ukbd_check(keyboard_t *kbd)
1419 {
1420 	struct ukbd_softc *sc = kbd->kb_data;
1421 
1422 	UKBD_LOCK_ASSERT();
1423 
1424 	if (!KBD_IS_ACTIVE(kbd))
1425 		return (0);
1426 
1427 	if (sc->sc_flags & UKBD_FLAG_POLLING)
1428 		ukbd_do_poll(sc, 0);
1429 
1430 #ifdef UKBD_EMULATE_ATSCANCODE
1431 	if (sc->sc_buffered_char[0]) {
1432 		return (1);
1433 	}
1434 #endif
1435 	if (sc->sc_inputs > 0) {
1436 		return (1);
1437 	}
1438 	return (0);
1439 }
1440 
1441 /* check if char is waiting */
1442 static int
1443 ukbd_check_char_locked(keyboard_t *kbd)
1444 {
1445 	struct ukbd_softc *sc = kbd->kb_data;
1446 
1447 	UKBD_LOCK_ASSERT();
1448 
1449 	if (!KBD_IS_ACTIVE(kbd))
1450 		return (0);
1451 
1452 	if ((sc->sc_composed_char > 0) &&
1453 	    (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1454 		return (1);
1455 	}
1456 	return (ukbd_check(kbd));
1457 }
1458 
1459 static int
1460 ukbd_check_char(keyboard_t *kbd)
1461 {
1462 	int result;
1463 
1464 	UKBD_LOCK();
1465 	result = ukbd_check_char_locked(kbd);
1466 	UKBD_UNLOCK();
1467 
1468 	return (result);
1469 }
1470 
1471 /* read one byte from the keyboard if it's allowed */
1472 /* Currently unused. */
1473 static int
1474 ukbd_read(keyboard_t *kbd, int wait)
1475 {
1476 	struct ukbd_softc *sc = kbd->kb_data;
1477 	int32_t usbcode;
1478 #ifdef UKBD_EMULATE_ATSCANCODE
1479 	uint32_t keycode;
1480 	uint32_t scancode;
1481 
1482 #endif
1483 
1484 	UKBD_LOCK_ASSERT();
1485 
1486 	if (!KBD_IS_ACTIVE(kbd))
1487 		return (-1);
1488 
1489 #ifdef UKBD_EMULATE_ATSCANCODE
1490 	if (sc->sc_buffered_char[0]) {
1491 		scancode = sc->sc_buffered_char[0];
1492 		if (scancode & SCAN_PREFIX) {
1493 			sc->sc_buffered_char[0] &= ~SCAN_PREFIX;
1494 			return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1495 		}
1496 		sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1497 		sc->sc_buffered_char[1] = 0;
1498 		return (scancode);
1499 	}
1500 #endif					/* UKBD_EMULATE_ATSCANCODE */
1501 
1502 	/* XXX */
1503 	usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1504 	if (!KBD_IS_ACTIVE(kbd) || (usbcode == -1))
1505 		return (-1);
1506 
1507 	++(kbd->kb_count);
1508 
1509 #ifdef UKBD_EMULATE_ATSCANCODE
1510 	keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1511 	if (keycode == NN) {
1512 		return -1;
1513 	}
1514 	return (ukbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1515 	    (usbcode & KEY_RELEASE)));
1516 #else					/* !UKBD_EMULATE_ATSCANCODE */
1517 	return (usbcode);
1518 #endif					/* UKBD_EMULATE_ATSCANCODE */
1519 }
1520 
1521 /* read char from the keyboard */
1522 static uint32_t
1523 ukbd_read_char_locked(keyboard_t *kbd, int wait)
1524 {
1525 	struct ukbd_softc *sc = kbd->kb_data;
1526 	uint32_t action;
1527 	uint32_t keycode;
1528 	int32_t usbcode;
1529 #ifdef UKBD_EMULATE_ATSCANCODE
1530 	uint32_t scancode;
1531 #endif
1532 
1533 	UKBD_LOCK_ASSERT();
1534 
1535 	if (!KBD_IS_ACTIVE(kbd))
1536 		return (NOKEY);
1537 
1538 next_code:
1539 
1540 	/* do we have a composed char to return ? */
1541 
1542 	if ((sc->sc_composed_char > 0) &&
1543 	    (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1544 
1545 		action = sc->sc_composed_char;
1546 		sc->sc_composed_char = 0;
1547 
1548 		if (action > 0xFF) {
1549 			goto errkey;
1550 		}
1551 		goto done;
1552 	}
1553 #ifdef UKBD_EMULATE_ATSCANCODE
1554 
1555 	/* do we have a pending raw scan code? */
1556 
1557 	if (sc->sc_mode == K_RAW) {
1558 		scancode = sc->sc_buffered_char[0];
1559 		if (scancode) {
1560 			if (scancode & SCAN_PREFIX) {
1561 				sc->sc_buffered_char[0] = (scancode & ~SCAN_PREFIX);
1562 				return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1563 			}
1564 			sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1565 			sc->sc_buffered_char[1] = 0;
1566 			return (scancode);
1567 		}
1568 	}
1569 #endif					/* UKBD_EMULATE_ATSCANCODE */
1570 
1571 	/* see if there is something in the keyboard port */
1572 	/* XXX */
1573 	usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1574 	if (usbcode == -1) {
1575 		return (NOKEY);
1576 	}
1577 	++kbd->kb_count;
1578 
1579 #ifdef UKBD_EMULATE_ATSCANCODE
1580 	/* USB key index -> key code -> AT scan code */
1581 	keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1582 	if (keycode == NN) {
1583 		return (NOKEY);
1584 	}
1585 	/* return an AT scan code for the K_RAW mode */
1586 	if (sc->sc_mode == K_RAW) {
1587 		return (ukbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1588 		    (usbcode & KEY_RELEASE)));
1589 	}
1590 #else					/* !UKBD_EMULATE_ATSCANCODE */
1591 
1592 	/* return the byte as is for the K_RAW mode */
1593 	if (sc->sc_mode == K_RAW) {
1594 		return (usbcode);
1595 	}
1596 	/* USB key index -> key code */
1597 	keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1598 	if (keycode == NN) {
1599 		return (NOKEY);
1600 	}
1601 #endif					/* UKBD_EMULATE_ATSCANCODE */
1602 
1603 	switch (keycode) {
1604 	case 0x38:			/* left alt (compose key) */
1605 		if (usbcode & KEY_RELEASE) {
1606 			if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1607 				sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1608 
1609 				if (sc->sc_composed_char > 0xFF) {
1610 					sc->sc_composed_char = 0;
1611 				}
1612 			}
1613 		} else {
1614 			if (!(sc->sc_flags & UKBD_FLAG_COMPOSE)) {
1615 				sc->sc_flags |= UKBD_FLAG_COMPOSE;
1616 				sc->sc_composed_char = 0;
1617 			}
1618 		}
1619 		break;
1620 	}
1621 
1622 	/* return the key code in the K_CODE mode */
1623 	if (usbcode & KEY_RELEASE) {
1624 		keycode |= SCAN_RELEASE;
1625 	}
1626 	if (sc->sc_mode == K_CODE) {
1627 		return (keycode);
1628 	}
1629 	/* compose a character code */
1630 	if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1631 		switch (keycode) {
1632 			/* key pressed, process it */
1633 		case 0x47:
1634 		case 0x48:
1635 		case 0x49:		/* keypad 7,8,9 */
1636 			sc->sc_composed_char *= 10;
1637 			sc->sc_composed_char += keycode - 0x40;
1638 			goto check_composed;
1639 
1640 		case 0x4B:
1641 		case 0x4C:
1642 		case 0x4D:		/* keypad 4,5,6 */
1643 			sc->sc_composed_char *= 10;
1644 			sc->sc_composed_char += keycode - 0x47;
1645 			goto check_composed;
1646 
1647 		case 0x4F:
1648 		case 0x50:
1649 		case 0x51:		/* keypad 1,2,3 */
1650 			sc->sc_composed_char *= 10;
1651 			sc->sc_composed_char += keycode - 0x4E;
1652 			goto check_composed;
1653 
1654 		case 0x52:		/* keypad 0 */
1655 			sc->sc_composed_char *= 10;
1656 			goto check_composed;
1657 
1658 			/* key released, no interest here */
1659 		case SCAN_RELEASE | 0x47:
1660 		case SCAN_RELEASE | 0x48:
1661 		case SCAN_RELEASE | 0x49:	/* keypad 7,8,9 */
1662 		case SCAN_RELEASE | 0x4B:
1663 		case SCAN_RELEASE | 0x4C:
1664 		case SCAN_RELEASE | 0x4D:	/* keypad 4,5,6 */
1665 		case SCAN_RELEASE | 0x4F:
1666 		case SCAN_RELEASE | 0x50:
1667 		case SCAN_RELEASE | 0x51:	/* keypad 1,2,3 */
1668 		case SCAN_RELEASE | 0x52:	/* keypad 0 */
1669 			goto next_code;
1670 
1671 		case 0x38:		/* left alt key */
1672 			break;
1673 
1674 		default:
1675 			if (sc->sc_composed_char > 0) {
1676 				sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1677 				sc->sc_composed_char = 0;
1678 				goto errkey;
1679 			}
1680 			break;
1681 		}
1682 	}
1683 	/* keycode to key action */
1684 	action = genkbd_keyaction(kbd, SCAN_CHAR(keycode),
1685 	    (keycode & SCAN_RELEASE),
1686 	    &sc->sc_state, &sc->sc_accents);
1687 	if (action == NOKEY) {
1688 		goto next_code;
1689 	}
1690 done:
1691 	return (action);
1692 
1693 check_composed:
1694 	if (sc->sc_composed_char <= 0xFF) {
1695 		goto next_code;
1696 	}
1697 errkey:
1698 	return (ERRKEY);
1699 }
1700 
1701 /* Currently wait is always false. */
1702 static uint32_t
1703 ukbd_read_char(keyboard_t *kbd, int wait)
1704 {
1705 	uint32_t keycode;
1706 
1707 	UKBD_LOCK();
1708 	keycode = ukbd_read_char_locked(kbd, wait);
1709 	UKBD_UNLOCK();
1710 
1711 	return (keycode);
1712 }
1713 
1714 /* some useful control functions */
1715 static int
1716 ukbd_ioctl_locked(keyboard_t *kbd, u_long cmd, caddr_t arg)
1717 {
1718 	struct ukbd_softc *sc = kbd->kb_data;
1719 	int i;
1720 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1721     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1722 	int ival;
1723 
1724 #endif
1725 
1726 	UKBD_LOCK_ASSERT();
1727 
1728 	switch (cmd) {
1729 	case KDGKBMODE:		/* get keyboard mode */
1730 		*(int *)arg = sc->sc_mode;
1731 		break;
1732 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1733     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1734 	case _IO('K', 7):
1735 		ival = IOCPARM_IVAL(arg);
1736 		arg = (caddr_t)&ival;
1737 		/* FALLTHROUGH */
1738 #endif
1739 	case KDSKBMODE:		/* set keyboard mode */
1740 		switch (*(int *)arg) {
1741 		case K_XLATE:
1742 			if (sc->sc_mode != K_XLATE) {
1743 				/* make lock key state and LED state match */
1744 				sc->sc_state &= ~LOCK_MASK;
1745 				sc->sc_state |= KBD_LED_VAL(kbd);
1746 			}
1747 			/* FALLTHROUGH */
1748 		case K_RAW:
1749 		case K_CODE:
1750 			if (sc->sc_mode != *(int *)arg) {
1751 				if ((sc->sc_flags & UKBD_FLAG_POLLING) == 0)
1752 					ukbd_clear_state(kbd);
1753 				sc->sc_mode = *(int *)arg;
1754 			}
1755 			break;
1756 		default:
1757 			return (EINVAL);
1758 		}
1759 		break;
1760 
1761 	case KDGETLED:			/* get keyboard LED */
1762 		*(int *)arg = KBD_LED_VAL(kbd);
1763 		break;
1764 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1765     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1766 	case _IO('K', 66):
1767 		ival = IOCPARM_IVAL(arg);
1768 		arg = (caddr_t)&ival;
1769 		/* FALLTHROUGH */
1770 #endif
1771 	case KDSETLED:			/* set keyboard LED */
1772 		/* NOTE: lock key state in "sc_state" won't be changed */
1773 		if (*(int *)arg & ~LOCK_MASK)
1774 			return (EINVAL);
1775 
1776 		i = *(int *)arg;
1777 
1778 		/* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1779 		if (sc->sc_mode == K_XLATE &&
1780 		    kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1781 			if (i & ALKED)
1782 				i |= CLKED;
1783 			else
1784 				i &= ~CLKED;
1785 		}
1786 		if (KBD_HAS_DEVICE(kbd))
1787 			ukbd_set_leds(sc, i);
1788 
1789 		KBD_LED_VAL(kbd) = *(int *)arg;
1790 		break;
1791 	case KDGKBSTATE:		/* get lock key state */
1792 		*(int *)arg = sc->sc_state & LOCK_MASK;
1793 		break;
1794 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1795     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1796 	case _IO('K', 20):
1797 		ival = IOCPARM_IVAL(arg);
1798 		arg = (caddr_t)&ival;
1799 		/* FALLTHROUGH */
1800 #endif
1801 	case KDSKBSTATE:		/* set lock key state */
1802 		if (*(int *)arg & ~LOCK_MASK) {
1803 			return (EINVAL);
1804 		}
1805 		sc->sc_state &= ~LOCK_MASK;
1806 		sc->sc_state |= *(int *)arg;
1807 
1808 		/* set LEDs and quit */
1809 		return (ukbd_ioctl(kbd, KDSETLED, arg));
1810 
1811 	case KDSETREPEAT:		/* set keyboard repeat rate (new
1812 					 * interface) */
1813 		if (!KBD_HAS_DEVICE(kbd)) {
1814 			return (0);
1815 		}
1816 		/*
1817 		 * Convert negative, zero and tiny args to the same limits
1818 		 * as atkbd.  We could support delays of 1 msec, but
1819 		 * anything much shorter than the shortest atkbd value
1820 		 * of 250.34 is almost unusable as well as incompatible.
1821 		 */
1822 		kbd->kb_delay1 = imax(((int *)arg)[0], 250);
1823 		kbd->kb_delay2 = imax(((int *)arg)[1], 34);
1824 #ifdef EVDEV_SUPPORT
1825 		if (sc->sc_evdev != NULL)
1826 			evdev_push_repeats(sc->sc_evdev, kbd);
1827 #endif
1828 		return (0);
1829 
1830 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1831     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1832 	case _IO('K', 67):
1833 		ival = IOCPARM_IVAL(arg);
1834 		arg = (caddr_t)&ival;
1835 		/* FALLTHROUGH */
1836 #endif
1837 	case KDSETRAD:			/* set keyboard repeat rate (old
1838 					 * interface) */
1839 		return (ukbd_set_typematic(kbd, *(int *)arg));
1840 
1841 	case PIO_KEYMAP:		/* set keyboard translation table */
1842 	case OPIO_KEYMAP:		/* set keyboard translation table
1843 					 * (compat) */
1844 	case PIO_KEYMAPENT:		/* set keyboard translation table
1845 					 * entry */
1846 	case PIO_DEADKEYMAP:		/* set accent key translation table */
1847 		sc->sc_accents = 0;
1848 		/* FALLTHROUGH */
1849 	default:
1850 		return (genkbd_commonioctl(kbd, cmd, arg));
1851 	}
1852 
1853 	return (0);
1854 }
1855 
1856 static int
1857 ukbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
1858 {
1859 	int result;
1860 
1861 	/*
1862 	 * XXX Check if someone is calling us from a critical section:
1863 	 */
1864 	if (curthread->td_critnest != 0)
1865 		return (EDEADLK);
1866 
1867 	/*
1868 	 * XXX KDGKBSTATE, KDSKBSTATE and KDSETLED can be called from any
1869 	 * context where printf(9) can be called, which among other things
1870 	 * includes interrupt filters and threads with any kinds of locks
1871 	 * already held.  For this reason it would be dangerous to acquire
1872 	 * the Giant here unconditionally.  On the other hand we have to
1873 	 * have it to handle the ioctl.
1874 	 * So we make our best effort to auto-detect whether we can grab
1875 	 * the Giant or not.  Blame syscons(4) for this.
1876 	 */
1877 	switch (cmd) {
1878 	case KDGKBSTATE:
1879 	case KDSKBSTATE:
1880 	case KDSETLED:
1881 		if (!mtx_owned(&Giant) && !USB_IN_POLLING_MODE_FUNC())
1882 			return (EDEADLK);	/* best I could come up with */
1883 		/* FALLTHROUGH */
1884 	default:
1885 		UKBD_LOCK();
1886 		result = ukbd_ioctl_locked(kbd, cmd, arg);
1887 		UKBD_UNLOCK();
1888 		return (result);
1889 	}
1890 }
1891 
1892 
1893 /* clear the internal state of the keyboard */
1894 static void
1895 ukbd_clear_state(keyboard_t *kbd)
1896 {
1897 	struct ukbd_softc *sc = kbd->kb_data;
1898 
1899 	UKBD_LOCK_ASSERT();
1900 
1901 	sc->sc_flags &= ~(UKBD_FLAG_COMPOSE | UKBD_FLAG_POLLING);
1902 	sc->sc_state &= LOCK_MASK;	/* preserve locking key state */
1903 	sc->sc_accents = 0;
1904 	sc->sc_composed_char = 0;
1905 #ifdef UKBD_EMULATE_ATSCANCODE
1906 	sc->sc_buffered_char[0] = 0;
1907 	sc->sc_buffered_char[1] = 0;
1908 #endif
1909 	memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1910 	memset(&sc->sc_odata, 0, sizeof(sc->sc_odata));
1911 	sc->sc_repeat_time = 0;
1912 	sc->sc_repeat_key = 0;
1913 }
1914 
1915 /* save the internal state, not used */
1916 static int
1917 ukbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1918 {
1919 	return (len == 0) ? 1 : -1;
1920 }
1921 
1922 /* set the internal state, not used */
1923 static int
1924 ukbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1925 {
1926 	return (EINVAL);
1927 }
1928 
1929 static int
1930 ukbd_poll(keyboard_t *kbd, int on)
1931 {
1932 	struct ukbd_softc *sc = kbd->kb_data;
1933 
1934 	UKBD_LOCK();
1935 	/*
1936 	 * Keep a reference count on polling to allow recursive
1937 	 * cngrab() during a panic for example.
1938 	 */
1939 	if (on)
1940 		sc->sc_polling++;
1941 	else if (sc->sc_polling > 0)
1942 		sc->sc_polling--;
1943 
1944 	if (sc->sc_polling != 0) {
1945 		sc->sc_flags |= UKBD_FLAG_POLLING;
1946 		sc->sc_poll_thread = curthread;
1947 	} else {
1948 		sc->sc_flags &= ~UKBD_FLAG_POLLING;
1949 		sc->sc_delay = 0;
1950 	}
1951 	UKBD_UNLOCK();
1952 
1953 	return (0);
1954 }
1955 
1956 /* local functions */
1957 
1958 static void
1959 ukbd_set_leds(struct ukbd_softc *sc, uint8_t leds)
1960 {
1961 
1962 	UKBD_LOCK_ASSERT();
1963 	DPRINTF("leds=0x%02x\n", leds);
1964 
1965 	sc->sc_leds = leds;
1966 	sc->sc_flags |= UKBD_FLAG_SET_LEDS;
1967 
1968 	/* start transfer, if not already started */
1969 
1970 	usbd_transfer_start(sc->sc_xfer[UKBD_CTRL_LED]);
1971 }
1972 
1973 static int
1974 ukbd_set_typematic(keyboard_t *kbd, int code)
1975 {
1976 #ifdef EVDEV_SUPPORT
1977 	struct ukbd_softc *sc = kbd->kb_data;
1978 #endif
1979 	static const int delays[] = {250, 500, 750, 1000};
1980 	static const int rates[] = {34, 38, 42, 46, 50, 55, 59, 63,
1981 		68, 76, 84, 92, 100, 110, 118, 126,
1982 		136, 152, 168, 184, 200, 220, 236, 252,
1983 	272, 304, 336, 368, 400, 440, 472, 504};
1984 
1985 	if (code & ~0x7f) {
1986 		return (EINVAL);
1987 	}
1988 	kbd->kb_delay1 = delays[(code >> 5) & 3];
1989 	kbd->kb_delay2 = rates[code & 0x1f];
1990 #ifdef EVDEV_SUPPORT
1991 	if (sc->sc_evdev != NULL)
1992 		evdev_push_repeats(sc->sc_evdev, kbd);
1993 #endif
1994 	return (0);
1995 }
1996 
1997 #ifdef UKBD_EMULATE_ATSCANCODE
1998 static uint32_t
1999 ukbd_atkeycode(int usbcode, const uint64_t *bitmap)
2000 {
2001 	uint32_t keycode;
2002 
2003 	keycode = ukbd_trtab[KEY_INDEX(usbcode)];
2004 
2005 	/*
2006 	 * Translate Alt-PrintScreen to SysRq.
2007 	 *
2008 	 * Some or all AT keyboards connected through USB have already
2009 	 * mapped Alted PrintScreens to an unusual usbcode (0x8a).
2010 	 * ukbd_trtab translates this to 0x7e, and key2scan() would
2011 	 * translate that to 0x79 (Intl' 4).  Assume that if we have
2012 	 * an Alted 0x7e here then it actually is an Alted PrintScreen.
2013 	 *
2014 	 * The usual usbcode for all PrintScreens is 0x46.  ukbd_trtab
2015 	 * translates this to 0x5c, so the Alt check to classify 0x5c
2016 	 * is routine.
2017 	 */
2018 	if ((keycode == 0x5c || keycode == 0x7e) &&
2019 	    (UKBD_KEY_PRESSED(bitmap, 0xe2 /* ALT-L */) ||
2020 	     UKBD_KEY_PRESSED(bitmap, 0xe6 /* ALT-R */)))
2021 		return (0x54);
2022 	return (keycode);
2023 }
2024 
2025 static int
2026 ukbd_key2scan(struct ukbd_softc *sc, int code, const uint64_t *bitmap, int up)
2027 {
2028 	static const int scan[] = {
2029 		/* 89 */
2030 		0x11c,	/* Enter */
2031 		/* 90-99 */
2032 		0x11d,	/* Ctrl-R */
2033 		0x135,	/* Divide */
2034 		0x137,	/* PrintScreen */
2035 		0x138,	/* Alt-R */
2036 		0x147,	/* Home */
2037 		0x148,	/* Up */
2038 		0x149,	/* PageUp */
2039 		0x14b,	/* Left */
2040 		0x14d,	/* Right */
2041 		0x14f,	/* End */
2042 		/* 100-109 */
2043 		0x150,	/* Down */
2044 		0x151,	/* PageDown */
2045 		0x152,	/* Insert */
2046 		0x153,	/* Delete */
2047 		0x146,	/* Pause/Break */
2048 		0x15b,	/* Win_L(Super_L) */
2049 		0x15c,	/* Win_R(Super_R) */
2050 		0x15d,	/* Application(Menu) */
2051 
2052 		/* SUN TYPE 6 USB KEYBOARD */
2053 		0x168,	/* Sun Type 6 Help */
2054 		0x15e,	/* Sun Type 6 Stop */
2055 		/* 110 - 119 */
2056 		0x15f,	/* Sun Type 6 Again */
2057 		0x160,	/* Sun Type 6 Props */
2058 		0x161,	/* Sun Type 6 Undo */
2059 		0x162,	/* Sun Type 6 Front */
2060 		0x163,	/* Sun Type 6 Copy */
2061 		0x164,	/* Sun Type 6 Open */
2062 		0x165,	/* Sun Type 6 Paste */
2063 		0x166,	/* Sun Type 6 Find */
2064 		0x167,	/* Sun Type 6 Cut */
2065 		0x125,	/* Sun Type 6 Mute */
2066 		/* 120 - 130 */
2067 		0x11f,	/* Sun Type 6 VolumeDown */
2068 		0x11e,	/* Sun Type 6 VolumeUp */
2069 		0x120,	/* Sun Type 6 PowerDown */
2070 
2071 		/* Japanese 106/109 keyboard */
2072 		0x73,	/* Keyboard Intl' 1 (backslash / underscore) */
2073 		0x70,	/* Keyboard Intl' 2 (Katakana / Hiragana) */
2074 		0x7d,	/* Keyboard Intl' 3 (Yen sign) (Not using in jp106/109) */
2075 		0x79,	/* Keyboard Intl' 4 (Henkan) */
2076 		0x7b,	/* Keyboard Intl' 5 (Muhenkan) */
2077 		0x5c,	/* Keyboard Intl' 6 (Keypad ,) (For PC-9821 layout) */
2078 		0x71,   /* Apple Keyboard JIS (Kana) */
2079 		0x72,   /* Apple Keyboard JIS (Eisu) */
2080 	};
2081 
2082 	if ((code >= 89) && (code < (int)(89 + nitems(scan)))) {
2083 		code = scan[code - 89];
2084 	}
2085 	/* PrintScreen */
2086 	if (code == 0x137 && (!(
2087 	    UKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
2088 	    UKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */) ||
2089 	    UKBD_KEY_PRESSED(bitmap, 0xe1 /* SHIFT-L */) ||
2090 	    UKBD_KEY_PRESSED(bitmap, 0xe5 /* SHIFT-R */)))) {
2091 		code |= SCAN_PREFIX_SHIFT;
2092 	}
2093 	/* Pause/Break */
2094 	if ((code == 0x146) && (!(
2095 	    UKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
2096 	    UKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */)))) {
2097 		code = (0x45 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL);
2098 	}
2099 	code |= (up ? SCAN_RELEASE : SCAN_PRESS);
2100 
2101 	if (code & SCAN_PREFIX) {
2102 		if (code & SCAN_PREFIX_CTL) {
2103 			/* Ctrl */
2104 			sc->sc_buffered_char[0] = (0x1d | (code & SCAN_RELEASE));
2105 			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX);
2106 		} else if (code & SCAN_PREFIX_SHIFT) {
2107 			/* Shift */
2108 			sc->sc_buffered_char[0] = (0x2a | (code & SCAN_RELEASE));
2109 			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX_SHIFT);
2110 		} else {
2111 			sc->sc_buffered_char[0] = (code & ~SCAN_PREFIX);
2112 			sc->sc_buffered_char[1] = 0;
2113 		}
2114 		return ((code & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
2115 	}
2116 	return (code);
2117 
2118 }
2119 
2120 #endif					/* UKBD_EMULATE_ATSCANCODE */
2121 
2122 static keyboard_switch_t ukbdsw = {
2123 	.probe = &ukbd__probe,
2124 	.init = &ukbd_init,
2125 	.term = &ukbd_term,
2126 	.intr = &ukbd_intr,
2127 	.test_if = &ukbd_test_if,
2128 	.enable = &ukbd_enable,
2129 	.disable = &ukbd_disable,
2130 	.read = &ukbd_read,
2131 	.check = &ukbd_check,
2132 	.read_char = &ukbd_read_char,
2133 	.check_char = &ukbd_check_char,
2134 	.ioctl = &ukbd_ioctl,
2135 	.lock = &ukbd_lock,
2136 	.clear_state = &ukbd_clear_state,
2137 	.get_state = &ukbd_get_state,
2138 	.set_state = &ukbd_set_state,
2139 	.poll = &ukbd_poll,
2140 };
2141 
2142 KEYBOARD_DRIVER(ukbd, ukbdsw, ukbd_configure);
2143 
2144 static int
2145 ukbd_driver_load(module_t mod, int what, void *arg)
2146 {
2147 	switch (what) {
2148 	case MOD_LOAD:
2149 		kbd_add_driver(&ukbd_kbd_driver);
2150 		break;
2151 	case MOD_UNLOAD:
2152 		kbd_delete_driver(&ukbd_kbd_driver);
2153 		break;
2154 	}
2155 	return (0);
2156 }
2157 
2158 static devclass_t ukbd_devclass;
2159 
2160 static device_method_t ukbd_methods[] = {
2161 	DEVMETHOD(device_probe, ukbd_probe),
2162 	DEVMETHOD(device_attach, ukbd_attach),
2163 	DEVMETHOD(device_detach, ukbd_detach),
2164 	DEVMETHOD(device_resume, ukbd_resume),
2165 
2166 	DEVMETHOD_END
2167 };
2168 
2169 static driver_t ukbd_driver = {
2170 	.name = "ukbd",
2171 	.methods = ukbd_methods,
2172 	.size = sizeof(struct ukbd_softc),
2173 };
2174 
2175 DRIVER_MODULE(ukbd, uhub, ukbd_driver, ukbd_devclass, ukbd_driver_load, 0);
2176 MODULE_DEPEND(ukbd, usb, 1, 1, 1);
2177 #ifdef EVDEV_SUPPORT
2178 MODULE_DEPEND(ukbd, evdev, 1, 1, 1);
2179 #endif
2180 MODULE_VERSION(ukbd, 1);
2181 USB_PNP_HOST_INFO(ukbd_devs);
2182