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