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