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