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