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