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