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