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