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