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