Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.git] / sys / dev / usbmisc / ukbd / ukbd.c
1 /*
2  * $FreeBSD: src/sys/dev/usb/ukbd.c,v 1.45 2003/10/04 21:41:01 joe Exp $
3  * $DragonFly: src/sys/dev/usbmisc/ukbd/ukbd.c,v 1.27 2008/08/14 20:55:53 hasso Exp $
4  */
5
6 /*
7  * (MPSAFE)
8  *
9  * Copyright (c) 1998 The NetBSD Foundation, Inc.
10  * All rights reserved.
11  *
12  * This code is derived from software contributed to The NetBSD Foundation
13  * by Lennart Augustsson (lennart@augustsson.net) at
14  * Carlstedt Research & Technology.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. All advertising materials mentioning features or use of this software
25  *    must display the following acknowledgement:
26  *        This product includes software developed by the NetBSD
27  *        Foundation, Inc. and its contributors.
28  * 4. Neither the name of The NetBSD Foundation nor the names of its
29  *    contributors may be used to endorse or promote products derived
30  *    from this software without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
33  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
34  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
35  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
36  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
37  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
38  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
39  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
40  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
41  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
42  * POSSIBILITY OF SUCH DAMAGE.
43  */
44
45 /*
46  * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf
47  */
48
49 #include "opt_kbd.h"
50 #include "opt_ukbd.h"
51
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/kernel.h>
55 #include <sys/module.h>
56 #include <sys/bus.h>
57 #include <sys/file.h>
58 #include <machine/limits.h>
59 #include <sys/select.h>
60 #include <sys/sysctl.h>
61 #include <sys/thread2.h>
62
63 #include <bus/usb/usb.h>
64 #include <bus/usb/usbhid.h>
65 #include <bus/usb/usbdi.h>
66 #include <bus/usb/usbdi_util.h>
67 #include <bus/usb/usb_quirks.h>
68 #include <bus/usb/hid.h>
69
70 #include <sys/kbio.h>
71 #include <dev/misc/kbd/kbdreg.h>
72
73 #define UKBD_EMULATE_ATSCANCODE 1
74
75 #define DRIVER_NAME     "ukbd"
76
77 #define delay(d)         DELAY(d)
78
79 #ifdef USB_DEBUG
80 #define DPRINTF(x)      if (ukbddebug) kprintf x
81 #define DPRINTFN(n,x)   if (ukbddebug>(n)) kprintf x
82 int     ukbddebug = 0;
83 SYSCTL_NODE(_hw_usb, OID_AUTO, ukbd, CTLFLAG_RW, 0, "USB ukbd");
84 SYSCTL_INT(_hw_usb_ukbd, OID_AUTO, debug, CTLFLAG_RW,
85            &ukbddebug, 0, "ukbd debug level");
86 #else
87 #define DPRINTF(x)
88 #define DPRINTFN(n,x)
89 #endif
90
91 #define UPROTO_BOOT_KEYBOARD 1
92
93 #define NKEYCODE 6
94
95 struct ukbd_data {
96         u_int8_t        modifiers;
97 #define MOD_CONTROL_L   0x01
98 #define MOD_CONTROL_R   0x10
99 #define MOD_SHIFT_L     0x02
100 #define MOD_SHIFT_R     0x20
101 #define MOD_ALT_L       0x04
102 #define MOD_ALT_R       0x40
103 #define MOD_WIN_L       0x08
104 #define MOD_WIN_R       0x80
105         u_int8_t        reserved;
106         u_int8_t        keycode[NKEYCODE];
107 };
108
109 #define MAXKEYS (NMOD+2*NKEYCODE)
110
111 typedef struct ukbd_softc {
112         device_t                sc_dev;         /* base device */
113 } ukbd_softc_t;
114
115 #define UKBD_CHUNK      128     /* chunk size for read */
116 #define UKBD_BSIZE      1020    /* buffer size */
117
118 typedef void usbd_intr_t(usbd_xfer_handle, usbd_private_handle, usbd_status);
119 typedef void usbd_disco_t(void *);
120
121 static int              ukbd_resume(device_t self);
122 static usbd_intr_t      ukbd_intr;
123 static int              ukbd_driver_load(module_t mod, int what, void *arg);
124
125 static keyboard_t       default_kbd;
126
127 static device_probe_t ukbd_match;
128 static device_attach_t ukbd_attach;
129 static device_detach_t ukbd_detach;
130
131 static devclass_t ukbd_devclass;
132
133 static kobj_method_t ukbd_methods[] = {
134         DEVMETHOD(device_probe, ukbd_match),
135         DEVMETHOD(device_attach, ukbd_attach),
136         DEVMETHOD(device_detach, ukbd_detach),
137         DEVMETHOD(device_resume, ukbd_resume),
138         {0,0}
139 };
140
141 static driver_t ukbd_driver = {
142         "ukbd",
143         ukbd_methods,
144         sizeof(struct ukbd_softc)
145 };
146
147 MODULE_DEPEND(ukbd, usb, 1, 1, 1);
148
149 static int
150 ukbd_match(device_t self)
151 {
152         struct usb_attach_arg *uaa = device_get_ivars(self);
153
154         keyboard_switch_t *sw;
155         void *arg[2];
156         int unit = device_get_unit(self);
157
158         lwkt_gettoken(&tty_token);
159         sw = kbd_get_switch(DRIVER_NAME);
160         if (sw == NULL) {
161                 lwkt_reltoken(&tty_token);
162                 return (UMATCH_NONE);
163         }
164
165         arg[0] = (void *)uaa;
166         arg[1] = (void *)ukbd_intr;
167         if ((*sw->probe)(unit, (void *)arg, 0)) {
168                 lwkt_reltoken(&tty_token);
169                 return (UMATCH_NONE);
170         }
171
172         lwkt_reltoken(&tty_token);
173         return (UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
174 }
175
176 static int
177 ukbd_attach(device_t self)
178 {
179         struct ukbd_softc *sc = device_get_softc(self);
180         struct usb_attach_arg *uaa = device_get_ivars(self);
181
182         keyboard_switch_t *sw;
183         keyboard_t *kbd;
184         void *arg[2];
185         int unit = device_get_unit(self);
186
187         lwkt_gettoken(&tty_token);
188
189         sc->sc_dev = self;
190
191         sw = kbd_get_switch(DRIVER_NAME);
192         if (sw == NULL) {
193                 lwkt_reltoken(&tty_token);
194                 return ENXIO;
195         }
196
197         arg[0] = (void *)uaa;
198         arg[1] = (void *)ukbd_intr;
199         kbd = NULL;
200         if ((*sw->probe)(unit, (void *)arg, 0)) {
201                 lwkt_reltoken(&tty_token);
202                 return ENXIO;
203         }
204         if ((*sw->init)(unit, &kbd, (void *)arg, 0)) {
205                 lwkt_reltoken(&tty_token);
206                 return ENXIO;
207         }
208         (*sw->enable)(kbd);
209
210 #ifdef KBD_INSTALL_CDEV
211         if (kbd_attach(kbd)) {
212                 lwkt_reltoken(&tty_token);
213                 return ENXIO;
214         }
215 #endif
216         if (bootverbose)
217                 (*sw->diag)(kbd, bootverbose);
218
219         lwkt_reltoken(&tty_token);
220         return 0;
221 }
222
223 int
224 ukbd_detach(device_t self)
225 {
226         keyboard_t *kbd;
227         int error;
228
229         lwkt_gettoken(&tty_token);
230         kbd = kbd_get_keyboard(kbd_find_keyboard(DRIVER_NAME,
231                                                  device_get_unit(self)));
232         if (kbd == NULL) {
233                 DPRINTF(("%s: keyboard not attached!?\n", device_get_nameunit(self)));
234                 lwkt_reltoken(&tty_token);
235                 return ENXIO;
236         }
237         kbd_disable(kbd);
238
239 #ifdef KBD_INSTALL_CDEV
240         error = kbd_detach(kbd);
241         if (error) {
242                 lwkt_reltoken(&tty_token);
243                 return error;
244         }
245 #endif
246         error = kbd_term(kbd);
247         if (error) {
248                 lwkt_reltoken(&tty_token);
249                 return error;
250         }
251
252         DPRINTF(("%s: disconnected\n", device_get_nameunit(self)));
253
254         lwkt_reltoken(&tty_token);
255         return (0);
256 }
257
258 static int
259 ukbd_resume(device_t self)
260 {
261         keyboard_t *kbd;
262
263         lwkt_gettoken(&tty_token);
264         kbd = kbd_get_keyboard(kbd_find_keyboard(DRIVER_NAME,
265                                                  device_get_unit(self)));
266         if (kbd)
267                 kbd_clear_state(kbd);
268
269         lwkt_reltoken(&tty_token);
270         return (0);
271 }
272
273 void
274 ukbd_intr(usbd_xfer_handle xfer, usbd_private_handle addr, usbd_status status)
275 {
276         keyboard_t *kbd = (keyboard_t *)addr;
277
278         lwkt_gettoken(&tty_token);
279         kbd_intr(kbd, (void *)status);
280         lwkt_reltoken(&tty_token);
281 }
282
283 DRIVER_MODULE(ukbd, uhub, ukbd_driver, ukbd_devclass, ukbd_driver_load, 0);
284
285
286 #define UKBD_DEFAULT    0
287
288 #define KEY_ERROR       0x01
289
290 #define KEY_PRESS       0
291 #define KEY_RELEASE     0x400
292 #define KEY_INDEX(c)    ((c) & ~KEY_RELEASE)
293
294 #define SCAN_PRESS      0
295 #define SCAN_RELEASE    0x80
296 #define SCAN_PREFIX_E0  0x100
297 #define SCAN_PREFIX_E1  0x200
298 #define SCAN_PREFIX_CTL 0x400
299 #define SCAN_PREFIX_SHIFT 0x800
300 #define SCAN_PREFIX     (SCAN_PREFIX_E0 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL \
301                          | SCAN_PREFIX_SHIFT)
302 #define SCAN_CHAR(c)    ((c) & 0x7f)
303
304 #define NMOD 8
305 static struct {
306         int mask, key;
307 } ukbd_mods[NMOD] = {
308         { MOD_CONTROL_L, 0xe0 },
309         { MOD_CONTROL_R, 0xe4 },
310         { MOD_SHIFT_L,   0xe1 },
311         { MOD_SHIFT_R,   0xe5 },
312         { MOD_ALT_L,     0xe2 },
313         { MOD_ALT_R,     0xe6 },
314         { MOD_WIN_L,     0xe3 },
315         { MOD_WIN_R,     0xe7 },
316 };
317
318 #define NN 0                    /* no translation */
319 /*
320  * Translate USB keycodes to AT keyboard scancodes.
321  */
322 /*
323  * FIXME: Mac USB keyboard generates:
324  * 0x53: keypad NumLock/Clear
325  * 0x66: Power
326  * 0x67: keypad =
327  * 0x68: F13
328  * 0x69: F14
329  * 0x6a: F15
330  */
331 static u_int8_t ukbd_trtab[256] = {
332            0,   0,   0,   0,  30,  48,  46,  32, /* 00 - 07 */
333           18,  33,  34,  35,  23,  36,  37,  38, /* 08 - 0F */
334           50,  49,  24,  25,  16,  19,  31,  20, /* 10 - 17 */
335           22,  47,  17,  45,  21,  44,   2,   3, /* 18 - 1F */
336            4,   5,   6,   7,   8,   9,  10,  11, /* 20 - 27 */
337           28,   1,  14,  15,  57,  12,  13,  26, /* 28 - 2F */
338           27,  43,  43,  39,  40,  41,  51,  52, /* 30 - 37 */
339           53,  58,  59,  60,  61,  62,  63,  64, /* 38 - 3F */
340           65,  66,  67,  68,  87,  88,  92,  70, /* 40 - 47 */
341          104, 102,  94,  96, 103,  99, 101,  98, /* 48 - 4F */
342           97, 100,  95,  69,  91,  55,  74,  78, /* 50 - 57 */
343           89,  79,  80,  81,  75,  76,  77,  71, /* 58 - 5F */
344           72,  73,  82,  83,  86, 107, 122,  NN, /* 60 - 67 */
345           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* 68 - 6F */
346           NN,  NN,  NN,  NN, 115, 108, 111, 113, /* 70 - 77 */
347           109, 110, 112, 118, 114, 116, 117, 119, /* 78 - 7F */
348           121, 120,  NN,  NN,  NN,  NN,  NN, 115, /* 80 - 87 */
349          112, 125, 121, 123,  NN,  NN,  NN,  NN, /* 88 - 8F */
350           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* 90 - 97 */
351           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* 98 - 9F */
352           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* A0 - A7 */
353           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* A8 - AF */
354           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* B0 - B7 */
355           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* B8 - BF */
356           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* C0 - C7 */
357           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* C8 - CF */
358           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* D0 - D7 */
359           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* D8 - DF */
360           29,  42,  56, 105,  90,  54,  93, 106, /* E0 - E7 */
361           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* E8 - EF */
362           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* F0 - F7 */
363           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* F8 - FF */
364 };
365
366 typedef struct ukbd_state {
367         usbd_interface_handle ks_iface; /* interface */
368         usbd_pipe_handle ks_intrpipe;   /* interrupt pipe */
369         struct usb_attach_arg *ks_uaa;
370         int ks_ep_addr;
371
372         struct ukbd_data ks_ndata;
373         struct ukbd_data ks_odata;
374         u_long          ks_ntime[NKEYCODE];
375         u_long          ks_otime[NKEYCODE];
376
377 #define INPUTBUFSIZE    (NMOD + 2*NKEYCODE)
378         u_int           ks_input[INPUTBUFSIZE]; /* input buffer */
379         int             ks_inputs;
380         int             ks_inputhead;
381         int             ks_inputtail;
382
383         int             ks_ifstate;
384 #define INTRENABLED     (1 << 0)
385 #define DISCONNECTED    (1 << 1)
386
387         struct callout ks_timeout;
388
389         int             ks_mode;        /* input mode (K_XLATE,K_RAW,K_CODE) */
390         int             ks_flags;       /* flags */
391 #define COMPOSE         (1 << 0)
392         int             ks_polling;
393         int             ks_state;       /* shift/lock key state */
394         int             ks_accents;     /* accent key index (> 0) */
395         u_int           ks_composed_char; /* composed char code (> 0) */
396 #ifdef UKBD_EMULATE_ATSCANCODE
397         u_int           ks_buffered_char[2];
398 #endif
399 } ukbd_state_t;
400
401 /* keyboard driver declaration */
402 static int              ukbd_configure(int flags);
403 static kbd_probe_t      ukbd_probe;
404 static kbd_init_t       ukbd_init;
405 static kbd_term_t       ukbd_term;
406 static kbd_intr_t       ukbd_interrupt;
407 static kbd_test_if_t    ukbd_test_if;
408 static kbd_enable_t     ukbd_enable;
409 static kbd_disable_t    ukbd_disable;
410 static kbd_read_t       ukbd_read;
411 static kbd_check_t      ukbd_check;
412 static kbd_read_char_t  ukbd_read_char;
413 static kbd_check_char_t ukbd_check_char;
414 static kbd_ioctl_t      ukbd_ioctl;
415 static kbd_lock_t       ukbd_lock;
416 static kbd_clear_state_t ukbd_clear_state;
417 static kbd_get_state_t  ukbd_get_state;
418 static kbd_set_state_t  ukbd_set_state;
419 static kbd_poll_mode_t  ukbd_poll;
420
421 keyboard_switch_t ukbdsw = {
422         ukbd_probe,
423         ukbd_init,
424         ukbd_term,
425         ukbd_interrupt,
426         ukbd_test_if,
427         ukbd_enable,
428         ukbd_disable,
429         ukbd_read,
430         ukbd_check,
431         ukbd_read_char,
432         ukbd_check_char,
433         ukbd_ioctl,
434         ukbd_lock,
435         ukbd_clear_state,
436         ukbd_get_state,
437         ukbd_set_state,
438         genkbd_get_fkeystr,
439         ukbd_poll,
440         genkbd_diag,
441 };
442
443 KEYBOARD_DRIVER(ukbd, ukbdsw, ukbd_configure);
444
445 /* local functions */
446 static int              ukbd_enable_intr(keyboard_t *kbd, int on,
447                                          usbd_intr_t *func);
448 static timeout_t        ukbd_timeout;
449
450 static int              ukbd_getc(ukbd_state_t *state, int wait);
451 static int              probe_keyboard(struct usb_attach_arg *uaa, int flags);
452 static int              init_keyboard(ukbd_state_t *state, int *type,
453                                       int flags);
454 static void             set_leds(ukbd_state_t *state, int leds);
455 static int              set_typematic(keyboard_t *kbd, int code);
456 #ifdef UKBD_EMULATE_ATSCANCODE
457 static int              keycode2scancode(int keycode, int shift, int up);
458 #endif
459
460 /* local variables */
461
462 /* the initial key map, accent map and fkey strings */
463 #if defined(UKBD_DFLT_KEYMAP) && !defined(KLD_MODULE)
464 #define KBD_DFLT_KEYMAP
465 #include "ukbdmap.h"
466 #endif
467 #include <dev/misc/kbd/kbdtables.h>
468
469 /* structures for the default keyboard */
470 static ukbd_state_t     default_kbd_state;
471 static keymap_t         default_keymap;
472 static accentmap_t      default_accentmap;
473 static fkeytab_t        default_fkeytab[NUM_FKEYS];
474
475 /*
476  * The back door to the keyboard driver!
477  * This function is called by the console driver, via the kbdio module,
478  * to tickle keyboard drivers when the low-level console is being initialized.
479  * Almost nothing in the kernel has been initialied yet.  Try to probe
480  * keyboards if possible.
481  * NOTE: because of the way the low-level conole is initialized, this routine
482  * may be called more than once!!
483  */
484 static int
485 ukbd_configure(int flags)
486 {
487         return 0;
488
489 #if 0 /* not yet */
490         keyboard_t *kbd;
491         device_t device;
492         struct usb_attach_arg *uaa;
493         void *arg[2];
494
495         device = devclass_get_device(ukbd_devclass, UKBD_DEFAULT);
496         if (device == NULL)
497                 return 0;
498         uaa = (struct usb_attach_arg *)device_get_ivars(device);
499         if (uaa == NULL)
500                 return 0;
501
502         /* probe the default keyboard */
503         arg[0] = (void *)uaa;
504         arg[1] = (void *)ukbd_intr;
505         kbd = NULL;
506         if (ukbd_probe(UKBD_DEFAULT, arg, flags))
507                 return 0;
508         if (ukbd_init(UKBD_DEFAULT, &kbd, arg, flags))
509                 return 0;
510
511         /* return the number of found keyboards */
512         return 1;
513 #endif
514 }
515
516 /* low-level functions */
517
518 /* detect a keyboard */
519 static int
520 ukbd_probe(int unit, void *arg, int flags)
521 {
522         void **data;
523         struct usb_attach_arg *uaa;
524
525         data = (void **)arg;
526         uaa = (struct usb_attach_arg *)data[0];
527
528         if (unit == UKBD_DEFAULT) {
529                 if (KBD_IS_PROBED(&default_kbd))
530                         return 0;
531         }
532         if (probe_keyboard(uaa, flags))
533                 return ENXIO;
534         return 0;
535 }
536
537 /*
538  * Reset and initialize the device.  Note that unit 0 (UKBD_DEFAULT) is an
539  * always-connected device once it has been initially detected.  We do not
540  * deregister it if the usb keyboard is unplugged to avoid losing the 
541  * connection to the console.  This feature also handles the USB bus reset
542  * which detaches and reattaches USB devices during boot.
543  */
544 static int
545 ukbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
546 {
547         keyboard_t *kbd;
548         ukbd_state_t *state;
549         keymap_t *keymap;
550         accentmap_t *accmap;
551         fkeytab_t *fkeymap;
552         int fkeymap_size;
553         void **data = (void **)arg;
554         struct usb_attach_arg *uaa = (struct usb_attach_arg *)data[0];
555
556         lwkt_gettoken(&tty_token);
557         if (unit == UKBD_DEFAULT) {
558                 *kbdp = kbd = &default_kbd;
559                 if (KBD_IS_INITIALIZED(kbd) && KBD_IS_CONFIGURED(kbd)) {
560                         lwkt_reltoken(&tty_token);
561                         return 0;
562                 }
563                 state = &default_kbd_state;
564                 keymap = &default_keymap;
565                 accmap = &default_accentmap;
566                 fkeymap = default_fkeytab;
567                 fkeymap_size =
568                         sizeof(default_fkeytab)/sizeof(default_fkeytab[0]);
569         } else if (*kbdp == NULL) {
570                 *kbdp = kbd = kmalloc(sizeof(*kbd), M_DEVBUF, M_INTWAIT | M_ZERO);
571                 state = kmalloc(sizeof(*state), M_DEVBUF, M_INTWAIT);
572                 keymap = kmalloc(sizeof(key_map), M_DEVBUF, M_INTWAIT);
573                 accmap = kmalloc(sizeof(accent_map), M_DEVBUF, M_INTWAIT);
574                 fkeymap = kmalloc(sizeof(fkey_tab), M_DEVBUF, M_INTWAIT);
575                 fkeymap_size = sizeof(fkey_tab)/sizeof(fkey_tab[0]);
576                 if ((state == NULL) || (keymap == NULL) || (accmap == NULL)
577                      || (fkeymap == NULL)) {
578                         if (state != NULL)
579                                 kfree(state, M_DEVBUF);
580                         if (keymap != NULL)
581                                 kfree(keymap, M_DEVBUF);
582                         if (accmap != NULL)
583                                 kfree(accmap, M_DEVBUF);
584                         if (fkeymap != NULL)
585                                 kfree(fkeymap, M_DEVBUF);
586                         kfree(kbd, M_DEVBUF);
587                         lwkt_reltoken(&tty_token);
588                         return ENOMEM;
589                 }
590         } else if (KBD_IS_INITIALIZED(*kbdp) && KBD_IS_CONFIGURED(*kbdp)) {
591                 lwkt_reltoken(&tty_token);
592                 return 0;
593         } else {
594                 kbd = *kbdp;
595                 state = (ukbd_state_t *)kbd->kb_data;
596                 keymap = kbd->kb_keymap;
597                 accmap = kbd->kb_accentmap;
598                 fkeymap = kbd->kb_fkeytab;
599                 fkeymap_size = kbd->kb_fkeytab_size;
600         }
601
602         if (!KBD_IS_PROBED(kbd)) {
603                 kbd_init_struct(kbd, DRIVER_NAME, KB_OTHER,
604                                 unit, flags, KB_PRI_USB,
605                                 0, 0);
606                 bzero(state, sizeof(*state));
607                 bcopy(&key_map, keymap, sizeof(key_map));
608                 bcopy(&accent_map, accmap, sizeof(accent_map));
609                 bcopy(fkey_tab, fkeymap,
610                       imin(fkeymap_size*sizeof(fkeymap[0]), sizeof(fkey_tab)));
611                 kbd_set_maps(kbd, keymap, accmap, fkeymap, fkeymap_size);
612                 kbd->kb_data = (void *)state;
613
614                 if (probe_keyboard(uaa, flags)) {
615                         lwkt_reltoken(&tty_token);
616                         return ENXIO;
617                 } else {
618                         KBD_FOUND_DEVICE(kbd);
619                 }
620                 ukbd_clear_state(kbd);
621
622                 /*
623                  * If reattatching to an already open keyboard (e.g. console),
624                  * try to restore the translation mode.  Otherwise set the
625                  * translation mode to, well, translation mode so we don't
626                  * get garbage.
627                  */
628                 state->ks_mode = K_XLATE;
629                 state->ks_iface = uaa->iface;
630                 state->ks_uaa = uaa;
631                 state->ks_ifstate = 0;
632                 callout_init_mp(&state->ks_timeout);
633                 /*
634                  * FIXME: set the initial value for lock keys in ks_state
635                  * according to the BIOS data?
636                  */
637                 KBD_PROBE_DONE(kbd);
638         }
639         if (!KBD_IS_INITIALIZED(kbd) && !(flags & KB_CONF_PROBE_ONLY)) {
640                 if (KBD_HAS_DEVICE(kbd)
641                     && init_keyboard((ukbd_state_t *)kbd->kb_data,
642                                      &kbd->kb_type, kbd->kb_flags)) {
643                         lwkt_reltoken(&tty_token);
644                         return ENXIO;
645                 }
646                 ukbd_ioctl(kbd, KDSETLED, (caddr_t)&(state->ks_state));
647         }
648         if (!KBD_IS_CONFIGURED(kbd)) {
649                 if (kbd_register(kbd) < 0) {
650                         kbd->kb_flags = 0;
651                         /* XXX: Missing free()'s */
652                         lwkt_reltoken(&tty_token);
653                         return ENXIO;
654                 }
655                 if (ukbd_enable_intr(kbd, TRUE, (usbd_intr_t *)data[1]) == 0)
656                         ukbd_timeout((void *)kbd);
657                 KBD_CONFIG_DONE(kbd);
658         }
659
660         lwkt_reltoken(&tty_token);
661         return 0;
662 }
663
664 static int
665 ukbd_enable_intr(keyboard_t *kbd, int on, usbd_intr_t *func)
666 {
667         ukbd_state_t *state = (ukbd_state_t *)kbd->kb_data;
668         usbd_status err;
669
670         lwkt_gettoken(&tty_token);
671         if (on) {
672                 /* Set up interrupt pipe. */
673                 if (state->ks_ifstate & INTRENABLED) {
674                         lwkt_reltoken(&tty_token);
675                         return EBUSY;
676                 }
677
678                 state->ks_ifstate |= INTRENABLED;
679                 err = usbd_open_pipe_intr(state->ks_iface, state->ks_ep_addr,
680                                         USBD_SHORT_XFER_OK | USBD_CALLBACK_LAST,
681                                         &state->ks_intrpipe, kbd,
682                                         &state->ks_ndata,
683                                         sizeof(state->ks_ndata), func,
684                                         USBD_DEFAULT_INTERVAL);
685                 if (err) {
686                         lwkt_reltoken(&tty_token);
687                         return (EIO);
688                 }
689         } else {
690                 /* Disable interrupts. */
691                 usbd_abort_pipe(state->ks_intrpipe);
692                 usbd_close_pipe(state->ks_intrpipe);
693
694                 state->ks_ifstate &= ~INTRENABLED;
695         }
696
697         lwkt_reltoken(&tty_token);
698         return (0);
699 }
700
701 /* finish using this keyboard */
702 static int
703 ukbd_term(keyboard_t *kbd)
704 {
705         ukbd_state_t *state;
706         int error;
707
708         crit_enter();
709         lwkt_gettoken(&tty_token);
710         state = (ukbd_state_t *)kbd->kb_data;
711         DPRINTF(("ukbd_term: ks_ifstate=0x%x\n", state->ks_ifstate));
712
713         callout_stop(&state->ks_timeout);
714
715         if (state->ks_ifstate & INTRENABLED)
716                 ukbd_enable_intr(kbd, FALSE, NULL);
717         if (state->ks_ifstate & INTRENABLED) {
718                 lwkt_reltoken(&tty_token);
719                 crit_exit();
720                 DPRINTF(("ukbd_term: INTRENABLED!\n"));
721                 return ENXIO;
722         }
723
724         error = kbd_unregister(kbd);
725         DPRINTF(("ukbd_term: kbd_unregister() %d\n", error));
726         if (error == 0) {
727                 kbd->kb_flags = 0;
728                 if (kbd != &default_kbd) {
729                         kfree(kbd->kb_keymap, M_DEVBUF);
730                         kfree(kbd->kb_accentmap, M_DEVBUF);
731                         kfree(kbd->kb_fkeytab, M_DEVBUF);
732                         kfree(state, M_DEVBUF);
733                         kfree(kbd, M_DEVBUF);
734                 }
735         }
736         lwkt_reltoken(&tty_token);
737         crit_exit();
738         return error;
739 }
740
741 /* keyboard interrupt routine */
742
743 static void
744 ukbd_timeout(void *arg)
745 {
746         keyboard_t *kbd;
747         ukbd_state_t *state;
748
749         lwkt_gettoken(&tty_token);
750         kbd = (keyboard_t *)arg;
751         state = (ukbd_state_t *)kbd->kb_data;
752         crit_enter();
753         kbd_intr(kbd, (void *)USBD_NORMAL_COMPLETION);
754         callout_reset(&state->ks_timeout, hz / 40, ukbd_timeout, arg);
755         crit_exit();
756         lwkt_reltoken(&tty_token);
757 }
758
759 static int
760 ukbd_interrupt(keyboard_t *kbd, void *arg)
761 {
762         usbd_status status = (usbd_status)arg;
763         ukbd_state_t *state;
764         struct ukbd_data *ud;
765         struct timeval tv;
766         u_long now;
767         int mod, omod;
768         int key, c;
769         int i, j;
770
771         lwkt_gettoken(&tty_token);
772
773         DPRINTFN(5, ("ukbd_intr: status=%d\n", status));
774         if (status == USBD_CANCELLED) {
775                 lwkt_reltoken(&tty_token);
776                 return 0;
777         }
778
779         state = (ukbd_state_t *)kbd->kb_data;
780         ud = &state->ks_ndata;
781
782         if (status != USBD_NORMAL_COMPLETION) {
783                 DPRINTF(("ukbd_intr: status=%d\n", status));
784                 if (status == USBD_STALLED)
785                     usbd_clear_endpoint_stall_async(state->ks_intrpipe);
786                 lwkt_reltoken(&tty_token);
787                 return 0;
788         }
789
790         if (ud->keycode[0] == KEY_ERROR) {
791                 lwkt_reltoken(&tty_token);
792                 return 0;               /* ignore  */
793         }
794
795         getmicrouptime(&tv);
796         now = (u_long)tv.tv_sec*1000 + (u_long)tv.tv_usec/1000;
797
798 #define ADDKEY1(c)              \
799         if (state->ks_inputs < INPUTBUFSIZE) {                          \
800                 state->ks_input[state->ks_inputtail] = (c);             \
801                 ++state->ks_inputs;                                     \
802                 state->ks_inputtail = (state->ks_inputtail + 1)%INPUTBUFSIZE; \
803         }
804
805         mod = ud->modifiers;
806         omod = state->ks_odata.modifiers;
807         if (mod != omod) {
808                 for (i = 0; i < NMOD; i++)
809                         if (( mod & ukbd_mods[i].mask) !=
810                             (omod & ukbd_mods[i].mask))
811                                 ADDKEY1(ukbd_mods[i].key |
812                                        (mod & ukbd_mods[i].mask
813                                           ? KEY_PRESS : KEY_RELEASE));
814         }
815
816         /* Check for released keys. */
817         for (i = 0; i < NKEYCODE; i++) {
818                 key = state->ks_odata.keycode[i];
819                 if (key == 0)
820                         continue;
821                 for (j = 0; j < NKEYCODE; j++) {
822                         if (ud->keycode[j] == 0)
823                                 continue;
824                         if (key == ud->keycode[j])
825                                 goto rfound;
826                 }
827                 ADDKEY1(key | KEY_RELEASE);
828         rfound:
829                 ;
830         }
831
832         /* Check for pressed keys. */
833         for (i = 0; i < NKEYCODE; i++) {
834                 key = ud->keycode[i];
835                 if (key == 0)
836                         continue;
837                 state->ks_ntime[i] = now + kbd->kb_delay1;
838                 for (j = 0; j < NKEYCODE; j++) {
839                         if (state->ks_odata.keycode[j] == 0)
840                                 continue;
841                         if (key == state->ks_odata.keycode[j]) {
842                                 state->ks_ntime[i] = state->ks_otime[j];
843                                 if (state->ks_otime[j] > now)
844                                         goto pfound;
845                                 state->ks_ntime[i] = now + kbd->kb_delay2;
846                                 break;
847                         }
848                 }
849                 ADDKEY1(key | KEY_PRESS);
850                 /*
851                  * If any other key is presently down, force its repeat to be
852                  * well in the future (100s).  This makes the last key to be
853                  * pressed do the autorepeat.
854                  */
855                 for (j = 0; j < NKEYCODE; j++) {
856                         if (j != i)
857                                 state->ks_ntime[j] = now + 100 * 1000;
858                 }
859         pfound:
860                 ;
861         }
862
863         state->ks_odata = *ud;
864         bcopy(state->ks_ntime, state->ks_otime, sizeof(state->ks_ntime));
865         if (state->ks_inputs <= 0) {
866                 lwkt_reltoken(&tty_token);
867                 return 0;
868         }
869
870 #ifdef USB_DEBUG
871         for (i = state->ks_inputhead, j = 0; j < state->ks_inputs; ++j,
872                 i = (i + 1)%INPUTBUFSIZE) {
873                 c = state->ks_input[i];
874                 DPRINTF(("0x%x (%d) %s\n", c, c,
875                         (c & KEY_RELEASE) ? "released":"pressed"));
876         }
877         if (ud->modifiers)
878                 DPRINTF(("mod:0x%04x ", ud->modifiers));
879         for (i = 0; i < NKEYCODE; i++) {
880                 if (ud->keycode[i])
881                         DPRINTF(("%d ", ud->keycode[i]));
882         }
883         DPRINTF(("\n"));
884 #endif /* USB_DEBUG */
885
886         if (state->ks_polling) {
887                 lwkt_reltoken(&tty_token);
888                 return 0;
889         }
890
891         if (KBD_IS_ACTIVE(kbd) && KBD_IS_BUSY(kbd)) {
892                 /* let the callback function to process the input */
893                 (*kbd->kb_callback.kc_func)(kbd, KBDIO_KEYINPUT,
894                                             kbd->kb_callback.kc_arg);
895         } else {
896                 /* read and discard the input; no one is waiting for it */
897                 do {
898                         c = ukbd_read_char(kbd, FALSE);
899                 } while (c != NOKEY);
900         }
901
902         lwkt_reltoken(&tty_token);
903         return 0;
904 }
905
906 static int
907 ukbd_getc(ukbd_state_t *state, int wait)
908 {
909         int c;
910
911         lwkt_gettoken(&tty_token);
912         if (state->ks_polling) {
913                 DPRINTFN(1,("ukbd_getc: polling\n"));
914                 crit_enter();
915                 while (state->ks_inputs <= 0) {
916                         usbd_dopoll(state->ks_iface);
917                         if (wait == 0)
918                                 break;
919                 }
920                 crit_exit();
921         }
922         crit_enter();
923         if (state->ks_inputs <= 0) {
924                 c = -1;
925         } else {
926                 c = state->ks_input[state->ks_inputhead];
927                 --state->ks_inputs;
928                 state->ks_inputhead = (state->ks_inputhead + 1)%INPUTBUFSIZE;
929         }
930         crit_exit();
931
932         lwkt_reltoken(&tty_token);
933         return c;
934 }
935
936 /* test the interface to the device */
937 static int
938 ukbd_test_if(keyboard_t *kbd)
939 {
940         return 0;
941 }
942
943 /*
944  * Enable the access to the device; until this function is called,
945  * the client cannot read from the keyboard.
946  */
947 static int
948 ukbd_enable(keyboard_t *kbd)
949 {
950         crit_enter();
951         lwkt_gettoken(&tty_token);
952         KBD_ACTIVATE(kbd);
953         lwkt_reltoken(&tty_token);
954         crit_exit();
955         return 0;
956 }
957
958 /* disallow the access to the device */
959 static int
960 ukbd_disable(keyboard_t *kbd)
961 {
962         crit_enter();
963         lwkt_gettoken(&tty_token);
964         KBD_DEACTIVATE(kbd);
965         lwkt_reltoken(&tty_token);
966         crit_exit();
967         return 0;
968 }
969
970 /* read one byte from the keyboard if it's allowed */
971 static int
972 ukbd_read(keyboard_t *kbd, int wait)
973 {
974         ukbd_state_t *state;
975         int usbcode;
976 #ifdef UKBD_EMULATE_ATSCANCODE
977         int keycode;
978         int scancode;
979 #endif
980
981         lwkt_gettoken(&tty_token);
982         state = (ukbd_state_t *)kbd->kb_data;
983 #ifdef UKBD_EMULATE_ATSCANCODE
984         if (state->ks_buffered_char[0]) {
985                 scancode = state->ks_buffered_char[0];
986                 if (scancode & SCAN_PREFIX) {
987                         state->ks_buffered_char[0] = scancode & ~SCAN_PREFIX;
988                         lwkt_reltoken(&tty_token);
989                         return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
990                 } else {
991                         state->ks_buffered_char[0] = state->ks_buffered_char[1];
992                         state->ks_buffered_char[1] = 0;
993                         lwkt_reltoken(&tty_token);
994                         return scancode;
995                 }
996         }
997 #endif /* UKBD_EMULATE_ATSCANCODE */
998
999         usbcode = ukbd_getc(state, wait);
1000         if (!KBD_IS_ACTIVE(kbd) || (usbcode == -1)) {
1001                 lwkt_reltoken(&tty_token);
1002                 return -1;
1003         }
1004         ++kbd->kb_count;
1005 #ifdef UKBD_EMULATE_ATSCANCODE
1006         keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1007         if (keycode == NN) {
1008                 lwkt_reltoken(&tty_token);
1009                 return -1;
1010         }
1011
1012         scancode = keycode2scancode(keycode, state->ks_ndata.modifiers,
1013                                     usbcode & KEY_RELEASE);
1014         if (scancode & SCAN_PREFIX) {
1015                 if (scancode & SCAN_PREFIX_CTL) {
1016                         state->ks_buffered_char[0] =
1017                                 0x1d | (scancode & SCAN_RELEASE); /* Ctrl */
1018                         state->ks_buffered_char[1] = scancode & ~SCAN_PREFIX;
1019                 } else if (scancode & SCAN_PREFIX_SHIFT) {
1020                         state->ks_buffered_char[0] =
1021                                 0x2a | (scancode & SCAN_RELEASE); /* Shift */
1022                         state->ks_buffered_char[1] =
1023                                 scancode & ~SCAN_PREFIX_SHIFT;
1024                 } else {
1025                         state->ks_buffered_char[0] = scancode & ~SCAN_PREFIX;
1026                         state->ks_buffered_char[1] = 0;
1027                 }
1028                 lwkt_reltoken(&tty_token);
1029                 return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1030         }
1031         lwkt_reltoken(&tty_token);
1032         return scancode;
1033 #else /* !UKBD_EMULATE_ATSCANCODE */
1034         lwkt_reltoken(&tty_token);
1035         return usbcode;
1036 #endif /* UKBD_EMULATE_ATSCANCODE */
1037 }
1038
1039 /* check if data is waiting */
1040 static int
1041 ukbd_check(keyboard_t *kbd)
1042 {
1043         ukbd_state_t *state;
1044
1045         lwkt_gettoken(&tty_token);
1046         if (!KBD_IS_ACTIVE(kbd)) {
1047                 lwkt_reltoken(&tty_token);
1048                 return FALSE;
1049         }
1050         state = (ukbd_state_t *)kbd->kb_data;
1051         if (state->ks_polling) {
1052                 crit_enter();
1053                 usbd_dopoll(state->ks_iface);
1054                 crit_exit();
1055         }
1056 #ifdef UKBD_EMULATE_ATSCANCODE
1057         if (((ukbd_state_t *)kbd->kb_data)->ks_buffered_char[0]) {
1058                 lwkt_reltoken(&tty_token);
1059                 return TRUE;
1060         }
1061 #endif
1062         if (((ukbd_state_t *)kbd->kb_data)->ks_inputs > 0) {
1063                 lwkt_reltoken(&tty_token);
1064                 return TRUE;
1065         }
1066
1067         lwkt_reltoken(&tty_token);
1068         return FALSE;
1069 }
1070
1071 /* read char from the keyboard */
1072 static u_int
1073 ukbd_read_char(keyboard_t *kbd, int wait)
1074 {
1075         ukbd_state_t *state;
1076         u_int action;
1077         int usbcode;
1078         int keycode;
1079 #ifdef UKBD_EMULATE_ATSCANCODE
1080         int scancode;
1081 #endif
1082
1083         lwkt_gettoken(&tty_token);
1084         state = (ukbd_state_t *)kbd->kb_data;
1085 next_code:
1086         /* do we have a composed char to return? */
1087         if (!(state->ks_flags & COMPOSE) && (state->ks_composed_char > 0)) {
1088                 action = state->ks_composed_char;
1089                 state->ks_composed_char = 0;
1090                 if (action > UCHAR_MAX) {
1091                         lwkt_reltoken(&tty_token);
1092                         return ERRKEY;
1093                 }
1094                 lwkt_reltoken(&tty_token);
1095                 return action;
1096         }
1097
1098 #ifdef UKBD_EMULATE_ATSCANCODE
1099         /* do we have a pending raw scan code? */
1100         if (state->ks_mode == K_RAW) {
1101                 if (state->ks_buffered_char[0]) {
1102                         scancode = state->ks_buffered_char[0];
1103                         if (scancode & SCAN_PREFIX) {
1104                                 state->ks_buffered_char[0] =
1105                                         scancode & ~SCAN_PREFIX;
1106                                 lwkt_reltoken(&tty_token);
1107                                 return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1108                         } else {
1109                                 state->ks_buffered_char[0] =
1110                                         state->ks_buffered_char[1];
1111                                 state->ks_buffered_char[1] = 0;
1112                                 lwkt_reltoken(&tty_token);
1113                                 return scancode;
1114                         }
1115                 }
1116         }
1117 #endif /* UKBD_EMULATE_ATSCANCODE */
1118
1119         /* see if there is something in the keyboard port */
1120         /* XXX */
1121         usbcode = ukbd_getc(state, wait);
1122         if (usbcode == -1) {
1123                 lwkt_reltoken(&tty_token);
1124                 return NOKEY;
1125         }
1126         ++kbd->kb_count;
1127
1128 #ifdef UKBD_EMULATE_ATSCANCODE
1129         /* USB key index -> key code -> AT scan code */
1130         keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1131         if (keycode == NN) {
1132                 lwkt_reltoken(&tty_token);
1133                 return NOKEY;
1134         }
1135
1136         /* return an AT scan code for the K_RAW mode */
1137         if (state->ks_mode == K_RAW) {
1138                 scancode = keycode2scancode(keycode, state->ks_ndata.modifiers,
1139                                             usbcode & KEY_RELEASE);
1140                 if (scancode & SCAN_PREFIX) {
1141                         if (scancode & SCAN_PREFIX_CTL) {
1142                                 state->ks_buffered_char[0] =
1143                                         0x1d | (scancode & SCAN_RELEASE);
1144                                 state->ks_buffered_char[1] =
1145                                         scancode & ~SCAN_PREFIX;
1146                         } else if (scancode & SCAN_PREFIX_SHIFT) {
1147                                 state->ks_buffered_char[0] =
1148                                         0x2a | (scancode & SCAN_RELEASE);
1149                                 state->ks_buffered_char[1] =
1150                                         scancode & ~SCAN_PREFIX_SHIFT;
1151                         } else {
1152                                 state->ks_buffered_char[0] =
1153                                         scancode & ~SCAN_PREFIX;
1154                                 state->ks_buffered_char[1] = 0;
1155                         }
1156                         lwkt_reltoken(&tty_token);
1157                         return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1158                 }
1159                 lwkt_reltoken(&tty_token);
1160                 return scancode;
1161         }
1162 #else /* !UKBD_EMULATE_ATSCANCODE */
1163         /* return the byte as is for the K_RAW mode */
1164         if (state->ks_mode == K_RAW) {
1165                 lwkt_reltoken(&tty_token);
1166                 return usbcode;
1167         }
1168
1169         /* USB key index -> key code */
1170         keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1171         if (keycode == NN) {
1172                 lwkt_reltoken(&tty_token);
1173                 return NOKEY;
1174         }
1175 #endif /* UKBD_EMULATE_ATSCANCODE */
1176
1177         switch (keycode) {
1178         case 0x38:      /* left alt (compose key) */
1179                 if (usbcode & KEY_RELEASE) {
1180                         if (state->ks_flags & COMPOSE) {
1181                                 state->ks_flags &= ~COMPOSE;
1182                                 if (state->ks_composed_char > UCHAR_MAX)
1183                                         state->ks_composed_char = 0;
1184                         }
1185                 } else {
1186                         if (!(state->ks_flags & COMPOSE)) {
1187                                 state->ks_flags |= COMPOSE;
1188                                 state->ks_composed_char = 0;
1189                         }
1190                 }
1191                 break;
1192         /* XXX: I don't like these... */
1193         case 0x5c:      /* print screen */
1194                 if (state->ks_flags & ALTS)
1195                         keycode = 0x54; /* sysrq */
1196                 break;
1197         case 0x68:      /* pause/break */
1198                 if (state->ks_flags & CTLS)
1199                         keycode = 0x6c; /* break */
1200                 break;
1201         }
1202
1203         /* return the key code in the K_CODE mode */
1204         if (usbcode & KEY_RELEASE)
1205                 keycode |= SCAN_RELEASE;
1206         if (state->ks_mode == K_CODE) {
1207                 lwkt_reltoken(&tty_token);
1208                 return keycode;
1209         }
1210
1211         /* compose a character code */
1212         if (state->ks_flags & COMPOSE) {
1213                 switch (keycode) {
1214                 /* key pressed, process it */
1215                 case 0x47: case 0x48: case 0x49:        /* keypad 7,8,9 */
1216                         state->ks_composed_char *= 10;
1217                         state->ks_composed_char += keycode - 0x40;
1218                         if (state->ks_composed_char > UCHAR_MAX) {
1219                                 lwkt_reltoken(&tty_token);
1220                                 return ERRKEY;
1221                         }
1222                         goto next_code;
1223                 case 0x4B: case 0x4C: case 0x4D:        /* keypad 4,5,6 */
1224                         state->ks_composed_char *= 10;
1225                         state->ks_composed_char += keycode - 0x47;
1226                         if (state->ks_composed_char > UCHAR_MAX) {
1227                                 lwkt_reltoken(&tty_token);
1228                                 return ERRKEY;
1229                         }
1230                         goto next_code;
1231                 case 0x4F: case 0x50: case 0x51:        /* keypad 1,2,3 */
1232                         state->ks_composed_char *= 10;
1233                         state->ks_composed_char += keycode - 0x4E;
1234                         if (state->ks_composed_char > UCHAR_MAX) {
1235                                 lwkt_reltoken(&tty_token);
1236                                 return ERRKEY;
1237                         }
1238                         goto next_code;
1239                 case 0x52:                              /* keypad 0 */
1240                         state->ks_composed_char *= 10;
1241                         if (state->ks_composed_char > UCHAR_MAX) {
1242                                 lwkt_reltoken(&tty_token);
1243                                 return ERRKEY;
1244                         }
1245                         goto next_code;
1246
1247                 /* key released, no interest here */
1248                 case SCAN_RELEASE | 0x47:
1249                 case SCAN_RELEASE | 0x48:
1250                 case SCAN_RELEASE | 0x49:               /* keypad 7,8,9 */
1251                 case SCAN_RELEASE | 0x4B:
1252                 case SCAN_RELEASE | 0x4C:
1253                 case SCAN_RELEASE | 0x4D:               /* keypad 4,5,6 */
1254                 case SCAN_RELEASE | 0x4F:
1255                 case SCAN_RELEASE | 0x50:
1256                 case SCAN_RELEASE | 0x51:               /* keypad 1,2,3 */
1257                 case SCAN_RELEASE | 0x52:               /* keypad 0 */
1258                         goto next_code;
1259
1260                 case 0x38:                              /* left alt key */
1261                         break;
1262
1263                 default:
1264                         if (state->ks_composed_char > 0) {
1265                                 state->ks_flags &= ~COMPOSE;
1266                                 state->ks_composed_char = 0;
1267                                 lwkt_reltoken(&tty_token);
1268                                 return ERRKEY;
1269                         }
1270                         break;
1271                 }
1272         }
1273
1274         /* keycode to key action */
1275         action = genkbd_keyaction(kbd, SCAN_CHAR(keycode),
1276                                   keycode & SCAN_RELEASE, &state->ks_state,
1277                                   &state->ks_accents);
1278         if (action == NOKEY) {
1279                 goto next_code;
1280         } else {
1281                 lwkt_reltoken(&tty_token);
1282                 return action;
1283         }
1284         /* NOTREACHED */
1285         lwkt_reltoken(&tty_token);
1286 }
1287
1288 /* check if char is waiting */
1289 static int
1290 ukbd_check_char(keyboard_t *kbd)
1291 {
1292         ukbd_state_t *state;
1293         int ret;
1294
1295         lwkt_gettoken(&tty_token);
1296         if (!KBD_IS_ACTIVE(kbd)) {
1297                 lwkt_reltoken(&tty_token);
1298                 return FALSE;
1299         }
1300         state = (ukbd_state_t *)kbd->kb_data;
1301         if (!(state->ks_flags & COMPOSE) && (state->ks_composed_char > 0)) {
1302                 lwkt_reltoken(&tty_token);
1303                 return TRUE;
1304         }
1305         ret = (ukbd_check(kbd));
1306
1307         lwkt_reltoken(&tty_token);
1308         return ret;
1309 }
1310
1311 /* some useful control functions */
1312 static int
1313 ukbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
1314 {
1315         /* trasnlate LED_XXX bits into the device specific bits */
1316         static u_char ledmap[8] = {
1317                 0, 2, 1, 3, 4, 6, 5, 7,
1318         };
1319         ukbd_state_t *state = kbd->kb_data;
1320         int i;
1321
1322         crit_enter();
1323         lwkt_gettoken(&tty_token);
1324         switch (cmd) {
1325         case KDGKBMODE:         /* get keyboard mode */
1326                 *(int *)arg = state->ks_mode;
1327                 break;
1328         case KDSKBMODE:         /* set keyboard mode */
1329                 switch (*(int *)arg) {
1330                 case K_XLATE:
1331                         if (state->ks_mode != K_XLATE) {
1332                                 /* make lock key state and LED state match */
1333                                 state->ks_state &= ~LOCK_MASK;
1334                                 state->ks_state |= KBD_LED_VAL(kbd);
1335                         }
1336                         /* FALLTHROUGH */
1337                 case K_RAW:
1338                 case K_CODE:
1339                         if (state->ks_mode != *(int *)arg) {
1340                                 ukbd_clear_state(kbd);
1341                                 state->ks_mode = *(int *)arg;
1342                                 kbd->kb_savemode = state->ks_mode;
1343                         }
1344                         break;
1345                 default:
1346                         lwkt_reltoken(&tty_token);
1347                         crit_exit();
1348                         return EINVAL;
1349                 }
1350                 break;
1351
1352         case KDGETLED:          /* get keyboard LED */
1353                 *(int *)arg = KBD_LED_VAL(kbd);
1354                 break;
1355         case KDSETLED:          /* set keyboard LED */
1356                 /* NOTE: lock key state in ks_state won't be changed */
1357                 if (*(int *)arg & ~LOCK_MASK) {
1358                         lwkt_reltoken(&tty_token);
1359                         crit_exit();
1360                         return EINVAL;
1361                 }
1362                 i = *(int *)arg;
1363                 /* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1364                 if (state->ks_mode == K_XLATE &&
1365                     kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1366                         if (i & ALKED)
1367                                 i |= CLKED;
1368                         else
1369                                 i &= ~CLKED;
1370                 }
1371                 if (KBD_HAS_DEVICE(kbd)) {
1372                         set_leds(state, ledmap[i & LED_MASK]);
1373                         /* XXX: error check? */
1374                 }
1375                 KBD_LED_VAL(kbd) = *(int *)arg;
1376                 break;
1377
1378         case KDGKBSTATE:        /* get lock key state */
1379                 *(int *)arg = state->ks_state & LOCK_MASK;
1380                 break;
1381         case KDSKBSTATE:        /* set lock key state */
1382                 if (*(int *)arg & ~LOCK_MASK) {
1383                         lwkt_reltoken(&tty_token);
1384                         crit_exit();
1385                         return EINVAL;
1386                 }
1387                 state->ks_state &= ~LOCK_MASK;
1388                 state->ks_state |= *(int *)arg;
1389                 lwkt_reltoken(&tty_token);
1390                 crit_exit();
1391                 /* set LEDs and quit */
1392                 return ukbd_ioctl(kbd, KDSETLED, arg);
1393
1394         case KDSETREPEAT:       /* set keyboard repeat rate (new interface) */
1395                 crit_exit();
1396                 if (!KBD_HAS_DEVICE(kbd)) {
1397                         lwkt_reltoken(&tty_token);
1398                         return 0;
1399                 }
1400                 if (((int *)arg)[1] < 0) {
1401                         lwkt_reltoken(&tty_token);
1402                         return EINVAL;
1403                 }
1404                 if (((int *)arg)[0] < 0) {
1405                         lwkt_reltoken(&tty_token);
1406                         return EINVAL;
1407                 }
1408                 else if (((int *)arg)[0] == 0)  /* fastest possible value */
1409                         kbd->kb_delay1 = 200;
1410                 else
1411                         kbd->kb_delay1 = ((int *)arg)[0];
1412                 kbd->kb_delay2 = ((int *)arg)[1];
1413                 lwkt_reltoken(&tty_token);
1414                 return 0;
1415
1416         case KDSETRAD:          /* set keyboard repeat rate (old interface) */
1417                 crit_exit();
1418                 lwkt_reltoken(&tty_token);
1419                 return set_typematic(kbd, *(int *)arg);
1420
1421         case PIO_KEYMAP:        /* set keyboard translation table */
1422         case PIO_KEYMAPENT:     /* set keyboard translation table entry */
1423         case PIO_DEADKEYMAP:    /* set accent key translation table */
1424                 state->ks_accents = 0;
1425                 /* FALLTHROUGH */
1426         default:
1427                 crit_exit();
1428                 lwkt_reltoken(&tty_token);
1429                 return genkbd_commonioctl(kbd, cmd, arg);
1430
1431 #ifdef USB_DEBUG
1432         case USB_SETDEBUG:
1433                 ukbddebug = *(int *)arg;
1434                 break;
1435 #endif
1436         }
1437
1438         crit_exit();
1439         lwkt_reltoken(&tty_token);
1440         return 0;
1441 }
1442
1443 /* lock the access to the keyboard */
1444 static int
1445 ukbd_lock(keyboard_t *kbd, int lock)
1446 {
1447         /* XXX ? */
1448         return TRUE;
1449 }
1450
1451 /* clear the internal state of the keyboard */
1452 static void
1453 ukbd_clear_state(keyboard_t *kbd)
1454 {
1455         ukbd_state_t *state;
1456
1457         lwkt_gettoken(&tty_token);
1458         state = (ukbd_state_t *)kbd->kb_data;
1459         state->ks_flags = 0;
1460         state->ks_polling = 0;
1461         state->ks_state &= LOCK_MASK;   /* preserve locking key state */
1462         state->ks_accents = 0;
1463         state->ks_composed_char = 0;
1464 #ifdef UKBD_EMULATE_ATSCANCODE
1465         state->ks_buffered_char[0] = 0;
1466         state->ks_buffered_char[1] = 0;
1467 #endif
1468         bzero(&state->ks_ndata, sizeof(state->ks_ndata));
1469         bzero(&state->ks_odata, sizeof(state->ks_odata));
1470         bzero(&state->ks_ntime, sizeof(state->ks_ntime));
1471         bzero(&state->ks_otime, sizeof(state->ks_otime));
1472         lwkt_reltoken(&tty_token);
1473 }
1474
1475 /* save the internal state */
1476 static int
1477 ukbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1478 {
1479         if (len == 0)
1480                 return sizeof(ukbd_state_t);
1481         if (len < sizeof(ukbd_state_t))
1482                 return -1;
1483         lwkt_gettoken(&tty_token);
1484         bcopy(kbd->kb_data, buf, sizeof(ukbd_state_t));
1485         lwkt_reltoken(&tty_token);
1486         return 0;
1487 }
1488
1489 /* set the internal state */
1490 static int
1491 ukbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1492 {
1493         if (len < sizeof(ukbd_state_t))
1494                 return ENOMEM;
1495         lwkt_gettoken(&tty_token);
1496         bcopy(buf, kbd->kb_data, sizeof(ukbd_state_t));
1497         lwkt_reltoken(&tty_token);
1498         return 0;
1499 }
1500
1501 static int
1502 ukbd_poll(keyboard_t *kbd, int on)
1503 {
1504         ukbd_state_t *state;
1505         usbd_device_handle dev;
1506
1507         lwkt_gettoken(&tty_token);
1508         state = (ukbd_state_t *)kbd->kb_data;
1509         usbd_interface2device_handle(state->ks_iface, &dev);
1510
1511         crit_enter();
1512         if (on) {
1513                 ++state->ks_polling;
1514                 if (state->ks_polling == 1)
1515                         usbd_set_polling(dev, on);
1516         } else {
1517                 --state->ks_polling;
1518                 if (state->ks_polling == 0)
1519                         usbd_set_polling(dev, on);
1520         }
1521         crit_exit();
1522         lwkt_reltoken(&tty_token);
1523         return 0;
1524 }
1525
1526 /* local functions */
1527
1528 static int
1529 probe_keyboard(struct usb_attach_arg *uaa, int flags)
1530 {
1531         usb_interface_descriptor_t *id;
1532
1533         if (!uaa->iface)        /* we attach to ifaces only */
1534                 return EINVAL;
1535
1536         /* Check that this is a keyboard that speaks the boot protocol. */
1537         id = usbd_get_interface_descriptor(uaa->iface);
1538         if (id
1539             && id->bInterfaceClass == UICLASS_HID
1540             && id->bInterfaceSubClass == UISUBCLASS_BOOT
1541             && id->bInterfaceProtocol == UPROTO_BOOT_KEYBOARD)
1542                 return 0;       /* found it */
1543
1544         return EINVAL;
1545 }
1546
1547 static int
1548 init_keyboard(ukbd_state_t *state, int *type, int flags)
1549 {
1550         usb_endpoint_descriptor_t *ed;
1551         usbd_status err;
1552
1553         *type = KB_OTHER;
1554
1555         state->ks_ifstate |= DISCONNECTED;
1556
1557         ed = usbd_interface2endpoint_descriptor(state->ks_iface, 0);
1558         if (!ed) {
1559                 kprintf("ukbd: could not read endpoint descriptor\n");
1560                 return EIO;
1561         }
1562
1563         DPRINTFN(10,("ukbd:init_keyboard: \
1564 bLength=%d bDescriptorType=%d bEndpointAddress=%d-%s bmAttributes=%d wMaxPacketSize=%d bInterval=%d\n",
1565                ed->bLength, ed->bDescriptorType,
1566                UE_GET_ADDR(ed->bEndpointAddress),
1567                UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN ? "in":"out",
1568                UE_GET_XFERTYPE(ed->bmAttributes),
1569                UGETW(ed->wMaxPacketSize), ed->bInterval));
1570
1571         if (UE_GET_DIR(ed->bEndpointAddress) != UE_DIR_IN ||
1572             UE_GET_XFERTYPE(ed->bmAttributes) != UE_INTERRUPT) {
1573                 kprintf("ukbd: unexpected endpoint\n");
1574                 return EINVAL;
1575         }
1576
1577         if ((usbd_get_quirks(state->ks_uaa->device)->uq_flags & UQ_NO_SET_PROTO) == 0) {
1578                 err = usbd_set_protocol(state->ks_iface, 0);
1579                 DPRINTFN(5, ("ukbd:init_keyboard: protocol set\n"));
1580                 if (err) {
1581                         kprintf("ukbd: set protocol failed\n");
1582                         return EIO;
1583                 }
1584         }
1585         /* Ignore if SETIDLE fails since it is not crucial. */
1586         usbd_set_idle(state->ks_iface, 0, 0);
1587
1588         state->ks_ep_addr = ed->bEndpointAddress;
1589         state->ks_ifstate &= ~DISCONNECTED;
1590
1591         return 0;
1592 }
1593
1594 static void
1595 set_leds(ukbd_state_t *state, int leds)
1596 {
1597         u_int8_t res = leds;
1598
1599         DPRINTF(("ukbd:set_leds: state=%p leds=%d\n", state, leds));
1600
1601         usbd_set_report_async(state->ks_iface, UHID_OUTPUT_REPORT, 0, &res, 1);
1602 }
1603
1604 static int
1605 set_typematic(keyboard_t *kbd, int code)
1606 {
1607         static int delays[] = { 250, 500, 750, 1000 };
1608         static int rates[] = {  34,  38,  42,  46,  50,  55,  59,  63,
1609                                 68,  76,  84,  92, 100, 110, 118, 126,
1610                                136, 152, 168, 184, 200, 220, 236, 252,
1611                                272, 304, 336, 368, 400, 440, 472, 504 };
1612
1613         if (code & ~0x7f)
1614                 return EINVAL;
1615         kbd->kb_delay1 = delays[(code >> 5) & 3];
1616         kbd->kb_delay2 = rates[code & 0x1f];
1617         return 0;
1618 }
1619
1620 #ifdef UKBD_EMULATE_ATSCANCODE
1621 static int
1622 keycode2scancode(int keycode, int shift, int up)
1623 {
1624         static int scan[] = {
1625                 0x1c, 0x1d, 0x35,
1626                 0x37 | SCAN_PREFIX_SHIFT, /* PrintScreen */
1627                 0x38, 0x47, 0x48, 0x49, 0x4b, 0x4d, 0x4f,
1628                 0x50, 0x51, 0x52, 0x53,
1629                 0x46,   /* XXX Pause/Break */
1630                 0x5b, 0x5c, 0x5d,
1631         };
1632         int scancode;
1633
1634         scancode = keycode;
1635         if ((keycode >= 89) && (keycode < 89 + sizeof(scan)/sizeof(scan[0])))
1636                 scancode = scan[keycode - 89] | SCAN_PREFIX_E0;
1637         /* Pause/Break */
1638         if ((keycode == 104) && !(shift & (MOD_CONTROL_L | MOD_CONTROL_R)))
1639                 scancode = 0x45 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL;
1640         if (shift & (MOD_SHIFT_L | MOD_SHIFT_R))
1641                 scancode &= ~SCAN_PREFIX_SHIFT;
1642         return (scancode | (up ? SCAN_RELEASE : SCAN_PRESS));
1643 }
1644 #endif /* UKBD_EMULATE_ATSCANCODE */
1645
1646 static int
1647 ukbd_driver_load(module_t mod, int what, void *arg)
1648 {
1649         switch (what) {
1650                 case MOD_LOAD:
1651                         kbd_add_driver(&ukbd_kbd_driver);
1652                         break;
1653                 case MOD_UNLOAD:
1654                         kbd_delete_driver(&ukbd_kbd_driver);
1655                         break;
1656         }
1657         return usbd_driver_load(mod, what, 0);
1658 }