xref: /freebsd/sys/dev/usb/input/ukbd.c (revision cdebaff820b2a4915a16cedfd511823d78aab171)
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_SUPPORT
76 #include <dev/evdev/input.h>
77 #include <dev/evdev/evdev.h>
78 #endif
79 
80 #include <sys/ioccom.h>
81 #include <sys/filio.h>
82 #include <sys/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_SUPPORT
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_SUPPORT
367 static const 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_SUPPORT
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_SUPPORT
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_SUPPORT
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_SUPPORT
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_SUPPORT
1435 	evdev_free(sc->sc_evdev);
1436 #endif
1437 
1438 	if (KBD_IS_CONFIGURED(&sc->sc_kbd)) {
1439 		error = kbd_unregister(&sc->sc_kbd);
1440 		if (error) {
1441 			/* usb attach cannot return an error */
1442 			device_printf(dev, "WARNING: kbd_unregister() "
1443 			    "returned non-zero! (ignored)\n");
1444 		}
1445 	}
1446 	sc->sc_kbd.kb_flags = 0;
1447 
1448 	usbd_transfer_unsetup(sc->sc_xfer, UKBD_N_TRANSFER);
1449 
1450 	usb_callout_drain(&sc->sc_callout);
1451 
1452 	DPRINTF("%s: disconnected\n",
1453 	    device_get_nameunit(dev));
1454 
1455 	return (0);
1456 }
1457 
1458 static int
1459 ukbd_resume(device_t dev)
1460 {
1461 	struct ukbd_softc *sc = device_get_softc(dev);
1462 
1463 	UKBD_LOCK_ASSERT();
1464 
1465 	ukbd_clear_state(&sc->sc_kbd);
1466 
1467 	return (0);
1468 }
1469 
1470 /* early keyboard probe, not supported */
1471 static int
1472 ukbd_configure(int flags)
1473 {
1474 	return (0);
1475 }
1476 
1477 /* detect a keyboard, not used */
1478 static int
1479 ukbd__probe(int unit, void *arg, int flags)
1480 {
1481 	return (ENXIO);
1482 }
1483 
1484 /* reset and initialize the device, not used */
1485 static int
1486 ukbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
1487 {
1488 	return (ENXIO);
1489 }
1490 
1491 /* test the interface to the device, not used */
1492 static int
1493 ukbd_test_if(keyboard_t *kbd)
1494 {
1495 	return (0);
1496 }
1497 
1498 /* finish using this keyboard, not used */
1499 static int
1500 ukbd_term(keyboard_t *kbd)
1501 {
1502 	return (ENXIO);
1503 }
1504 
1505 /* keyboard interrupt routine, not used */
1506 static int
1507 ukbd_intr(keyboard_t *kbd, void *arg)
1508 {
1509 	return (0);
1510 }
1511 
1512 /* lock the access to the keyboard, not used */
1513 static int
1514 ukbd_lock(keyboard_t *kbd, int lock)
1515 {
1516 	return (1);
1517 }
1518 
1519 /*
1520  * Enable the access to the device; until this function is called,
1521  * the client cannot read from the keyboard.
1522  */
1523 static int
1524 ukbd_enable(keyboard_t *kbd)
1525 {
1526 
1527 	UKBD_LOCK();
1528 	KBD_ACTIVATE(kbd);
1529 	UKBD_UNLOCK();
1530 
1531 	return (0);
1532 }
1533 
1534 /* disallow the access to the device */
1535 static int
1536 ukbd_disable(keyboard_t *kbd)
1537 {
1538 
1539 	UKBD_LOCK();
1540 	KBD_DEACTIVATE(kbd);
1541 	UKBD_UNLOCK();
1542 
1543 	return (0);
1544 }
1545 
1546 /* check if data is waiting */
1547 /* Currently unused. */
1548 static int
1549 ukbd_check(keyboard_t *kbd)
1550 {
1551 	struct ukbd_softc *sc = kbd->kb_data;
1552 
1553 	UKBD_LOCK_ASSERT();
1554 
1555 	if (!KBD_IS_ACTIVE(kbd))
1556 		return (0);
1557 
1558 	if (sc->sc_flags & UKBD_FLAG_POLLING)
1559 		ukbd_do_poll(sc, 0);
1560 
1561 #ifdef UKBD_EMULATE_ATSCANCODE
1562 	if (sc->sc_buffered_char[0]) {
1563 		return (1);
1564 	}
1565 #endif
1566 	if (sc->sc_inputs > 0) {
1567 		return (1);
1568 	}
1569 	return (0);
1570 }
1571 
1572 /* check if char is waiting */
1573 static int
1574 ukbd_check_char_locked(keyboard_t *kbd)
1575 {
1576 	struct ukbd_softc *sc = kbd->kb_data;
1577 
1578 	UKBD_LOCK_ASSERT();
1579 
1580 	if (!KBD_IS_ACTIVE(kbd))
1581 		return (0);
1582 
1583 	if ((sc->sc_composed_char > 0) &&
1584 	    (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1585 		return (1);
1586 	}
1587 	return (ukbd_check(kbd));
1588 }
1589 
1590 static int
1591 ukbd_check_char(keyboard_t *kbd)
1592 {
1593 	int result;
1594 
1595 	UKBD_LOCK();
1596 	result = ukbd_check_char_locked(kbd);
1597 	UKBD_UNLOCK();
1598 
1599 	return (result);
1600 }
1601 
1602 /* read one byte from the keyboard if it's allowed */
1603 /* Currently unused. */
1604 static int
1605 ukbd_read(keyboard_t *kbd, int wait)
1606 {
1607 	struct ukbd_softc *sc = kbd->kb_data;
1608 	int32_t usbcode;
1609 #ifdef UKBD_EMULATE_ATSCANCODE
1610 	uint32_t keycode;
1611 	uint32_t scancode;
1612 
1613 #endif
1614 
1615 	UKBD_LOCK_ASSERT();
1616 
1617 	if (!KBD_IS_ACTIVE(kbd))
1618 		return (-1);
1619 
1620 #ifdef UKBD_EMULATE_ATSCANCODE
1621 	if (sc->sc_buffered_char[0]) {
1622 		scancode = sc->sc_buffered_char[0];
1623 		if (scancode & SCAN_PREFIX) {
1624 			sc->sc_buffered_char[0] &= ~SCAN_PREFIX;
1625 			return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1626 		}
1627 		sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1628 		sc->sc_buffered_char[1] = 0;
1629 		return (scancode);
1630 	}
1631 #endif					/* UKBD_EMULATE_ATSCANCODE */
1632 
1633 	/* XXX */
1634 	usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1635 	if (!KBD_IS_ACTIVE(kbd) || (usbcode == -1))
1636 		return (-1);
1637 
1638 	++(kbd->kb_count);
1639 
1640 #ifdef UKBD_EMULATE_ATSCANCODE
1641 	keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.modifiers);
1642 	if (keycode == NN) {
1643 		return -1;
1644 	}
1645 	return (ukbd_key2scan(sc, keycode, sc->sc_ndata.modifiers,
1646 	    (usbcode & KEY_RELEASE)));
1647 #else					/* !UKBD_EMULATE_ATSCANCODE */
1648 	return (usbcode);
1649 #endif					/* UKBD_EMULATE_ATSCANCODE */
1650 }
1651 
1652 /* read char from the keyboard */
1653 static uint32_t
1654 ukbd_read_char_locked(keyboard_t *kbd, int wait)
1655 {
1656 	struct ukbd_softc *sc = kbd->kb_data;
1657 	uint32_t action;
1658 	uint32_t keycode;
1659 	int32_t usbcode;
1660 #ifdef UKBD_EMULATE_ATSCANCODE
1661 	uint32_t scancode;
1662 #endif
1663 
1664 	UKBD_LOCK_ASSERT();
1665 
1666 	if (!KBD_IS_ACTIVE(kbd))
1667 		return (NOKEY);
1668 
1669 next_code:
1670 
1671 	/* do we have a composed char to return ? */
1672 
1673 	if ((sc->sc_composed_char > 0) &&
1674 	    (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1675 
1676 		action = sc->sc_composed_char;
1677 		sc->sc_composed_char = 0;
1678 
1679 		if (action > 0xFF) {
1680 			goto errkey;
1681 		}
1682 		goto done;
1683 	}
1684 #ifdef UKBD_EMULATE_ATSCANCODE
1685 
1686 	/* do we have a pending raw scan code? */
1687 
1688 	if (sc->sc_mode == K_RAW) {
1689 		scancode = sc->sc_buffered_char[0];
1690 		if (scancode) {
1691 			if (scancode & SCAN_PREFIX) {
1692 				sc->sc_buffered_char[0] = (scancode & ~SCAN_PREFIX);
1693 				return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1694 			}
1695 			sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1696 			sc->sc_buffered_char[1] = 0;
1697 			return (scancode);
1698 		}
1699 	}
1700 #endif					/* UKBD_EMULATE_ATSCANCODE */
1701 
1702 	/* see if there is something in the keyboard port */
1703 	/* XXX */
1704 	usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1705 	if (usbcode == -1) {
1706 		return (NOKEY);
1707 	}
1708 	++kbd->kb_count;
1709 
1710 #ifdef UKBD_EMULATE_ATSCANCODE
1711 	/* USB key index -> key code -> AT scan code */
1712 	keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.modifiers);
1713 	if (keycode == NN) {
1714 		return (NOKEY);
1715 	}
1716 	/* return an AT scan code for the K_RAW mode */
1717 	if (sc->sc_mode == K_RAW) {
1718 		return (ukbd_key2scan(sc, keycode, sc->sc_ndata.modifiers,
1719 		    (usbcode & KEY_RELEASE)));
1720 	}
1721 #else					/* !UKBD_EMULATE_ATSCANCODE */
1722 
1723 	/* return the byte as is for the K_RAW mode */
1724 	if (sc->sc_mode == K_RAW) {
1725 		return (usbcode);
1726 	}
1727 	/* USB key index -> key code */
1728 	keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1729 	if (keycode == NN) {
1730 		return (NOKEY);
1731 	}
1732 #endif					/* UKBD_EMULATE_ATSCANCODE */
1733 
1734 	switch (keycode) {
1735 	case 0x38:			/* left alt (compose key) */
1736 		if (usbcode & KEY_RELEASE) {
1737 			if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1738 				sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1739 
1740 				if (sc->sc_composed_char > 0xFF) {
1741 					sc->sc_composed_char = 0;
1742 				}
1743 			}
1744 		} else {
1745 			if (!(sc->sc_flags & UKBD_FLAG_COMPOSE)) {
1746 				sc->sc_flags |= UKBD_FLAG_COMPOSE;
1747 				sc->sc_composed_char = 0;
1748 			}
1749 		}
1750 		break;
1751 	}
1752 
1753 	/* return the key code in the K_CODE mode */
1754 	if (usbcode & KEY_RELEASE) {
1755 		keycode |= SCAN_RELEASE;
1756 	}
1757 	if (sc->sc_mode == K_CODE) {
1758 		return (keycode);
1759 	}
1760 	/* compose a character code */
1761 	if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1762 		switch (keycode) {
1763 			/* key pressed, process it */
1764 		case 0x47:
1765 		case 0x48:
1766 		case 0x49:		/* keypad 7,8,9 */
1767 			sc->sc_composed_char *= 10;
1768 			sc->sc_composed_char += keycode - 0x40;
1769 			goto check_composed;
1770 
1771 		case 0x4B:
1772 		case 0x4C:
1773 		case 0x4D:		/* keypad 4,5,6 */
1774 			sc->sc_composed_char *= 10;
1775 			sc->sc_composed_char += keycode - 0x47;
1776 			goto check_composed;
1777 
1778 		case 0x4F:
1779 		case 0x50:
1780 		case 0x51:		/* keypad 1,2,3 */
1781 			sc->sc_composed_char *= 10;
1782 			sc->sc_composed_char += keycode - 0x4E;
1783 			goto check_composed;
1784 
1785 		case 0x52:		/* keypad 0 */
1786 			sc->sc_composed_char *= 10;
1787 			goto check_composed;
1788 
1789 			/* key released, no interest here */
1790 		case SCAN_RELEASE | 0x47:
1791 		case SCAN_RELEASE | 0x48:
1792 		case SCAN_RELEASE | 0x49:	/* keypad 7,8,9 */
1793 		case SCAN_RELEASE | 0x4B:
1794 		case SCAN_RELEASE | 0x4C:
1795 		case SCAN_RELEASE | 0x4D:	/* keypad 4,5,6 */
1796 		case SCAN_RELEASE | 0x4F:
1797 		case SCAN_RELEASE | 0x50:
1798 		case SCAN_RELEASE | 0x51:	/* keypad 1,2,3 */
1799 		case SCAN_RELEASE | 0x52:	/* keypad 0 */
1800 			goto next_code;
1801 
1802 		case 0x38:		/* left alt key */
1803 			break;
1804 
1805 		default:
1806 			if (sc->sc_composed_char > 0) {
1807 				sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1808 				sc->sc_composed_char = 0;
1809 				goto errkey;
1810 			}
1811 			break;
1812 		}
1813 	}
1814 	/* keycode to key action */
1815 	action = genkbd_keyaction(kbd, SCAN_CHAR(keycode),
1816 	    (keycode & SCAN_RELEASE),
1817 	    &sc->sc_state, &sc->sc_accents);
1818 	if (action == NOKEY) {
1819 		goto next_code;
1820 	}
1821 done:
1822 	return (action);
1823 
1824 check_composed:
1825 	if (sc->sc_composed_char <= 0xFF) {
1826 		goto next_code;
1827 	}
1828 errkey:
1829 	return (ERRKEY);
1830 }
1831 
1832 /* Currently wait is always false. */
1833 static uint32_t
1834 ukbd_read_char(keyboard_t *kbd, int wait)
1835 {
1836 	uint32_t keycode;
1837 
1838 	UKBD_LOCK();
1839 	keycode = ukbd_read_char_locked(kbd, wait);
1840 	UKBD_UNLOCK();
1841 
1842 	return (keycode);
1843 }
1844 
1845 /* some useful control functions */
1846 static int
1847 ukbd_ioctl_locked(keyboard_t *kbd, u_long cmd, caddr_t arg)
1848 {
1849 	struct ukbd_softc *sc = kbd->kb_data;
1850 	int i;
1851 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1852     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1853 	int ival;
1854 
1855 #endif
1856 
1857 	UKBD_LOCK_ASSERT();
1858 
1859 	switch (cmd) {
1860 	case KDGKBMODE:		/* get keyboard mode */
1861 		*(int *)arg = sc->sc_mode;
1862 		break;
1863 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1864     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1865 	case _IO('K', 7):
1866 		ival = IOCPARM_IVAL(arg);
1867 		arg = (caddr_t)&ival;
1868 		/* FALLTHROUGH */
1869 #endif
1870 	case KDSKBMODE:		/* set keyboard mode */
1871 		switch (*(int *)arg) {
1872 		case K_XLATE:
1873 			if (sc->sc_mode != K_XLATE) {
1874 				/* make lock key state and LED state match */
1875 				sc->sc_state &= ~LOCK_MASK;
1876 				sc->sc_state |= KBD_LED_VAL(kbd);
1877 			}
1878 			/* FALLTHROUGH */
1879 		case K_RAW:
1880 		case K_CODE:
1881 			if (sc->sc_mode != *(int *)arg) {
1882 				if ((sc->sc_flags & UKBD_FLAG_POLLING) == 0)
1883 					ukbd_clear_state(kbd);
1884 				sc->sc_mode = *(int *)arg;
1885 			}
1886 			break;
1887 		default:
1888 			return (EINVAL);
1889 		}
1890 		break;
1891 
1892 	case KDGETLED:			/* get keyboard LED */
1893 		*(int *)arg = KBD_LED_VAL(kbd);
1894 		break;
1895 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1896     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1897 	case _IO('K', 66):
1898 		ival = IOCPARM_IVAL(arg);
1899 		arg = (caddr_t)&ival;
1900 		/* FALLTHROUGH */
1901 #endif
1902 	case KDSETLED:			/* set keyboard LED */
1903 		/* NOTE: lock key state in "sc_state" won't be changed */
1904 		if (*(int *)arg & ~LOCK_MASK)
1905 			return (EINVAL);
1906 
1907 		i = *(int *)arg;
1908 
1909 		/* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1910 		if (sc->sc_mode == K_XLATE &&
1911 		    kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1912 			if (i & ALKED)
1913 				i |= CLKED;
1914 			else
1915 				i &= ~CLKED;
1916 		}
1917 		if (KBD_HAS_DEVICE(kbd))
1918 			ukbd_set_leds(sc, i);
1919 
1920 		KBD_LED_VAL(kbd) = *(int *)arg;
1921 		break;
1922 	case KDGKBSTATE:		/* get lock key state */
1923 		*(int *)arg = sc->sc_state & LOCK_MASK;
1924 		break;
1925 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1926     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1927 	case _IO('K', 20):
1928 		ival = IOCPARM_IVAL(arg);
1929 		arg = (caddr_t)&ival;
1930 		/* FALLTHROUGH */
1931 #endif
1932 	case KDSKBSTATE:		/* set lock key state */
1933 		if (*(int *)arg & ~LOCK_MASK) {
1934 			return (EINVAL);
1935 		}
1936 		sc->sc_state &= ~LOCK_MASK;
1937 		sc->sc_state |= *(int *)arg;
1938 
1939 		/* set LEDs and quit */
1940 		return (ukbd_ioctl(kbd, KDSETLED, arg));
1941 
1942 	case KDSETREPEAT:		/* set keyboard repeat rate (new
1943 					 * interface) */
1944 		if (!KBD_HAS_DEVICE(kbd)) {
1945 			return (0);
1946 		}
1947 		/*
1948 		 * Convert negative, zero and tiny args to the same limits
1949 		 * as atkbd.  We could support delays of 1 msec, but
1950 		 * anything much shorter than the shortest atkbd value
1951 		 * of 250.34 is almost unusable as well as incompatible.
1952 		 */
1953 		kbd->kb_delay1 = imax(((int *)arg)[0], 250);
1954 		kbd->kb_delay2 = imax(((int *)arg)[1], 34);
1955 #ifdef EVDEV_SUPPORT
1956 		if (sc->sc_evdev != NULL)
1957 			evdev_push_repeats(sc->sc_evdev, kbd);
1958 #endif
1959 		return (0);
1960 
1961 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1962     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1963 	case _IO('K', 67):
1964 		ival = IOCPARM_IVAL(arg);
1965 		arg = (caddr_t)&ival;
1966 		/* FALLTHROUGH */
1967 #endif
1968 	case KDSETRAD:			/* set keyboard repeat rate (old
1969 					 * interface) */
1970 		return (ukbd_set_typematic(kbd, *(int *)arg));
1971 
1972 	case PIO_KEYMAP:		/* set keyboard translation table */
1973 	case OPIO_KEYMAP:		/* set keyboard translation table
1974 					 * (compat) */
1975 	case PIO_KEYMAPENT:		/* set keyboard translation table
1976 					 * entry */
1977 	case PIO_DEADKEYMAP:		/* set accent key translation table */
1978 		sc->sc_accents = 0;
1979 		/* FALLTHROUGH */
1980 	default:
1981 		return (genkbd_commonioctl(kbd, cmd, arg));
1982 	}
1983 
1984 	return (0);
1985 }
1986 
1987 static int
1988 ukbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
1989 {
1990 	int result;
1991 
1992 	/*
1993 	 * XXX Check if someone is calling us from a critical section:
1994 	 */
1995 	if (curthread->td_critnest != 0)
1996 		return (EDEADLK);
1997 
1998 	/*
1999 	 * XXX KDGKBSTATE, KDSKBSTATE and KDSETLED can be called from any
2000 	 * context where printf(9) can be called, which among other things
2001 	 * includes interrupt filters and threads with any kinds of locks
2002 	 * already held.  For this reason it would be dangerous to acquire
2003 	 * the Giant here unconditionally.  On the other hand we have to
2004 	 * have it to handle the ioctl.
2005 	 * So we make our best effort to auto-detect whether we can grab
2006 	 * the Giant or not.  Blame syscons(4) for this.
2007 	 */
2008 	switch (cmd) {
2009 	case KDGKBSTATE:
2010 	case KDSKBSTATE:
2011 	case KDSETLED:
2012 		if (!mtx_owned(&Giant) && !USB_IN_POLLING_MODE_FUNC())
2013 			return (EDEADLK);	/* best I could come up with */
2014 		/* FALLTHROUGH */
2015 	default:
2016 		UKBD_LOCK();
2017 		result = ukbd_ioctl_locked(kbd, cmd, arg);
2018 		UKBD_UNLOCK();
2019 		return (result);
2020 	}
2021 }
2022 
2023 
2024 /* clear the internal state of the keyboard */
2025 static void
2026 ukbd_clear_state(keyboard_t *kbd)
2027 {
2028 	struct ukbd_softc *sc = kbd->kb_data;
2029 
2030 	UKBD_LOCK_ASSERT();
2031 
2032 	sc->sc_flags &= ~(UKBD_FLAG_COMPOSE | UKBD_FLAG_POLLING);
2033 	sc->sc_state &= LOCK_MASK;	/* preserve locking key state */
2034 	sc->sc_accents = 0;
2035 	sc->sc_composed_char = 0;
2036 #ifdef UKBD_EMULATE_ATSCANCODE
2037 	sc->sc_buffered_char[0] = 0;
2038 	sc->sc_buffered_char[1] = 0;
2039 #endif
2040 	memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
2041 	memset(&sc->sc_odata, 0, sizeof(sc->sc_odata));
2042 	memset(&sc->sc_ntime, 0, sizeof(sc->sc_ntime));
2043 	memset(&sc->sc_otime, 0, sizeof(sc->sc_otime));
2044 }
2045 
2046 /* save the internal state, not used */
2047 static int
2048 ukbd_get_state(keyboard_t *kbd, void *buf, size_t len)
2049 {
2050 	return (len == 0) ? 1 : -1;
2051 }
2052 
2053 /* set the internal state, not used */
2054 static int
2055 ukbd_set_state(keyboard_t *kbd, void *buf, size_t len)
2056 {
2057 	return (EINVAL);
2058 }
2059 
2060 static int
2061 ukbd_poll(keyboard_t *kbd, int on)
2062 {
2063 	struct ukbd_softc *sc = kbd->kb_data;
2064 
2065 	UKBD_LOCK();
2066 	/*
2067 	 * Keep a reference count on polling to allow recursive
2068 	 * cngrab() during a panic for example.
2069 	 */
2070 	if (on)
2071 		sc->sc_polling++;
2072 	else if (sc->sc_polling > 0)
2073 		sc->sc_polling--;
2074 
2075 	if (sc->sc_polling != 0) {
2076 		sc->sc_flags |= UKBD_FLAG_POLLING;
2077 		sc->sc_poll_thread = curthread;
2078 	} else {
2079 		sc->sc_flags &= ~UKBD_FLAG_POLLING;
2080 		sc->sc_delay = 0;
2081 	}
2082 	UKBD_UNLOCK();
2083 
2084 	return (0);
2085 }
2086 
2087 /* local functions */
2088 
2089 static void
2090 ukbd_set_leds(struct ukbd_softc *sc, uint8_t leds)
2091 {
2092 
2093 	UKBD_LOCK_ASSERT();
2094 	DPRINTF("leds=0x%02x\n", leds);
2095 
2096 	sc->sc_leds = leds;
2097 	sc->sc_flags |= UKBD_FLAG_SET_LEDS;
2098 
2099 	/* start transfer, if not already started */
2100 
2101 	usbd_transfer_start(sc->sc_xfer[UKBD_CTRL_LED]);
2102 }
2103 
2104 static int
2105 ukbd_set_typematic(keyboard_t *kbd, int code)
2106 {
2107 #ifdef EVDEV_SUPPORT
2108 	struct ukbd_softc *sc = kbd->kb_data;
2109 #endif
2110 	static const int delays[] = {250, 500, 750, 1000};
2111 	static const int rates[] = {34, 38, 42, 46, 50, 55, 59, 63,
2112 		68, 76, 84, 92, 100, 110, 118, 126,
2113 		136, 152, 168, 184, 200, 220, 236, 252,
2114 	272, 304, 336, 368, 400, 440, 472, 504};
2115 
2116 	if (code & ~0x7f) {
2117 		return (EINVAL);
2118 	}
2119 	kbd->kb_delay1 = delays[(code >> 5) & 3];
2120 	kbd->kb_delay2 = rates[code & 0x1f];
2121 #ifdef EVDEV_SUPPORT
2122 	if (sc->sc_evdev != NULL)
2123 		evdev_push_repeats(sc->sc_evdev, kbd);
2124 #endif
2125 	return (0);
2126 }
2127 
2128 #ifdef UKBD_EMULATE_ATSCANCODE
2129 static uint32_t
2130 ukbd_atkeycode(int usbcode, int shift)
2131 {
2132 	uint32_t keycode;
2133 
2134 	keycode = ukbd_trtab[KEY_INDEX(usbcode)];
2135 	/*
2136 	 * Translate Alt-PrintScreen to SysRq.
2137 	 *
2138 	 * Some or all AT keyboards connected through USB have already
2139 	 * mapped Alted PrintScreens to an unusual usbcode (0x8a).
2140 	 * ukbd_trtab translates this to 0x7e, and key2scan() would
2141 	 * translate that to 0x79 (Intl' 4).  Assume that if we have
2142 	 * an Alted 0x7e here then it actually is an Alted PrintScreen.
2143 	 *
2144 	 * The usual usbcode for all PrintScreens is 0x46.  ukbd_trtab
2145 	 * translates this to 0x5c, so the Alt check to classify 0x5c
2146 	 * is routine.
2147 	 */
2148 	if ((keycode == 0x5c || keycode == 0x7e) &&
2149 	    shift & (MOD_ALT_L | MOD_ALT_R))
2150 		return (0x54);
2151 	return (keycode);
2152 }
2153 
2154 static int
2155 ukbd_key2scan(struct ukbd_softc *sc, int code, int shift, int up)
2156 {
2157 	static const int scan[] = {
2158 		/* 89 */
2159 		0x11c,	/* Enter */
2160 		/* 90-99 */
2161 		0x11d,	/* Ctrl-R */
2162 		0x135,	/* Divide */
2163 		0x137,	/* PrintScreen */
2164 		0x138,	/* Alt-R */
2165 		0x147,	/* Home */
2166 		0x148,	/* Up */
2167 		0x149,	/* PageUp */
2168 		0x14b,	/* Left */
2169 		0x14d,	/* Right */
2170 		0x14f,	/* End */
2171 		/* 100-109 */
2172 		0x150,	/* Down */
2173 		0x151,	/* PageDown */
2174 		0x152,	/* Insert */
2175 		0x153,	/* Delete */
2176 		0x146,	/* Pause/Break */
2177 		0x15b,	/* Win_L(Super_L) */
2178 		0x15c,	/* Win_R(Super_R) */
2179 		0x15d,	/* Application(Menu) */
2180 
2181 		/* SUN TYPE 6 USB KEYBOARD */
2182 		0x168,	/* Sun Type 6 Help */
2183 		0x15e,	/* Sun Type 6 Stop */
2184 		/* 110 - 119 */
2185 		0x15f,	/* Sun Type 6 Again */
2186 		0x160,	/* Sun Type 6 Props */
2187 		0x161,	/* Sun Type 6 Undo */
2188 		0x162,	/* Sun Type 6 Front */
2189 		0x163,	/* Sun Type 6 Copy */
2190 		0x164,	/* Sun Type 6 Open */
2191 		0x165,	/* Sun Type 6 Paste */
2192 		0x166,	/* Sun Type 6 Find */
2193 		0x167,	/* Sun Type 6 Cut */
2194 		0x125,	/* Sun Type 6 Mute */
2195 		/* 120 - 130 */
2196 		0x11f,	/* Sun Type 6 VolumeDown */
2197 		0x11e,	/* Sun Type 6 VolumeUp */
2198 		0x120,	/* Sun Type 6 PowerDown */
2199 
2200 		/* Japanese 106/109 keyboard */
2201 		0x73,	/* Keyboard Intl' 1 (backslash / underscore) */
2202 		0x70,	/* Keyboard Intl' 2 (Katakana / Hiragana) */
2203 		0x7d,	/* Keyboard Intl' 3 (Yen sign) (Not using in jp106/109) */
2204 		0x79,	/* Keyboard Intl' 4 (Henkan) */
2205 		0x7b,	/* Keyboard Intl' 5 (Muhenkan) */
2206 		0x5c,	/* Keyboard Intl' 6 (Keypad ,) (For PC-9821 layout) */
2207 		0x71,   /* Apple Keyboard JIS (Kana) */
2208 		0x72,   /* Apple Keyboard JIS (Eisu) */
2209 	};
2210 
2211 	if ((code >= 89) && (code < (int)(89 + nitems(scan)))) {
2212 		code = scan[code - 89];
2213 	}
2214 	/* PrintScreen */
2215 	if (code == 0x137 && (!(shift & (MOD_CONTROL_L | MOD_CONTROL_R |
2216 	    MOD_SHIFT_L | MOD_SHIFT_R)))) {
2217 		code |= SCAN_PREFIX_SHIFT;
2218 	}
2219 	/* Pause/Break */
2220 	if ((code == 0x146) && (!(shift & (MOD_CONTROL_L | MOD_CONTROL_R)))) {
2221 		code = (0x45 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL);
2222 	}
2223 	code |= (up ? SCAN_RELEASE : SCAN_PRESS);
2224 
2225 	if (code & SCAN_PREFIX) {
2226 		if (code & SCAN_PREFIX_CTL) {
2227 			/* Ctrl */
2228 			sc->sc_buffered_char[0] = (0x1d | (code & SCAN_RELEASE));
2229 			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX);
2230 		} else if (code & SCAN_PREFIX_SHIFT) {
2231 			/* Shift */
2232 			sc->sc_buffered_char[0] = (0x2a | (code & SCAN_RELEASE));
2233 			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX_SHIFT);
2234 		} else {
2235 			sc->sc_buffered_char[0] = (code & ~SCAN_PREFIX);
2236 			sc->sc_buffered_char[1] = 0;
2237 		}
2238 		return ((code & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
2239 	}
2240 	return (code);
2241 
2242 }
2243 
2244 #endif					/* UKBD_EMULATE_ATSCANCODE */
2245 
2246 static keyboard_switch_t ukbdsw = {
2247 	.probe = &ukbd__probe,
2248 	.init = &ukbd_init,
2249 	.term = &ukbd_term,
2250 	.intr = &ukbd_intr,
2251 	.test_if = &ukbd_test_if,
2252 	.enable = &ukbd_enable,
2253 	.disable = &ukbd_disable,
2254 	.read = &ukbd_read,
2255 	.check = &ukbd_check,
2256 	.read_char = &ukbd_read_char,
2257 	.check_char = &ukbd_check_char,
2258 	.ioctl = &ukbd_ioctl,
2259 	.lock = &ukbd_lock,
2260 	.clear_state = &ukbd_clear_state,
2261 	.get_state = &ukbd_get_state,
2262 	.set_state = &ukbd_set_state,
2263 	.get_fkeystr = &genkbd_get_fkeystr,
2264 	.poll = &ukbd_poll,
2265 	.diag = &genkbd_diag,
2266 };
2267 
2268 KEYBOARD_DRIVER(ukbd, ukbdsw, ukbd_configure);
2269 
2270 static int
2271 ukbd_driver_load(module_t mod, int what, void *arg)
2272 {
2273 	switch (what) {
2274 	case MOD_LOAD:
2275 		kbd_add_driver(&ukbd_kbd_driver);
2276 		break;
2277 	case MOD_UNLOAD:
2278 		kbd_delete_driver(&ukbd_kbd_driver);
2279 		break;
2280 	}
2281 	return (0);
2282 }
2283 
2284 static devclass_t ukbd_devclass;
2285 
2286 static device_method_t ukbd_methods[] = {
2287 	DEVMETHOD(device_probe, ukbd_probe),
2288 	DEVMETHOD(device_attach, ukbd_attach),
2289 	DEVMETHOD(device_detach, ukbd_detach),
2290 	DEVMETHOD(device_resume, ukbd_resume),
2291 
2292 	DEVMETHOD_END
2293 };
2294 
2295 static driver_t ukbd_driver = {
2296 	.name = "ukbd",
2297 	.methods = ukbd_methods,
2298 	.size = sizeof(struct ukbd_softc),
2299 };
2300 
2301 DRIVER_MODULE(ukbd, uhub, ukbd_driver, ukbd_devclass, ukbd_driver_load, 0);
2302 MODULE_DEPEND(ukbd, usb, 1, 1, 1);
2303 #ifdef EVDEV_SUPPORT
2304 MODULE_DEPEND(ukbd, evdev, 1, 1, 1);
2305 #endif
2306 MODULE_VERSION(ukbd, 1);
2307 USB_PNP_HOST_INFO(ukbd_devs);
2308