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