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