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