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