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