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