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