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