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