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