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