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