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