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