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