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