1 #include <sys/cdefs.h>
2 __FBSDID("$FreeBSD: stable/12/sys/dev/usb/input/ukbd.c 369343 2021-02-23 23:46:40Z wulf $");
3 
4 
5 /*-
6  * SPDX-License-Identifier: BSD-2-Clause-NetBSD
7  *
8  * Copyright (c) 1998 The NetBSD Foundation, Inc.
9  * All rights reserved.
10  *
11  * This code is derived from software contributed to The NetBSD Foundation
12  * by Lennart Augustsson (lennart@augustsson.net) at
13  * Carlstedt Research & Technology.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
28  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  *
36  */
37 
38 /*
39  * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf
40  */
41 
42 #include "opt_kbd.h"
43 #include "opt_ukbd.h"
44 #include "opt_evdev.h"
45 
46 #include <sys/stdint.h>
47 #include <sys/stddef.h>
48 #include <sys/param.h>
49 #include <sys/queue.h>
50 #include <sys/types.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/bus.h>
54 #include <sys/module.h>
55 #include <sys/lock.h>
56 #include <sys/mutex.h>
57 #include <sys/condvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/sx.h>
60 #include <sys/unistd.h>
61 #include <sys/callout.h>
62 #include <sys/malloc.h>
63 #include <sys/priv.h>
64 #include <sys/proc.h>
65 
66 #include <dev/usb/usb.h>
67 #include <dev/usb/usbdi.h>
68 #include <dev/usb/usbdi_util.h>
69 #include <dev/usb/usbhid.h>
70 
71 #define	USB_DEBUG_VAR ukbd_debug
72 #include <dev/usb/usb_debug.h>
73 
74 #include <dev/usb/quirk/usb_quirk.h>
75 
76 #ifdef EVDEV_SUPPORT
77 #include <dev/evdev/input.h>
78 #include <dev/evdev/evdev.h>
79 #endif
80 
81 #include <sys/ioccom.h>
82 #include <sys/filio.h>
83 #include <sys/kbio.h>
84 
85 #include <dev/kbd/kbdreg.h>
86 
87 /* the initial key map, accent map and fkey strings */
88 #if defined(UKBD_DFLT_KEYMAP) && !defined(KLD_MODULE)
89 #define	KBD_DFLT_KEYMAP
90 #include "ukbdmap.h"
91 #endif
92 
93 /* the following file must be included after "ukbdmap.h" */
94 #include <dev/kbd/kbdtables.h>
95 
96 #ifdef USB_DEBUG
97 static int ukbd_debug = 0;
98 static int ukbd_no_leds = 0;
99 static int ukbd_pollrate = 0;
100 
101 static SYSCTL_NODE(_hw_usb, OID_AUTO, ukbd, CTLFLAG_RW, 0, "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
ukbd_any_key_pressed(struct ukbd_softc * sc)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
ukbd_any_key_valid(struct ukbd_softc * sc)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
ukbd_is_modifier_key(uint32_t key)351 ukbd_is_modifier_key(uint32_t key)
352 {
353 
354 	return (key >= 0xe0 && key <= 0xe7);
355 }
356 
357 static void
ukbd_start_timer(struct ukbd_softc * sc)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
ukbd_put_key(struct ukbd_softc * sc,uint32_t key)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
ukbd_do_poll(struct ukbd_softc * sc,uint8_t wait)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 
440 		usbd_transfer_poll(sc->sc_xfer, UKBD_N_TRANSFER);
441 
442 		/* Delay-optimised support for repetition of keys */
443 		if (ukbd_any_key_pressed(sc)) {
444 			/* a key is pressed - need timekeeping */
445 			DELAY(1000);
446 
447 			/* 1 millisecond has passed */
448 			sc->sc_time_ms += 1;
449 		}
450 
451 		ukbd_interrupt(sc);
452 
453 		if (!wait)
454 			break;
455 	}
456 }
457 
458 static int32_t
ukbd_get_key(struct ukbd_softc * sc,uint8_t wait)459 ukbd_get_key(struct ukbd_softc *sc, uint8_t wait)
460 {
461 	int32_t c;
462 
463 	UKBD_LOCK_ASSERT();
464 	KASSERT((USB_IN_POLLING_MODE_FUNC() == 0) ||
465 	    (sc->sc_flags & UKBD_FLAG_POLLING) != 0,
466 	    ("not polling in kdb or panic\n"));
467 
468 	if (sc->sc_inputs == 0 &&
469 	    (sc->sc_flags & UKBD_FLAG_GONE) == 0) {
470 		/* start transfer, if not already started */
471 		usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_0]);
472 		usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_1]);
473 	}
474 
475 	if (sc->sc_flags & UKBD_FLAG_POLLING)
476 		ukbd_do_poll(sc, wait);
477 
478 	if (sc->sc_inputs == 0) {
479 		c = -1;
480 	} else {
481 		c = sc->sc_input[sc->sc_inputhead];
482 		--(sc->sc_inputs);
483 		++(sc->sc_inputhead);
484 		if (sc->sc_inputhead >= UKBD_IN_BUF_SIZE) {
485 			sc->sc_inputhead = 0;
486 		}
487 	}
488 	return (c);
489 }
490 
491 static void
ukbd_interrupt(struct ukbd_softc * sc)492 ukbd_interrupt(struct ukbd_softc *sc)
493 {
494 	const uint32_t now = sc->sc_time_ms;
495 	unsigned key;
496 
497 	UKBD_LOCK_ASSERT();
498 
499 	/* Check for modifier key changes first */
500 	for (key = 0xe0; key != 0xe8; key++) {
501 		const uint64_t mask = 1ULL << (key % 64);
502 		const uint64_t delta =
503 		    sc->sc_odata.bitmap[key / 64] ^
504 		    sc->sc_ndata.bitmap[key / 64];
505 
506 		if (delta & mask) {
507 			if (sc->sc_odata.bitmap[key / 64] & mask)
508 				ukbd_put_key(sc, key | KEY_RELEASE);
509 			else
510 				ukbd_put_key(sc, key | KEY_PRESS);
511 		}
512 	}
513 
514 	/* Check for key changes */
515 	for (key = 0; key != UKBD_NKEYCODE; key++) {
516 		const uint64_t mask = 1ULL << (key % 64);
517 		const uint64_t delta =
518 		    sc->sc_odata.bitmap[key / 64] ^
519 		    sc->sc_ndata.bitmap[key / 64];
520 
521 		if (mask == 1 && delta == 0) {
522 			key += 63;
523 			continue;	/* skip empty areas */
524 		} else if (ukbd_is_modifier_key(key)) {
525 			continue;
526 		} else if (delta & mask) {
527 			if (sc->sc_odata.bitmap[key / 64] & mask) {
528 				ukbd_put_key(sc, key | KEY_RELEASE);
529 
530 				/* clear repeating key, if any */
531 				if (sc->sc_repeat_key == key)
532 					sc->sc_repeat_key = 0;
533 			} else {
534 				ukbd_put_key(sc, key | KEY_PRESS);
535 
536 				sc->sc_co_basetime = sbinuptime();
537 				sc->sc_delay = sc->sc_kbd.kb_delay1;
538 				ukbd_start_timer(sc);
539 
540 				/* set repeat time for last key */
541 				sc->sc_repeat_time = now + sc->sc_kbd.kb_delay1;
542 				sc->sc_repeat_key = key;
543 			}
544 		}
545 	}
546 
547 	/* synchronize old data with new data */
548 	sc->sc_odata = sc->sc_ndata;
549 
550 	/* check if last key is still pressed */
551 	if (sc->sc_repeat_key != 0) {
552 		const int32_t dtime = (sc->sc_repeat_time - now);
553 
554 		/* check if time has elapsed */
555 		if (dtime <= 0) {
556 			ukbd_put_key(sc, sc->sc_repeat_key | KEY_PRESS);
557 			sc->sc_repeat_time = now + sc->sc_kbd.kb_delay2;
558 		}
559 	}
560 
561 #ifdef EVDEV_SUPPORT
562 	if (evdev_rcpt_mask & EVDEV_RCPT_HW_KBD && sc->sc_evdev != NULL)
563 		evdev_sync(sc->sc_evdev);
564 #endif
565 
566 	/* wakeup keyboard system */
567 	ukbd_event_keyinput(sc);
568 }
569 
570 static void
ukbd_event_keyinput(struct ukbd_softc * sc)571 ukbd_event_keyinput(struct ukbd_softc *sc)
572 {
573 	int c;
574 
575 	UKBD_LOCK_ASSERT();
576 
577 	if ((sc->sc_flags & UKBD_FLAG_POLLING) != 0)
578 		return;
579 
580 	if (sc->sc_inputs == 0)
581 		return;
582 
583 	if (KBD_IS_ACTIVE(&sc->sc_kbd) &&
584 	    KBD_IS_BUSY(&sc->sc_kbd)) {
585 		/* let the callback function process the input */
586 		(sc->sc_kbd.kb_callback.kc_func) (&sc->sc_kbd, KBDIO_KEYINPUT,
587 		    sc->sc_kbd.kb_callback.kc_arg);
588 	} else {
589 		/* read and discard the input, no one is waiting for it */
590 		do {
591 			c = ukbd_read_char(&sc->sc_kbd, 0);
592 		} while (c != NOKEY);
593 	}
594 }
595 
596 static void
ukbd_timeout(void * arg)597 ukbd_timeout(void *arg)
598 {
599 	struct ukbd_softc *sc = arg;
600 
601 	UKBD_LOCK_ASSERT();
602 
603 	sc->sc_time_ms += sc->sc_delay;
604 	sc->sc_delay = 0;
605 
606 	ukbd_interrupt(sc);
607 
608 	/* Make sure any leftover key events gets read out */
609 	ukbd_event_keyinput(sc);
610 
611 	if (ukbd_any_key_pressed(sc) || (sc->sc_inputs != 0)) {
612 		ukbd_start_timer(sc);
613 	}
614 }
615 
616 static uint32_t
ukbd_apple_fn(uint32_t keycode)617 ukbd_apple_fn(uint32_t keycode)
618 {
619 	switch (keycode) {
620 	case 0x28: return 0x49; /* RETURN -> INSERT */
621 	case 0x2a: return 0x4c; /* BACKSPACE -> DEL */
622 	case 0x50: return 0x4a; /* LEFT ARROW -> HOME */
623 	case 0x4f: return 0x4d; /* RIGHT ARROW -> END */
624 	case 0x52: return 0x4b; /* UP ARROW -> PGUP */
625 	case 0x51: return 0x4e; /* DOWN ARROW -> PGDN */
626 	default: return keycode;
627 	}
628 }
629 
630 static uint32_t
ukbd_apple_swap(uint32_t keycode)631 ukbd_apple_swap(uint32_t keycode)
632 {
633 	switch (keycode) {
634 	case 0x35: return 0x64;
635 	case 0x64: return 0x35;
636 	default: return keycode;
637 	}
638 }
639 
640 static void
ukbd_intr_callback(struct usb_xfer * xfer,usb_error_t error)641 ukbd_intr_callback(struct usb_xfer *xfer, usb_error_t error)
642 {
643 	struct ukbd_softc *sc = usbd_xfer_softc(xfer);
644 	struct usb_page_cache *pc;
645 	uint32_t i;
646 	uint8_t id;
647 	uint8_t modifiers;
648 	int offset;
649 	int len;
650 
651 	UKBD_LOCK_ASSERT();
652 
653 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
654 	pc = usbd_xfer_get_frame(xfer, 0);
655 
656 	switch (USB_GET_STATE(xfer)) {
657 	case USB_ST_TRANSFERRED:
658 		DPRINTF("actlen=%d bytes\n", len);
659 
660 		if (len == 0) {
661 			DPRINTF("zero length data\n");
662 			goto tr_setup;
663 		}
664 
665 		if (sc->sc_kbd_id != 0) {
666 			/* check and remove HID ID byte */
667 			usbd_copy_out(pc, 0, &id, 1);
668 			offset = 1;
669 			len--;
670 			if (len == 0) {
671 				DPRINTF("zero length data\n");
672 				goto tr_setup;
673 			}
674 		} else {
675 			offset = 0;
676 			id = 0;
677 		}
678 
679 		if (len > UKBD_BUFFER_SIZE)
680 			len = UKBD_BUFFER_SIZE;
681 
682 		/* get data */
683 		usbd_copy_out(pc, offset, sc->sc_buffer, len);
684 
685 		/* clear temporary storage */
686 		memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
687 
688 		/* clear modifiers */
689 		modifiers = 0;
690 
691 		/* scan through HID data */
692 		if ((sc->sc_flags & UKBD_FLAG_APPLE_EJECT) &&
693 		    (id == sc->sc_id_apple_eject)) {
694 			if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_apple_eject))
695 				modifiers |= MOD_EJECT;
696 		}
697 		if ((sc->sc_flags & UKBD_FLAG_APPLE_FN) &&
698 		    (id == sc->sc_id_apple_fn)) {
699 			if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_apple_fn))
700 				modifiers |= MOD_FN;
701 		}
702 
703 		for (i = 0; i != UKBD_NKEYCODE; i++) {
704 			const uint64_t valid = sc->sc_loc_key_valid[i / 64];
705 			const uint64_t mask = 1ULL << (i % 64);
706 
707 			if (mask == 1 && valid == 0) {
708 				i += 63;
709 				continue;	/* skip empty areas */
710 			} else if (~valid & mask) {
711 				continue;	/* location is not valid */
712 			} else if (id != sc->sc_id_loc_key[i]) {
713 				continue;	/* invalid HID ID */
714 			} else if (i == 0) {
715 				struct hid_location tmp_loc = sc->sc_loc_key[0];
716 				/* range check array size */
717 				if (tmp_loc.count > UKBD_NKEYCODE)
718 					tmp_loc.count = UKBD_NKEYCODE;
719 				while (tmp_loc.count--) {
720 					uint32_t key =
721 					    hid_get_data_unsigned(sc->sc_buffer, len, &tmp_loc);
722 					/* advance to next location */
723 					tmp_loc.pos += tmp_loc.size;
724 					if (key == KEY_ERROR) {
725 						DPRINTF("KEY_ERROR\n");
726 						sc->sc_ndata = sc->sc_odata;
727 						goto tr_setup; /* ignore */
728 					}
729 					if (modifiers & MOD_FN)
730 						key = ukbd_apple_fn(key);
731 					if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP)
732 						key = ukbd_apple_swap(key);
733 					if (key == KEY_NONE || key >= UKBD_NKEYCODE)
734 						continue;
735 					/* set key in bitmap */
736 					sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
737 				}
738 			} else if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_key[i])) {
739 				uint32_t key = i;
740 
741 				if (modifiers & MOD_FN)
742 					key = ukbd_apple_fn(key);
743 				if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP)
744 					key = ukbd_apple_swap(key);
745 				if (key == KEY_NONE || key == KEY_ERROR || key >= UKBD_NKEYCODE)
746 					continue;
747 				/* set key in bitmap */
748 				sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
749 			}
750 		}
751 #ifdef USB_DEBUG
752 		DPRINTF("modifiers = 0x%04x\n", modifiers);
753 		for (i = 0; i != UKBD_NKEYCODE; i++) {
754 			const uint64_t valid = sc->sc_ndata.bitmap[i / 64];
755 			const uint64_t mask = 1ULL << (i % 64);
756 
757 			if (valid & mask)
758 				DPRINTF("Key 0x%02x pressed\n", i);
759 		}
760 #endif
761 		ukbd_interrupt(sc);
762 
763 	case USB_ST_SETUP:
764 tr_setup:
765 		if (sc->sc_inputs < UKBD_IN_BUF_FULL) {
766 			usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
767 			usbd_transfer_submit(xfer);
768 		} else {
769 			DPRINTF("input queue is full!\n");
770 		}
771 		break;
772 
773 	default:			/* Error */
774 		DPRINTF("error=%s\n", usbd_errstr(error));
775 
776 		if (error != USB_ERR_CANCELLED) {
777 			/* try to clear stall first */
778 			usbd_xfer_set_stall(xfer);
779 			goto tr_setup;
780 		}
781 		break;
782 	}
783 }
784 
785 static void
ukbd_set_leds_callback(struct usb_xfer * xfer,usb_error_t error)786 ukbd_set_leds_callback(struct usb_xfer *xfer, usb_error_t error)
787 {
788 	struct ukbd_softc *sc = usbd_xfer_softc(xfer);
789 	struct usb_device_request req;
790 	struct usb_page_cache *pc;
791 	uint8_t id;
792 	uint8_t any;
793 	int len;
794 
795 	UKBD_LOCK_ASSERT();
796 
797 #ifdef USB_DEBUG
798 	if (ukbd_no_leds)
799 		return;
800 #endif
801 
802 	switch (USB_GET_STATE(xfer)) {
803 	case USB_ST_TRANSFERRED:
804 	case USB_ST_SETUP:
805 		if (!(sc->sc_flags & UKBD_FLAG_SET_LEDS))
806 			break;
807 		sc->sc_flags &= ~UKBD_FLAG_SET_LEDS;
808 
809 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
810 		req.bRequest = UR_SET_REPORT;
811 		USETW2(req.wValue, UHID_OUTPUT_REPORT, 0);
812 		req.wIndex[0] = sc->sc_iface_no;
813 		req.wIndex[1] = 0;
814 		req.wLength[1] = 0;
815 
816 		memset(sc->sc_buffer, 0, UKBD_BUFFER_SIZE);
817 
818 		id = 0;
819 		any = 0;
820 
821 		/* Assumption: All led bits must be in the same ID. */
822 
823 		if (sc->sc_flags & UKBD_FLAG_NUMLOCK) {
824 			if (sc->sc_leds & NLKED) {
825 				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
826 				    &sc->sc_loc_numlock, 1);
827 			}
828 			id = sc->sc_id_numlock;
829 			any = 1;
830 		}
831 
832 		if (sc->sc_flags & UKBD_FLAG_SCROLLLOCK) {
833 			if (sc->sc_leds & SLKED) {
834 				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
835 				    &sc->sc_loc_scrolllock, 1);
836 			}
837 			id = sc->sc_id_scrolllock;
838 			any = 1;
839 		}
840 
841 		if (sc->sc_flags & UKBD_FLAG_CAPSLOCK) {
842 			if (sc->sc_leds & CLKED) {
843 				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
844 				    &sc->sc_loc_capslock, 1);
845 			}
846 			id = sc->sc_id_capslock;
847 			any = 1;
848 		}
849 
850 		/* if no leds, nothing to do */
851 		if (!any)
852 			break;
853 
854 		/* range check output report length */
855 		len = sc->sc_led_size;
856 		if (len > (UKBD_BUFFER_SIZE - 1))
857 			len = (UKBD_BUFFER_SIZE - 1);
858 
859 		/* check if we need to prefix an ID byte */
860 		sc->sc_buffer[0] = id;
861 
862 		pc = usbd_xfer_get_frame(xfer, 1);
863 		if (id != 0) {
864 			len++;
865 			usbd_copy_in(pc, 0, sc->sc_buffer, len);
866 		} else {
867 			usbd_copy_in(pc, 0, sc->sc_buffer + 1, len);
868 		}
869 		req.wLength[0] = len;
870 		usbd_xfer_set_frame_len(xfer, 1, len);
871 
872 		DPRINTF("len=%d, id=%d\n", len, id);
873 
874 		/* setup control request last */
875 		pc = usbd_xfer_get_frame(xfer, 0);
876 		usbd_copy_in(pc, 0, &req, sizeof(req));
877 		usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
878 
879 		/* start data transfer */
880 		usbd_xfer_set_frames(xfer, 2);
881 		usbd_transfer_submit(xfer);
882 		break;
883 
884 	default:			/* Error */
885 		DPRINTFN(1, "error=%s\n", usbd_errstr(error));
886 		break;
887 	}
888 }
889 
890 static const struct usb_config ukbd_config[UKBD_N_TRANSFER] = {
891 
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
ukbd_probe(device_t dev)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
ukbd_parse_hid(struct ukbd_softc * sc,const uint8_t * ptr,uint32_t len)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(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(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
ukbd_attach(device_t dev)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 
1169 		DPRINTF("Forcing boot protocol\n");
1170 
1171 		err = usbd_req_set_protocol(sc->sc_udev, NULL,
1172 			sc->sc_iface_index, 0);
1173 
1174 		if (err != 0) {
1175 			DPRINTF("Set protocol error=%s (ignored)\n",
1176 			    usbd_errstr(err));
1177 		}
1178 
1179 		ukbd_parse_hid(sc, ukbd_boot_desc, sizeof(ukbd_boot_desc));
1180 	}
1181 
1182 	/* ignore if SETIDLE fails, hence it is not crucial */
1183 	usbd_req_set_idle(sc->sc_udev, NULL, sc->sc_iface_index, 0, 0);
1184 
1185 	ukbd_ioctl(kbd, KDSETLED, (caddr_t)&sc->sc_state);
1186 
1187 	KBD_INIT_DONE(kbd);
1188 
1189 	if (kbd_register(kbd) < 0) {
1190 		goto detach;
1191 	}
1192 	KBD_CONFIG_DONE(kbd);
1193 
1194 	ukbd_enable(kbd);
1195 
1196 #ifdef KBD_INSTALL_CDEV
1197 	if (kbd_attach(kbd)) {
1198 		goto detach;
1199 	}
1200 #endif
1201 
1202 #ifdef EVDEV_SUPPORT
1203 	evdev = evdev_alloc();
1204 	evdev_set_name(evdev, device_get_desc(dev));
1205 	evdev_set_phys(evdev, device_get_nameunit(dev));
1206 	evdev_set_id(evdev, BUS_USB, uaa->info.idVendor,
1207 	   uaa->info.idProduct, 0);
1208 	evdev_set_serial(evdev, usb_get_serial(uaa->device));
1209 	evdev_set_methods(evdev, kbd, &ukbd_evdev_methods);
1210 	evdev_support_event(evdev, EV_SYN);
1211 	evdev_support_event(evdev, EV_KEY);
1212 	if (sc->sc_flags & (UKBD_FLAG_NUMLOCK | UKBD_FLAG_CAPSLOCK |
1213 			    UKBD_FLAG_SCROLLLOCK))
1214 		evdev_support_event(evdev, EV_LED);
1215 	evdev_support_event(evdev, EV_REP);
1216 
1217 	for (i = 0x00; i <= 0xFF; i++)
1218 		evdev_support_key(evdev, evdev_hid2key(i));
1219 	if (sc->sc_flags & UKBD_FLAG_NUMLOCK)
1220 		evdev_support_led(evdev, LED_NUML);
1221 	if (sc->sc_flags & UKBD_FLAG_CAPSLOCK)
1222 		evdev_support_led(evdev, LED_CAPSL);
1223 	if (sc->sc_flags & UKBD_FLAG_SCROLLLOCK)
1224 		evdev_support_led(evdev, LED_SCROLLL);
1225 
1226 	if (evdev_register_mtx(evdev, &Giant))
1227 		evdev_free(evdev);
1228 	else
1229 		sc->sc_evdev = evdev;
1230 #endif
1231 
1232 	sc->sc_flags |= UKBD_FLAG_ATTACHED;
1233 
1234 	if (bootverbose) {
1235 		kbdd_diag(kbd, bootverbose);
1236 	}
1237 
1238 #ifdef USB_DEBUG
1239 	/* check for polling rate override */
1240 	rate = ukbd_pollrate;
1241 	if (rate > 0) {
1242 		if (rate > 1000)
1243 			rate = 1;
1244 		else
1245 			rate = 1000 / rate;
1246 
1247 		/* set new polling interval in ms */
1248 		usbd_xfer_set_interval(sc->sc_xfer[UKBD_INTR_DT_0], rate);
1249 		usbd_xfer_set_interval(sc->sc_xfer[UKBD_INTR_DT_1], rate);
1250 	}
1251 #endif
1252 	/* start the keyboard */
1253 	usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_0]);
1254 	usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_1]);
1255 
1256 	return (0);			/* success */
1257 
1258 detach:
1259 	ukbd_detach(dev);
1260 	return (ENXIO);			/* error */
1261 }
1262 
1263 static int
ukbd_detach(device_t dev)1264 ukbd_detach(device_t dev)
1265 {
1266 	struct ukbd_softc *sc = device_get_softc(dev);
1267 	int error;
1268 
1269 	UKBD_LOCK_ASSERT();
1270 
1271 	DPRINTF("\n");
1272 
1273 	sc->sc_flags |= UKBD_FLAG_GONE;
1274 
1275 	usb_callout_stop(&sc->sc_callout);
1276 
1277 	/* kill any stuck keys */
1278 	if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
1279 		/* stop receiving events from the USB keyboard */
1280 		usbd_transfer_stop(sc->sc_xfer[UKBD_INTR_DT_0]);
1281 		usbd_transfer_stop(sc->sc_xfer[UKBD_INTR_DT_1]);
1282 
1283 		/* release all leftover keys, if any */
1284 		memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1285 
1286 		/* process releasing of all keys */
1287 		ukbd_interrupt(sc);
1288 	}
1289 
1290 	ukbd_disable(&sc->sc_kbd);
1291 
1292 #ifdef KBD_INSTALL_CDEV
1293 	if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
1294 		error = kbd_detach(&sc->sc_kbd);
1295 		if (error) {
1296 			/* usb attach cannot return an error */
1297 			device_printf(dev, "WARNING: kbd_detach() "
1298 			    "returned non-zero! (ignored)\n");
1299 		}
1300 	}
1301 #endif
1302 
1303 #ifdef EVDEV_SUPPORT
1304 	evdev_free(sc->sc_evdev);
1305 #endif
1306 
1307 	if (KBD_IS_CONFIGURED(&sc->sc_kbd)) {
1308 		error = kbd_unregister(&sc->sc_kbd);
1309 		if (error) {
1310 			/* usb attach cannot return an error */
1311 			device_printf(dev, "WARNING: kbd_unregister() "
1312 			    "returned non-zero! (ignored)\n");
1313 		}
1314 	}
1315 	sc->sc_kbd.kb_flags = 0;
1316 
1317 	usbd_transfer_unsetup(sc->sc_xfer, UKBD_N_TRANSFER);
1318 
1319 	usb_callout_drain(&sc->sc_callout);
1320 
1321 	DPRINTF("%s: disconnected\n",
1322 	    device_get_nameunit(dev));
1323 
1324 	return (0);
1325 }
1326 
1327 static int
ukbd_resume(device_t dev)1328 ukbd_resume(device_t dev)
1329 {
1330 	struct ukbd_softc *sc = device_get_softc(dev);
1331 
1332 	UKBD_LOCK_ASSERT();
1333 
1334 	ukbd_clear_state(&sc->sc_kbd);
1335 
1336 	return (0);
1337 }
1338 
1339 #ifdef EVDEV_SUPPORT
1340 static void
ukbd_ev_event(struct evdev_dev * evdev,uint16_t type,uint16_t code,int32_t value)1341 ukbd_ev_event(struct evdev_dev *evdev, uint16_t type, uint16_t code,
1342     int32_t value)
1343 {
1344 	keyboard_t *kbd = evdev_get_softc(evdev);
1345 
1346 	if (evdev_rcpt_mask & EVDEV_RCPT_HW_KBD &&
1347 	    (type == EV_LED || type == EV_REP)) {
1348 		mtx_lock(&Giant);
1349 		kbd_ev_event(kbd, type, code, value);
1350 		mtx_unlock(&Giant);
1351 	}
1352 }
1353 #endif
1354 
1355 /* early keyboard probe, not supported */
1356 static int
ukbd_configure(int flags)1357 ukbd_configure(int flags)
1358 {
1359 	return (0);
1360 }
1361 
1362 /* detect a keyboard, not used */
1363 static int
ukbd__probe(int unit,void * arg,int flags)1364 ukbd__probe(int unit, void *arg, int flags)
1365 {
1366 	return (ENXIO);
1367 }
1368 
1369 /* reset and initialize the device, not used */
1370 static int
ukbd_init(int unit,keyboard_t ** kbdp,void * arg,int flags)1371 ukbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
1372 {
1373 	return (ENXIO);
1374 }
1375 
1376 /* test the interface to the device, not used */
1377 static int
ukbd_test_if(keyboard_t * kbd)1378 ukbd_test_if(keyboard_t *kbd)
1379 {
1380 	return (0);
1381 }
1382 
1383 /* finish using this keyboard, not used */
1384 static int
ukbd_term(keyboard_t * kbd)1385 ukbd_term(keyboard_t *kbd)
1386 {
1387 	return (ENXIO);
1388 }
1389 
1390 /* keyboard interrupt routine, not used */
1391 static int
ukbd_intr(keyboard_t * kbd,void * arg)1392 ukbd_intr(keyboard_t *kbd, void *arg)
1393 {
1394 	return (0);
1395 }
1396 
1397 /* lock the access to the keyboard, not used */
1398 static int
ukbd_lock(keyboard_t * kbd,int lock)1399 ukbd_lock(keyboard_t *kbd, int lock)
1400 {
1401 	return (1);
1402 }
1403 
1404 /*
1405  * Enable the access to the device; until this function is called,
1406  * the client cannot read from the keyboard.
1407  */
1408 static int
ukbd_enable(keyboard_t * kbd)1409 ukbd_enable(keyboard_t *kbd)
1410 {
1411 
1412 	UKBD_LOCK();
1413 	KBD_ACTIVATE(kbd);
1414 	UKBD_UNLOCK();
1415 
1416 	return (0);
1417 }
1418 
1419 /* disallow the access to the device */
1420 static int
ukbd_disable(keyboard_t * kbd)1421 ukbd_disable(keyboard_t *kbd)
1422 {
1423 
1424 	UKBD_LOCK();
1425 	KBD_DEACTIVATE(kbd);
1426 	UKBD_UNLOCK();
1427 
1428 	return (0);
1429 }
1430 
1431 /* check if data is waiting */
1432 /* Currently unused. */
1433 static int
ukbd_check(keyboard_t * kbd)1434 ukbd_check(keyboard_t *kbd)
1435 {
1436 	struct ukbd_softc *sc = kbd->kb_data;
1437 
1438 	UKBD_LOCK_ASSERT();
1439 
1440 	if (!KBD_IS_ACTIVE(kbd))
1441 		return (0);
1442 
1443 	if (sc->sc_flags & UKBD_FLAG_POLLING)
1444 		ukbd_do_poll(sc, 0);
1445 
1446 #ifdef UKBD_EMULATE_ATSCANCODE
1447 	if (sc->sc_buffered_char[0]) {
1448 		return (1);
1449 	}
1450 #endif
1451 	if (sc->sc_inputs > 0) {
1452 		return (1);
1453 	}
1454 	return (0);
1455 }
1456 
1457 /* check if char is waiting */
1458 static int
ukbd_check_char_locked(keyboard_t * kbd)1459 ukbd_check_char_locked(keyboard_t *kbd)
1460 {
1461 	struct ukbd_softc *sc = kbd->kb_data;
1462 
1463 	UKBD_LOCK_ASSERT();
1464 
1465 	if (!KBD_IS_ACTIVE(kbd))
1466 		return (0);
1467 
1468 	if ((sc->sc_composed_char > 0) &&
1469 	    (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1470 		return (1);
1471 	}
1472 	return (ukbd_check(kbd));
1473 }
1474 
1475 static int
ukbd_check_char(keyboard_t * kbd)1476 ukbd_check_char(keyboard_t *kbd)
1477 {
1478 	int result;
1479 
1480 	UKBD_LOCK();
1481 	result = ukbd_check_char_locked(kbd);
1482 	UKBD_UNLOCK();
1483 
1484 	return (result);
1485 }
1486 
1487 /* read one byte from the keyboard if it's allowed */
1488 /* Currently unused. */
1489 static int
ukbd_read(keyboard_t * kbd,int wait)1490 ukbd_read(keyboard_t *kbd, int wait)
1491 {
1492 	struct ukbd_softc *sc = kbd->kb_data;
1493 	int32_t usbcode;
1494 #ifdef UKBD_EMULATE_ATSCANCODE
1495 	uint32_t keycode;
1496 	uint32_t scancode;
1497 
1498 #endif
1499 
1500 	UKBD_LOCK_ASSERT();
1501 
1502 	if (!KBD_IS_ACTIVE(kbd))
1503 		return (-1);
1504 
1505 #ifdef UKBD_EMULATE_ATSCANCODE
1506 	if (sc->sc_buffered_char[0]) {
1507 		scancode = sc->sc_buffered_char[0];
1508 		if (scancode & SCAN_PREFIX) {
1509 			sc->sc_buffered_char[0] &= ~SCAN_PREFIX;
1510 			return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1511 		}
1512 		sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1513 		sc->sc_buffered_char[1] = 0;
1514 		return (scancode);
1515 	}
1516 #endif					/* UKBD_EMULATE_ATSCANCODE */
1517 
1518 	/* XXX */
1519 	usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1520 	if (!KBD_IS_ACTIVE(kbd) || (usbcode == -1))
1521 		return (-1);
1522 
1523 	++(kbd->kb_count);
1524 
1525 #ifdef UKBD_EMULATE_ATSCANCODE
1526 	keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1527 	if (keycode == NN) {
1528 		return -1;
1529 	}
1530 	return (ukbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1531 	    (usbcode & KEY_RELEASE)));
1532 #else					/* !UKBD_EMULATE_ATSCANCODE */
1533 	return (usbcode);
1534 #endif					/* UKBD_EMULATE_ATSCANCODE */
1535 }
1536 
1537 /* read char from the keyboard */
1538 static uint32_t
ukbd_read_char_locked(keyboard_t * kbd,int wait)1539 ukbd_read_char_locked(keyboard_t *kbd, int wait)
1540 {
1541 	struct ukbd_softc *sc = kbd->kb_data;
1542 	uint32_t action;
1543 	uint32_t keycode;
1544 	int32_t usbcode;
1545 #ifdef UKBD_EMULATE_ATSCANCODE
1546 	uint32_t scancode;
1547 #endif
1548 
1549 	UKBD_LOCK_ASSERT();
1550 
1551 	if (!KBD_IS_ACTIVE(kbd))
1552 		return (NOKEY);
1553 
1554 next_code:
1555 
1556 	/* do we have a composed char to return ? */
1557 
1558 	if ((sc->sc_composed_char > 0) &&
1559 	    (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1560 
1561 		action = sc->sc_composed_char;
1562 		sc->sc_composed_char = 0;
1563 
1564 		if (action > 0xFF) {
1565 			goto errkey;
1566 		}
1567 		goto done;
1568 	}
1569 #ifdef UKBD_EMULATE_ATSCANCODE
1570 
1571 	/* do we have a pending raw scan code? */
1572 
1573 	if (sc->sc_mode == K_RAW) {
1574 		scancode = sc->sc_buffered_char[0];
1575 		if (scancode) {
1576 			if (scancode & SCAN_PREFIX) {
1577 				sc->sc_buffered_char[0] = (scancode & ~SCAN_PREFIX);
1578 				return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1579 			}
1580 			sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1581 			sc->sc_buffered_char[1] = 0;
1582 			return (scancode);
1583 		}
1584 	}
1585 #endif					/* UKBD_EMULATE_ATSCANCODE */
1586 
1587 	/* see if there is something in the keyboard port */
1588 	/* XXX */
1589 	usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1590 	if (usbcode == -1) {
1591 		return (NOKEY);
1592 	}
1593 	++kbd->kb_count;
1594 
1595 #ifdef UKBD_EMULATE_ATSCANCODE
1596 	/* USB key index -> key code -> AT scan code */
1597 	keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1598 	if (keycode == NN) {
1599 		return (NOKEY);
1600 	}
1601 	/* return an AT scan code for the K_RAW mode */
1602 	if (sc->sc_mode == K_RAW) {
1603 		return (ukbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1604 		    (usbcode & KEY_RELEASE)));
1605 	}
1606 #else					/* !UKBD_EMULATE_ATSCANCODE */
1607 
1608 	/* return the byte as is for the K_RAW mode */
1609 	if (sc->sc_mode == K_RAW) {
1610 		return (usbcode);
1611 	}
1612 	/* USB key index -> key code */
1613 	keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1614 	if (keycode == NN) {
1615 		return (NOKEY);
1616 	}
1617 #endif					/* UKBD_EMULATE_ATSCANCODE */
1618 
1619 	switch (keycode) {
1620 	case 0x38:			/* left alt (compose key) */
1621 		if (usbcode & KEY_RELEASE) {
1622 			if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1623 				sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1624 
1625 				if (sc->sc_composed_char > 0xFF) {
1626 					sc->sc_composed_char = 0;
1627 				}
1628 			}
1629 		} else {
1630 			if (!(sc->sc_flags & UKBD_FLAG_COMPOSE)) {
1631 				sc->sc_flags |= UKBD_FLAG_COMPOSE;
1632 				sc->sc_composed_char = 0;
1633 			}
1634 		}
1635 		break;
1636 	}
1637 
1638 	/* return the key code in the K_CODE mode */
1639 	if (usbcode & KEY_RELEASE) {
1640 		keycode |= SCAN_RELEASE;
1641 	}
1642 	if (sc->sc_mode == K_CODE) {
1643 		return (keycode);
1644 	}
1645 	/* compose a character code */
1646 	if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1647 		switch (keycode) {
1648 			/* key pressed, process it */
1649 		case 0x47:
1650 		case 0x48:
1651 		case 0x49:		/* keypad 7,8,9 */
1652 			sc->sc_composed_char *= 10;
1653 			sc->sc_composed_char += keycode - 0x40;
1654 			goto check_composed;
1655 
1656 		case 0x4B:
1657 		case 0x4C:
1658 		case 0x4D:		/* keypad 4,5,6 */
1659 			sc->sc_composed_char *= 10;
1660 			sc->sc_composed_char += keycode - 0x47;
1661 			goto check_composed;
1662 
1663 		case 0x4F:
1664 		case 0x50:
1665 		case 0x51:		/* keypad 1,2,3 */
1666 			sc->sc_composed_char *= 10;
1667 			sc->sc_composed_char += keycode - 0x4E;
1668 			goto check_composed;
1669 
1670 		case 0x52:		/* keypad 0 */
1671 			sc->sc_composed_char *= 10;
1672 			goto check_composed;
1673 
1674 			/* key released, no interest here */
1675 		case SCAN_RELEASE | 0x47:
1676 		case SCAN_RELEASE | 0x48:
1677 		case SCAN_RELEASE | 0x49:	/* keypad 7,8,9 */
1678 		case SCAN_RELEASE | 0x4B:
1679 		case SCAN_RELEASE | 0x4C:
1680 		case SCAN_RELEASE | 0x4D:	/* keypad 4,5,6 */
1681 		case SCAN_RELEASE | 0x4F:
1682 		case SCAN_RELEASE | 0x50:
1683 		case SCAN_RELEASE | 0x51:	/* keypad 1,2,3 */
1684 		case SCAN_RELEASE | 0x52:	/* keypad 0 */
1685 			goto next_code;
1686 
1687 		case 0x38:		/* left alt key */
1688 			break;
1689 
1690 		default:
1691 			if (sc->sc_composed_char > 0) {
1692 				sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1693 				sc->sc_composed_char = 0;
1694 				goto errkey;
1695 			}
1696 			break;
1697 		}
1698 	}
1699 	/* keycode to key action */
1700 	action = genkbd_keyaction(kbd, SCAN_CHAR(keycode),
1701 	    (keycode & SCAN_RELEASE),
1702 	    &sc->sc_state, &sc->sc_accents);
1703 	if (action == NOKEY) {
1704 		goto next_code;
1705 	}
1706 done:
1707 	return (action);
1708 
1709 check_composed:
1710 	if (sc->sc_composed_char <= 0xFF) {
1711 		goto next_code;
1712 	}
1713 errkey:
1714 	return (ERRKEY);
1715 }
1716 
1717 /* Currently wait is always false. */
1718 static uint32_t
ukbd_read_char(keyboard_t * kbd,int wait)1719 ukbd_read_char(keyboard_t *kbd, int wait)
1720 {
1721 	uint32_t keycode;
1722 
1723 	UKBD_LOCK();
1724 	keycode = ukbd_read_char_locked(kbd, wait);
1725 	UKBD_UNLOCK();
1726 
1727 	return (keycode);
1728 }
1729 
1730 /* some useful control functions */
1731 static int
ukbd_ioctl_locked(keyboard_t * kbd,u_long cmd,caddr_t arg)1732 ukbd_ioctl_locked(keyboard_t *kbd, u_long cmd, caddr_t arg)
1733 {
1734 	struct ukbd_softc *sc = kbd->kb_data;
1735 	int i;
1736 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1737     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1738 	int ival;
1739 
1740 #endif
1741 
1742 	UKBD_LOCK_ASSERT();
1743 
1744 	switch (cmd) {
1745 	case KDGKBMODE:		/* get keyboard mode */
1746 		*(int *)arg = sc->sc_mode;
1747 		break;
1748 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1749     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1750 	case _IO('K', 7):
1751 		ival = IOCPARM_IVAL(arg);
1752 		arg = (caddr_t)&ival;
1753 		/* FALLTHROUGH */
1754 #endif
1755 	case KDSKBMODE:		/* set keyboard mode */
1756 		switch (*(int *)arg) {
1757 		case K_XLATE:
1758 			if (sc->sc_mode != K_XLATE) {
1759 				/* make lock key state and LED state match */
1760 				sc->sc_state &= ~LOCK_MASK;
1761 				sc->sc_state |= KBD_LED_VAL(kbd);
1762 			}
1763 			/* FALLTHROUGH */
1764 		case K_RAW:
1765 		case K_CODE:
1766 			if (sc->sc_mode != *(int *)arg) {
1767 				if ((sc->sc_flags & UKBD_FLAG_POLLING) == 0)
1768 					ukbd_clear_state(kbd);
1769 				sc->sc_mode = *(int *)arg;
1770 			}
1771 			break;
1772 		default:
1773 			return (EINVAL);
1774 		}
1775 		break;
1776 
1777 	case KDGETLED:			/* get keyboard LED */
1778 		*(int *)arg = KBD_LED_VAL(kbd);
1779 		break;
1780 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1781     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1782 	case _IO('K', 66):
1783 		ival = IOCPARM_IVAL(arg);
1784 		arg = (caddr_t)&ival;
1785 		/* FALLTHROUGH */
1786 #endif
1787 	case KDSETLED:			/* set keyboard LED */
1788 		/* NOTE: lock key state in "sc_state" won't be changed */
1789 		if (*(int *)arg & ~LOCK_MASK)
1790 			return (EINVAL);
1791 
1792 		i = *(int *)arg;
1793 
1794 		/* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1795 		if (sc->sc_mode == K_XLATE &&
1796 		    kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1797 			if (i & ALKED)
1798 				i |= CLKED;
1799 			else
1800 				i &= ~CLKED;
1801 		}
1802 		if (KBD_HAS_DEVICE(kbd))
1803 			ukbd_set_leds(sc, i);
1804 
1805 		KBD_LED_VAL(kbd) = *(int *)arg;
1806 		break;
1807 	case KDGKBSTATE:		/* get lock key state */
1808 		*(int *)arg = sc->sc_state & LOCK_MASK;
1809 		break;
1810 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1811     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1812 	case _IO('K', 20):
1813 		ival = IOCPARM_IVAL(arg);
1814 		arg = (caddr_t)&ival;
1815 		/* FALLTHROUGH */
1816 #endif
1817 	case KDSKBSTATE:		/* set lock key state */
1818 		if (*(int *)arg & ~LOCK_MASK) {
1819 			return (EINVAL);
1820 		}
1821 		sc->sc_state &= ~LOCK_MASK;
1822 		sc->sc_state |= *(int *)arg;
1823 
1824 		/* set LEDs and quit */
1825 		return (ukbd_ioctl(kbd, KDSETLED, arg));
1826 
1827 	case KDSETREPEAT:		/* set keyboard repeat rate (new
1828 					 * interface) */
1829 		if (!KBD_HAS_DEVICE(kbd)) {
1830 			return (0);
1831 		}
1832 		/*
1833 		 * Convert negative, zero and tiny args to the same limits
1834 		 * as atkbd.  We could support delays of 1 msec, but
1835 		 * anything much shorter than the shortest atkbd value
1836 		 * of 250.34 is almost unusable as well as incompatible.
1837 		 */
1838 		kbd->kb_delay1 = imax(((int *)arg)[0], 250);
1839 		kbd->kb_delay2 = imax(((int *)arg)[1], 34);
1840 #ifdef EVDEV_SUPPORT
1841 		if (sc->sc_evdev != NULL)
1842 			evdev_push_repeats(sc->sc_evdev, kbd);
1843 #endif
1844 		return (0);
1845 
1846 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1847     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1848 	case _IO('K', 67):
1849 		ival = IOCPARM_IVAL(arg);
1850 		arg = (caddr_t)&ival;
1851 		/* FALLTHROUGH */
1852 #endif
1853 	case KDSETRAD:			/* set keyboard repeat rate (old
1854 					 * interface) */
1855 		return (ukbd_set_typematic(kbd, *(int *)arg));
1856 
1857 	case PIO_KEYMAP:		/* set keyboard translation table */
1858 	case OPIO_KEYMAP:		/* set keyboard translation table
1859 					 * (compat) */
1860 	case PIO_KEYMAPENT:		/* set keyboard translation table
1861 					 * entry */
1862 	case PIO_DEADKEYMAP:		/* set accent key translation table */
1863 		sc->sc_accents = 0;
1864 		/* FALLTHROUGH */
1865 	default:
1866 		return (genkbd_commonioctl(kbd, cmd, arg));
1867 	}
1868 
1869 	return (0);
1870 }
1871 
1872 static int
ukbd_ioctl(keyboard_t * kbd,u_long cmd,caddr_t arg)1873 ukbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
1874 {
1875 	int result;
1876 
1877 	/*
1878 	 * XXX Check if someone is calling us from a critical section:
1879 	 */
1880 	if (curthread->td_critnest != 0)
1881 		return (EDEADLK);
1882 
1883 	/*
1884 	 * XXX KDGKBSTATE, KDSKBSTATE and KDSETLED can be called from any
1885 	 * context where printf(9) can be called, which among other things
1886 	 * includes interrupt filters and threads with any kinds of locks
1887 	 * already held.  For this reason it would be dangerous to acquire
1888 	 * the Giant here unconditionally.  On the other hand we have to
1889 	 * have it to handle the ioctl.
1890 	 * So we make our best effort to auto-detect whether we can grab
1891 	 * the Giant or not.  Blame syscons(4) for this.
1892 	 */
1893 	switch (cmd) {
1894 	case KDGKBSTATE:
1895 	case KDSKBSTATE:
1896 	case KDSETLED:
1897 		if (!mtx_owned(&Giant) && !USB_IN_POLLING_MODE_FUNC())
1898 			return (EDEADLK);	/* best I could come up with */
1899 		/* FALLTHROUGH */
1900 	default:
1901 		UKBD_LOCK();
1902 		result = ukbd_ioctl_locked(kbd, cmd, arg);
1903 		UKBD_UNLOCK();
1904 		return (result);
1905 	}
1906 }
1907 
1908 
1909 /* clear the internal state of the keyboard */
1910 static void
ukbd_clear_state(keyboard_t * kbd)1911 ukbd_clear_state(keyboard_t *kbd)
1912 {
1913 	struct ukbd_softc *sc = kbd->kb_data;
1914 
1915 	UKBD_LOCK_ASSERT();
1916 
1917 	sc->sc_flags &= ~(UKBD_FLAG_COMPOSE | UKBD_FLAG_POLLING);
1918 	sc->sc_state &= LOCK_MASK;	/* preserve locking key state */
1919 	sc->sc_accents = 0;
1920 	sc->sc_composed_char = 0;
1921 #ifdef UKBD_EMULATE_ATSCANCODE
1922 	sc->sc_buffered_char[0] = 0;
1923 	sc->sc_buffered_char[1] = 0;
1924 #endif
1925 	memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1926 	memset(&sc->sc_odata, 0, sizeof(sc->sc_odata));
1927 	sc->sc_repeat_time = 0;
1928 	sc->sc_repeat_key = 0;
1929 }
1930 
1931 /* save the internal state, not used */
1932 static int
ukbd_get_state(keyboard_t * kbd,void * buf,size_t len)1933 ukbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1934 {
1935 	return (len == 0) ? 1 : -1;
1936 }
1937 
1938 /* set the internal state, not used */
1939 static int
ukbd_set_state(keyboard_t * kbd,void * buf,size_t len)1940 ukbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1941 {
1942 	return (EINVAL);
1943 }
1944 
1945 static int
ukbd_poll(keyboard_t * kbd,int on)1946 ukbd_poll(keyboard_t *kbd, int on)
1947 {
1948 	struct ukbd_softc *sc = kbd->kb_data;
1949 
1950 	UKBD_LOCK();
1951 	/*
1952 	 * Keep a reference count on polling to allow recursive
1953 	 * cngrab() during a panic for example.
1954 	 */
1955 	if (on)
1956 		sc->sc_polling++;
1957 	else if (sc->sc_polling > 0)
1958 		sc->sc_polling--;
1959 
1960 	if (sc->sc_polling != 0) {
1961 		sc->sc_flags |= UKBD_FLAG_POLLING;
1962 		sc->sc_poll_thread = curthread;
1963 	} else {
1964 		sc->sc_flags &= ~UKBD_FLAG_POLLING;
1965 		sc->sc_delay = 0;
1966 	}
1967 	UKBD_UNLOCK();
1968 
1969 	return (0);
1970 }
1971 
1972 /* local functions */
1973 
1974 static void
ukbd_set_leds(struct ukbd_softc * sc,uint8_t leds)1975 ukbd_set_leds(struct ukbd_softc *sc, uint8_t leds)
1976 {
1977 
1978 	UKBD_LOCK_ASSERT();
1979 	DPRINTF("leds=0x%02x\n", leds);
1980 
1981 #ifdef EVDEV_SUPPORT
1982 	if (sc->sc_evdev != NULL)
1983 		evdev_push_leds(sc->sc_evdev, leds);
1984 #endif
1985 
1986 	sc->sc_leds = leds;
1987 	sc->sc_flags |= UKBD_FLAG_SET_LEDS;
1988 
1989 	/* start transfer, if not already started */
1990 
1991 	usbd_transfer_start(sc->sc_xfer[UKBD_CTRL_LED]);
1992 }
1993 
1994 static int
ukbd_set_typematic(keyboard_t * kbd,int code)1995 ukbd_set_typematic(keyboard_t *kbd, int code)
1996 {
1997 #ifdef EVDEV_SUPPORT
1998 	struct ukbd_softc *sc = kbd->kb_data;
1999 #endif
2000 	static const int delays[] = {250, 500, 750, 1000};
2001 	static const int rates[] = {34, 38, 42, 46, 50, 55, 59, 63,
2002 		68, 76, 84, 92, 100, 110, 118, 126,
2003 		136, 152, 168, 184, 200, 220, 236, 252,
2004 	272, 304, 336, 368, 400, 440, 472, 504};
2005 
2006 	if (code & ~0x7f) {
2007 		return (EINVAL);
2008 	}
2009 	kbd->kb_delay1 = delays[(code >> 5) & 3];
2010 	kbd->kb_delay2 = rates[code & 0x1f];
2011 #ifdef EVDEV_SUPPORT
2012 	if (sc->sc_evdev != NULL)
2013 		evdev_push_repeats(sc->sc_evdev, kbd);
2014 #endif
2015 	return (0);
2016 }
2017 
2018 #ifdef UKBD_EMULATE_ATSCANCODE
2019 static uint32_t
ukbd_atkeycode(int usbcode,const uint64_t * bitmap)2020 ukbd_atkeycode(int usbcode, const uint64_t *bitmap)
2021 {
2022 	uint32_t keycode;
2023 
2024 	keycode = ukbd_trtab[KEY_INDEX(usbcode)];
2025 
2026 	/*
2027 	 * Translate Alt-PrintScreen to SysRq.
2028 	 *
2029 	 * Some or all AT keyboards connected through USB have already
2030 	 * mapped Alted PrintScreens to an unusual usbcode (0x8a).
2031 	 * ukbd_trtab translates this to 0x7e, and key2scan() would
2032 	 * translate that to 0x79 (Intl' 4).  Assume that if we have
2033 	 * an Alted 0x7e here then it actually is an Alted PrintScreen.
2034 	 *
2035 	 * The usual usbcode for all PrintScreens is 0x46.  ukbd_trtab
2036 	 * translates this to 0x5c, so the Alt check to classify 0x5c
2037 	 * is routine.
2038 	 */
2039 	if ((keycode == 0x5c || keycode == 0x7e) &&
2040 	    (UKBD_KEY_PRESSED(bitmap, 0xe2 /* ALT-L */) ||
2041 	     UKBD_KEY_PRESSED(bitmap, 0xe6 /* ALT-R */)))
2042 		return (0x54);
2043 	return (keycode);
2044 }
2045 
2046 static int
ukbd_key2scan(struct ukbd_softc * sc,int code,const uint64_t * bitmap,int up)2047 ukbd_key2scan(struct ukbd_softc *sc, int code, const uint64_t *bitmap, int up)
2048 {
2049 	static const int scan[] = {
2050 		/* 89 */
2051 		0x11c,	/* Enter */
2052 		/* 90-99 */
2053 		0x11d,	/* Ctrl-R */
2054 		0x135,	/* Divide */
2055 		0x137,	/* PrintScreen */
2056 		0x138,	/* Alt-R */
2057 		0x147,	/* Home */
2058 		0x148,	/* Up */
2059 		0x149,	/* PageUp */
2060 		0x14b,	/* Left */
2061 		0x14d,	/* Right */
2062 		0x14f,	/* End */
2063 		/* 100-109 */
2064 		0x150,	/* Down */
2065 		0x151,	/* PageDown */
2066 		0x152,	/* Insert */
2067 		0x153,	/* Delete */
2068 		0x146,	/* Pause/Break */
2069 		0x15b,	/* Win_L(Super_L) */
2070 		0x15c,	/* Win_R(Super_R) */
2071 		0x15d,	/* Application(Menu) */
2072 
2073 		/* SUN TYPE 6 USB KEYBOARD */
2074 		0x168,	/* Sun Type 6 Help */
2075 		0x15e,	/* Sun Type 6 Stop */
2076 		/* 110 - 119 */
2077 		0x15f,	/* Sun Type 6 Again */
2078 		0x160,	/* Sun Type 6 Props */
2079 		0x161,	/* Sun Type 6 Undo */
2080 		0x162,	/* Sun Type 6 Front */
2081 		0x163,	/* Sun Type 6 Copy */
2082 		0x164,	/* Sun Type 6 Open */
2083 		0x165,	/* Sun Type 6 Paste */
2084 		0x166,	/* Sun Type 6 Find */
2085 		0x167,	/* Sun Type 6 Cut */
2086 		0x125,	/* Sun Type 6 Mute */
2087 		/* 120 - 130 */
2088 		0x11f,	/* Sun Type 6 VolumeDown */
2089 		0x11e,	/* Sun Type 6 VolumeUp */
2090 		0x120,	/* Sun Type 6 PowerDown */
2091 
2092 		/* Japanese 106/109 keyboard */
2093 		0x73,	/* Keyboard Intl' 1 (backslash / underscore) */
2094 		0x70,	/* Keyboard Intl' 2 (Katakana / Hiragana) */
2095 		0x7d,	/* Keyboard Intl' 3 (Yen sign) (Not using in jp106/109) */
2096 		0x79,	/* Keyboard Intl' 4 (Henkan) */
2097 		0x7b,	/* Keyboard Intl' 5 (Muhenkan) */
2098 		0x5c,	/* Keyboard Intl' 6 (Keypad ,) (For PC-9821 layout) */
2099 		0x71,   /* Apple Keyboard JIS (Kana) */
2100 		0x72,   /* Apple Keyboard JIS (Eisu) */
2101 	};
2102 
2103 	if ((code >= 89) && (code < (int)(89 + nitems(scan)))) {
2104 		code = scan[code - 89];
2105 	}
2106 	/* PrintScreen */
2107 	if (code == 0x137 && (!(
2108 	    UKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
2109 	    UKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */) ||
2110 	    UKBD_KEY_PRESSED(bitmap, 0xe1 /* SHIFT-L */) ||
2111 	    UKBD_KEY_PRESSED(bitmap, 0xe5 /* SHIFT-R */)))) {
2112 		code |= SCAN_PREFIX_SHIFT;
2113 	}
2114 	/* Pause/Break */
2115 	if ((code == 0x146) && (!(
2116 	    UKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
2117 	    UKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */)))) {
2118 		code = (0x45 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL);
2119 	}
2120 	code |= (up ? SCAN_RELEASE : SCAN_PRESS);
2121 
2122 	if (code & SCAN_PREFIX) {
2123 		if (code & SCAN_PREFIX_CTL) {
2124 			/* Ctrl */
2125 			sc->sc_buffered_char[0] = (0x1d | (code & SCAN_RELEASE));
2126 			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX);
2127 		} else if (code & SCAN_PREFIX_SHIFT) {
2128 			/* Shift */
2129 			sc->sc_buffered_char[0] = (0x2a | (code & SCAN_RELEASE));
2130 			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX_SHIFT);
2131 		} else {
2132 			sc->sc_buffered_char[0] = (code & ~SCAN_PREFIX);
2133 			sc->sc_buffered_char[1] = 0;
2134 		}
2135 		return ((code & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
2136 	}
2137 	return (code);
2138 
2139 }
2140 
2141 #endif					/* UKBD_EMULATE_ATSCANCODE */
2142 
2143 static keyboard_switch_t ukbdsw = {
2144 	.probe = &ukbd__probe,
2145 	.init = &ukbd_init,
2146 	.term = &ukbd_term,
2147 	.intr = &ukbd_intr,
2148 	.test_if = &ukbd_test_if,
2149 	.enable = &ukbd_enable,
2150 	.disable = &ukbd_disable,
2151 	.read = &ukbd_read,
2152 	.check = &ukbd_check,
2153 	.read_char = &ukbd_read_char,
2154 	.check_char = &ukbd_check_char,
2155 	.ioctl = &ukbd_ioctl,
2156 	.lock = &ukbd_lock,
2157 	.clear_state = &ukbd_clear_state,
2158 	.get_state = &ukbd_get_state,
2159 	.set_state = &ukbd_set_state,
2160 	.poll = &ukbd_poll,
2161 };
2162 
2163 KEYBOARD_DRIVER(ukbd, ukbdsw, ukbd_configure);
2164 
2165 static int
ukbd_driver_load(module_t mod,int what,void * arg)2166 ukbd_driver_load(module_t mod, int what, void *arg)
2167 {
2168 	switch (what) {
2169 	case MOD_LOAD:
2170 		kbd_add_driver(&ukbd_kbd_driver);
2171 		break;
2172 	case MOD_UNLOAD:
2173 		kbd_delete_driver(&ukbd_kbd_driver);
2174 		break;
2175 	}
2176 	return (0);
2177 }
2178 
2179 static devclass_t ukbd_devclass;
2180 
2181 static device_method_t ukbd_methods[] = {
2182 	DEVMETHOD(device_probe, ukbd_probe),
2183 	DEVMETHOD(device_attach, ukbd_attach),
2184 	DEVMETHOD(device_detach, ukbd_detach),
2185 	DEVMETHOD(device_resume, ukbd_resume),
2186 
2187 	DEVMETHOD_END
2188 };
2189 
2190 static driver_t ukbd_driver = {
2191 	.name = "ukbd",
2192 	.methods = ukbd_methods,
2193 	.size = sizeof(struct ukbd_softc),
2194 };
2195 
2196 DRIVER_MODULE(ukbd, uhub, ukbd_driver, ukbd_devclass, ukbd_driver_load, 0);
2197 MODULE_DEPEND(ukbd, usb, 1, 1, 1);
2198 #ifdef EVDEV_SUPPORT
2199 MODULE_DEPEND(ukbd, evdev, 1, 1, 1);
2200 #endif
2201 MODULE_VERSION(ukbd, 1);
2202 USB_PNP_HOST_INFO(ukbd_devs);
2203