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