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