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