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