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