Merge from vendor branch BIND:
[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.14 2005/06/02 20:40:56 dillon 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 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
58 #include <sys/limits.h>
59 #else
60 #include <machine/limits.h>
61 #endif
62 #if defined(__FreeBSD__) && __FreeBSD_version >= 500014
63 #include <sys/selinfo.h>
64 #else
65 #include <sys/select.h>
66 #endif
67 #include <sys/vnode.h>
68 #include <sys/sysctl.h>
69 #include <sys/thread2.h>
70
71 #include <bus/usb/usb.h>
72 #include <bus/usb/usbhid.h>
73 #include <bus/usb/usbdi.h>
74 #include <bus/usb/usbdi_util.h>
75 #include <bus/usb/usbdevs.h>
76 #include <bus/usb/usb_quirks.h>
77 #include <bus/usb/hid.h>
78
79 #include <sys/kbio.h>
80 #include <dev/misc/kbd/kbdreg.h>
81
82 #define UKBD_EMULATE_ATSCANCODE 1
83
84 #define DRIVER_NAME     "ukbd"
85
86 #define delay(d)         DELAY(d)
87
88 #ifdef USB_DEBUG
89 #define DPRINTF(x)      if (ukbddebug) logprintf x
90 #define DPRINTFN(n,x)   if (ukbddebug>(n)) logprintf x
91 int     ukbddebug = 0;
92 SYSCTL_NODE(_hw_usb, OID_AUTO, ukbd, CTLFLAG_RW, 0, "USB ukbd");
93 SYSCTL_INT(_hw_usb_ukbd, OID_AUTO, debug, CTLFLAG_RW,
94            &ukbddebug, 0, "ukbd debug level");
95 #else
96 #define DPRINTF(x)
97 #define DPRINTFN(n,x)
98 #endif
99
100 #define UPROTO_BOOT_KEYBOARD 1
101
102 #define NKEYCODE 6
103
104 struct ukbd_data {
105         u_int8_t        modifiers;
106 #define MOD_CONTROL_L   0x01
107 #define MOD_CONTROL_R   0x10
108 #define MOD_SHIFT_L     0x02
109 #define MOD_SHIFT_R     0x20
110 #define MOD_ALT_L       0x04
111 #define MOD_ALT_R       0x40
112 #define MOD_WIN_L       0x08
113 #define MOD_WIN_R       0x80
114         u_int8_t        reserved;
115         u_int8_t        keycode[NKEYCODE];
116 };
117
118 #define MAXKEYS (NMOD+2*NKEYCODE)
119
120 typedef struct ukbd_softc {
121         device_t                sc_dev;         /* base device */
122 } ukbd_softc_t;
123
124 #define UKBD_CHUNK      128     /* chunk size for read */
125 #define UKBD_BSIZE      1020    /* buffer size */
126
127 typedef void usbd_intr_t(usbd_xfer_handle, usbd_private_handle, usbd_status);
128 typedef void usbd_disco_t(void *);
129
130 Static int              ukbd_resume(device_t self);
131 Static usbd_intr_t      ukbd_intr;
132 Static int              ukbd_driver_load(module_t mod, int what, void *arg);
133 Static int              ukbd_default_term(keyboard_t *kbd);
134
135 Static keyboard_t       default_kbd;
136
137 USB_DECLARE_DRIVER_INIT(ukbd, DEVMETHOD(device_resume, ukbd_resume));
138
139 USB_MATCH(ukbd)
140 {
141         USB_MATCH_START(ukbd, uaa);
142
143         keyboard_switch_t *sw;
144         void *arg[2];
145         int unit = device_get_unit(self);
146
147         sw = kbd_get_switch(DRIVER_NAME);
148         if (sw == NULL)
149                 return (UMATCH_NONE);
150
151         arg[0] = (void *)uaa;
152         arg[1] = (void *)ukbd_intr;
153         if ((*sw->probe)(unit, (void *)arg, 0))
154                 return (UMATCH_NONE);
155
156         return (UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
157 }
158
159 USB_ATTACH(ukbd)
160 {
161         USB_ATTACH_START(ukbd, sc, uaa);
162         usbd_interface_handle iface = uaa->iface;
163         usb_interface_descriptor_t *id;
164         char devinfo[1024];
165
166         keyboard_switch_t *sw;
167         keyboard_t *kbd;
168         void *arg[2];
169         int unit = device_get_unit(self);
170
171         sw = kbd_get_switch(DRIVER_NAME);
172         if (sw == NULL)
173                 USB_ATTACH_ERROR_RETURN;
174
175         id = usbd_get_interface_descriptor(iface);
176         usbd_devinfo(uaa->device, 0, devinfo);
177         USB_ATTACH_SETUP;
178         printf("%s: %s, iclass %d/%d\n", USBDEVNAME(sc->sc_dev),
179                devinfo, id->bInterfaceClass, id->bInterfaceSubClass);
180
181         arg[0] = (void *)uaa;
182         arg[1] = (void *)ukbd_intr;
183         kbd = NULL;
184         if ((*sw->probe)(unit, (void *)arg, 0))
185                 USB_ATTACH_ERROR_RETURN;
186         if ((*sw->init)(unit, &kbd, (void *)arg, 0))
187                 USB_ATTACH_ERROR_RETURN;
188         (*sw->enable)(kbd);
189
190 #ifdef KBD_INSTALL_CDEV
191         if (kbd_attach(kbd))
192                 USB_ATTACH_ERROR_RETURN;
193 #endif
194         if (bootverbose)
195                 (*sw->diag)(kbd, bootverbose);
196
197         USB_ATTACH_SUCCESS_RETURN;
198 }
199
200 int
201 ukbd_detach(device_t self)
202 {
203         keyboard_t *kbd;
204         int error;
205
206         kbd = kbd_get_keyboard(kbd_find_keyboard(DRIVER_NAME,
207                                                  device_get_unit(self)));
208         if (kbd == NULL) {
209                 DPRINTF(("%s: keyboard not attached!?\n", USBDEVNAME(self)));
210                 return ENXIO;
211         }
212         (*kbdsw[kbd->kb_index]->disable)(kbd);
213
214 #ifdef KBD_INSTALL_CDEV
215         if (kbd != &default_kbd) {
216                 error = kbd_detach(kbd);
217                 if (error)
218                         return error;
219         }
220 #endif
221         if (kbd == &default_kbd) {
222                 ukbd_default_term(kbd);
223         } else {
224                 error = (*kbdsw[kbd->kb_index]->term)(kbd);
225                 if (error)
226                         return error;
227         }
228
229         DPRINTF(("%s: disconnected\n", USBDEVNAME(self)));
230
231         return (0);
232 }
233
234 Static int
235 ukbd_resume(device_t self)
236 {
237         keyboard_t *kbd;
238
239         kbd = kbd_get_keyboard(kbd_find_keyboard(DRIVER_NAME,
240                                                  device_get_unit(self)));
241         if (kbd)
242                 (*kbdsw[kbd->kb_index]->clear_state)(kbd);
243         return (0);
244 }
245
246 void
247 ukbd_intr(usbd_xfer_handle xfer, usbd_private_handle addr, usbd_status status)
248 {
249         keyboard_t *kbd = (keyboard_t *)addr;
250
251         (*kbdsw[kbd->kb_index]->intr)(kbd, (void *)status);
252 }
253
254 DRIVER_MODULE(ukbd, uhub, ukbd_driver, ukbd_devclass, ukbd_driver_load, 0);
255
256
257 #define UKBD_DEFAULT    0
258
259 #define KEY_ERROR       0x01
260
261 #define KEY_PRESS       0
262 #define KEY_RELEASE     0x400
263 #define KEY_INDEX(c)    ((c) & ~KEY_RELEASE)
264
265 #define SCAN_PRESS      0
266 #define SCAN_RELEASE    0x80
267 #define SCAN_PREFIX_E0  0x100
268 #define SCAN_PREFIX_E1  0x200
269 #define SCAN_PREFIX_CTL 0x400
270 #define SCAN_PREFIX_SHIFT 0x800
271 #define SCAN_PREFIX     (SCAN_PREFIX_E0 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL \
272                          | SCAN_PREFIX_SHIFT)
273 #define SCAN_CHAR(c)    ((c) & 0x7f)
274
275 #define NMOD 8
276 Static struct {
277         int mask, key;
278 } ukbd_mods[NMOD] = {
279         { MOD_CONTROL_L, 0xe0 },
280         { MOD_CONTROL_R, 0xe4 },
281         { MOD_SHIFT_L,   0xe1 },
282         { MOD_SHIFT_R,   0xe5 },
283         { MOD_ALT_L,     0xe2 },
284         { MOD_ALT_R,     0xe6 },
285         { MOD_WIN_L,     0xe3 },
286         { MOD_WIN_R,     0xe7 },
287 };
288
289 #define NN 0                    /* no translation */
290 /*
291  * Translate USB keycodes to AT keyboard scancodes.
292  */
293 /*
294  * FIXME: Mac USB keyboard generates:
295  * 0x53: keypad NumLock/Clear
296  * 0x66: Power
297  * 0x67: keypad =
298  * 0x68: F13
299  * 0x69: F14
300  * 0x6a: F15
301  */
302 Static u_int8_t ukbd_trtab[256] = {
303            0,   0,   0,   0,  30,  48,  46,  32, /* 00 - 07 */
304           18,  33,  34,  35,  23,  36,  37,  38, /* 08 - 0F */
305           50,  49,  24,  25,  16,  19,  31,  20, /* 10 - 17 */
306           22,  47,  17,  45,  21,  44,   2,   3, /* 18 - 1F */
307            4,   5,   6,   7,   8,   9,  10,  11, /* 20 - 27 */
308           28,   1,  14,  15,  57,  12,  13,  26, /* 28 - 2F */
309           27,  43,  43,  39,  40,  41,  51,  52, /* 30 - 37 */
310           53,  58,  59,  60,  61,  62,  63,  64, /* 38 - 3F */
311           65,  66,  67,  68,  87,  88,  92,  70, /* 40 - 47 */
312          104, 102,  94,  96, 103,  99, 101,  98, /* 48 - 4F */
313           97, 100,  95,  69,  91,  55,  74,  78, /* 50 - 57 */
314           89,  79,  80,  81,  75,  76,  77,  71, /* 58 - 5F */
315           72,  73,  82,  83,  86, 107,  NN,  NN, /* 60 - 67 */
316           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* 68 - 6F */
317           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* 70 - 77 */
318           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* 78 - 7F */
319           NN,  NN,  NN,  NN,  NN,  NN,  NN, 115, /* 80 - 87 */
320          112, 125, 121, 123,  NN,  NN,  NN,  NN, /* 88 - 8F */
321           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* 90 - 97 */
322           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* 98 - 9F */
323           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* A0 - A7 */
324           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* A8 - AF */
325           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* B0 - B7 */
326           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* B8 - BF */
327           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* C0 - C7 */
328           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* C8 - CF */
329           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* D0 - D7 */
330           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* D8 - DF */
331           29,  42,  56, 105,  90,  54,  93, 106, /* E0 - E7 */
332           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* E8 - EF */
333           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* F0 - F7 */
334           NN,  NN,  NN,  NN,  NN,  NN,  NN,  NN, /* F8 - FF */
335 };
336
337 typedef struct ukbd_state {
338         usbd_interface_handle ks_iface; /* interface */
339         usbd_pipe_handle ks_intrpipe;   /* interrupt pipe */
340         struct usb_attach_arg *ks_uaa;
341         int ks_ep_addr;
342
343         struct ukbd_data ks_ndata;
344         struct ukbd_data ks_odata;
345         u_long          ks_ntime[NKEYCODE];
346         u_long          ks_otime[NKEYCODE];
347
348 #define INPUTBUFSIZE    (NMOD + 2*NKEYCODE)
349         u_int           ks_input[INPUTBUFSIZE]; /* input buffer */
350         int             ks_inputs;
351         int             ks_inputhead;
352         int             ks_inputtail;
353
354         int             ks_ifstate;
355 #define INTRENABLED     (1 << 0)
356 #define DISCONNECTED    (1 << 1)
357
358         struct callout ks_timeout;
359
360         int             ks_mode;        /* input mode (K_XLATE,K_RAW,K_CODE) */
361         int             ks_flags;       /* flags */
362 #define COMPOSE         (1 << 0)
363         int             ks_polling;
364         int             ks_state;       /* shift/lock key state */
365         int             ks_accents;     /* accent key index (> 0) */
366         u_int           ks_composed_char; /* composed char code (> 0) */
367 #ifdef UKBD_EMULATE_ATSCANCODE
368         u_int           ks_buffered_char[2];
369 #endif
370 } ukbd_state_t;
371
372 /* keyboard driver declaration */
373 Static int              ukbd_configure(int flags);
374 Static kbd_probe_t      ukbd_probe;
375 Static kbd_init_t       ukbd_init;
376 Static kbd_term_t       ukbd_term;
377 Static kbd_intr_t       ukbd_interrupt;
378 Static kbd_test_if_t    ukbd_test_if;
379 Static kbd_enable_t     ukbd_enable;
380 Static kbd_disable_t    ukbd_disable;
381 Static kbd_read_t       ukbd_read;
382 Static kbd_check_t      ukbd_check;
383 Static kbd_read_char_t  ukbd_read_char;
384 Static kbd_check_char_t ukbd_check_char;
385 Static kbd_ioctl_t      ukbd_ioctl;
386 Static kbd_lock_t       ukbd_lock;
387 Static kbd_clear_state_t ukbd_clear_state;
388 Static kbd_get_state_t  ukbd_get_state;
389 Static kbd_set_state_t  ukbd_set_state;
390 Static kbd_poll_mode_t  ukbd_poll;
391
392 keyboard_switch_t ukbdsw = {
393         ukbd_probe,
394         ukbd_init,
395         ukbd_term,
396         ukbd_interrupt,
397         ukbd_test_if,
398         ukbd_enable,
399         ukbd_disable,
400         ukbd_read,
401         ukbd_check,
402         ukbd_read_char,
403         ukbd_check_char,
404         ukbd_ioctl,
405         ukbd_lock,
406         ukbd_clear_state,
407         ukbd_get_state,
408         ukbd_set_state,
409         genkbd_get_fkeystr,
410         ukbd_poll,
411         genkbd_diag,
412 };
413
414 KEYBOARD_DRIVER(ukbd, ukbdsw, ukbd_configure);
415
416 /* local functions */
417 Static int              ukbd_enable_intr(keyboard_t *kbd, int on,
418                                          usbd_intr_t *func);
419 Static timeout_t        ukbd_timeout;
420
421 Static int              ukbd_getc(ukbd_state_t *state);
422 Static int              probe_keyboard(struct usb_attach_arg *uaa, int flags);
423 Static int              init_keyboard(ukbd_state_t *state, int *type,
424                                       int flags);
425 Static void             set_leds(ukbd_state_t *state, int leds);
426 Static int              set_typematic(keyboard_t *kbd, int code);
427 #ifdef UKBD_EMULATE_ATSCANCODE
428 Static int              keycode2scancode(int keycode, int shift, int up);
429 #endif
430
431 /* local variables */
432
433 /* the initial key map, accent map and fkey strings */
434 #if defined(UKBD_DFLT_KEYMAP) && !defined(KLD_MODULE)
435 #define KBD_DFLT_KEYMAP
436 #include "ukbdmap.h"
437 #endif
438 #include <dev/misc/kbd/kbdtables.h>
439
440 /* structures for the default keyboard */
441 Static ukbd_state_t     default_kbd_state;
442 Static keymap_t         default_keymap;
443 Static accentmap_t      default_accentmap;
444 Static fkeytab_t        default_fkeytab[NUM_FKEYS];
445
446 /*
447  * The back door to the keyboard driver!
448  * This function is called by the console driver, via the kbdio module,
449  * to tickle keyboard drivers when the low-level console is being initialized.
450  * Almost nothing in the kernel has been initialied yet.  Try to probe
451  * keyboards if possible.
452  * NOTE: because of the way the low-level conole is initialized, this routine
453  * may be called more than once!!
454  */
455 Static int
456 ukbd_configure(int flags)
457 {
458         return 0;
459
460 #if 0 /* not yet */
461         keyboard_t *kbd;
462         device_t device;
463         struct usb_attach_arg *uaa;
464         void *arg[2];
465
466         device = devclass_get_device(ukbd_devclass, UKBD_DEFAULT);
467         if (device == NULL)
468                 return 0;
469         uaa = (struct usb_attach_arg *)device_get_ivars(device);
470         if (uaa == NULL)
471                 return 0;
472
473         /* probe the default keyboard */
474         arg[0] = (void *)uaa;
475         arg[1] = (void *)ukbd_intr;
476         kbd = NULL;
477         if (ukbd_probe(UKBD_DEFAULT, arg, flags))
478                 return 0;
479         if (ukbd_init(UKBD_DEFAULT, &kbd, arg, flags))
480                 return 0;
481
482         /* return the number of found keyboards */
483         return 1;
484 #endif
485 }
486
487 /* low-level functions */
488
489 /* detect a keyboard */
490 Static int
491 ukbd_probe(int unit, void *arg, int flags)
492 {
493         void **data;
494         struct usb_attach_arg *uaa;
495
496         data = (void **)arg;
497         uaa = (struct usb_attach_arg *)data[0];
498
499         if (unit == UKBD_DEFAULT) {
500                 if (KBD_IS_PROBED(&default_kbd))
501                         return 0;
502         }
503         if (probe_keyboard(uaa, flags))
504                 return ENXIO;
505         return 0;
506 }
507
508 /*
509  * Reset and initialize the device.  Note that unit 0 (UKBD_DEFAULT) is an
510  * always-connected device once it has been initially detected.  We do not
511  * deregister it if the usb keyboard is unplugged to avoid losing the 
512  * connection to the console.  This feature also handles the USB bus reset
513  * which detaches and reattaches USB devices during boot.
514  */
515 Static int
516 ukbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
517 {
518         keyboard_t *kbd;
519         ukbd_state_t *state;
520         keymap_t *keymap;
521         accentmap_t *accmap;
522         fkeytab_t *fkeymap;
523         int fkeymap_size;
524         void **data = (void **)arg;
525         struct usb_attach_arg *uaa = (struct usb_attach_arg *)data[0];
526
527         if (unit == UKBD_DEFAULT) {
528                 *kbdp = kbd = &default_kbd;
529                 if (KBD_IS_INITIALIZED(kbd) && KBD_IS_CONFIGURED(kbd))
530                         return 0;
531                 state = &default_kbd_state;
532                 keymap = &default_keymap;
533                 accmap = &default_accentmap;
534                 fkeymap = default_fkeytab;
535                 fkeymap_size =
536                         sizeof(default_fkeytab)/sizeof(default_fkeytab[0]);
537         } else if (*kbdp == NULL) {
538                 *kbdp = kbd = malloc(sizeof(*kbd), M_DEVBUF, M_INTWAIT | M_ZERO);
539                 state = malloc(sizeof(*state), M_DEVBUF, M_INTWAIT);
540                 keymap = malloc(sizeof(key_map), M_DEVBUF, M_INTWAIT);
541                 accmap = malloc(sizeof(accent_map), M_DEVBUF, M_INTWAIT);
542                 fkeymap = malloc(sizeof(fkey_tab), M_DEVBUF, M_INTWAIT);
543                 fkeymap_size = sizeof(fkey_tab)/sizeof(fkey_tab[0]);
544                 if ((state == NULL) || (keymap == NULL) || (accmap == NULL)
545                      || (fkeymap == NULL)) {
546                         if (state != NULL)
547                                 free(state, M_DEVBUF);
548                         if (keymap != NULL)
549                                 free(keymap, M_DEVBUF);
550                         if (accmap != NULL)
551                                 free(accmap, M_DEVBUF);
552                         if (fkeymap != NULL)
553                                 free(fkeymap, M_DEVBUF);
554                         free(kbd, M_DEVBUF);
555                         return ENOMEM;
556                 }
557         } else if (KBD_IS_INITIALIZED(*kbdp) && KBD_IS_CONFIGURED(*kbdp)) {
558                 return 0;
559         } else {
560                 kbd = *kbdp;
561                 state = (ukbd_state_t *)kbd->kb_data;
562                 keymap = kbd->kb_keymap;
563                 accmap = kbd->kb_accentmap;
564                 fkeymap = kbd->kb_fkeytab;
565                 fkeymap_size = kbd->kb_fkeytab_size;
566         }
567
568         if (!KBD_IS_PROBED(kbd)) {
569                 if (KBD_IS_CONFIGURED(kbd)) {
570                         kbd_reinit_struct(kbd, flags, KB_PRI_USB);
571                 } else {
572                         kbd_init_struct(kbd, DRIVER_NAME, KB_OTHER, 
573                                         unit, flags, KB_PRI_USB,
574                                         0, 0);
575                 }
576                 bzero(state, sizeof(*state));
577                 bcopy(&key_map, keymap, sizeof(key_map));
578                 bcopy(&accent_map, accmap, sizeof(accent_map));
579                 bcopy(fkey_tab, fkeymap,
580                       imin(fkeymap_size*sizeof(fkeymap[0]), sizeof(fkey_tab)));
581                 kbd_set_maps(kbd, keymap, accmap, fkeymap, fkeymap_size);
582                 kbd->kb_data = (void *)state;
583
584                 if (probe_keyboard(uaa, flags))
585                         return ENXIO;
586                 else
587                         KBD_FOUND_DEVICE(kbd);
588                 ukbd_clear_state(kbd);
589
590                 /*
591                  * Initialize the translation mode only if we are not
592                  * reattaching to an already open keyboard (e.g. console).
593                  * Otherwise we might rip the translation mode out from
594                  * under X.
595                  */
596                 if (!KBD_IS_CONFIGURED(kbd))
597                         state->ks_mode = K_XLATE;
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                         free(kbd->kb_keymap, M_DEVBUF);
686                         free(kbd->kb_accentmap, M_DEVBUF);
687                         free(kbd->kb_fkeytab, M_DEVBUF);
688                         free(state, M_DEVBUF);
689                         free(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         if (state->ks_inputs > 0)
1195                 return TRUE;
1196         return FALSE;
1197 }
1198
1199 /* some useful control functions */
1200 Static int
1201 ukbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
1202 {
1203         /* trasnlate LED_XXX bits into the device specific bits */
1204         static u_char ledmap[8] = {
1205                 0, 2, 1, 3, 4, 6, 5, 7,
1206         };
1207         ukbd_state_t *state = kbd->kb_data;
1208         int i;
1209
1210         crit_enter();
1211         switch (cmd) {
1212         case KDGKBMODE:         /* get keyboard mode */
1213                 *(int *)arg = state->ks_mode;
1214                 break;
1215         case KDSKBMODE:         /* set keyboard mode */
1216                 switch (*(int *)arg) {
1217                 case K_XLATE:
1218                         if (state->ks_mode != K_XLATE) {
1219                                 /* make lock key state and LED state match */
1220                                 state->ks_state &= ~LOCK_MASK;
1221                                 state->ks_state |= KBD_LED_VAL(kbd);
1222                         }
1223                         /* FALLTHROUGH */
1224                 case K_RAW:
1225                 case K_CODE:
1226                         if (state->ks_mode != *(int *)arg) {
1227                                 ukbd_clear_state(kbd);
1228                                 state->ks_mode = *(int *)arg;
1229                         }
1230                         break;
1231                 default:
1232                         crit_exit();
1233                         return EINVAL;
1234                 }
1235                 break;
1236
1237         case KDGETLED:          /* get keyboard LED */
1238                 *(int *)arg = KBD_LED_VAL(kbd);
1239                 break;
1240         case KDSETLED:          /* set keyboard LED */
1241                 /* NOTE: lock key state in ks_state won't be changed */
1242                 if (*(int *)arg & ~LOCK_MASK) {
1243                         crit_exit();
1244                         return EINVAL;
1245                 }
1246                 i = *(int *)arg;
1247                 /* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1248                 if (kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1249                         if (i & ALKED)
1250                                 i |= CLKED;
1251                         else
1252                                 i &= ~CLKED;
1253                 }
1254                 if (KBD_HAS_DEVICE(kbd)) {
1255                         set_leds(state, ledmap[i & LED_MASK]);
1256                         /* XXX: error check? */
1257                 }
1258                 KBD_LED_VAL(kbd) = *(int *)arg;
1259                 break;
1260
1261         case KDGKBSTATE:        /* get lock key state */
1262                 *(int *)arg = state->ks_state & LOCK_MASK;
1263                 break;
1264         case KDSKBSTATE:        /* set lock key state */
1265                 if (*(int *)arg & ~LOCK_MASK) {
1266                         crit_exit();
1267                         return EINVAL;
1268                 }
1269                 state->ks_state &= ~LOCK_MASK;
1270                 state->ks_state |= *(int *)arg;
1271                 crit_exit();
1272                 /* set LEDs and quit */
1273                 return ukbd_ioctl(kbd, KDSETLED, arg);
1274
1275         case KDSETREPEAT:       /* set keyboard repeat rate (new interface) */
1276                 crit_exit();
1277                 if (!KBD_HAS_DEVICE(kbd))
1278                         return 0;
1279                 if (((int *)arg)[1] < 0)
1280                         return EINVAL;
1281                 if (((int *)arg)[0] < 0)
1282                         return EINVAL;
1283                 else if (((int *)arg)[0] == 0)  /* fastest possible value */
1284                         kbd->kb_delay1 = 200;
1285                 else
1286                         kbd->kb_delay1 = ((int *)arg)[0];
1287                 kbd->kb_delay2 = ((int *)arg)[1];
1288                 return 0;
1289
1290         case KDSETRAD:          /* set keyboard repeat rate (old interface) */
1291                 crit_exit();
1292                 return set_typematic(kbd, *(int *)arg);
1293
1294         case PIO_KEYMAP:        /* set keyboard translation table */
1295         case PIO_KEYMAPENT:     /* set keyboard translation table entry */
1296         case PIO_DEADKEYMAP:    /* set accent key translation table */
1297                 state->ks_accents = 0;
1298                 /* FALLTHROUGH */
1299         default:
1300                 crit_exit();
1301                 return genkbd_commonioctl(kbd, cmd, arg);
1302
1303 #ifdef USB_DEBUG
1304         case USB_SETDEBUG:
1305                 ukbddebug = *(int *)arg;
1306                 break;
1307 #endif
1308         }
1309
1310         crit_exit();
1311         return 0;
1312 }
1313
1314 /* lock the access to the keyboard */
1315 Static int
1316 ukbd_lock(keyboard_t *kbd, int lock)
1317 {
1318         /* XXX ? */
1319         return TRUE;
1320 }
1321
1322 /* clear the internal state of the keyboard */
1323 Static void
1324 ukbd_clear_state(keyboard_t *kbd)
1325 {
1326         ukbd_state_t *state;
1327
1328         state = (ukbd_state_t *)kbd->kb_data;
1329         state->ks_flags = 0;
1330         state->ks_polling = 0;
1331         state->ks_state &= LOCK_MASK;   /* preserve locking key state */
1332         state->ks_accents = 0;
1333         state->ks_composed_char = 0;
1334 #ifdef UKBD_EMULATE_ATSCANCODE
1335         state->ks_buffered_char[0] = 0;
1336         state->ks_buffered_char[1] = 0;
1337 #endif
1338         bzero(&state->ks_ndata, sizeof(state->ks_ndata));
1339         bzero(&state->ks_odata, sizeof(state->ks_odata));
1340         bzero(&state->ks_ntime, sizeof(state->ks_ntime));
1341         bzero(&state->ks_otime, sizeof(state->ks_otime));
1342 }
1343
1344 /* save the internal state */
1345 Static int
1346 ukbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1347 {
1348         if (len == 0)
1349                 return sizeof(ukbd_state_t);
1350         if (len < sizeof(ukbd_state_t))
1351                 return -1;
1352         bcopy(kbd->kb_data, buf, sizeof(ukbd_state_t));
1353         return 0;
1354 }
1355
1356 /* set the internal state */
1357 Static int
1358 ukbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1359 {
1360         if (len < sizeof(ukbd_state_t))
1361                 return ENOMEM;
1362         bcopy(buf, kbd->kb_data, sizeof(ukbd_state_t));
1363         return 0;
1364 }
1365
1366 Static int
1367 ukbd_poll(keyboard_t *kbd, int on)
1368 {
1369         ukbd_state_t *state;
1370         usbd_device_handle dev;
1371
1372         state = (ukbd_state_t *)kbd->kb_data;
1373         usbd_interface2device_handle(state->ks_iface, &dev);
1374
1375         crit_enter();
1376         if (on) {
1377                 if (state->ks_polling == 0)
1378                         usbd_set_polling(dev, on);
1379                 ++state->ks_polling;
1380         } else {
1381                 --state->ks_polling;
1382                 if (state->ks_polling == 0)
1383                         usbd_set_polling(dev, on);
1384         }
1385         crit_exit();
1386         return 0;
1387 }
1388
1389 /* local functions */
1390
1391 Static int
1392 probe_keyboard(struct usb_attach_arg *uaa, int flags)
1393 {
1394         usb_interface_descriptor_t *id;
1395
1396         if (!uaa->iface)        /* we attach to ifaces only */
1397                 return EINVAL;
1398
1399         /* Check that this is a keyboard that speaks the boot protocol. */
1400         id = usbd_get_interface_descriptor(uaa->iface);
1401         if (id
1402             && id->bInterfaceClass == UICLASS_HID
1403             && id->bInterfaceSubClass == UISUBCLASS_BOOT
1404             && id->bInterfaceProtocol == UPROTO_BOOT_KEYBOARD)
1405                 return 0;       /* found it */
1406
1407         return EINVAL;
1408 }
1409
1410 Static int
1411 init_keyboard(ukbd_state_t *state, int *type, int flags)
1412 {
1413         usb_endpoint_descriptor_t *ed;
1414         usbd_status err;
1415
1416         *type = KB_OTHER;
1417
1418         state->ks_ifstate |= DISCONNECTED;
1419
1420         ed = usbd_interface2endpoint_descriptor(state->ks_iface, 0);
1421         if (!ed) {
1422                 printf("ukbd: could not read endpoint descriptor\n");
1423                 return EIO;
1424         }
1425
1426         DPRINTFN(10,("ukbd:init_keyboard: \
1427 bLength=%d bDescriptorType=%d bEndpointAddress=%d-%s bmAttributes=%d wMaxPacketSize=%d bInterval=%d\n",
1428                ed->bLength, ed->bDescriptorType,
1429                UE_GET_ADDR(ed->bEndpointAddress),
1430                UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN ? "in":"out",
1431                UE_GET_XFERTYPE(ed->bmAttributes),
1432                UGETW(ed->wMaxPacketSize), ed->bInterval));
1433
1434         if (UE_GET_DIR(ed->bEndpointAddress) != UE_DIR_IN ||
1435             UE_GET_XFERTYPE(ed->bmAttributes) != UE_INTERRUPT) {
1436                 printf("ukbd: unexpected endpoint\n");
1437                 return EINVAL;
1438         }
1439
1440         if ((usbd_get_quirks(state->ks_uaa->device)->uq_flags & UQ_NO_SET_PROTO) == 0) {
1441                 err = usbd_set_protocol(state->ks_iface, 0);
1442                 DPRINTFN(5, ("ukbd:init_keyboard: protocol set\n"));
1443                 if (err) {
1444                         printf("ukbd: set protocol failed\n");
1445                         return EIO;
1446                 }
1447         }
1448         /* Ignore if SETIDLE fails since it is not crucial. */
1449         usbd_set_idle(state->ks_iface, 0, 0);
1450
1451         state->ks_ep_addr = ed->bEndpointAddress;
1452         state->ks_ifstate &= ~DISCONNECTED;
1453
1454         return 0;
1455 }
1456
1457 Static void
1458 set_leds(ukbd_state_t *state, int leds)
1459 {
1460         u_int8_t res = leds;
1461
1462         DPRINTF(("ukbd:set_leds: state=%p leds=%d\n", state, leds));
1463
1464         usbd_set_report_async(state->ks_iface, UHID_OUTPUT_REPORT, 0, &res, 1);
1465 }
1466
1467 Static int
1468 set_typematic(keyboard_t *kbd, int code)
1469 {
1470         static int delays[] = { 250, 500, 750, 1000 };
1471         static int rates[] = {  34,  38,  42,  46,  50,  55,  59,  63,
1472                                 68,  76,  84,  92, 100, 110, 118, 126,
1473                                136, 152, 168, 184, 200, 220, 236, 252,
1474                                272, 304, 336, 368, 400, 440, 472, 504 };
1475
1476         if (code & ~0x7f)
1477                 return EINVAL;
1478         kbd->kb_delay1 = delays[(code >> 5) & 3];
1479         kbd->kb_delay2 = rates[code & 0x1f];
1480         return 0;
1481 }
1482
1483 #ifdef UKBD_EMULATE_ATSCANCODE
1484 Static int
1485 keycode2scancode(int keycode, int shift, int up)
1486 {
1487         static int scan[] = {
1488                 0x1c, 0x1d, 0x35,
1489                 0x37 | SCAN_PREFIX_SHIFT, /* PrintScreen */
1490                 0x38, 0x47, 0x48, 0x49, 0x4b, 0x4d, 0x4f,
1491                 0x50, 0x51, 0x52, 0x53,
1492                 0x46,   /* XXX Pause/Break */
1493                 0x5b, 0x5c, 0x5d,
1494         };
1495         int scancode;
1496
1497         scancode = keycode;
1498         if ((keycode >= 89) && (keycode < 89 + sizeof(scan)/sizeof(scan[0])))
1499                 scancode = scan[keycode - 89] | SCAN_PREFIX_E0;
1500         /* Pause/Break */
1501         if ((keycode == 104) && !(shift & (MOD_CONTROL_L | MOD_CONTROL_R)))
1502                 scancode = 0x45 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL;
1503         if (shift & (MOD_SHIFT_L | MOD_SHIFT_R))
1504                 scancode &= ~SCAN_PREFIX_SHIFT;
1505         return (scancode | (up ? SCAN_RELEASE : SCAN_PRESS));
1506 }
1507 #endif /* UKBD_EMULATE_ATSCANCODE */
1508
1509 Static int
1510 ukbd_driver_load(module_t mod, int what, void *arg)
1511 {
1512         switch (what) {
1513                 case MOD_LOAD:
1514                         kbd_add_driver(&ukbd_kbd_driver);
1515                         break;
1516                 case MOD_UNLOAD:
1517                         kbd_delete_driver(&ukbd_kbd_driver);
1518                         break;
1519         }
1520         return usbd_driver_load(mod, what, 0);
1521 }