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