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