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