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