xref: /freebsd/sys/dev/usb/input/ukbd.c (revision 2f513db7)
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, 0, "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 		evdev_sync(sc->sc_evdev);
396 	}
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 
442 		usbd_transfer_poll(sc->sc_xfer, UKBD_N_TRANSFER);
443 
444 		/* Delay-optimised support for repetition of keys */
445 		if (ukbd_any_key_pressed(sc)) {
446 			/* a key is pressed - need timekeeping */
447 			DELAY(1000);
448 
449 			/* 1 millisecond has passed */
450 			sc->sc_time_ms += 1;
451 		}
452 
453 		ukbd_interrupt(sc);
454 
455 		if (!wait)
456 			break;
457 	}
458 }
459 
460 static int32_t
461 ukbd_get_key(struct ukbd_softc *sc, uint8_t wait)
462 {
463 	int32_t c;
464 
465 	UKBD_LOCK_ASSERT();
466 	KASSERT((USB_IN_POLLING_MODE_FUNC() == 0) ||
467 	    (sc->sc_flags & UKBD_FLAG_POLLING) != 0,
468 	    ("not polling in kdb or panic\n"));
469 
470 	if (sc->sc_inputs == 0 &&
471 	    (sc->sc_flags & UKBD_FLAG_GONE) == 0) {
472 		/* start transfer, if not already started */
473 		usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_0]);
474 		usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_1]);
475 	}
476 
477 	if (sc->sc_flags & UKBD_FLAG_POLLING)
478 		ukbd_do_poll(sc, wait);
479 
480 	if (sc->sc_inputs == 0) {
481 		c = -1;
482 	} else {
483 		c = sc->sc_input[sc->sc_inputhead];
484 		--(sc->sc_inputs);
485 		++(sc->sc_inputhead);
486 		if (sc->sc_inputhead >= UKBD_IN_BUF_SIZE) {
487 			sc->sc_inputhead = 0;
488 		}
489 	}
490 	return (c);
491 }
492 
493 static void
494 ukbd_interrupt(struct ukbd_softc *sc)
495 {
496 	const uint32_t now = sc->sc_time_ms;
497 	unsigned key;
498 
499 	UKBD_LOCK_ASSERT();
500 
501 	/* Check for key changes */
502 	for (key = 0; key != UKBD_NKEYCODE; key++) {
503 		const uint64_t mask = 1ULL << (key % 64);
504 		const uint64_t delta =
505 		    sc->sc_odata.bitmap[key / 64] ^
506 		    sc->sc_ndata.bitmap[key / 64];
507 
508 		if (mask == 1 && delta == 0) {
509 			key += 63;
510 			continue;	/* skip empty areas */
511 		} else if (delta & mask) {
512 			if (sc->sc_odata.bitmap[key / 64] & mask) {
513 				ukbd_put_key(sc, key | KEY_RELEASE);
514 
515 				/* clear repeating key, if any */
516 				if (sc->sc_repeat_key == key)
517 					sc->sc_repeat_key = 0;
518 			} else {
519 				ukbd_put_key(sc, key | KEY_PRESS);
520 
521 				if (ukbd_is_modifier_key(key))
522 					continue;
523 
524 				/*
525 				 * Check for first new key and set
526 				 * initial delay and [re]start timer:
527 				 */
528 				if (sc->sc_repeat_key == 0) {
529 					sc->sc_co_basetime = sbinuptime();
530 					sc->sc_delay = sc->sc_kbd.kb_delay1;
531 					ukbd_start_timer(sc);
532 				}
533 
534 				/* set repeat time for last key */
535 				sc->sc_repeat_time = now + sc->sc_kbd.kb_delay1;
536 				sc->sc_repeat_key = key;
537 			}
538 		}
539 	}
540 
541 	/* synchronize old data with new data */
542 	sc->sc_odata = sc->sc_ndata;
543 
544 	/* check if last key is still pressed */
545 	if (sc->sc_repeat_key != 0) {
546 		const int32_t dtime = (sc->sc_repeat_time - now);
547 
548 		/* check if time has elapsed */
549 		if (dtime <= 0) {
550 			ukbd_put_key(sc, sc->sc_repeat_key | KEY_PRESS);
551 			sc->sc_repeat_time = now + sc->sc_kbd.kb_delay2;
552 		}
553 	}
554 
555 	/* wakeup keyboard system */
556 	ukbd_event_keyinput(sc);
557 }
558 
559 static void
560 ukbd_event_keyinput(struct ukbd_softc *sc)
561 {
562 	int c;
563 
564 	UKBD_LOCK_ASSERT();
565 
566 	if ((sc->sc_flags & UKBD_FLAG_POLLING) != 0)
567 		return;
568 
569 	if (sc->sc_inputs == 0)
570 		return;
571 
572 	if (KBD_IS_ACTIVE(&sc->sc_kbd) &&
573 	    KBD_IS_BUSY(&sc->sc_kbd)) {
574 		/* let the callback function process the input */
575 		(sc->sc_kbd.kb_callback.kc_func) (&sc->sc_kbd, KBDIO_KEYINPUT,
576 		    sc->sc_kbd.kb_callback.kc_arg);
577 	} else {
578 		/* read and discard the input, no one is waiting for it */
579 		do {
580 			c = ukbd_read_char(&sc->sc_kbd, 0);
581 		} while (c != NOKEY);
582 	}
583 }
584 
585 static void
586 ukbd_timeout(void *arg)
587 {
588 	struct ukbd_softc *sc = arg;
589 
590 	UKBD_LOCK_ASSERT();
591 
592 	sc->sc_time_ms += sc->sc_delay;
593 	sc->sc_delay = 0;
594 
595 	ukbd_interrupt(sc);
596 
597 	/* Make sure any leftover key events gets read out */
598 	ukbd_event_keyinput(sc);
599 
600 	if (ukbd_any_key_pressed(sc) || (sc->sc_inputs != 0)) {
601 		ukbd_start_timer(sc);
602 	}
603 }
604 
605 static uint32_t
606 ukbd_apple_fn(uint32_t keycode)
607 {
608 	switch (keycode) {
609 	case 0x28: return 0x49; /* RETURN -> INSERT */
610 	case 0x2a: return 0x4c; /* BACKSPACE -> DEL */
611 	case 0x50: return 0x4a; /* LEFT ARROW -> HOME */
612 	case 0x4f: return 0x4d; /* RIGHT ARROW -> END */
613 	case 0x52: return 0x4b; /* UP ARROW -> PGUP */
614 	case 0x51: return 0x4e; /* DOWN ARROW -> PGDN */
615 	default: return keycode;
616 	}
617 }
618 
619 static uint32_t
620 ukbd_apple_swap(uint32_t keycode)
621 {
622 	switch (keycode) {
623 	case 0x35: return 0x64;
624 	case 0x64: return 0x35;
625 	default: return keycode;
626 	}
627 }
628 
629 static void
630 ukbd_intr_callback(struct usb_xfer *xfer, usb_error_t error)
631 {
632 	struct ukbd_softc *sc = usbd_xfer_softc(xfer);
633 	struct usb_page_cache *pc;
634 	uint32_t i;
635 	uint8_t id;
636 	uint8_t modifiers;
637 	int offset;
638 	int len;
639 
640 	UKBD_LOCK_ASSERT();
641 
642 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
643 	pc = usbd_xfer_get_frame(xfer, 0);
644 
645 	switch (USB_GET_STATE(xfer)) {
646 	case USB_ST_TRANSFERRED:
647 		DPRINTF("actlen=%d bytes\n", len);
648 
649 		if (len == 0) {
650 			DPRINTF("zero length data\n");
651 			goto tr_setup;
652 		}
653 
654 		if (sc->sc_kbd_id != 0) {
655 			/* check and remove HID ID byte */
656 			usbd_copy_out(pc, 0, &id, 1);
657 			offset = 1;
658 			len--;
659 			if (len == 0) {
660 				DPRINTF("zero length data\n");
661 				goto tr_setup;
662 			}
663 		} else {
664 			offset = 0;
665 			id = 0;
666 		}
667 
668 		if (len > UKBD_BUFFER_SIZE)
669 			len = UKBD_BUFFER_SIZE;
670 
671 		/* get data */
672 		usbd_copy_out(pc, offset, sc->sc_buffer, len);
673 
674 		/* clear temporary storage */
675 		memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
676 
677 		/* clear modifiers */
678 		modifiers = 0;
679 
680 		/* scan through HID data */
681 		if ((sc->sc_flags & UKBD_FLAG_APPLE_EJECT) &&
682 		    (id == sc->sc_id_apple_eject)) {
683 			if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_apple_eject))
684 				modifiers |= MOD_EJECT;
685 		}
686 		if ((sc->sc_flags & UKBD_FLAG_APPLE_FN) &&
687 		    (id == sc->sc_id_apple_fn)) {
688 			if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_apple_fn))
689 				modifiers |= MOD_FN;
690 		}
691 
692 		for (i = 0; i != UKBD_NKEYCODE; i++) {
693 			const uint64_t valid = sc->sc_loc_key_valid[i / 64];
694 			const uint64_t mask = 1ULL << (i % 64);
695 
696 			if (mask == 1 && valid == 0) {
697 				i += 63;
698 				continue;	/* skip empty areas */
699 			} else if (~valid & mask) {
700 				continue;	/* location is not valid */
701 			} else if (id != sc->sc_id_loc_key[i]) {
702 				continue;	/* invalid HID ID */
703 			} else if (i == 0) {
704 				offset = sc->sc_loc_key[0].count;
705 				if (offset < 0 || offset > len)
706 					offset = len;
707 				while (offset--) {
708 					uint32_t key =
709 					    hid_get_data(sc->sc_buffer + offset, len - offset,
710 					    &sc->sc_loc_key[i]);
711 					if (modifiers & MOD_FN)
712 						key = ukbd_apple_fn(key);
713 					if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP)
714 						key = ukbd_apple_swap(key);
715 					if (key == KEY_NONE || key == KEY_ERROR || key >= UKBD_NKEYCODE)
716 						continue;
717 					/* set key in bitmap */
718 					sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
719 				}
720 			} else if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_key[i])) {
721 				uint32_t key = i;
722 
723 				if (modifiers & MOD_FN)
724 					key = ukbd_apple_fn(key);
725 				if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP)
726 					key = ukbd_apple_swap(key);
727 				if (key == KEY_NONE || key == KEY_ERROR || key >= UKBD_NKEYCODE)
728 					continue;
729 				/* set key in bitmap */
730 				sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
731 			}
732 		}
733 #ifdef USB_DEBUG
734 		DPRINTF("modifiers = 0x%04x\n", modifiers);
735 		for (i = 0; i != UKBD_NKEYCODE; i++) {
736 			const uint64_t valid = sc->sc_ndata.bitmap[i / 64];
737 			const uint64_t mask = 1ULL << (i % 64);
738 
739 			if (valid & mask)
740 				DPRINTF("Key 0x%02x pressed\n", i);
741 		}
742 #endif
743 		ukbd_interrupt(sc);
744 
745 	case USB_ST_SETUP:
746 tr_setup:
747 		if (sc->sc_inputs < UKBD_IN_BUF_FULL) {
748 			usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
749 			usbd_transfer_submit(xfer);
750 		} else {
751 			DPRINTF("input queue is full!\n");
752 		}
753 		break;
754 
755 	default:			/* Error */
756 		DPRINTF("error=%s\n", usbd_errstr(error));
757 
758 		if (error != USB_ERR_CANCELLED) {
759 			/* try to clear stall first */
760 			usbd_xfer_set_stall(xfer);
761 			goto tr_setup;
762 		}
763 		break;
764 	}
765 }
766 
767 static void
768 ukbd_set_leds_callback(struct usb_xfer *xfer, usb_error_t error)
769 {
770 	struct ukbd_softc *sc = usbd_xfer_softc(xfer);
771 	struct usb_device_request req;
772 	struct usb_page_cache *pc;
773 	uint8_t id;
774 	uint8_t any;
775 	int len;
776 
777 	UKBD_LOCK_ASSERT();
778 
779 #ifdef USB_DEBUG
780 	if (ukbd_no_leds)
781 		return;
782 #endif
783 
784 	switch (USB_GET_STATE(xfer)) {
785 	case USB_ST_TRANSFERRED:
786 	case USB_ST_SETUP:
787 		if (!(sc->sc_flags & UKBD_FLAG_SET_LEDS))
788 			break;
789 		sc->sc_flags &= ~UKBD_FLAG_SET_LEDS;
790 
791 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
792 		req.bRequest = UR_SET_REPORT;
793 		USETW2(req.wValue, UHID_OUTPUT_REPORT, 0);
794 		req.wIndex[0] = sc->sc_iface_no;
795 		req.wIndex[1] = 0;
796 		req.wLength[1] = 0;
797 
798 		memset(sc->sc_buffer, 0, UKBD_BUFFER_SIZE);
799 
800 		id = 0;
801 		any = 0;
802 
803 		/* Assumption: All led bits must be in the same ID. */
804 
805 		if (sc->sc_flags & UKBD_FLAG_NUMLOCK) {
806 			if (sc->sc_leds & NLKED) {
807 				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
808 				    &sc->sc_loc_numlock, 1);
809 			}
810 			id = sc->sc_id_numlock;
811 			any = 1;
812 		}
813 
814 		if (sc->sc_flags & UKBD_FLAG_SCROLLLOCK) {
815 			if (sc->sc_leds & SLKED) {
816 				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
817 				    &sc->sc_loc_scrolllock, 1);
818 			}
819 			id = sc->sc_id_scrolllock;
820 			any = 1;
821 		}
822 
823 		if (sc->sc_flags & UKBD_FLAG_CAPSLOCK) {
824 			if (sc->sc_leds & CLKED) {
825 				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
826 				    &sc->sc_loc_capslock, 1);
827 			}
828 			id = sc->sc_id_capslock;
829 			any = 1;
830 		}
831 
832 		/* if no leds, nothing to do */
833 		if (!any)
834 			break;
835 
836 #ifdef EVDEV_SUPPORT
837 		if (sc->sc_evdev != NULL)
838 			evdev_push_leds(sc->sc_evdev, sc->sc_leds);
839 #endif
840 
841 		/* range check output report length */
842 		len = sc->sc_led_size;
843 		if (len > (UKBD_BUFFER_SIZE - 1))
844 			len = (UKBD_BUFFER_SIZE - 1);
845 
846 		/* check if we need to prefix an ID byte */
847 		sc->sc_buffer[0] = id;
848 
849 		pc = usbd_xfer_get_frame(xfer, 1);
850 		if (id != 0) {
851 			len++;
852 			usbd_copy_in(pc, 0, sc->sc_buffer, len);
853 		} else {
854 			usbd_copy_in(pc, 0, sc->sc_buffer + 1, len);
855 		}
856 		req.wLength[0] = len;
857 		usbd_xfer_set_frame_len(xfer, 1, len);
858 
859 		DPRINTF("len=%d, id=%d\n", len, id);
860 
861 		/* setup control request last */
862 		pc = usbd_xfer_get_frame(xfer, 0);
863 		usbd_copy_in(pc, 0, &req, sizeof(req));
864 		usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
865 
866 		/* start data transfer */
867 		usbd_xfer_set_frames(xfer, 2);
868 		usbd_transfer_submit(xfer);
869 		break;
870 
871 	default:			/* Error */
872 		DPRINTFN(1, "error=%s\n", usbd_errstr(error));
873 		break;
874 	}
875 }
876 
877 static const struct usb_config ukbd_config[UKBD_N_TRANSFER] = {
878 
879 	[UKBD_INTR_DT_0] = {
880 		.type = UE_INTERRUPT,
881 		.endpoint = UE_ADDR_ANY,
882 		.direction = UE_DIR_IN,
883 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
884 		.bufsize = 0,	/* use wMaxPacketSize */
885 		.callback = &ukbd_intr_callback,
886 	},
887 
888 	[UKBD_INTR_DT_1] = {
889 		.type = UE_INTERRUPT,
890 		.endpoint = UE_ADDR_ANY,
891 		.direction = UE_DIR_IN,
892 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
893 		.bufsize = 0,	/* use wMaxPacketSize */
894 		.callback = &ukbd_intr_callback,
895 	},
896 
897 	[UKBD_CTRL_LED] = {
898 		.type = UE_CONTROL,
899 		.endpoint = 0x00,	/* Control pipe */
900 		.direction = UE_DIR_ANY,
901 		.bufsize = sizeof(struct usb_device_request) + UKBD_BUFFER_SIZE,
902 		.callback = &ukbd_set_leds_callback,
903 		.timeout = 1000,	/* 1 second */
904 	},
905 };
906 
907 /* A match on these entries will load ukbd */
908 static const STRUCT_USB_HOST_ID __used ukbd_devs[] = {
909 	{USB_IFACE_CLASS(UICLASS_HID),
910 	 USB_IFACE_SUBCLASS(UISUBCLASS_BOOT),
911 	 USB_IFACE_PROTOCOL(UIPROTO_BOOT_KEYBOARD),},
912 };
913 
914 static int
915 ukbd_probe(device_t dev)
916 {
917 	keyboard_switch_t *sw = kbd_get_switch(UKBD_DRIVER_NAME);
918 	struct usb_attach_arg *uaa = device_get_ivars(dev);
919 	void *d_ptr;
920 	int error;
921 	uint16_t d_len;
922 
923 	UKBD_LOCK_ASSERT();
924 	DPRINTFN(11, "\n");
925 
926 	if (sw == NULL) {
927 		return (ENXIO);
928 	}
929 	if (uaa->usb_mode != USB_MODE_HOST) {
930 		return (ENXIO);
931 	}
932 
933 	if (uaa->info.bInterfaceClass != UICLASS_HID)
934 		return (ENXIO);
935 
936 	if (usb_test_quirk(uaa, UQ_KBD_IGNORE))
937 		return (ENXIO);
938 
939 	if ((uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) &&
940 	    (uaa->info.bInterfaceProtocol == UIPROTO_BOOT_KEYBOARD))
941 		return (BUS_PROBE_DEFAULT);
942 
943 	error = usbd_req_get_hid_desc(uaa->device, NULL,
944 	    &d_ptr, &d_len, M_TEMP, uaa->info.bIfaceIndex);
945 
946 	if (error)
947 		return (ENXIO);
948 
949 	if (hid_is_keyboard(d_ptr, d_len)) {
950 		if (hid_is_mouse(d_ptr, d_len)) {
951 			/*
952 			 * NOTE: We currently don't support USB mouse
953 			 * and USB keyboard on the same USB endpoint.
954 			 * Let "ums" driver win.
955 			 */
956 			error = ENXIO;
957 		} else {
958 			error = BUS_PROBE_DEFAULT;
959 		}
960 	} else {
961 		error = ENXIO;
962 	}
963 	free(d_ptr, M_TEMP);
964 	return (error);
965 }
966 
967 static void
968 ukbd_parse_hid(struct ukbd_softc *sc, const uint8_t *ptr, uint32_t len)
969 {
970 	uint32_t flags;
971 	uint32_t key;
972 
973 	/* reset detected bits */
974 	sc->sc_flags &= ~UKBD_FLAG_HID_MASK;
975 
976 	/* reset detected keys */
977 	memset(sc->sc_loc_key_valid, 0, sizeof(sc->sc_loc_key_valid));
978 
979 	/* check if there is an ID byte */
980 	sc->sc_kbd_size = hid_report_size(ptr, len,
981 	    hid_input, &sc->sc_kbd_id);
982 
983 	/* investigate if this is an Apple Keyboard */
984 	if (hid_locate(ptr, len,
985 	    HID_USAGE2(HUP_CONSUMER, HUG_APPLE_EJECT),
986 	    hid_input, 0, &sc->sc_loc_apple_eject, &flags,
987 	    &sc->sc_id_apple_eject)) {
988 		if (flags & HIO_VARIABLE)
989 			sc->sc_flags |= UKBD_FLAG_APPLE_EJECT |
990 			    UKBD_FLAG_APPLE_SWAP;
991 		DPRINTFN(1, "Found Apple eject-key\n");
992 	}
993 	if (hid_locate(ptr, len,
994 	    HID_USAGE2(0xFFFF, 0x0003),
995 	    hid_input, 0, &sc->sc_loc_apple_fn, &flags,
996 	    &sc->sc_id_apple_fn)) {
997 		if (flags & HIO_VARIABLE)
998 			sc->sc_flags |= UKBD_FLAG_APPLE_FN;
999 		DPRINTFN(1, "Found Apple FN-key\n");
1000 	}
1001 
1002 	/* figure out event buffer */
1003 	if (hid_locate(ptr, len,
1004 	    HID_USAGE2(HUP_KEYBOARD, 0x00),
1005 	    hid_input, 0, &sc->sc_loc_key[0], &flags,
1006 	    &sc->sc_id_loc_key[0])) {
1007 		if (flags & HIO_VARIABLE) {
1008 			DPRINTFN(1, "Ignoring keyboard event control\n");
1009 		} else {
1010 			sc->sc_loc_key_valid[0] |= 1;
1011 			DPRINTFN(1, "Found keyboard event array\n");
1012 		}
1013 	}
1014 
1015 	/* figure out the keys */
1016 	for (key = 1; key != UKBD_NKEYCODE; key++) {
1017 		if (hid_locate(ptr, len,
1018 		    HID_USAGE2(HUP_KEYBOARD, key),
1019 		    hid_input, 0, &sc->sc_loc_key[key], &flags,
1020 		    &sc->sc_id_loc_key[key])) {
1021 			if (flags & HIO_VARIABLE) {
1022 				sc->sc_loc_key_valid[key / 64] |=
1023 				    1ULL << (key % 64);
1024 				DPRINTFN(1, "Found key 0x%02x\n", key);
1025 			}
1026 		}
1027 	}
1028 
1029 	/* figure out leds on keyboard */
1030 	sc->sc_led_size = hid_report_size(ptr, len,
1031 	    hid_output, NULL);
1032 
1033 	if (hid_locate(ptr, len,
1034 	    HID_USAGE2(HUP_LEDS, 0x01),
1035 	    hid_output, 0, &sc->sc_loc_numlock, &flags,
1036 	    &sc->sc_id_numlock)) {
1037 		if (flags & HIO_VARIABLE)
1038 			sc->sc_flags |= UKBD_FLAG_NUMLOCK;
1039 		DPRINTFN(1, "Found keyboard numlock\n");
1040 	}
1041 	if (hid_locate(ptr, len,
1042 	    HID_USAGE2(HUP_LEDS, 0x02),
1043 	    hid_output, 0, &sc->sc_loc_capslock, &flags,
1044 	    &sc->sc_id_capslock)) {
1045 		if (flags & HIO_VARIABLE)
1046 			sc->sc_flags |= UKBD_FLAG_CAPSLOCK;
1047 		DPRINTFN(1, "Found keyboard capslock\n");
1048 	}
1049 	if (hid_locate(ptr, len,
1050 	    HID_USAGE2(HUP_LEDS, 0x03),
1051 	    hid_output, 0, &sc->sc_loc_scrolllock, &flags,
1052 	    &sc->sc_id_scrolllock)) {
1053 		if (flags & HIO_VARIABLE)
1054 			sc->sc_flags |= UKBD_FLAG_SCROLLLOCK;
1055 		DPRINTFN(1, "Found keyboard scrolllock\n");
1056 	}
1057 }
1058 
1059 static int
1060 ukbd_attach(device_t dev)
1061 {
1062 	struct ukbd_softc *sc = device_get_softc(dev);
1063 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1064 	int unit = device_get_unit(dev);
1065 	keyboard_t *kbd = &sc->sc_kbd;
1066 	void *hid_ptr = NULL;
1067 	usb_error_t err;
1068 	uint16_t n;
1069 	uint16_t hid_len;
1070 #ifdef EVDEV_SUPPORT
1071 	struct evdev_dev *evdev;
1072 	int i;
1073 #endif
1074 #ifdef USB_DEBUG
1075 	int rate;
1076 #endif
1077 	UKBD_LOCK_ASSERT();
1078 
1079 	kbd_init_struct(kbd, UKBD_DRIVER_NAME, KB_OTHER, unit, 0, 0, 0);
1080 
1081 	kbd->kb_data = (void *)sc;
1082 
1083 	device_set_usb_desc(dev);
1084 
1085 	sc->sc_udev = uaa->device;
1086 	sc->sc_iface = uaa->iface;
1087 	sc->sc_iface_index = uaa->info.bIfaceIndex;
1088 	sc->sc_iface_no = uaa->info.bIfaceNum;
1089 	sc->sc_mode = K_XLATE;
1090 
1091 	usb_callout_init_mtx(&sc->sc_callout, &Giant, 0);
1092 
1093 #ifdef UKBD_NO_POLLING
1094 	err = usbd_transfer_setup(uaa->device,
1095 	    &uaa->info.bIfaceIndex, sc->sc_xfer, ukbd_config,
1096 	    UKBD_N_TRANSFER, sc, &Giant);
1097 #else
1098 	/*
1099 	 * Setup the UKBD USB transfers one by one, so they are memory
1100 	 * independent which allows for handling panics triggered by
1101 	 * the keyboard driver itself, typically via CTRL+ALT+ESC
1102 	 * sequences. Or if the USB keyboard driver was processing a
1103 	 * key at the moment of panic.
1104 	 */
1105 	for (n = 0; n != UKBD_N_TRANSFER; n++) {
1106 		err = usbd_transfer_setup(uaa->device,
1107 		    &uaa->info.bIfaceIndex, sc->sc_xfer + n, ukbd_config + n,
1108 		    1, sc, &Giant);
1109 		if (err)
1110 			break;
1111 	}
1112 #endif
1113 
1114 	if (err) {
1115 		DPRINTF("error=%s\n", usbd_errstr(err));
1116 		goto detach;
1117 	}
1118 	/* setup default keyboard maps */
1119 
1120 	sc->sc_keymap = key_map;
1121 	sc->sc_accmap = accent_map;
1122 	for (n = 0; n < UKBD_NFKEY; n++) {
1123 		sc->sc_fkeymap[n] = fkey_tab[n];
1124 	}
1125 
1126 	kbd_set_maps(kbd, &sc->sc_keymap, &sc->sc_accmap,
1127 	    sc->sc_fkeymap, UKBD_NFKEY);
1128 
1129 	KBD_FOUND_DEVICE(kbd);
1130 
1131 	ukbd_clear_state(kbd);
1132 
1133 	/*
1134 	 * FIXME: set the initial value for lock keys in "sc_state"
1135 	 * according to the BIOS data?
1136 	 */
1137 	KBD_PROBE_DONE(kbd);
1138 
1139 	/* get HID descriptor */
1140 	err = usbd_req_get_hid_desc(uaa->device, NULL, &hid_ptr,
1141 	    &hid_len, M_TEMP, uaa->info.bIfaceIndex);
1142 
1143 	if (err == 0) {
1144 		DPRINTF("Parsing HID descriptor of %d bytes\n",
1145 		    (int)hid_len);
1146 
1147 		ukbd_parse_hid(sc, hid_ptr, hid_len);
1148 
1149 		free(hid_ptr, M_TEMP);
1150 	}
1151 
1152 	/* check if we should use the boot protocol */
1153 	if (usb_test_quirk(uaa, UQ_KBD_BOOTPROTO) ||
1154 	    (err != 0) || ukbd_any_key_valid(sc) == false) {
1155 
1156 		DPRINTF("Forcing boot protocol\n");
1157 
1158 		err = usbd_req_set_protocol(sc->sc_udev, NULL,
1159 			sc->sc_iface_index, 0);
1160 
1161 		if (err != 0) {
1162 			DPRINTF("Set protocol error=%s (ignored)\n",
1163 			    usbd_errstr(err));
1164 		}
1165 
1166 		ukbd_parse_hid(sc, ukbd_boot_desc, sizeof(ukbd_boot_desc));
1167 	}
1168 
1169 	/* ignore if SETIDLE fails, hence it is not crucial */
1170 	usbd_req_set_idle(sc->sc_udev, NULL, sc->sc_iface_index, 0, 0);
1171 
1172 	ukbd_ioctl(kbd, KDSETLED, (caddr_t)&sc->sc_state);
1173 
1174 	KBD_INIT_DONE(kbd);
1175 
1176 	if (kbd_register(kbd) < 0) {
1177 		goto detach;
1178 	}
1179 	KBD_CONFIG_DONE(kbd);
1180 
1181 	ukbd_enable(kbd);
1182 
1183 #ifdef KBD_INSTALL_CDEV
1184 	if (kbd_attach(kbd)) {
1185 		goto detach;
1186 	}
1187 #endif
1188 
1189 #ifdef EVDEV_SUPPORT
1190 	evdev = evdev_alloc();
1191 	evdev_set_name(evdev, device_get_desc(dev));
1192 	evdev_set_phys(evdev, device_get_nameunit(dev));
1193 	evdev_set_id(evdev, BUS_USB, uaa->info.idVendor,
1194 	   uaa->info.idProduct, 0);
1195 	evdev_set_serial(evdev, usb_get_serial(uaa->device));
1196 	evdev_set_methods(evdev, kbd, &ukbd_evdev_methods);
1197 	evdev_support_event(evdev, EV_SYN);
1198 	evdev_support_event(evdev, EV_KEY);
1199 	if (sc->sc_flags & (UKBD_FLAG_NUMLOCK | UKBD_FLAG_CAPSLOCK |
1200 			    UKBD_FLAG_SCROLLLOCK))
1201 		evdev_support_event(evdev, EV_LED);
1202 	evdev_support_event(evdev, EV_REP);
1203 
1204 	for (i = 0x00; i <= 0xFF; i++)
1205 		evdev_support_key(evdev, evdev_hid2key(i));
1206 	if (sc->sc_flags & UKBD_FLAG_NUMLOCK)
1207 		evdev_support_led(evdev, LED_NUML);
1208 	if (sc->sc_flags & UKBD_FLAG_CAPSLOCK)
1209 		evdev_support_led(evdev, LED_CAPSL);
1210 	if (sc->sc_flags & UKBD_FLAG_SCROLLLOCK)
1211 		evdev_support_led(evdev, LED_SCROLLL);
1212 
1213 	if (evdev_register_mtx(evdev, &Giant))
1214 		evdev_free(evdev);
1215 	else
1216 		sc->sc_evdev = evdev;
1217 #endif
1218 
1219 	sc->sc_flags |= UKBD_FLAG_ATTACHED;
1220 
1221 	if (bootverbose) {
1222 		kbdd_diag(kbd, bootverbose);
1223 	}
1224 
1225 #ifdef USB_DEBUG
1226 	/* check for polling rate override */
1227 	rate = ukbd_pollrate;
1228 	if (rate > 0) {
1229 		if (rate > 1000)
1230 			rate = 1;
1231 		else
1232 			rate = 1000 / rate;
1233 
1234 		/* set new polling interval in ms */
1235 		usbd_xfer_set_interval(sc->sc_xfer[UKBD_INTR_DT_0], rate);
1236 		usbd_xfer_set_interval(sc->sc_xfer[UKBD_INTR_DT_1], rate);
1237 	}
1238 #endif
1239 	/* start the keyboard */
1240 	usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_0]);
1241 	usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_1]);
1242 
1243 	return (0);			/* success */
1244 
1245 detach:
1246 	ukbd_detach(dev);
1247 	return (ENXIO);			/* error */
1248 }
1249 
1250 static int
1251 ukbd_detach(device_t dev)
1252 {
1253 	struct ukbd_softc *sc = device_get_softc(dev);
1254 	int error;
1255 
1256 	UKBD_LOCK_ASSERT();
1257 
1258 	DPRINTF("\n");
1259 
1260 	sc->sc_flags |= UKBD_FLAG_GONE;
1261 
1262 	usb_callout_stop(&sc->sc_callout);
1263 
1264 	/* kill any stuck keys */
1265 	if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
1266 		/* stop receiving events from the USB keyboard */
1267 		usbd_transfer_stop(sc->sc_xfer[UKBD_INTR_DT_0]);
1268 		usbd_transfer_stop(sc->sc_xfer[UKBD_INTR_DT_1]);
1269 
1270 		/* release all leftover keys, if any */
1271 		memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1272 
1273 		/* process releasing of all keys */
1274 		ukbd_interrupt(sc);
1275 	}
1276 
1277 	ukbd_disable(&sc->sc_kbd);
1278 
1279 #ifdef KBD_INSTALL_CDEV
1280 	if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
1281 		error = kbd_detach(&sc->sc_kbd);
1282 		if (error) {
1283 			/* usb attach cannot return an error */
1284 			device_printf(dev, "WARNING: kbd_detach() "
1285 			    "returned non-zero! (ignored)\n");
1286 		}
1287 	}
1288 #endif
1289 
1290 #ifdef EVDEV_SUPPORT
1291 	evdev_free(sc->sc_evdev);
1292 #endif
1293 
1294 	if (KBD_IS_CONFIGURED(&sc->sc_kbd)) {
1295 		error = kbd_unregister(&sc->sc_kbd);
1296 		if (error) {
1297 			/* usb attach cannot return an error */
1298 			device_printf(dev, "WARNING: kbd_unregister() "
1299 			    "returned non-zero! (ignored)\n");
1300 		}
1301 	}
1302 	sc->sc_kbd.kb_flags = 0;
1303 
1304 	usbd_transfer_unsetup(sc->sc_xfer, UKBD_N_TRANSFER);
1305 
1306 	usb_callout_drain(&sc->sc_callout);
1307 
1308 	DPRINTF("%s: disconnected\n",
1309 	    device_get_nameunit(dev));
1310 
1311 	return (0);
1312 }
1313 
1314 static int
1315 ukbd_resume(device_t dev)
1316 {
1317 	struct ukbd_softc *sc = device_get_softc(dev);
1318 
1319 	UKBD_LOCK_ASSERT();
1320 
1321 	ukbd_clear_state(&sc->sc_kbd);
1322 
1323 	return (0);
1324 }
1325 
1326 #ifdef EVDEV_SUPPORT
1327 static void
1328 ukbd_ev_event(struct evdev_dev *evdev, uint16_t type, uint16_t code,
1329     int32_t value)
1330 {
1331 	keyboard_t *kbd = evdev_get_softc(evdev);
1332 
1333 	if (evdev_rcpt_mask & EVDEV_RCPT_HW_KBD &&
1334 	    (type == EV_LED || type == EV_REP)) {
1335 		mtx_lock(&Giant);
1336 		kbd_ev_event(kbd, type, code, value);
1337 		mtx_unlock(&Giant);
1338 	}
1339 }
1340 #endif
1341 
1342 /* early keyboard probe, not supported */
1343 static int
1344 ukbd_configure(int flags)
1345 {
1346 	return (0);
1347 }
1348 
1349 /* detect a keyboard, not used */
1350 static int
1351 ukbd__probe(int unit, void *arg, int flags)
1352 {
1353 	return (ENXIO);
1354 }
1355 
1356 /* reset and initialize the device, not used */
1357 static int
1358 ukbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
1359 {
1360 	return (ENXIO);
1361 }
1362 
1363 /* test the interface to the device, not used */
1364 static int
1365 ukbd_test_if(keyboard_t *kbd)
1366 {
1367 	return (0);
1368 }
1369 
1370 /* finish using this keyboard, not used */
1371 static int
1372 ukbd_term(keyboard_t *kbd)
1373 {
1374 	return (ENXIO);
1375 }
1376 
1377 /* keyboard interrupt routine, not used */
1378 static int
1379 ukbd_intr(keyboard_t *kbd, void *arg)
1380 {
1381 	return (0);
1382 }
1383 
1384 /* lock the access to the keyboard, not used */
1385 static int
1386 ukbd_lock(keyboard_t *kbd, int lock)
1387 {
1388 	return (1);
1389 }
1390 
1391 /*
1392  * Enable the access to the device; until this function is called,
1393  * the client cannot read from the keyboard.
1394  */
1395 static int
1396 ukbd_enable(keyboard_t *kbd)
1397 {
1398 
1399 	UKBD_LOCK();
1400 	KBD_ACTIVATE(kbd);
1401 	UKBD_UNLOCK();
1402 
1403 	return (0);
1404 }
1405 
1406 /* disallow the access to the device */
1407 static int
1408 ukbd_disable(keyboard_t *kbd)
1409 {
1410 
1411 	UKBD_LOCK();
1412 	KBD_DEACTIVATE(kbd);
1413 	UKBD_UNLOCK();
1414 
1415 	return (0);
1416 }
1417 
1418 /* check if data is waiting */
1419 /* Currently unused. */
1420 static int
1421 ukbd_check(keyboard_t *kbd)
1422 {
1423 	struct ukbd_softc *sc = kbd->kb_data;
1424 
1425 	UKBD_LOCK_ASSERT();
1426 
1427 	if (!KBD_IS_ACTIVE(kbd))
1428 		return (0);
1429 
1430 	if (sc->sc_flags & UKBD_FLAG_POLLING)
1431 		ukbd_do_poll(sc, 0);
1432 
1433 #ifdef UKBD_EMULATE_ATSCANCODE
1434 	if (sc->sc_buffered_char[0]) {
1435 		return (1);
1436 	}
1437 #endif
1438 	if (sc->sc_inputs > 0) {
1439 		return (1);
1440 	}
1441 	return (0);
1442 }
1443 
1444 /* check if char is waiting */
1445 static int
1446 ukbd_check_char_locked(keyboard_t *kbd)
1447 {
1448 	struct ukbd_softc *sc = kbd->kb_data;
1449 
1450 	UKBD_LOCK_ASSERT();
1451 
1452 	if (!KBD_IS_ACTIVE(kbd))
1453 		return (0);
1454 
1455 	if ((sc->sc_composed_char > 0) &&
1456 	    (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1457 		return (1);
1458 	}
1459 	return (ukbd_check(kbd));
1460 }
1461 
1462 static int
1463 ukbd_check_char(keyboard_t *kbd)
1464 {
1465 	int result;
1466 
1467 	UKBD_LOCK();
1468 	result = ukbd_check_char_locked(kbd);
1469 	UKBD_UNLOCK();
1470 
1471 	return (result);
1472 }
1473 
1474 /* read one byte from the keyboard if it's allowed */
1475 /* Currently unused. */
1476 static int
1477 ukbd_read(keyboard_t *kbd, int wait)
1478 {
1479 	struct ukbd_softc *sc = kbd->kb_data;
1480 	int32_t usbcode;
1481 #ifdef UKBD_EMULATE_ATSCANCODE
1482 	uint32_t keycode;
1483 	uint32_t scancode;
1484 
1485 #endif
1486 
1487 	UKBD_LOCK_ASSERT();
1488 
1489 	if (!KBD_IS_ACTIVE(kbd))
1490 		return (-1);
1491 
1492 #ifdef UKBD_EMULATE_ATSCANCODE
1493 	if (sc->sc_buffered_char[0]) {
1494 		scancode = sc->sc_buffered_char[0];
1495 		if (scancode & SCAN_PREFIX) {
1496 			sc->sc_buffered_char[0] &= ~SCAN_PREFIX;
1497 			return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1498 		}
1499 		sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1500 		sc->sc_buffered_char[1] = 0;
1501 		return (scancode);
1502 	}
1503 #endif					/* UKBD_EMULATE_ATSCANCODE */
1504 
1505 	/* XXX */
1506 	usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1507 	if (!KBD_IS_ACTIVE(kbd) || (usbcode == -1))
1508 		return (-1);
1509 
1510 	++(kbd->kb_count);
1511 
1512 #ifdef UKBD_EMULATE_ATSCANCODE
1513 	keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1514 	if (keycode == NN) {
1515 		return -1;
1516 	}
1517 	return (ukbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1518 	    (usbcode & KEY_RELEASE)));
1519 #else					/* !UKBD_EMULATE_ATSCANCODE */
1520 	return (usbcode);
1521 #endif					/* UKBD_EMULATE_ATSCANCODE */
1522 }
1523 
1524 /* read char from the keyboard */
1525 static uint32_t
1526 ukbd_read_char_locked(keyboard_t *kbd, int wait)
1527 {
1528 	struct ukbd_softc *sc = kbd->kb_data;
1529 	uint32_t action;
1530 	uint32_t keycode;
1531 	int32_t usbcode;
1532 #ifdef UKBD_EMULATE_ATSCANCODE
1533 	uint32_t scancode;
1534 #endif
1535 
1536 	UKBD_LOCK_ASSERT();
1537 
1538 	if (!KBD_IS_ACTIVE(kbd))
1539 		return (NOKEY);
1540 
1541 next_code:
1542 
1543 	/* do we have a composed char to return ? */
1544 
1545 	if ((sc->sc_composed_char > 0) &&
1546 	    (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1547 
1548 		action = sc->sc_composed_char;
1549 		sc->sc_composed_char = 0;
1550 
1551 		if (action > 0xFF) {
1552 			goto errkey;
1553 		}
1554 		goto done;
1555 	}
1556 #ifdef UKBD_EMULATE_ATSCANCODE
1557 
1558 	/* do we have a pending raw scan code? */
1559 
1560 	if (sc->sc_mode == K_RAW) {
1561 		scancode = sc->sc_buffered_char[0];
1562 		if (scancode) {
1563 			if (scancode & SCAN_PREFIX) {
1564 				sc->sc_buffered_char[0] = (scancode & ~SCAN_PREFIX);
1565 				return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1566 			}
1567 			sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1568 			sc->sc_buffered_char[1] = 0;
1569 			return (scancode);
1570 		}
1571 	}
1572 #endif					/* UKBD_EMULATE_ATSCANCODE */
1573 
1574 	/* see if there is something in the keyboard port */
1575 	/* XXX */
1576 	usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1577 	if (usbcode == -1) {
1578 		return (NOKEY);
1579 	}
1580 	++kbd->kb_count;
1581 
1582 #ifdef UKBD_EMULATE_ATSCANCODE
1583 	/* USB key index -> key code -> AT scan code */
1584 	keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1585 	if (keycode == NN) {
1586 		return (NOKEY);
1587 	}
1588 	/* return an AT scan code for the K_RAW mode */
1589 	if (sc->sc_mode == K_RAW) {
1590 		return (ukbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1591 		    (usbcode & KEY_RELEASE)));
1592 	}
1593 #else					/* !UKBD_EMULATE_ATSCANCODE */
1594 
1595 	/* return the byte as is for the K_RAW mode */
1596 	if (sc->sc_mode == K_RAW) {
1597 		return (usbcode);
1598 	}
1599 	/* USB key index -> key code */
1600 	keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1601 	if (keycode == NN) {
1602 		return (NOKEY);
1603 	}
1604 #endif					/* UKBD_EMULATE_ATSCANCODE */
1605 
1606 	switch (keycode) {
1607 	case 0x38:			/* left alt (compose key) */
1608 		if (usbcode & KEY_RELEASE) {
1609 			if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1610 				sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1611 
1612 				if (sc->sc_composed_char > 0xFF) {
1613 					sc->sc_composed_char = 0;
1614 				}
1615 			}
1616 		} else {
1617 			if (!(sc->sc_flags & UKBD_FLAG_COMPOSE)) {
1618 				sc->sc_flags |= UKBD_FLAG_COMPOSE;
1619 				sc->sc_composed_char = 0;
1620 			}
1621 		}
1622 		break;
1623 	}
1624 
1625 	/* return the key code in the K_CODE mode */
1626 	if (usbcode & KEY_RELEASE) {
1627 		keycode |= SCAN_RELEASE;
1628 	}
1629 	if (sc->sc_mode == K_CODE) {
1630 		return (keycode);
1631 	}
1632 	/* compose a character code */
1633 	if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1634 		switch (keycode) {
1635 			/* key pressed, process it */
1636 		case 0x47:
1637 		case 0x48:
1638 		case 0x49:		/* keypad 7,8,9 */
1639 			sc->sc_composed_char *= 10;
1640 			sc->sc_composed_char += keycode - 0x40;
1641 			goto check_composed;
1642 
1643 		case 0x4B:
1644 		case 0x4C:
1645 		case 0x4D:		/* keypad 4,5,6 */
1646 			sc->sc_composed_char *= 10;
1647 			sc->sc_composed_char += keycode - 0x47;
1648 			goto check_composed;
1649 
1650 		case 0x4F:
1651 		case 0x50:
1652 		case 0x51:		/* keypad 1,2,3 */
1653 			sc->sc_composed_char *= 10;
1654 			sc->sc_composed_char += keycode - 0x4E;
1655 			goto check_composed;
1656 
1657 		case 0x52:		/* keypad 0 */
1658 			sc->sc_composed_char *= 10;
1659 			goto check_composed;
1660 
1661 			/* key released, no interest here */
1662 		case SCAN_RELEASE | 0x47:
1663 		case SCAN_RELEASE | 0x48:
1664 		case SCAN_RELEASE | 0x49:	/* keypad 7,8,9 */
1665 		case SCAN_RELEASE | 0x4B:
1666 		case SCAN_RELEASE | 0x4C:
1667 		case SCAN_RELEASE | 0x4D:	/* keypad 4,5,6 */
1668 		case SCAN_RELEASE | 0x4F:
1669 		case SCAN_RELEASE | 0x50:
1670 		case SCAN_RELEASE | 0x51:	/* keypad 1,2,3 */
1671 		case SCAN_RELEASE | 0x52:	/* keypad 0 */
1672 			goto next_code;
1673 
1674 		case 0x38:		/* left alt key */
1675 			break;
1676 
1677 		default:
1678 			if (sc->sc_composed_char > 0) {
1679 				sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1680 				sc->sc_composed_char = 0;
1681 				goto errkey;
1682 			}
1683 			break;
1684 		}
1685 	}
1686 	/* keycode to key action */
1687 	action = genkbd_keyaction(kbd, SCAN_CHAR(keycode),
1688 	    (keycode & SCAN_RELEASE),
1689 	    &sc->sc_state, &sc->sc_accents);
1690 	if (action == NOKEY) {
1691 		goto next_code;
1692 	}
1693 done:
1694 	return (action);
1695 
1696 check_composed:
1697 	if (sc->sc_composed_char <= 0xFF) {
1698 		goto next_code;
1699 	}
1700 errkey:
1701 	return (ERRKEY);
1702 }
1703 
1704 /* Currently wait is always false. */
1705 static uint32_t
1706 ukbd_read_char(keyboard_t *kbd, int wait)
1707 {
1708 	uint32_t keycode;
1709 
1710 	UKBD_LOCK();
1711 	keycode = ukbd_read_char_locked(kbd, wait);
1712 	UKBD_UNLOCK();
1713 
1714 	return (keycode);
1715 }
1716 
1717 /* some useful control functions */
1718 static int
1719 ukbd_ioctl_locked(keyboard_t *kbd, u_long cmd, caddr_t arg)
1720 {
1721 	struct ukbd_softc *sc = kbd->kb_data;
1722 	int i;
1723 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1724     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1725 	int ival;
1726 
1727 #endif
1728 
1729 	UKBD_LOCK_ASSERT();
1730 
1731 	switch (cmd) {
1732 	case KDGKBMODE:		/* get keyboard mode */
1733 		*(int *)arg = sc->sc_mode;
1734 		break;
1735 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1736     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1737 	case _IO('K', 7):
1738 		ival = IOCPARM_IVAL(arg);
1739 		arg = (caddr_t)&ival;
1740 		/* FALLTHROUGH */
1741 #endif
1742 	case KDSKBMODE:		/* set keyboard mode */
1743 		switch (*(int *)arg) {
1744 		case K_XLATE:
1745 			if (sc->sc_mode != K_XLATE) {
1746 				/* make lock key state and LED state match */
1747 				sc->sc_state &= ~LOCK_MASK;
1748 				sc->sc_state |= KBD_LED_VAL(kbd);
1749 			}
1750 			/* FALLTHROUGH */
1751 		case K_RAW:
1752 		case K_CODE:
1753 			if (sc->sc_mode != *(int *)arg) {
1754 				if ((sc->sc_flags & UKBD_FLAG_POLLING) == 0)
1755 					ukbd_clear_state(kbd);
1756 				sc->sc_mode = *(int *)arg;
1757 			}
1758 			break;
1759 		default:
1760 			return (EINVAL);
1761 		}
1762 		break;
1763 
1764 	case KDGETLED:			/* get keyboard LED */
1765 		*(int *)arg = KBD_LED_VAL(kbd);
1766 		break;
1767 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1768     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1769 	case _IO('K', 66):
1770 		ival = IOCPARM_IVAL(arg);
1771 		arg = (caddr_t)&ival;
1772 		/* FALLTHROUGH */
1773 #endif
1774 	case KDSETLED:			/* set keyboard LED */
1775 		/* NOTE: lock key state in "sc_state" won't be changed */
1776 		if (*(int *)arg & ~LOCK_MASK)
1777 			return (EINVAL);
1778 
1779 		i = *(int *)arg;
1780 
1781 		/* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1782 		if (sc->sc_mode == K_XLATE &&
1783 		    kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1784 			if (i & ALKED)
1785 				i |= CLKED;
1786 			else
1787 				i &= ~CLKED;
1788 		}
1789 		if (KBD_HAS_DEVICE(kbd))
1790 			ukbd_set_leds(sc, i);
1791 
1792 		KBD_LED_VAL(kbd) = *(int *)arg;
1793 		break;
1794 	case KDGKBSTATE:		/* get lock key state */
1795 		*(int *)arg = sc->sc_state & LOCK_MASK;
1796 		break;
1797 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1798     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1799 	case _IO('K', 20):
1800 		ival = IOCPARM_IVAL(arg);
1801 		arg = (caddr_t)&ival;
1802 		/* FALLTHROUGH */
1803 #endif
1804 	case KDSKBSTATE:		/* set lock key state */
1805 		if (*(int *)arg & ~LOCK_MASK) {
1806 			return (EINVAL);
1807 		}
1808 		sc->sc_state &= ~LOCK_MASK;
1809 		sc->sc_state |= *(int *)arg;
1810 
1811 		/* set LEDs and quit */
1812 		return (ukbd_ioctl(kbd, KDSETLED, arg));
1813 
1814 	case KDSETREPEAT:		/* set keyboard repeat rate (new
1815 					 * interface) */
1816 		if (!KBD_HAS_DEVICE(kbd)) {
1817 			return (0);
1818 		}
1819 		/*
1820 		 * Convert negative, zero and tiny args to the same limits
1821 		 * as atkbd.  We could support delays of 1 msec, but
1822 		 * anything much shorter than the shortest atkbd value
1823 		 * of 250.34 is almost unusable as well as incompatible.
1824 		 */
1825 		kbd->kb_delay1 = imax(((int *)arg)[0], 250);
1826 		kbd->kb_delay2 = imax(((int *)arg)[1], 34);
1827 #ifdef EVDEV_SUPPORT
1828 		if (sc->sc_evdev != NULL)
1829 			evdev_push_repeats(sc->sc_evdev, kbd);
1830 #endif
1831 		return (0);
1832 
1833 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1834     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1835 	case _IO('K', 67):
1836 		ival = IOCPARM_IVAL(arg);
1837 		arg = (caddr_t)&ival;
1838 		/* FALLTHROUGH */
1839 #endif
1840 	case KDSETRAD:			/* set keyboard repeat rate (old
1841 					 * interface) */
1842 		return (ukbd_set_typematic(kbd, *(int *)arg));
1843 
1844 	case PIO_KEYMAP:		/* set keyboard translation table */
1845 	case OPIO_KEYMAP:		/* set keyboard translation table
1846 					 * (compat) */
1847 	case PIO_KEYMAPENT:		/* set keyboard translation table
1848 					 * entry */
1849 	case PIO_DEADKEYMAP:		/* set accent key translation table */
1850 		sc->sc_accents = 0;
1851 		/* FALLTHROUGH */
1852 	default:
1853 		return (genkbd_commonioctl(kbd, cmd, arg));
1854 	}
1855 
1856 	return (0);
1857 }
1858 
1859 static int
1860 ukbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
1861 {
1862 	int result;
1863 
1864 	/*
1865 	 * XXX Check if someone is calling us from a critical section:
1866 	 */
1867 	if (curthread->td_critnest != 0)
1868 		return (EDEADLK);
1869 
1870 	/*
1871 	 * XXX KDGKBSTATE, KDSKBSTATE and KDSETLED can be called from any
1872 	 * context where printf(9) can be called, which among other things
1873 	 * includes interrupt filters and threads with any kinds of locks
1874 	 * already held.  For this reason it would be dangerous to acquire
1875 	 * the Giant here unconditionally.  On the other hand we have to
1876 	 * have it to handle the ioctl.
1877 	 * So we make our best effort to auto-detect whether we can grab
1878 	 * the Giant or not.  Blame syscons(4) for this.
1879 	 */
1880 	switch (cmd) {
1881 	case KDGKBSTATE:
1882 	case KDSKBSTATE:
1883 	case KDSETLED:
1884 		if (!mtx_owned(&Giant) && !USB_IN_POLLING_MODE_FUNC())
1885 			return (EDEADLK);	/* best I could come up with */
1886 		/* FALLTHROUGH */
1887 	default:
1888 		UKBD_LOCK();
1889 		result = ukbd_ioctl_locked(kbd, cmd, arg);
1890 		UKBD_UNLOCK();
1891 		return (result);
1892 	}
1893 }
1894 
1895 
1896 /* clear the internal state of the keyboard */
1897 static void
1898 ukbd_clear_state(keyboard_t *kbd)
1899 {
1900 	struct ukbd_softc *sc = kbd->kb_data;
1901 
1902 	UKBD_LOCK_ASSERT();
1903 
1904 	sc->sc_flags &= ~(UKBD_FLAG_COMPOSE | UKBD_FLAG_POLLING);
1905 	sc->sc_state &= LOCK_MASK;	/* preserve locking key state */
1906 	sc->sc_accents = 0;
1907 	sc->sc_composed_char = 0;
1908 #ifdef UKBD_EMULATE_ATSCANCODE
1909 	sc->sc_buffered_char[0] = 0;
1910 	sc->sc_buffered_char[1] = 0;
1911 #endif
1912 	memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1913 	memset(&sc->sc_odata, 0, sizeof(sc->sc_odata));
1914 	sc->sc_repeat_time = 0;
1915 	sc->sc_repeat_key = 0;
1916 }
1917 
1918 /* save the internal state, not used */
1919 static int
1920 ukbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1921 {
1922 	return (len == 0) ? 1 : -1;
1923 }
1924 
1925 /* set the internal state, not used */
1926 static int
1927 ukbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1928 {
1929 	return (EINVAL);
1930 }
1931 
1932 static int
1933 ukbd_poll(keyboard_t *kbd, int on)
1934 {
1935 	struct ukbd_softc *sc = kbd->kb_data;
1936 
1937 	UKBD_LOCK();
1938 	/*
1939 	 * Keep a reference count on polling to allow recursive
1940 	 * cngrab() during a panic for example.
1941 	 */
1942 	if (on)
1943 		sc->sc_polling++;
1944 	else if (sc->sc_polling > 0)
1945 		sc->sc_polling--;
1946 
1947 	if (sc->sc_polling != 0) {
1948 		sc->sc_flags |= UKBD_FLAG_POLLING;
1949 		sc->sc_poll_thread = curthread;
1950 	} else {
1951 		sc->sc_flags &= ~UKBD_FLAG_POLLING;
1952 		sc->sc_delay = 0;
1953 	}
1954 	UKBD_UNLOCK();
1955 
1956 	return (0);
1957 }
1958 
1959 /* local functions */
1960 
1961 static void
1962 ukbd_set_leds(struct ukbd_softc *sc, uint8_t leds)
1963 {
1964 
1965 	UKBD_LOCK_ASSERT();
1966 	DPRINTF("leds=0x%02x\n", leds);
1967 
1968 	sc->sc_leds = leds;
1969 	sc->sc_flags |= UKBD_FLAG_SET_LEDS;
1970 
1971 	/* start transfer, if not already started */
1972 
1973 	usbd_transfer_start(sc->sc_xfer[UKBD_CTRL_LED]);
1974 }
1975 
1976 static int
1977 ukbd_set_typematic(keyboard_t *kbd, int code)
1978 {
1979 #ifdef EVDEV_SUPPORT
1980 	struct ukbd_softc *sc = kbd->kb_data;
1981 #endif
1982 	static const int delays[] = {250, 500, 750, 1000};
1983 	static const int rates[] = {34, 38, 42, 46, 50, 55, 59, 63,
1984 		68, 76, 84, 92, 100, 110, 118, 126,
1985 		136, 152, 168, 184, 200, 220, 236, 252,
1986 	272, 304, 336, 368, 400, 440, 472, 504};
1987 
1988 	if (code & ~0x7f) {
1989 		return (EINVAL);
1990 	}
1991 	kbd->kb_delay1 = delays[(code >> 5) & 3];
1992 	kbd->kb_delay2 = rates[code & 0x1f];
1993 #ifdef EVDEV_SUPPORT
1994 	if (sc->sc_evdev != NULL)
1995 		evdev_push_repeats(sc->sc_evdev, kbd);
1996 #endif
1997 	return (0);
1998 }
1999 
2000 #ifdef UKBD_EMULATE_ATSCANCODE
2001 static uint32_t
2002 ukbd_atkeycode(int usbcode, const uint64_t *bitmap)
2003 {
2004 	uint32_t keycode;
2005 
2006 	keycode = ukbd_trtab[KEY_INDEX(usbcode)];
2007 
2008 	/*
2009 	 * Translate Alt-PrintScreen to SysRq.
2010 	 *
2011 	 * Some or all AT keyboards connected through USB have already
2012 	 * mapped Alted PrintScreens to an unusual usbcode (0x8a).
2013 	 * ukbd_trtab translates this to 0x7e, and key2scan() would
2014 	 * translate that to 0x79 (Intl' 4).  Assume that if we have
2015 	 * an Alted 0x7e here then it actually is an Alted PrintScreen.
2016 	 *
2017 	 * The usual usbcode for all PrintScreens is 0x46.  ukbd_trtab
2018 	 * translates this to 0x5c, so the Alt check to classify 0x5c
2019 	 * is routine.
2020 	 */
2021 	if ((keycode == 0x5c || keycode == 0x7e) &&
2022 	    (UKBD_KEY_PRESSED(bitmap, 0xe2 /* ALT-L */) ||
2023 	     UKBD_KEY_PRESSED(bitmap, 0xe6 /* ALT-R */)))
2024 		return (0x54);
2025 	return (keycode);
2026 }
2027 
2028 static int
2029 ukbd_key2scan(struct ukbd_softc *sc, int code, const uint64_t *bitmap, int up)
2030 {
2031 	static const int scan[] = {
2032 		/* 89 */
2033 		0x11c,	/* Enter */
2034 		/* 90-99 */
2035 		0x11d,	/* Ctrl-R */
2036 		0x135,	/* Divide */
2037 		0x137,	/* PrintScreen */
2038 		0x138,	/* Alt-R */
2039 		0x147,	/* Home */
2040 		0x148,	/* Up */
2041 		0x149,	/* PageUp */
2042 		0x14b,	/* Left */
2043 		0x14d,	/* Right */
2044 		0x14f,	/* End */
2045 		/* 100-109 */
2046 		0x150,	/* Down */
2047 		0x151,	/* PageDown */
2048 		0x152,	/* Insert */
2049 		0x153,	/* Delete */
2050 		0x146,	/* Pause/Break */
2051 		0x15b,	/* Win_L(Super_L) */
2052 		0x15c,	/* Win_R(Super_R) */
2053 		0x15d,	/* Application(Menu) */
2054 
2055 		/* SUN TYPE 6 USB KEYBOARD */
2056 		0x168,	/* Sun Type 6 Help */
2057 		0x15e,	/* Sun Type 6 Stop */
2058 		/* 110 - 119 */
2059 		0x15f,	/* Sun Type 6 Again */
2060 		0x160,	/* Sun Type 6 Props */
2061 		0x161,	/* Sun Type 6 Undo */
2062 		0x162,	/* Sun Type 6 Front */
2063 		0x163,	/* Sun Type 6 Copy */
2064 		0x164,	/* Sun Type 6 Open */
2065 		0x165,	/* Sun Type 6 Paste */
2066 		0x166,	/* Sun Type 6 Find */
2067 		0x167,	/* Sun Type 6 Cut */
2068 		0x125,	/* Sun Type 6 Mute */
2069 		/* 120 - 130 */
2070 		0x11f,	/* Sun Type 6 VolumeDown */
2071 		0x11e,	/* Sun Type 6 VolumeUp */
2072 		0x120,	/* Sun Type 6 PowerDown */
2073 
2074 		/* Japanese 106/109 keyboard */
2075 		0x73,	/* Keyboard Intl' 1 (backslash / underscore) */
2076 		0x70,	/* Keyboard Intl' 2 (Katakana / Hiragana) */
2077 		0x7d,	/* Keyboard Intl' 3 (Yen sign) (Not using in jp106/109) */
2078 		0x79,	/* Keyboard Intl' 4 (Henkan) */
2079 		0x7b,	/* Keyboard Intl' 5 (Muhenkan) */
2080 		0x5c,	/* Keyboard Intl' 6 (Keypad ,) (For PC-9821 layout) */
2081 		0x71,   /* Apple Keyboard JIS (Kana) */
2082 		0x72,   /* Apple Keyboard JIS (Eisu) */
2083 	};
2084 
2085 	if ((code >= 89) && (code < (int)(89 + nitems(scan)))) {
2086 		code = scan[code - 89];
2087 	}
2088 	/* PrintScreen */
2089 	if (code == 0x137 && (!(
2090 	    UKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
2091 	    UKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */) ||
2092 	    UKBD_KEY_PRESSED(bitmap, 0xe1 /* SHIFT-L */) ||
2093 	    UKBD_KEY_PRESSED(bitmap, 0xe5 /* SHIFT-R */)))) {
2094 		code |= SCAN_PREFIX_SHIFT;
2095 	}
2096 	/* Pause/Break */
2097 	if ((code == 0x146) && (!(
2098 	    UKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
2099 	    UKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */)))) {
2100 		code = (0x45 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL);
2101 	}
2102 	code |= (up ? SCAN_RELEASE : SCAN_PRESS);
2103 
2104 	if (code & SCAN_PREFIX) {
2105 		if (code & SCAN_PREFIX_CTL) {
2106 			/* Ctrl */
2107 			sc->sc_buffered_char[0] = (0x1d | (code & SCAN_RELEASE));
2108 			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX);
2109 		} else if (code & SCAN_PREFIX_SHIFT) {
2110 			/* Shift */
2111 			sc->sc_buffered_char[0] = (0x2a | (code & SCAN_RELEASE));
2112 			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX_SHIFT);
2113 		} else {
2114 			sc->sc_buffered_char[0] = (code & ~SCAN_PREFIX);
2115 			sc->sc_buffered_char[1] = 0;
2116 		}
2117 		return ((code & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
2118 	}
2119 	return (code);
2120 
2121 }
2122 
2123 #endif					/* UKBD_EMULATE_ATSCANCODE */
2124 
2125 static keyboard_switch_t ukbdsw = {
2126 	.probe = &ukbd__probe,
2127 	.init = &ukbd_init,
2128 	.term = &ukbd_term,
2129 	.intr = &ukbd_intr,
2130 	.test_if = &ukbd_test_if,
2131 	.enable = &ukbd_enable,
2132 	.disable = &ukbd_disable,
2133 	.read = &ukbd_read,
2134 	.check = &ukbd_check,
2135 	.read_char = &ukbd_read_char,
2136 	.check_char = &ukbd_check_char,
2137 	.ioctl = &ukbd_ioctl,
2138 	.lock = &ukbd_lock,
2139 	.clear_state = &ukbd_clear_state,
2140 	.get_state = &ukbd_get_state,
2141 	.set_state = &ukbd_set_state,
2142 	.poll = &ukbd_poll,
2143 };
2144 
2145 KEYBOARD_DRIVER(ukbd, ukbdsw, ukbd_configure);
2146 
2147 static int
2148 ukbd_driver_load(module_t mod, int what, void *arg)
2149 {
2150 	switch (what) {
2151 	case MOD_LOAD:
2152 		kbd_add_driver(&ukbd_kbd_driver);
2153 		break;
2154 	case MOD_UNLOAD:
2155 		kbd_delete_driver(&ukbd_kbd_driver);
2156 		break;
2157 	}
2158 	return (0);
2159 }
2160 
2161 static devclass_t ukbd_devclass;
2162 
2163 static device_method_t ukbd_methods[] = {
2164 	DEVMETHOD(device_probe, ukbd_probe),
2165 	DEVMETHOD(device_attach, ukbd_attach),
2166 	DEVMETHOD(device_detach, ukbd_detach),
2167 	DEVMETHOD(device_resume, ukbd_resume),
2168 
2169 	DEVMETHOD_END
2170 };
2171 
2172 static driver_t ukbd_driver = {
2173 	.name = "ukbd",
2174 	.methods = ukbd_methods,
2175 	.size = sizeof(struct ukbd_softc),
2176 };
2177 
2178 DRIVER_MODULE(ukbd, uhub, ukbd_driver, ukbd_devclass, ukbd_driver_load, 0);
2179 MODULE_DEPEND(ukbd, usb, 1, 1, 1);
2180 #ifdef EVDEV_SUPPORT
2181 MODULE_DEPEND(ukbd, evdev, 1, 1, 1);
2182 #endif
2183 MODULE_VERSION(ukbd, 1);
2184 USB_PNP_HOST_INFO(ukbd_devs);
2185