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