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