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