]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/usb/input/ukbd.c
Fix build of USB bootloader code by adding checks for _STANDALONE being defined.
[FreeBSD/FreeBSD.git] / sys / dev / usb / input / ukbd.c
1 #include <sys/cdefs.h>
2 __FBSDID("$FreeBSD$");
3
4 /*-
5  * SPDX-License-Identifier: BSD-2-Clause-NetBSD
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  *
23  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
24  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
27  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  *
35  */
36
37 /*
38  * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf
39  */
40
41 #include "opt_kbd.h"
42 #include "opt_ukbd.h"
43 #include "opt_evdev.h"
44
45 #include <sys/stdint.h>
46 #include <sys/stddef.h>
47 #include <sys/param.h>
48 #include <sys/queue.h>
49 #include <sys/types.h>
50 #include <sys/systm.h>
51 #include <sys/kernel.h>
52 #include <sys/bus.h>
53 #include <sys/module.h>
54 #include <sys/lock.h>
55 #include <sys/mutex.h>
56 #include <sys/condvar.h>
57 #include <sys/sysctl.h>
58 #include <sys/sx.h>
59 #include <sys/unistd.h>
60 #include <sys/callout.h>
61 #include <sys/malloc.h>
62 #include <sys/priv.h>
63 #include <sys/proc.h>
64
65 #include <dev/usb/usb.h>
66 #include <dev/usb/usbdi.h>
67 #include <dev/usb/usbdi_util.h>
68 #include <dev/usb/usbhid.h>
69
70 #define USB_DEBUG_VAR ukbd_debug
71 #include <dev/usb/usb_debug.h>
72
73 #include <dev/usb/quirk/usb_quirk.h>
74
75 #ifdef EVDEV_SUPPORT
76 #include <dev/evdev/input.h>
77 #include <dev/evdev/evdev.h>
78 #endif
79
80 #include <sys/ioccom.h>
81 #include <sys/filio.h>
82 #include <sys/kbio.h>
83
84 #include <dev/kbd/kbdreg.h>
85
86 /* the initial key map, accent map and fkey strings */
87 #if defined(UKBD_DFLT_KEYMAP) && !defined(KLD_MODULE)
88 #define KBD_DFLT_KEYMAP
89 #include "ukbdmap.h"
90 #endif
91
92 /* the following file must be included after "ukbdmap.h" */
93 #include <dev/kbd/kbdtables.h>
94
95 #ifdef USB_DEBUG
96 static int ukbd_debug = 0;
97 static int ukbd_no_leds = 0;
98 static int ukbd_pollrate = 0;
99
100 static SYSCTL_NODE(_hw_usb, OID_AUTO, ukbd, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
101     "USB keyboard");
102 SYSCTL_INT(_hw_usb_ukbd, OID_AUTO, debug, CTLFLAG_RWTUN,
103     &ukbd_debug, 0, "Debug level");
104 SYSCTL_INT(_hw_usb_ukbd, OID_AUTO, no_leds, CTLFLAG_RWTUN,
105     &ukbd_no_leds, 0, "Disables setting of keyboard leds");
106 SYSCTL_INT(_hw_usb_ukbd, OID_AUTO, pollrate, CTLFLAG_RWTUN,
107     &ukbd_pollrate, 0, "Force this polling rate, 1-1000Hz");
108 #endif
109
110 #define UKBD_EMULATE_ATSCANCODE        1
111 #define UKBD_DRIVER_NAME          "ukbd"
112 #define UKBD_NKEYCODE                 256 /* units */
113 #define UKBD_IN_BUF_SIZE  (4 * UKBD_NKEYCODE) /* scancodes */
114 #define UKBD_IN_BUF_FULL  ((UKBD_IN_BUF_SIZE / 2) - 1)  /* scancodes */
115 #define UKBD_NFKEY        (sizeof(fkey_tab)/sizeof(fkey_tab[0]))        /* units */
116 #define UKBD_BUFFER_SIZE              64        /* bytes */
117 #define UKBD_KEY_PRESSED(map, key) ({ \
118         CTASSERT((key) >= 0 && (key) < UKBD_NKEYCODE); \
119         ((map)[(key) / 64] & (1ULL << ((key) % 64))); \
120 })
121
122 #define MOD_EJECT       0x01
123 #define MOD_FN          0x02
124
125 struct ukbd_data {
126         uint64_t bitmap[howmany(UKBD_NKEYCODE, 64)];
127 };
128
129 enum {
130         UKBD_INTR_DT_0,
131         UKBD_INTR_DT_1,
132         UKBD_CTRL_LED,
133         UKBD_N_TRANSFER,
134 };
135
136 struct ukbd_softc {
137         keyboard_t sc_kbd;
138         keymap_t sc_keymap;
139         accentmap_t sc_accmap;
140         fkeytab_t sc_fkeymap[UKBD_NFKEY];
141         uint64_t sc_loc_key_valid[howmany(UKBD_NKEYCODE, 64)];
142         struct hid_location sc_loc_apple_eject;
143         struct hid_location sc_loc_apple_fn;
144         struct hid_location sc_loc_key[UKBD_NKEYCODE];
145         struct hid_location sc_loc_numlock;
146         struct hid_location sc_loc_capslock;
147         struct hid_location sc_loc_scrolllock;
148         struct usb_callout sc_callout;
149         struct ukbd_data sc_ndata;
150         struct ukbd_data sc_odata;
151
152         struct thread *sc_poll_thread;
153         struct usb_device *sc_udev;
154         struct usb_interface *sc_iface;
155         struct usb_xfer *sc_xfer[UKBD_N_TRANSFER];
156 #ifdef EVDEV_SUPPORT
157         struct evdev_dev *sc_evdev;
158 #endif
159
160         sbintime_t sc_co_basetime;
161         int     sc_delay;
162         uint32_t sc_repeat_time;
163         uint32_t sc_input[UKBD_IN_BUF_SIZE];    /* input buffer */
164         uint32_t sc_time_ms;
165         uint32_t sc_composed_char;      /* composed char code, if non-zero */
166 #ifdef UKBD_EMULATE_ATSCANCODE
167         uint32_t sc_buffered_char[2];
168 #endif
169         uint32_t sc_flags;              /* flags */
170 #define UKBD_FLAG_COMPOSE       0x00000001
171 #define UKBD_FLAG_POLLING       0x00000002
172 #define UKBD_FLAG_SET_LEDS      0x00000004
173 #define UKBD_FLAG_ATTACHED      0x00000010
174 #define UKBD_FLAG_GONE          0x00000020
175
176 #define UKBD_FLAG_HID_MASK      0x003fffc0
177 #define UKBD_FLAG_APPLE_EJECT   0x00000040
178 #define UKBD_FLAG_APPLE_FN      0x00000080
179 #define UKBD_FLAG_APPLE_SWAP    0x00000100
180 #define UKBD_FLAG_NUMLOCK       0x00080000
181 #define UKBD_FLAG_CAPSLOCK      0x00100000
182 #define UKBD_FLAG_SCROLLLOCK    0x00200000
183
184         int     sc_mode;                /* input mode (K_XLATE,K_RAW,K_CODE) */
185         int     sc_state;               /* shift/lock key state */
186         int     sc_accents;             /* accent key index (> 0) */
187         int     sc_polling;             /* polling recursion count */
188         int     sc_led_size;
189         int     sc_kbd_size;
190
191         uint16_t sc_inputs;
192         uint16_t sc_inputhead;
193         uint16_t sc_inputtail;
194
195         uint8_t sc_leds;                /* store for async led requests */
196         uint8_t sc_iface_index;
197         uint8_t sc_iface_no;
198         uint8_t sc_id_apple_eject;
199         uint8_t sc_id_apple_fn;
200         uint8_t sc_id_loc_key[UKBD_NKEYCODE];
201         uint8_t sc_id_numlock;
202         uint8_t sc_id_capslock;
203         uint8_t sc_id_scrolllock;
204         uint8_t sc_kbd_id;
205         uint8_t sc_repeat_key;
206
207         uint8_t sc_buffer[UKBD_BUFFER_SIZE];
208 };
209
210 #define KEY_NONE          0x00
211 #define KEY_ERROR         0x01
212
213 #define KEY_PRESS         0
214 #define KEY_RELEASE       0x400
215 #define KEY_INDEX(c)      ((c) & 0xFF)
216
217 #define SCAN_PRESS        0
218 #define SCAN_RELEASE      0x80
219 #define SCAN_PREFIX_E0    0x100
220 #define SCAN_PREFIX_E1    0x200
221 #define SCAN_PREFIX_CTL   0x400
222 #define SCAN_PREFIX_SHIFT 0x800
223 #define SCAN_PREFIX     (SCAN_PREFIX_E0  | SCAN_PREFIX_E1 | \
224                          SCAN_PREFIX_CTL | SCAN_PREFIX_SHIFT)
225 #define SCAN_CHAR(c)    ((c) & 0x7f)
226
227 #define UKBD_LOCK()     USB_MTX_LOCK(&Giant)
228 #define UKBD_UNLOCK()   USB_MTX_UNLOCK(&Giant)
229 #define UKBD_LOCK_ASSERT()      USB_MTX_ASSERT(&Giant, MA_OWNED)
230
231 #define NN 0                            /* no translation */
232 /*
233  * Translate USB keycodes to AT keyboard scancodes.
234  */
235 /*
236  * FIXME: Mac USB keyboard generates:
237  * 0x53: keypad NumLock/Clear
238  * 0x66: Power
239  * 0x67: keypad =
240  * 0x68: F13
241  * 0x69: F14
242  * 0x6a: F15
243  * 
244  * USB Apple Keyboard JIS generates:
245  * 0x90: Kana
246  * 0x91: Eisu
247  */
248 static const uint8_t ukbd_trtab[256] = {
249         0, 0, 0, 0, 30, 48, 46, 32,     /* 00 - 07 */
250         18, 33, 34, 35, 23, 36, 37, 38, /* 08 - 0F */
251         50, 49, 24, 25, 16, 19, 31, 20, /* 10 - 17 */
252         22, 47, 17, 45, 21, 44, 2, 3,   /* 18 - 1F */
253         4, 5, 6, 7, 8, 9, 10, 11,       /* 20 - 27 */
254         28, 1, 14, 15, 57, 12, 13, 26,  /* 28 - 2F */
255         27, 43, 43, 39, 40, 41, 51, 52, /* 30 - 37 */
256         53, 58, 59, 60, 61, 62, 63, 64, /* 38 - 3F */
257         65, 66, 67, 68, 87, 88, 92, 70, /* 40 - 47 */
258         104, 102, 94, 96, 103, 99, 101, 98,     /* 48 - 4F */
259         97, 100, 95, 69, 91, 55, 74, 78,/* 50 - 57 */
260         89, 79, 80, 81, 75, 76, 77, 71, /* 58 - 5F */
261         72, 73, 82, 83, 86, 107, 122, NN,       /* 60 - 67 */
262         NN, NN, NN, NN, NN, NN, NN, NN, /* 68 - 6F */
263         NN, NN, NN, NN, 115, 108, 111, 113,     /* 70 - 77 */
264         109, 110, 112, 118, 114, 116, 117, 119, /* 78 - 7F */
265         121, 120, NN, NN, NN, NN, NN, 123,      /* 80 - 87 */
266         124, 125, 126, 127, 128, NN, NN, NN,    /* 88 - 8F */
267         129, 130, NN, NN, NN, NN, NN, NN,       /* 90 - 97 */
268         NN, NN, NN, NN, NN, NN, NN, NN, /* 98 - 9F */
269         NN, NN, NN, NN, NN, NN, NN, NN, /* A0 - A7 */
270         NN, NN, NN, NN, NN, NN, NN, NN, /* A8 - AF */
271         NN, NN, NN, NN, NN, NN, NN, NN, /* B0 - B7 */
272         NN, NN, NN, NN, NN, NN, NN, NN, /* B8 - BF */
273         NN, NN, NN, NN, NN, NN, NN, NN, /* C0 - C7 */
274         NN, NN, NN, NN, NN, NN, NN, NN, /* C8 - CF */
275         NN, NN, NN, NN, NN, NN, NN, NN, /* D0 - D7 */
276         NN, NN, NN, NN, NN, NN, NN, NN, /* D8 - DF */
277         29, 42, 56, 105, 90, 54, 93, 106,       /* E0 - E7 */
278         NN, NN, NN, NN, NN, NN, NN, NN, /* E8 - EF */
279         NN, NN, NN, NN, NN, NN, NN, NN, /* F0 - F7 */
280         NN, NN, NN, NN, NN, NN, NN, NN, /* F8 - FF */
281 };
282
283 static const uint8_t ukbd_boot_desc[] = {
284         0x05, 0x01, 0x09, 0x06, 0xa1,
285         0x01, 0x05, 0x07, 0x19, 0xe0,
286         0x29, 0xe7, 0x15, 0x00, 0x25,
287         0x01, 0x75, 0x01, 0x95, 0x08,
288         0x81, 0x02, 0x95, 0x01, 0x75,
289         0x08, 0x81, 0x01, 0x95, 0x03,
290         0x75, 0x01, 0x05, 0x08, 0x19,
291         0x01, 0x29, 0x03, 0x91, 0x02,
292         0x95, 0x05, 0x75, 0x01, 0x91,
293         0x01, 0x95, 0x06, 0x75, 0x08,
294         0x15, 0x00, 0x26, 0xff, 0x00,
295         0x05, 0x07, 0x19, 0x00, 0x2a,
296         0xff, 0x00, 0x81, 0x00, 0xc0
297 };
298
299 /* prototypes */
300 static void     ukbd_timeout(void *);
301 static void     ukbd_set_leds(struct ukbd_softc *, uint8_t);
302 static int      ukbd_set_typematic(keyboard_t *, int);
303 #ifdef UKBD_EMULATE_ATSCANCODE
304 static uint32_t ukbd_atkeycode(int, const uint64_t *);
305 static int      ukbd_key2scan(struct ukbd_softc *, int, const uint64_t *, int);
306 #endif
307 static uint32_t ukbd_read_char(keyboard_t *, int);
308 static void     ukbd_clear_state(keyboard_t *);
309 static int      ukbd_ioctl(keyboard_t *, u_long, caddr_t);
310 static int      ukbd_enable(keyboard_t *);
311 static int      ukbd_disable(keyboard_t *);
312 static void     ukbd_interrupt(struct ukbd_softc *);
313 static void     ukbd_event_keyinput(struct ukbd_softc *);
314
315 static device_probe_t ukbd_probe;
316 static device_attach_t ukbd_attach;
317 static device_detach_t ukbd_detach;
318 static device_resume_t ukbd_resume;
319
320 #ifdef EVDEV_SUPPORT
321 static evdev_event_t ukbd_ev_event;
322
323 static const struct evdev_methods ukbd_evdev_methods = {
324         .ev_event = ukbd_ev_event,
325 };
326 #endif
327
328 static bool
329 ukbd_any_key_pressed(struct ukbd_softc *sc)
330 {
331         bool ret = false;
332         unsigned i;
333
334         for (i = 0; i != howmany(UKBD_NKEYCODE, 64); i++)
335                 ret |= (sc->sc_odata.bitmap[i] != 0);
336         return (ret);
337 }
338
339 static bool
340 ukbd_any_key_valid(struct ukbd_softc *sc)
341 {
342         bool ret = false;
343         unsigned i;
344
345         for (i = 0; i != howmany(UKBD_NKEYCODE, 64); i++)
346                 ret |= (sc->sc_loc_key_valid[i] != 0);
347         return (ret);
348 }
349
350 static bool
351 ukbd_is_modifier_key(uint32_t key)
352 {
353
354         return (key >= 0xe0 && key <= 0xe7);
355 }
356
357 static void
358 ukbd_start_timer(struct ukbd_softc *sc)
359 {
360         sbintime_t delay, now, prec;
361
362         now = sbinuptime();
363
364         /* check if initial delay passed and fallback to key repeat delay */
365         if (sc->sc_delay == 0)
366                 sc->sc_delay = sc->sc_kbd.kb_delay2;
367
368         /* compute timeout */
369         delay = SBT_1MS * sc->sc_delay;
370         sc->sc_co_basetime += delay;
371
372         /* check if we are running behind */
373         if (sc->sc_co_basetime < now)
374                 sc->sc_co_basetime = now;
375
376         /* This is rarely called, so prefer precision to efficiency. */
377         prec = qmin(delay >> 7, SBT_1MS * 10);
378         usb_callout_reset_sbt(&sc->sc_callout, sc->sc_co_basetime, prec,
379             ukbd_timeout, sc, C_ABSOLUTE);
380 }
381
382 static void
383 ukbd_put_key(struct ukbd_softc *sc, uint32_t key)
384 {
385
386         UKBD_LOCK_ASSERT();
387
388         DPRINTF("0x%02x (%d) %s\n", key, key,
389             (key & KEY_RELEASE) ? "released" : "pressed");
390
391 #ifdef EVDEV_SUPPORT
392         if (evdev_rcpt_mask & EVDEV_RCPT_HW_KBD && sc->sc_evdev != NULL) {
393                 evdev_push_event(sc->sc_evdev, EV_KEY,
394                     evdev_hid2key(KEY_INDEX(key)), !(key & KEY_RELEASE));
395                 evdev_sync(sc->sc_evdev);
396         }
397 #endif
398
399         if (sc->sc_inputs < UKBD_IN_BUF_SIZE) {
400                 sc->sc_input[sc->sc_inputtail] = key;
401                 ++(sc->sc_inputs);
402                 ++(sc->sc_inputtail);
403                 if (sc->sc_inputtail >= UKBD_IN_BUF_SIZE) {
404                         sc->sc_inputtail = 0;
405                 }
406         } else {
407                 DPRINTF("input buffer is full\n");
408         }
409 }
410
411 static void
412 ukbd_do_poll(struct ukbd_softc *sc, uint8_t wait)
413 {
414
415         UKBD_LOCK_ASSERT();
416         KASSERT((sc->sc_flags & UKBD_FLAG_POLLING) != 0,
417             ("ukbd_do_poll called when not polling\n"));
418         DPRINTFN(2, "polling\n");
419
420         if (USB_IN_POLLING_MODE_FUNC() == 0) {
421                 /*
422                  * In this context the kernel is polling for input,
423                  * but the USB subsystem works in normal interrupt-driven
424                  * mode, so we just wait on the USB threads to do the job.
425                  * Note that we currently hold the Giant, but it's also used
426                  * as the transfer mtx, so we must release it while waiting.
427                  */
428                 while (sc->sc_inputs == 0) {
429                         /*
430                          * Give USB threads a chance to run.  Note that
431                          * kern_yield performs DROP_GIANT + PICKUP_GIANT.
432                          */
433                         kern_yield(PRI_UNCHANGED);
434                         if (!wait)
435                                 break;
436                 }
437                 return;
438         }
439
440         while (sc->sc_inputs == 0) {
441                 usbd_transfer_poll(sc->sc_xfer, UKBD_N_TRANSFER);
442
443                 /* Delay-optimised support for repetition of keys */
444                 if (ukbd_any_key_pressed(sc)) {
445                         /* a key is pressed - need timekeeping */
446                         DELAY(1000);
447
448                         /* 1 millisecond has passed */
449                         sc->sc_time_ms += 1;
450                 }
451
452                 ukbd_interrupt(sc);
453
454                 if (!wait)
455                         break;
456         }
457 }
458
459 static int32_t
460 ukbd_get_key(struct ukbd_softc *sc, uint8_t wait)
461 {
462         int32_t c;
463
464         UKBD_LOCK_ASSERT();
465         KASSERT((USB_IN_POLLING_MODE_FUNC() == 0) ||
466             (sc->sc_flags & UKBD_FLAG_POLLING) != 0,
467             ("not polling in kdb or panic\n"));
468
469         if (sc->sc_inputs == 0 &&
470             (sc->sc_flags & UKBD_FLAG_GONE) == 0) {
471                 /* start transfer, if not already started */
472                 usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_0]);
473                 usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_1]);
474         }
475
476         if (sc->sc_flags & UKBD_FLAG_POLLING)
477                 ukbd_do_poll(sc, wait);
478
479         if (sc->sc_inputs == 0) {
480                 c = -1;
481         } else {
482                 c = sc->sc_input[sc->sc_inputhead];
483                 --(sc->sc_inputs);
484                 ++(sc->sc_inputhead);
485                 if (sc->sc_inputhead >= UKBD_IN_BUF_SIZE) {
486                         sc->sc_inputhead = 0;
487                 }
488         }
489         return (c);
490 }
491
492 static void
493 ukbd_interrupt(struct ukbd_softc *sc)
494 {
495         const uint32_t now = sc->sc_time_ms;
496         unsigned key;
497
498         UKBD_LOCK_ASSERT();
499
500         /* Check for modifier key changes first */
501         for (key = 0xe0; key != 0xe8; key++) {
502                 const uint64_t mask = 1ULL << (key % 64);
503                 const uint64_t delta =
504                     sc->sc_odata.bitmap[key / 64] ^
505                     sc->sc_ndata.bitmap[key / 64];
506
507                 if (delta & mask) {
508                         if (sc->sc_odata.bitmap[key / 64] & mask)
509                                 ukbd_put_key(sc, key | KEY_RELEASE);
510                         else
511                                 ukbd_put_key(sc, key | KEY_PRESS);
512                 }
513         }
514
515         /* Check for key changes */
516         for (key = 0; key != UKBD_NKEYCODE; key++) {
517                 const uint64_t mask = 1ULL << (key % 64);
518                 const uint64_t delta =
519                     sc->sc_odata.bitmap[key / 64] ^
520                     sc->sc_ndata.bitmap[key / 64];
521
522                 if (mask == 1 && delta == 0) {
523                         key += 63;
524                         continue;       /* skip empty areas */
525                 } else if (ukbd_is_modifier_key(key)) {
526                         continue;
527                 } else if (delta & mask) {
528                         if (sc->sc_odata.bitmap[key / 64] & mask) {
529                                 ukbd_put_key(sc, key | KEY_RELEASE);
530
531                                 /* clear repeating key, if any */
532                                 if (sc->sc_repeat_key == key)
533                                         sc->sc_repeat_key = 0;
534                         } else {
535                                 ukbd_put_key(sc, key | KEY_PRESS);
536
537                                 sc->sc_co_basetime = sbinuptime();
538                                 sc->sc_delay = sc->sc_kbd.kb_delay1;
539                                 ukbd_start_timer(sc);
540
541                                 /* set repeat time for last key */
542                                 sc->sc_repeat_time = now + sc->sc_kbd.kb_delay1;
543                                 sc->sc_repeat_key = key;
544                         }
545                 }
546         }
547
548         /* synchronize old data with new data */
549         sc->sc_odata = sc->sc_ndata;
550
551         /* check if last key is still pressed */
552         if (sc->sc_repeat_key != 0) {
553                 const int32_t dtime = (sc->sc_repeat_time - now);
554
555                 /* check if time has elapsed */
556                 if (dtime <= 0) {
557                         ukbd_put_key(sc, sc->sc_repeat_key | KEY_PRESS);
558                         sc->sc_repeat_time = now + sc->sc_kbd.kb_delay2;
559                 }
560         }
561
562         /* wakeup keyboard system */
563         ukbd_event_keyinput(sc);
564 }
565
566 static void
567 ukbd_event_keyinput(struct ukbd_softc *sc)
568 {
569         int c;
570
571         UKBD_LOCK_ASSERT();
572
573         if ((sc->sc_flags & UKBD_FLAG_POLLING) != 0)
574                 return;
575
576         if (sc->sc_inputs == 0)
577                 return;
578
579         if (KBD_IS_ACTIVE(&sc->sc_kbd) &&
580             KBD_IS_BUSY(&sc->sc_kbd)) {
581                 /* let the callback function process the input */
582                 (sc->sc_kbd.kb_callback.kc_func) (&sc->sc_kbd, KBDIO_KEYINPUT,
583                     sc->sc_kbd.kb_callback.kc_arg);
584         } else {
585                 /* read and discard the input, no one is waiting for it */
586                 do {
587                         c = ukbd_read_char(&sc->sc_kbd, 0);
588                 } while (c != NOKEY);
589         }
590 }
591
592 static void
593 ukbd_timeout(void *arg)
594 {
595         struct ukbd_softc *sc = arg;
596
597         UKBD_LOCK_ASSERT();
598
599         sc->sc_time_ms += sc->sc_delay;
600         sc->sc_delay = 0;
601
602         ukbd_interrupt(sc);
603
604         /* Make sure any leftover key events gets read out */
605         ukbd_event_keyinput(sc);
606
607         if (ukbd_any_key_pressed(sc) || (sc->sc_inputs != 0)) {
608                 ukbd_start_timer(sc);
609         }
610 }
611
612 static uint32_t
613 ukbd_apple_fn(uint32_t keycode)
614 {
615         switch (keycode) {
616         case 0x28: return 0x49; /* RETURN -> INSERT */
617         case 0x2a: return 0x4c; /* BACKSPACE -> DEL */
618         case 0x50: return 0x4a; /* LEFT ARROW -> HOME */
619         case 0x4f: return 0x4d; /* RIGHT ARROW -> END */
620         case 0x52: return 0x4b; /* UP ARROW -> PGUP */
621         case 0x51: return 0x4e; /* DOWN ARROW -> PGDN */
622         default: return keycode;
623         }
624 }
625
626 static uint32_t
627 ukbd_apple_swap(uint32_t keycode)
628 {
629         switch (keycode) {
630         case 0x35: return 0x64;
631         case 0x64: return 0x35;
632         default: return keycode;
633         }
634 }
635
636 static void
637 ukbd_intr_callback(struct usb_xfer *xfer, usb_error_t error)
638 {
639         struct ukbd_softc *sc = usbd_xfer_softc(xfer);
640         struct usb_page_cache *pc;
641         uint32_t i;
642         uint8_t id;
643         uint8_t modifiers;
644         int offset;
645         int len;
646
647         UKBD_LOCK_ASSERT();
648
649         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
650         pc = usbd_xfer_get_frame(xfer, 0);
651
652         switch (USB_GET_STATE(xfer)) {
653         case USB_ST_TRANSFERRED:
654                 DPRINTF("actlen=%d bytes\n", len);
655
656                 if (len == 0) {
657                         DPRINTF("zero length data\n");
658                         goto tr_setup;
659                 }
660
661                 if (sc->sc_kbd_id != 0) {
662                         /* check and remove HID ID byte */
663                         usbd_copy_out(pc, 0, &id, 1);
664                         offset = 1;
665                         len--;
666                         if (len == 0) {
667                                 DPRINTF("zero length data\n");
668                                 goto tr_setup;
669                         }
670                 } else {
671                         offset = 0;
672                         id = 0;
673                 }
674
675                 if (len > UKBD_BUFFER_SIZE)
676                         len = UKBD_BUFFER_SIZE;
677
678                 /* get data */
679                 usbd_copy_out(pc, offset, sc->sc_buffer, len);
680
681                 /* clear temporary storage */
682                 memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
683
684                 /* clear modifiers */
685                 modifiers = 0;
686
687                 /* scan through HID data */
688                 if ((sc->sc_flags & UKBD_FLAG_APPLE_EJECT) &&
689                     (id == sc->sc_id_apple_eject)) {
690                         if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_apple_eject))
691                                 modifiers |= MOD_EJECT;
692                 }
693                 if ((sc->sc_flags & UKBD_FLAG_APPLE_FN) &&
694                     (id == sc->sc_id_apple_fn)) {
695                         if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_apple_fn))
696                                 modifiers |= MOD_FN;
697                 }
698
699                 for (i = 0; i != UKBD_NKEYCODE; i++) {
700                         const uint64_t valid = sc->sc_loc_key_valid[i / 64];
701                         const uint64_t mask = 1ULL << (i % 64);
702
703                         if (mask == 1 && valid == 0) {
704                                 i += 63;
705                                 continue;       /* skip empty areas */
706                         } else if (~valid & mask) {
707                                 continue;       /* location is not valid */
708                         } else if (id != sc->sc_id_loc_key[i]) {
709                                 continue;       /* invalid HID ID */
710                         } else if (i == 0) {
711                                 struct hid_location tmp_loc = sc->sc_loc_key[0];
712                                 /* range check array size */
713                                 if (tmp_loc.count > UKBD_NKEYCODE)
714                                         tmp_loc.count = UKBD_NKEYCODE;
715                                 while (tmp_loc.count--) {
716                                         uint32_t key =
717                                             hid_get_data_unsigned(sc->sc_buffer, len, &tmp_loc);
718                                         /* advance to next location */
719                                         tmp_loc.pos += tmp_loc.size;
720                                         if (modifiers & MOD_FN)
721                                                 key = ukbd_apple_fn(key);
722                                         if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP)
723                                                 key = ukbd_apple_swap(key);
724                                         if (key == KEY_NONE || key == KEY_ERROR || key >= UKBD_NKEYCODE)
725                                                 continue;
726                                         /* set key in bitmap */
727                                         sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
728                                 }
729                         } else if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_key[i])) {
730                                 uint32_t key = i;
731
732                                 if (modifiers & MOD_FN)
733                                         key = ukbd_apple_fn(key);
734                                 if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP)
735                                         key = ukbd_apple_swap(key);
736                                 if (key == KEY_NONE || key == KEY_ERROR || key >= UKBD_NKEYCODE)
737                                         continue;
738                                 /* set key in bitmap */
739                                 sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
740                         }
741                 }
742 #ifdef USB_DEBUG
743                 DPRINTF("modifiers = 0x%04x\n", modifiers);
744                 for (i = 0; i != UKBD_NKEYCODE; i++) {
745                         const uint64_t valid = sc->sc_ndata.bitmap[i / 64];
746                         const uint64_t mask = 1ULL << (i % 64);
747
748                         if (valid & mask)
749                                 DPRINTF("Key 0x%02x pressed\n", i);
750                 }
751 #endif
752                 ukbd_interrupt(sc);
753
754         case USB_ST_SETUP:
755 tr_setup:
756                 if (sc->sc_inputs < UKBD_IN_BUF_FULL) {
757                         usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
758                         usbd_transfer_submit(xfer);
759                 } else {
760                         DPRINTF("input queue is full!\n");
761                 }
762                 break;
763
764         default:                        /* Error */
765                 DPRINTF("error=%s\n", usbd_errstr(error));
766
767                 if (error != USB_ERR_CANCELLED) {
768                         /* try to clear stall first */
769                         usbd_xfer_set_stall(xfer);
770                         goto tr_setup;
771                 }
772                 break;
773         }
774 }
775
776 static void
777 ukbd_set_leds_callback(struct usb_xfer *xfer, usb_error_t error)
778 {
779         struct ukbd_softc *sc = usbd_xfer_softc(xfer);
780         struct usb_device_request req;
781         struct usb_page_cache *pc;
782         uint8_t id;
783         uint8_t any;
784         int len;
785
786         UKBD_LOCK_ASSERT();
787
788 #ifdef USB_DEBUG
789         if (ukbd_no_leds)
790                 return;
791 #endif
792
793         switch (USB_GET_STATE(xfer)) {
794         case USB_ST_TRANSFERRED:
795         case USB_ST_SETUP:
796                 if (!(sc->sc_flags & UKBD_FLAG_SET_LEDS))
797                         break;
798                 sc->sc_flags &= ~UKBD_FLAG_SET_LEDS;
799
800                 req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
801                 req.bRequest = UR_SET_REPORT;
802                 USETW2(req.wValue, UHID_OUTPUT_REPORT, 0);
803                 req.wIndex[0] = sc->sc_iface_no;
804                 req.wIndex[1] = 0;
805                 req.wLength[1] = 0;
806
807                 memset(sc->sc_buffer, 0, UKBD_BUFFER_SIZE);
808
809                 id = 0;
810                 any = 0;
811
812                 /* Assumption: All led bits must be in the same ID. */
813
814                 if (sc->sc_flags & UKBD_FLAG_NUMLOCK) {
815                         if (sc->sc_leds & NLKED) {
816                                 hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
817                                     &sc->sc_loc_numlock, 1);
818                         }
819                         id = sc->sc_id_numlock;
820                         any = 1;
821                 }
822
823                 if (sc->sc_flags & UKBD_FLAG_SCROLLLOCK) {
824                         if (sc->sc_leds & SLKED) {
825                                 hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
826                                     &sc->sc_loc_scrolllock, 1);
827                         }
828                         id = sc->sc_id_scrolllock;
829                         any = 1;
830                 }
831
832                 if (sc->sc_flags & UKBD_FLAG_CAPSLOCK) {
833                         if (sc->sc_leds & CLKED) {
834                                 hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
835                                     &sc->sc_loc_capslock, 1);
836                         }
837                         id = sc->sc_id_capslock;
838                         any = 1;
839                 }
840
841                 /* if no leds, nothing to do */
842                 if (!any)
843                         break;
844
845 #ifdef EVDEV_SUPPORT
846                 if (sc->sc_evdev != NULL)
847                         evdev_push_leds(sc->sc_evdev, sc->sc_leds);
848 #endif
849
850                 /* range check output report length */
851                 len = sc->sc_led_size;
852                 if (len > (UKBD_BUFFER_SIZE - 1))
853                         len = (UKBD_BUFFER_SIZE - 1);
854
855                 /* check if we need to prefix an ID byte */
856                 sc->sc_buffer[0] = id;
857
858                 pc = usbd_xfer_get_frame(xfer, 1);
859                 if (id != 0) {
860                         len++;
861                         usbd_copy_in(pc, 0, sc->sc_buffer, len);
862                 } else {
863                         usbd_copy_in(pc, 0, sc->sc_buffer + 1, len);
864                 }
865                 req.wLength[0] = len;
866                 usbd_xfer_set_frame_len(xfer, 1, len);
867
868                 DPRINTF("len=%d, id=%d\n", len, id);
869
870                 /* setup control request last */
871                 pc = usbd_xfer_get_frame(xfer, 0);
872                 usbd_copy_in(pc, 0, &req, sizeof(req));
873                 usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
874
875                 /* start data transfer */
876                 usbd_xfer_set_frames(xfer, 2);
877                 usbd_transfer_submit(xfer);
878                 break;
879
880         default:                        /* Error */
881                 DPRINTFN(1, "error=%s\n", usbd_errstr(error));
882                 break;
883         }
884 }
885
886 static const struct usb_config ukbd_config[UKBD_N_TRANSFER] = {
887         [UKBD_INTR_DT_0] = {
888                 .type = UE_INTERRUPT,
889                 .endpoint = UE_ADDR_ANY,
890                 .direction = UE_DIR_IN,
891                 .flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
892                 .bufsize = 0,   /* use wMaxPacketSize */
893                 .callback = &ukbd_intr_callback,
894         },
895
896         [UKBD_INTR_DT_1] = {
897                 .type = UE_INTERRUPT,
898                 .endpoint = UE_ADDR_ANY,
899                 .direction = UE_DIR_IN,
900                 .flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
901                 .bufsize = 0,   /* use wMaxPacketSize */
902                 .callback = &ukbd_intr_callback,
903         },
904
905         [UKBD_CTRL_LED] = {
906                 .type = UE_CONTROL,
907                 .endpoint = 0x00,       /* Control pipe */
908                 .direction = UE_DIR_ANY,
909                 .bufsize = sizeof(struct usb_device_request) + UKBD_BUFFER_SIZE,
910                 .callback = &ukbd_set_leds_callback,
911                 .timeout = 1000,        /* 1 second */
912         },
913 };
914
915 /* A match on these entries will load ukbd */
916 static const STRUCT_USB_HOST_ID __used ukbd_devs[] = {
917         {USB_IFACE_CLASS(UICLASS_HID),
918          USB_IFACE_SUBCLASS(UISUBCLASS_BOOT),
919          USB_IFACE_PROTOCOL(UIPROTO_BOOT_KEYBOARD),},
920 };
921
922 static int
923 ukbd_probe(device_t dev)
924 {
925         keyboard_switch_t *sw = kbd_get_switch(UKBD_DRIVER_NAME);
926         struct usb_attach_arg *uaa = device_get_ivars(dev);
927         void *d_ptr;
928         int error;
929         uint16_t d_len;
930
931         UKBD_LOCK_ASSERT();
932         DPRINTFN(11, "\n");
933
934         if (sw == NULL) {
935                 return (ENXIO);
936         }
937         if (uaa->usb_mode != USB_MODE_HOST) {
938                 return (ENXIO);
939         }
940
941         if (uaa->info.bInterfaceClass != UICLASS_HID)
942                 return (ENXIO);
943
944         if (usb_test_quirk(uaa, UQ_KBD_IGNORE))
945                 return (ENXIO);
946
947         if ((uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) &&
948             (uaa->info.bInterfaceProtocol == UIPROTO_BOOT_KEYBOARD))
949                 return (BUS_PROBE_DEFAULT);
950
951         error = usbd_req_get_hid_desc(uaa->device, NULL,
952             &d_ptr, &d_len, M_TEMP, uaa->info.bIfaceIndex);
953
954         if (error)
955                 return (ENXIO);
956
957         if (hid_is_keyboard(d_ptr, d_len)) {
958                 if (hid_is_mouse(d_ptr, d_len)) {
959                         /*
960                          * NOTE: We currently don't support USB mouse
961                          * and USB keyboard on the same USB endpoint.
962                          * Let "ums" driver win.
963                          */
964                         error = ENXIO;
965                 } else {
966                         error = BUS_PROBE_DEFAULT;
967                 }
968         } else {
969                 error = ENXIO;
970         }
971         free(d_ptr, M_TEMP);
972         return (error);
973 }
974
975 static void
976 ukbd_parse_hid(struct ukbd_softc *sc, const uint8_t *ptr, uint32_t len)
977 {
978         uint32_t flags;
979         uint32_t key;
980
981         /* reset detected bits */
982         sc->sc_flags &= ~UKBD_FLAG_HID_MASK;
983
984         /* reset detected keys */
985         memset(sc->sc_loc_key_valid, 0, sizeof(sc->sc_loc_key_valid));
986
987         /* check if there is an ID byte */
988         sc->sc_kbd_size = hid_report_size(ptr, len,
989             hid_input, &sc->sc_kbd_id);
990
991         /* investigate if this is an Apple Keyboard */
992         if (hid_locate(ptr, len,
993             HID_USAGE2(HUP_CONSUMER, HUG_APPLE_EJECT),
994             hid_input, 0, &sc->sc_loc_apple_eject, &flags,
995             &sc->sc_id_apple_eject)) {
996                 if (flags & HIO_VARIABLE)
997                         sc->sc_flags |= UKBD_FLAG_APPLE_EJECT | 
998                             UKBD_FLAG_APPLE_SWAP;
999                 DPRINTFN(1, "Found Apple eject-key\n");
1000         }
1001         if (hid_locate(ptr, len,
1002             HID_USAGE2(0xFFFF, 0x0003),
1003             hid_input, 0, &sc->sc_loc_apple_fn, &flags,
1004             &sc->sc_id_apple_fn)) {
1005                 if (flags & HIO_VARIABLE)
1006                         sc->sc_flags |= UKBD_FLAG_APPLE_FN;
1007                 DPRINTFN(1, "Found Apple FN-key\n");
1008         }
1009
1010         /* figure out event buffer */
1011         if (hid_locate(ptr, len,
1012             HID_USAGE2(HUP_KEYBOARD, 0x00),
1013             hid_input, 0, &sc->sc_loc_key[0], &flags,
1014             &sc->sc_id_loc_key[0])) {
1015                 if (flags & HIO_VARIABLE) {
1016                         DPRINTFN(1, "Ignoring keyboard event control\n");
1017                 } else {
1018                         sc->sc_loc_key_valid[0] |= 1;
1019                         DPRINTFN(1, "Found keyboard event array\n");
1020                 }
1021         }
1022
1023         /* figure out the keys */
1024         for (key = 1; key != UKBD_NKEYCODE; key++) {
1025                 if (hid_locate(ptr, len,
1026                     HID_USAGE2(HUP_KEYBOARD, key),
1027                     hid_input, 0, &sc->sc_loc_key[key], &flags,
1028                     &sc->sc_id_loc_key[key])) {
1029                         if (flags & HIO_VARIABLE) {
1030                                 sc->sc_loc_key_valid[key / 64] |=
1031                                     1ULL << (key % 64);
1032                                 DPRINTFN(1, "Found key 0x%02x\n", key);
1033                         }
1034                 }
1035         }
1036
1037         /* figure out leds on keyboard */
1038         sc->sc_led_size = hid_report_size(ptr, len,
1039             hid_output, NULL);
1040
1041         if (hid_locate(ptr, len,
1042             HID_USAGE2(HUP_LEDS, 0x01),
1043             hid_output, 0, &sc->sc_loc_numlock, &flags,
1044             &sc->sc_id_numlock)) {
1045                 if (flags & HIO_VARIABLE)
1046                         sc->sc_flags |= UKBD_FLAG_NUMLOCK;
1047                 DPRINTFN(1, "Found keyboard numlock\n");
1048         }
1049         if (hid_locate(ptr, len,
1050             HID_USAGE2(HUP_LEDS, 0x02),
1051             hid_output, 0, &sc->sc_loc_capslock, &flags,
1052             &sc->sc_id_capslock)) {
1053                 if (flags & HIO_VARIABLE)
1054                         sc->sc_flags |= UKBD_FLAG_CAPSLOCK;
1055                 DPRINTFN(1, "Found keyboard capslock\n");
1056         }
1057         if (hid_locate(ptr, len,
1058             HID_USAGE2(HUP_LEDS, 0x03),
1059             hid_output, 0, &sc->sc_loc_scrolllock, &flags,
1060             &sc->sc_id_scrolllock)) {
1061                 if (flags & HIO_VARIABLE)
1062                         sc->sc_flags |= UKBD_FLAG_SCROLLLOCK;
1063                 DPRINTFN(1, "Found keyboard scrolllock\n");
1064         }
1065 }
1066
1067 static int
1068 ukbd_attach(device_t dev)
1069 {
1070         struct ukbd_softc *sc = device_get_softc(dev);
1071         struct usb_attach_arg *uaa = device_get_ivars(dev);
1072         int unit = device_get_unit(dev);
1073         keyboard_t *kbd = &sc->sc_kbd;
1074         void *hid_ptr = NULL;
1075         usb_error_t err;
1076         uint16_t n;
1077         uint16_t hid_len;
1078 #ifdef EVDEV_SUPPORT
1079         struct evdev_dev *evdev;
1080         int i;
1081 #endif
1082 #ifdef USB_DEBUG
1083         int rate;
1084 #endif
1085         UKBD_LOCK_ASSERT();
1086
1087         kbd_init_struct(kbd, UKBD_DRIVER_NAME, KB_OTHER, unit, 0, 0, 0);
1088
1089         kbd->kb_data = (void *)sc;
1090
1091         device_set_usb_desc(dev);
1092
1093         sc->sc_udev = uaa->device;
1094         sc->sc_iface = uaa->iface;
1095         sc->sc_iface_index = uaa->info.bIfaceIndex;
1096         sc->sc_iface_no = uaa->info.bIfaceNum;
1097         sc->sc_mode = K_XLATE;
1098
1099         usb_callout_init_mtx(&sc->sc_callout, &Giant, 0);
1100
1101 #ifdef UKBD_NO_POLLING
1102         err = usbd_transfer_setup(uaa->device,
1103             &uaa->info.bIfaceIndex, sc->sc_xfer, ukbd_config,
1104             UKBD_N_TRANSFER, sc, &Giant);
1105 #else
1106         /*
1107          * Setup the UKBD USB transfers one by one, so they are memory
1108          * independent which allows for handling panics triggered by
1109          * the keyboard driver itself, typically via CTRL+ALT+ESC
1110          * sequences. Or if the USB keyboard driver was processing a
1111          * key at the moment of panic.
1112          */
1113         for (n = 0; n != UKBD_N_TRANSFER; n++) {
1114                 err = usbd_transfer_setup(uaa->device,
1115                     &uaa->info.bIfaceIndex, sc->sc_xfer + n, ukbd_config + n,
1116                     1, sc, &Giant);
1117                 if (err)
1118                         break;
1119         }
1120 #endif
1121
1122         if (err) {
1123                 DPRINTF("error=%s\n", usbd_errstr(err));
1124                 goto detach;
1125         }
1126         /* setup default keyboard maps */
1127
1128         sc->sc_keymap = key_map;
1129         sc->sc_accmap = accent_map;
1130         for (n = 0; n < UKBD_NFKEY; n++) {
1131                 sc->sc_fkeymap[n] = fkey_tab[n];
1132         }
1133
1134         kbd_set_maps(kbd, &sc->sc_keymap, &sc->sc_accmap,
1135             sc->sc_fkeymap, UKBD_NFKEY);
1136
1137         KBD_FOUND_DEVICE(kbd);
1138
1139         ukbd_clear_state(kbd);
1140
1141         /*
1142          * FIXME: set the initial value for lock keys in "sc_state"
1143          * according to the BIOS data?
1144          */
1145         KBD_PROBE_DONE(kbd);
1146
1147         /* get HID descriptor */
1148         err = usbd_req_get_hid_desc(uaa->device, NULL, &hid_ptr,
1149             &hid_len, M_TEMP, uaa->info.bIfaceIndex);
1150
1151         if (err == 0) {
1152                 DPRINTF("Parsing HID descriptor of %d bytes\n",
1153                     (int)hid_len);
1154
1155                 ukbd_parse_hid(sc, hid_ptr, hid_len);
1156
1157                 free(hid_ptr, M_TEMP);
1158         }
1159
1160         /* check if we should use the boot protocol */
1161         if (usb_test_quirk(uaa, UQ_KBD_BOOTPROTO) ||
1162             (err != 0) || ukbd_any_key_valid(sc) == false) {
1163                 DPRINTF("Forcing boot protocol\n");
1164
1165                 err = usbd_req_set_protocol(sc->sc_udev, NULL, 
1166                         sc->sc_iface_index, 0);
1167
1168                 if (err != 0) {
1169                         DPRINTF("Set protocol error=%s (ignored)\n",
1170                             usbd_errstr(err));
1171                 }
1172
1173                 ukbd_parse_hid(sc, ukbd_boot_desc, sizeof(ukbd_boot_desc));
1174         }
1175
1176         /* ignore if SETIDLE fails, hence it is not crucial */
1177         usbd_req_set_idle(sc->sc_udev, NULL, sc->sc_iface_index, 0, 0);
1178
1179         ukbd_ioctl(kbd, KDSETLED, (caddr_t)&sc->sc_state);
1180
1181         KBD_INIT_DONE(kbd);
1182
1183         if (kbd_register(kbd) < 0) {
1184                 goto detach;
1185         }
1186         KBD_CONFIG_DONE(kbd);
1187
1188         ukbd_enable(kbd);
1189
1190 #ifdef KBD_INSTALL_CDEV
1191         if (kbd_attach(kbd)) {
1192                 goto detach;
1193         }
1194 #endif
1195
1196 #ifdef EVDEV_SUPPORT
1197         evdev = evdev_alloc();
1198         evdev_set_name(evdev, device_get_desc(dev));
1199         evdev_set_phys(evdev, device_get_nameunit(dev));
1200         evdev_set_id(evdev, BUS_USB, uaa->info.idVendor,
1201            uaa->info.idProduct, 0);
1202         evdev_set_serial(evdev, usb_get_serial(uaa->device));
1203         evdev_set_methods(evdev, kbd, &ukbd_evdev_methods);
1204         evdev_support_event(evdev, EV_SYN);
1205         evdev_support_event(evdev, EV_KEY);
1206         if (sc->sc_flags & (UKBD_FLAG_NUMLOCK | UKBD_FLAG_CAPSLOCK |
1207                             UKBD_FLAG_SCROLLLOCK))
1208                 evdev_support_event(evdev, EV_LED);
1209         evdev_support_event(evdev, EV_REP);
1210
1211         for (i = 0x00; i <= 0xFF; i++)
1212                 evdev_support_key(evdev, evdev_hid2key(i));
1213         if (sc->sc_flags & UKBD_FLAG_NUMLOCK)
1214                 evdev_support_led(evdev, LED_NUML);
1215         if (sc->sc_flags & UKBD_FLAG_CAPSLOCK)
1216                 evdev_support_led(evdev, LED_CAPSL);
1217         if (sc->sc_flags & UKBD_FLAG_SCROLLLOCK)
1218                 evdev_support_led(evdev, LED_SCROLLL);
1219
1220         if (evdev_register_mtx(evdev, &Giant))
1221                 evdev_free(evdev);
1222         else
1223                 sc->sc_evdev = evdev;
1224 #endif
1225
1226         sc->sc_flags |= UKBD_FLAG_ATTACHED;
1227
1228         if (bootverbose) {
1229                 kbdd_diag(kbd, bootverbose);
1230         }
1231
1232 #ifdef USB_DEBUG
1233         /* check for polling rate override */
1234         rate = ukbd_pollrate;
1235         if (rate > 0) {
1236                 if (rate > 1000)
1237                         rate = 1;
1238                 else
1239                         rate = 1000 / rate;
1240
1241                 /* set new polling interval in ms */
1242                 usbd_xfer_set_interval(sc->sc_xfer[UKBD_INTR_DT_0], rate);
1243                 usbd_xfer_set_interval(sc->sc_xfer[UKBD_INTR_DT_1], rate);
1244         }
1245 #endif
1246         /* start the keyboard */
1247         usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_0]);
1248         usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_1]);
1249
1250         return (0);                     /* success */
1251
1252 detach:
1253         ukbd_detach(dev);
1254         return (ENXIO);                 /* error */
1255 }
1256
1257 static int
1258 ukbd_detach(device_t dev)
1259 {
1260         struct ukbd_softc *sc = device_get_softc(dev);
1261         int error;
1262
1263         UKBD_LOCK_ASSERT();
1264
1265         DPRINTF("\n");
1266
1267         sc->sc_flags |= UKBD_FLAG_GONE;
1268
1269         usb_callout_stop(&sc->sc_callout);
1270
1271         /* kill any stuck keys */
1272         if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
1273                 /* stop receiving events from the USB keyboard */
1274                 usbd_transfer_stop(sc->sc_xfer[UKBD_INTR_DT_0]);
1275                 usbd_transfer_stop(sc->sc_xfer[UKBD_INTR_DT_1]);
1276
1277                 /* release all leftover keys, if any */
1278                 memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1279
1280                 /* process releasing of all keys */
1281                 ukbd_interrupt(sc);
1282         }
1283
1284         ukbd_disable(&sc->sc_kbd);
1285
1286 #ifdef KBD_INSTALL_CDEV
1287         if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
1288                 error = kbd_detach(&sc->sc_kbd);
1289                 if (error) {
1290                         /* usb attach cannot return an error */
1291                         device_printf(dev, "WARNING: kbd_detach() "
1292                             "returned non-zero! (ignored)\n");
1293                 }
1294         }
1295 #endif
1296
1297 #ifdef EVDEV_SUPPORT
1298         evdev_free(sc->sc_evdev);
1299 #endif
1300
1301         if (KBD_IS_CONFIGURED(&sc->sc_kbd)) {
1302                 error = kbd_unregister(&sc->sc_kbd);
1303                 if (error) {
1304                         /* usb attach cannot return an error */
1305                         device_printf(dev, "WARNING: kbd_unregister() "
1306                             "returned non-zero! (ignored)\n");
1307                 }
1308         }
1309         sc->sc_kbd.kb_flags = 0;
1310
1311         usbd_transfer_unsetup(sc->sc_xfer, UKBD_N_TRANSFER);
1312
1313         usb_callout_drain(&sc->sc_callout);
1314
1315         DPRINTF("%s: disconnected\n",
1316             device_get_nameunit(dev));
1317
1318         return (0);
1319 }
1320
1321 static int
1322 ukbd_resume(device_t dev)
1323 {
1324         struct ukbd_softc *sc = device_get_softc(dev);
1325
1326         UKBD_LOCK_ASSERT();
1327
1328         ukbd_clear_state(&sc->sc_kbd);
1329
1330         return (0);
1331 }
1332
1333 #ifdef EVDEV_SUPPORT
1334 static void
1335 ukbd_ev_event(struct evdev_dev *evdev, uint16_t type, uint16_t code,
1336     int32_t value)
1337 {
1338         keyboard_t *kbd = evdev_get_softc(evdev);
1339
1340         if (evdev_rcpt_mask & EVDEV_RCPT_HW_KBD &&
1341             (type == EV_LED || type == EV_REP)) {
1342                 mtx_lock(&Giant);
1343                 kbd_ev_event(kbd, type, code, value);
1344                 mtx_unlock(&Giant);
1345         }
1346 }
1347 #endif
1348
1349 /* early keyboard probe, not supported */
1350 static int
1351 ukbd_configure(int flags)
1352 {
1353         return (0);
1354 }
1355
1356 /* detect a keyboard, not used */
1357 static int
1358 ukbd__probe(int unit, void *arg, int flags)
1359 {
1360         return (ENXIO);
1361 }
1362
1363 /* reset and initialize the device, not used */
1364 static int
1365 ukbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
1366 {
1367         return (ENXIO);
1368 }
1369
1370 /* test the interface to the device, not used */
1371 static int
1372 ukbd_test_if(keyboard_t *kbd)
1373 {
1374         return (0);
1375 }
1376
1377 /* finish using this keyboard, not used */
1378 static int
1379 ukbd_term(keyboard_t *kbd)
1380 {
1381         return (ENXIO);
1382 }
1383
1384 /* keyboard interrupt routine, not used */
1385 static int
1386 ukbd_intr(keyboard_t *kbd, void *arg)
1387 {
1388         return (0);
1389 }
1390
1391 /* lock the access to the keyboard, not used */
1392 static int
1393 ukbd_lock(keyboard_t *kbd, int lock)
1394 {
1395         return (1);
1396 }
1397
1398 /*
1399  * Enable the access to the device; until this function is called,
1400  * the client cannot read from the keyboard.
1401  */
1402 static int
1403 ukbd_enable(keyboard_t *kbd)
1404 {
1405
1406         UKBD_LOCK();
1407         KBD_ACTIVATE(kbd);
1408         UKBD_UNLOCK();
1409
1410         return (0);
1411 }
1412
1413 /* disallow the access to the device */
1414 static int
1415 ukbd_disable(keyboard_t *kbd)
1416 {
1417
1418         UKBD_LOCK();
1419         KBD_DEACTIVATE(kbd);
1420         UKBD_UNLOCK();
1421
1422         return (0);
1423 }
1424
1425 /* check if data is waiting */
1426 /* Currently unused. */
1427 static int
1428 ukbd_check(keyboard_t *kbd)
1429 {
1430         struct ukbd_softc *sc = kbd->kb_data;
1431
1432         UKBD_LOCK_ASSERT();
1433
1434         if (!KBD_IS_ACTIVE(kbd))
1435                 return (0);
1436
1437         if (sc->sc_flags & UKBD_FLAG_POLLING)
1438                 ukbd_do_poll(sc, 0);
1439
1440 #ifdef UKBD_EMULATE_ATSCANCODE
1441         if (sc->sc_buffered_char[0]) {
1442                 return (1);
1443         }
1444 #endif
1445         if (sc->sc_inputs > 0) {
1446                 return (1);
1447         }
1448         return (0);
1449 }
1450
1451 /* check if char is waiting */
1452 static int
1453 ukbd_check_char_locked(keyboard_t *kbd)
1454 {
1455         struct ukbd_softc *sc = kbd->kb_data;
1456
1457         UKBD_LOCK_ASSERT();
1458
1459         if (!KBD_IS_ACTIVE(kbd))
1460                 return (0);
1461
1462         if ((sc->sc_composed_char > 0) &&
1463             (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1464                 return (1);
1465         }
1466         return (ukbd_check(kbd));
1467 }
1468
1469 static int
1470 ukbd_check_char(keyboard_t *kbd)
1471 {
1472         int result;
1473
1474         UKBD_LOCK();
1475         result = ukbd_check_char_locked(kbd);
1476         UKBD_UNLOCK();
1477
1478         return (result);
1479 }
1480
1481 /* read one byte from the keyboard if it's allowed */
1482 /* Currently unused. */
1483 static int
1484 ukbd_read(keyboard_t *kbd, int wait)
1485 {
1486         struct ukbd_softc *sc = kbd->kb_data;
1487         int32_t usbcode;
1488 #ifdef UKBD_EMULATE_ATSCANCODE
1489         uint32_t keycode;
1490         uint32_t scancode;
1491
1492 #endif
1493
1494         UKBD_LOCK_ASSERT();
1495
1496         if (!KBD_IS_ACTIVE(kbd))
1497                 return (-1);
1498
1499 #ifdef UKBD_EMULATE_ATSCANCODE
1500         if (sc->sc_buffered_char[0]) {
1501                 scancode = sc->sc_buffered_char[0];
1502                 if (scancode & SCAN_PREFIX) {
1503                         sc->sc_buffered_char[0] &= ~SCAN_PREFIX;
1504                         return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1505                 }
1506                 sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1507                 sc->sc_buffered_char[1] = 0;
1508                 return (scancode);
1509         }
1510 #endif                                  /* UKBD_EMULATE_ATSCANCODE */
1511
1512         /* XXX */
1513         usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1514         if (!KBD_IS_ACTIVE(kbd) || (usbcode == -1))
1515                 return (-1);
1516
1517         ++(kbd->kb_count);
1518
1519 #ifdef UKBD_EMULATE_ATSCANCODE
1520         keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1521         if (keycode == NN) {
1522                 return -1;
1523         }
1524         return (ukbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1525             (usbcode & KEY_RELEASE)));
1526 #else                                   /* !UKBD_EMULATE_ATSCANCODE */
1527         return (usbcode);
1528 #endif                                  /* UKBD_EMULATE_ATSCANCODE */
1529 }
1530
1531 /* read char from the keyboard */
1532 static uint32_t
1533 ukbd_read_char_locked(keyboard_t *kbd, int wait)
1534 {
1535         struct ukbd_softc *sc = kbd->kb_data;
1536         uint32_t action;
1537         uint32_t keycode;
1538         int32_t usbcode;
1539 #ifdef UKBD_EMULATE_ATSCANCODE
1540         uint32_t scancode;
1541 #endif
1542
1543         UKBD_LOCK_ASSERT();
1544
1545         if (!KBD_IS_ACTIVE(kbd))
1546                 return (NOKEY);
1547
1548 next_code:
1549
1550         /* do we have a composed char to return ? */
1551
1552         if ((sc->sc_composed_char > 0) &&
1553             (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1554                 action = sc->sc_composed_char;
1555                 sc->sc_composed_char = 0;
1556
1557                 if (action > 0xFF) {
1558                         goto errkey;
1559                 }
1560                 goto done;
1561         }
1562 #ifdef UKBD_EMULATE_ATSCANCODE
1563
1564         /* do we have a pending raw scan code? */
1565
1566         if (sc->sc_mode == K_RAW) {
1567                 scancode = sc->sc_buffered_char[0];
1568                 if (scancode) {
1569                         if (scancode & SCAN_PREFIX) {
1570                                 sc->sc_buffered_char[0] = (scancode & ~SCAN_PREFIX);
1571                                 return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1572                         }
1573                         sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1574                         sc->sc_buffered_char[1] = 0;
1575                         return (scancode);
1576                 }
1577         }
1578 #endif                                  /* UKBD_EMULATE_ATSCANCODE */
1579
1580         /* see if there is something in the keyboard port */
1581         /* XXX */
1582         usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1583         if (usbcode == -1) {
1584                 return (NOKEY);
1585         }
1586         ++kbd->kb_count;
1587
1588 #ifdef UKBD_EMULATE_ATSCANCODE
1589         /* USB key index -> key code -> AT scan code */
1590         keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1591         if (keycode == NN) {
1592                 return (NOKEY);
1593         }
1594         /* return an AT scan code for the K_RAW mode */
1595         if (sc->sc_mode == K_RAW) {
1596                 return (ukbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1597                     (usbcode & KEY_RELEASE)));
1598         }
1599 #else                                   /* !UKBD_EMULATE_ATSCANCODE */
1600
1601         /* return the byte as is for the K_RAW mode */
1602         if (sc->sc_mode == K_RAW) {
1603                 return (usbcode);
1604         }
1605         /* USB key index -> key code */
1606         keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1607         if (keycode == NN) {
1608                 return (NOKEY);
1609         }
1610 #endif                                  /* UKBD_EMULATE_ATSCANCODE */
1611
1612         switch (keycode) {
1613         case 0x38:                      /* left alt (compose key) */
1614                 if (usbcode & KEY_RELEASE) {
1615                         if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1616                                 sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1617
1618                                 if (sc->sc_composed_char > 0xFF) {
1619                                         sc->sc_composed_char = 0;
1620                                 }
1621                         }
1622                 } else {
1623                         if (!(sc->sc_flags & UKBD_FLAG_COMPOSE)) {
1624                                 sc->sc_flags |= UKBD_FLAG_COMPOSE;
1625                                 sc->sc_composed_char = 0;
1626                         }
1627                 }
1628                 break;
1629         }
1630
1631         /* return the key code in the K_CODE mode */
1632         if (usbcode & KEY_RELEASE) {
1633                 keycode |= SCAN_RELEASE;
1634         }
1635         if (sc->sc_mode == K_CODE) {
1636                 return (keycode);
1637         }
1638         /* compose a character code */
1639         if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1640                 switch (keycode) {
1641                         /* key pressed, process it */
1642                 case 0x47:
1643                 case 0x48:
1644                 case 0x49:              /* keypad 7,8,9 */
1645                         sc->sc_composed_char *= 10;
1646                         sc->sc_composed_char += keycode - 0x40;
1647                         goto check_composed;
1648
1649                 case 0x4B:
1650                 case 0x4C:
1651                 case 0x4D:              /* keypad 4,5,6 */
1652                         sc->sc_composed_char *= 10;
1653                         sc->sc_composed_char += keycode - 0x47;
1654                         goto check_composed;
1655
1656                 case 0x4F:
1657                 case 0x50:
1658                 case 0x51:              /* keypad 1,2,3 */
1659                         sc->sc_composed_char *= 10;
1660                         sc->sc_composed_char += keycode - 0x4E;
1661                         goto check_composed;
1662
1663                 case 0x52:              /* keypad 0 */
1664                         sc->sc_composed_char *= 10;
1665                         goto check_composed;
1666
1667                         /* key released, no interest here */
1668                 case SCAN_RELEASE | 0x47:
1669                 case SCAN_RELEASE | 0x48:
1670                 case SCAN_RELEASE | 0x49:       /* keypad 7,8,9 */
1671                 case SCAN_RELEASE | 0x4B:
1672                 case SCAN_RELEASE | 0x4C:
1673                 case SCAN_RELEASE | 0x4D:       /* keypad 4,5,6 */
1674                 case SCAN_RELEASE | 0x4F:
1675                 case SCAN_RELEASE | 0x50:
1676                 case SCAN_RELEASE | 0x51:       /* keypad 1,2,3 */
1677                 case SCAN_RELEASE | 0x52:       /* keypad 0 */
1678                         goto next_code;
1679
1680                 case 0x38:              /* left alt key */
1681                         break;
1682
1683                 default:
1684                         if (sc->sc_composed_char > 0) {
1685                                 sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1686                                 sc->sc_composed_char = 0;
1687                                 goto errkey;
1688                         }
1689                         break;
1690                 }
1691         }
1692         /* keycode to key action */
1693         action = genkbd_keyaction(kbd, SCAN_CHAR(keycode),
1694             (keycode & SCAN_RELEASE),
1695             &sc->sc_state, &sc->sc_accents);
1696         if (action == NOKEY) {
1697                 goto next_code;
1698         }
1699 done:
1700         return (action);
1701
1702 check_composed:
1703         if (sc->sc_composed_char <= 0xFF) {
1704                 goto next_code;
1705         }
1706 errkey:
1707         return (ERRKEY);
1708 }
1709
1710 /* Currently wait is always false. */
1711 static uint32_t
1712 ukbd_read_char(keyboard_t *kbd, int wait)
1713 {
1714         uint32_t keycode;
1715
1716         UKBD_LOCK();
1717         keycode = ukbd_read_char_locked(kbd, wait);
1718         UKBD_UNLOCK();
1719
1720         return (keycode);
1721 }
1722
1723 /* some useful control functions */
1724 static int
1725 ukbd_ioctl_locked(keyboard_t *kbd, u_long cmd, caddr_t arg)
1726 {
1727         struct ukbd_softc *sc = kbd->kb_data;
1728         int i;
1729 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1730     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1731         int ival;
1732
1733 #endif
1734
1735         UKBD_LOCK_ASSERT();
1736
1737         switch (cmd) {
1738         case KDGKBMODE:         /* get keyboard mode */
1739                 *(int *)arg = sc->sc_mode;
1740                 break;
1741 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1742     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1743         case _IO('K', 7):
1744                 ival = IOCPARM_IVAL(arg);
1745                 arg = (caddr_t)&ival;
1746                 /* FALLTHROUGH */
1747 #endif
1748         case KDSKBMODE:         /* set keyboard mode */
1749                 switch (*(int *)arg) {
1750                 case K_XLATE:
1751                         if (sc->sc_mode != K_XLATE) {
1752                                 /* make lock key state and LED state match */
1753                                 sc->sc_state &= ~LOCK_MASK;
1754                                 sc->sc_state |= KBD_LED_VAL(kbd);
1755                         }
1756                         /* FALLTHROUGH */
1757                 case K_RAW:
1758                 case K_CODE:
1759                         if (sc->sc_mode != *(int *)arg) {
1760                                 if ((sc->sc_flags & UKBD_FLAG_POLLING) == 0)
1761                                         ukbd_clear_state(kbd);
1762                                 sc->sc_mode = *(int *)arg;
1763                         }
1764                         break;
1765                 default:
1766                         return (EINVAL);
1767                 }
1768                 break;
1769
1770         case KDGETLED:                  /* get keyboard LED */
1771                 *(int *)arg = KBD_LED_VAL(kbd);
1772                 break;
1773 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1774     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1775         case _IO('K', 66):
1776                 ival = IOCPARM_IVAL(arg);
1777                 arg = (caddr_t)&ival;
1778                 /* FALLTHROUGH */
1779 #endif
1780         case KDSETLED:                  /* set keyboard LED */
1781                 /* NOTE: lock key state in "sc_state" won't be changed */
1782                 if (*(int *)arg & ~LOCK_MASK)
1783                         return (EINVAL);
1784
1785                 i = *(int *)arg;
1786
1787                 /* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1788                 if (sc->sc_mode == K_XLATE &&
1789                     kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1790                         if (i & ALKED)
1791                                 i |= CLKED;
1792                         else
1793                                 i &= ~CLKED;
1794                 }
1795                 if (KBD_HAS_DEVICE(kbd))
1796                         ukbd_set_leds(sc, i);
1797
1798                 KBD_LED_VAL(kbd) = *(int *)arg;
1799                 break;
1800         case KDGKBSTATE:                /* get lock key state */
1801                 *(int *)arg = sc->sc_state & LOCK_MASK;
1802                 break;
1803 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1804     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1805         case _IO('K', 20):
1806                 ival = IOCPARM_IVAL(arg);
1807                 arg = (caddr_t)&ival;
1808                 /* FALLTHROUGH */
1809 #endif
1810         case KDSKBSTATE:                /* set lock key state */
1811                 if (*(int *)arg & ~LOCK_MASK) {
1812                         return (EINVAL);
1813                 }
1814                 sc->sc_state &= ~LOCK_MASK;
1815                 sc->sc_state |= *(int *)arg;
1816
1817                 /* set LEDs and quit */
1818                 return (ukbd_ioctl(kbd, KDSETLED, arg));
1819
1820         case KDSETREPEAT:               /* set keyboard repeat rate (new
1821                                          * interface) */
1822                 if (!KBD_HAS_DEVICE(kbd)) {
1823                         return (0);
1824                 }
1825                 /*
1826                  * Convert negative, zero and tiny args to the same limits
1827                  * as atkbd.  We could support delays of 1 msec, but
1828                  * anything much shorter than the shortest atkbd value
1829                  * of 250.34 is almost unusable as well as incompatible.
1830                  */
1831                 kbd->kb_delay1 = imax(((int *)arg)[0], 250);
1832                 kbd->kb_delay2 = imax(((int *)arg)[1], 34);
1833 #ifdef EVDEV_SUPPORT
1834                 if (sc->sc_evdev != NULL)
1835                         evdev_push_repeats(sc->sc_evdev, kbd);
1836 #endif
1837                 return (0);
1838
1839 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1840     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1841         case _IO('K', 67):
1842                 ival = IOCPARM_IVAL(arg);
1843                 arg = (caddr_t)&ival;
1844                 /* FALLTHROUGH */
1845 #endif
1846         case KDSETRAD:                  /* set keyboard repeat rate (old
1847                                          * interface) */
1848                 return (ukbd_set_typematic(kbd, *(int *)arg));
1849
1850         case PIO_KEYMAP:                /* set keyboard translation table */
1851         case OPIO_KEYMAP:               /* set keyboard translation table
1852                                          * (compat) */
1853         case PIO_KEYMAPENT:             /* set keyboard translation table
1854                                          * entry */
1855         case PIO_DEADKEYMAP:            /* set accent key translation table */
1856                 sc->sc_accents = 0;
1857                 /* FALLTHROUGH */
1858         default:
1859                 return (genkbd_commonioctl(kbd, cmd, arg));
1860         }
1861
1862         return (0);
1863 }
1864
1865 static int
1866 ukbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
1867 {
1868         int result;
1869
1870         /*
1871          * XXX Check if someone is calling us from a critical section:
1872          */
1873         if (curthread->td_critnest != 0)
1874                 return (EDEADLK);
1875
1876         /*
1877          * XXX KDGKBSTATE, KDSKBSTATE and KDSETLED can be called from any
1878          * context where printf(9) can be called, which among other things
1879          * includes interrupt filters and threads with any kinds of locks
1880          * already held.  For this reason it would be dangerous to acquire
1881          * the Giant here unconditionally.  On the other hand we have to
1882          * have it to handle the ioctl.
1883          * So we make our best effort to auto-detect whether we can grab
1884          * the Giant or not.  Blame syscons(4) for this.
1885          */
1886         switch (cmd) {
1887         case KDGKBSTATE:
1888         case KDSKBSTATE:
1889         case KDSETLED:
1890                 if (!mtx_owned(&Giant) && !USB_IN_POLLING_MODE_FUNC())
1891                         return (EDEADLK);       /* best I could come up with */
1892                 /* FALLTHROUGH */
1893         default:
1894                 UKBD_LOCK();
1895                 result = ukbd_ioctl_locked(kbd, cmd, arg);
1896                 UKBD_UNLOCK();
1897                 return (result);
1898         }
1899 }
1900
1901 /* clear the internal state of the keyboard */
1902 static void
1903 ukbd_clear_state(keyboard_t *kbd)
1904 {
1905         struct ukbd_softc *sc = kbd->kb_data;
1906
1907         UKBD_LOCK_ASSERT();
1908
1909         sc->sc_flags &= ~(UKBD_FLAG_COMPOSE | UKBD_FLAG_POLLING);
1910         sc->sc_state &= LOCK_MASK;      /* preserve locking key state */
1911         sc->sc_accents = 0;
1912         sc->sc_composed_char = 0;
1913 #ifdef UKBD_EMULATE_ATSCANCODE
1914         sc->sc_buffered_char[0] = 0;
1915         sc->sc_buffered_char[1] = 0;
1916 #endif
1917         memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1918         memset(&sc->sc_odata, 0, sizeof(sc->sc_odata));
1919         sc->sc_repeat_time = 0;
1920         sc->sc_repeat_key = 0;
1921 }
1922
1923 /* save the internal state, not used */
1924 static int
1925 ukbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1926 {
1927         return (len == 0) ? 1 : -1;
1928 }
1929
1930 /* set the internal state, not used */
1931 static int
1932 ukbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1933 {
1934         return (EINVAL);
1935 }
1936
1937 static int
1938 ukbd_poll(keyboard_t *kbd, int on)
1939 {
1940         struct ukbd_softc *sc = kbd->kb_data;
1941
1942         UKBD_LOCK();
1943         /*
1944          * Keep a reference count on polling to allow recursive
1945          * cngrab() during a panic for example.
1946          */
1947         if (on)
1948                 sc->sc_polling++;
1949         else if (sc->sc_polling > 0)
1950                 sc->sc_polling--;
1951
1952         if (sc->sc_polling != 0) {
1953                 sc->sc_flags |= UKBD_FLAG_POLLING;
1954                 sc->sc_poll_thread = curthread;
1955         } else {
1956                 sc->sc_flags &= ~UKBD_FLAG_POLLING;
1957                 sc->sc_delay = 0;
1958         }
1959         UKBD_UNLOCK();
1960
1961         return (0);
1962 }
1963
1964 /* local functions */
1965
1966 static void
1967 ukbd_set_leds(struct ukbd_softc *sc, uint8_t leds)
1968 {
1969
1970         UKBD_LOCK_ASSERT();
1971         DPRINTF("leds=0x%02x\n", leds);
1972
1973         sc->sc_leds = leds;
1974         sc->sc_flags |= UKBD_FLAG_SET_LEDS;
1975
1976         /* start transfer, if not already started */
1977
1978         usbd_transfer_start(sc->sc_xfer[UKBD_CTRL_LED]);
1979 }
1980
1981 static int
1982 ukbd_set_typematic(keyboard_t *kbd, int code)
1983 {
1984 #ifdef EVDEV_SUPPORT
1985         struct ukbd_softc *sc = kbd->kb_data;
1986 #endif
1987         static const int delays[] = {250, 500, 750, 1000};
1988         static const int rates[] = {34, 38, 42, 46, 50, 55, 59, 63,
1989                 68, 76, 84, 92, 100, 110, 118, 126,
1990                 136, 152, 168, 184, 200, 220, 236, 252,
1991         272, 304, 336, 368, 400, 440, 472, 504};
1992
1993         if (code & ~0x7f) {
1994                 return (EINVAL);
1995         }
1996         kbd->kb_delay1 = delays[(code >> 5) & 3];
1997         kbd->kb_delay2 = rates[code & 0x1f];
1998 #ifdef EVDEV_SUPPORT
1999         if (sc->sc_evdev != NULL)
2000                 evdev_push_repeats(sc->sc_evdev, kbd);
2001 #endif
2002         return (0);
2003 }
2004
2005 #ifdef UKBD_EMULATE_ATSCANCODE
2006 static uint32_t
2007 ukbd_atkeycode(int usbcode, const uint64_t *bitmap)
2008 {
2009         uint32_t keycode;
2010
2011         keycode = ukbd_trtab[KEY_INDEX(usbcode)];
2012
2013         /*
2014          * Translate Alt-PrintScreen to SysRq.
2015          *
2016          * Some or all AT keyboards connected through USB have already
2017          * mapped Alted PrintScreens to an unusual usbcode (0x8a).
2018          * ukbd_trtab translates this to 0x7e, and key2scan() would
2019          * translate that to 0x79 (Intl' 4).  Assume that if we have
2020          * an Alted 0x7e here then it actually is an Alted PrintScreen.
2021          *
2022          * The usual usbcode for all PrintScreens is 0x46.  ukbd_trtab
2023          * translates this to 0x5c, so the Alt check to classify 0x5c
2024          * is routine.
2025          */
2026         if ((keycode == 0x5c || keycode == 0x7e) &&
2027             (UKBD_KEY_PRESSED(bitmap, 0xe2 /* ALT-L */) ||
2028              UKBD_KEY_PRESSED(bitmap, 0xe6 /* ALT-R */)))
2029                 return (0x54);
2030         return (keycode);
2031 }
2032
2033 static int
2034 ukbd_key2scan(struct ukbd_softc *sc, int code, const uint64_t *bitmap, int up)
2035 {
2036         static const int scan[] = {
2037                 /* 89 */
2038                 0x11c,  /* Enter */
2039                 /* 90-99 */
2040                 0x11d,  /* Ctrl-R */
2041                 0x135,  /* Divide */
2042                 0x137,  /* PrintScreen */
2043                 0x138,  /* Alt-R */
2044                 0x147,  /* Home */
2045                 0x148,  /* Up */
2046                 0x149,  /* PageUp */
2047                 0x14b,  /* Left */
2048                 0x14d,  /* Right */
2049                 0x14f,  /* End */
2050                 /* 100-109 */
2051                 0x150,  /* Down */
2052                 0x151,  /* PageDown */
2053                 0x152,  /* Insert */
2054                 0x153,  /* Delete */
2055                 0x146,  /* Pause/Break */
2056                 0x15b,  /* Win_L(Super_L) */
2057                 0x15c,  /* Win_R(Super_R) */
2058                 0x15d,  /* Application(Menu) */
2059
2060                 /* SUN TYPE 6 USB KEYBOARD */
2061                 0x168,  /* Sun Type 6 Help */
2062                 0x15e,  /* Sun Type 6 Stop */
2063                 /* 110 - 119 */
2064                 0x15f,  /* Sun Type 6 Again */
2065                 0x160,  /* Sun Type 6 Props */
2066                 0x161,  /* Sun Type 6 Undo */
2067                 0x162,  /* Sun Type 6 Front */
2068                 0x163,  /* Sun Type 6 Copy */
2069                 0x164,  /* Sun Type 6 Open */
2070                 0x165,  /* Sun Type 6 Paste */
2071                 0x166,  /* Sun Type 6 Find */
2072                 0x167,  /* Sun Type 6 Cut */
2073                 0x125,  /* Sun Type 6 Mute */
2074                 /* 120 - 130 */
2075                 0x11f,  /* Sun Type 6 VolumeDown */
2076                 0x11e,  /* Sun Type 6 VolumeUp */
2077                 0x120,  /* Sun Type 6 PowerDown */
2078
2079                 /* Japanese 106/109 keyboard */
2080                 0x73,   /* Keyboard Intl' 1 (backslash / underscore) */
2081                 0x70,   /* Keyboard Intl' 2 (Katakana / Hiragana) */
2082                 0x7d,   /* Keyboard Intl' 3 (Yen sign) (Not using in jp106/109) */
2083                 0x79,   /* Keyboard Intl' 4 (Henkan) */
2084                 0x7b,   /* Keyboard Intl' 5 (Muhenkan) */
2085                 0x5c,   /* Keyboard Intl' 6 (Keypad ,) (For PC-9821 layout) */
2086                 0x71,   /* Apple Keyboard JIS (Kana) */
2087                 0x72,   /* Apple Keyboard JIS (Eisu) */
2088         };
2089
2090         if ((code >= 89) && (code < (int)(89 + nitems(scan)))) {
2091                 code = scan[code - 89];
2092         }
2093         /* PrintScreen */
2094         if (code == 0x137 && (!(
2095             UKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
2096             UKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */) ||
2097             UKBD_KEY_PRESSED(bitmap, 0xe1 /* SHIFT-L */) ||
2098             UKBD_KEY_PRESSED(bitmap, 0xe5 /* SHIFT-R */)))) {
2099                 code |= SCAN_PREFIX_SHIFT;
2100         }
2101         /* Pause/Break */
2102         if ((code == 0x146) && (!(
2103             UKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
2104             UKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */)))) {
2105                 code = (0x45 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL);
2106         }
2107         code |= (up ? SCAN_RELEASE : SCAN_PRESS);
2108
2109         if (code & SCAN_PREFIX) {
2110                 if (code & SCAN_PREFIX_CTL) {
2111                         /* Ctrl */
2112                         sc->sc_buffered_char[0] = (0x1d | (code & SCAN_RELEASE));
2113                         sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX);
2114                 } else if (code & SCAN_PREFIX_SHIFT) {
2115                         /* Shift */
2116                         sc->sc_buffered_char[0] = (0x2a | (code & SCAN_RELEASE));
2117                         sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX_SHIFT);
2118                 } else {
2119                         sc->sc_buffered_char[0] = (code & ~SCAN_PREFIX);
2120                         sc->sc_buffered_char[1] = 0;
2121                 }
2122                 return ((code & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
2123         }
2124         return (code);
2125
2126 }
2127
2128 #endif                                  /* UKBD_EMULATE_ATSCANCODE */
2129
2130 static keyboard_switch_t ukbdsw = {
2131         .probe = &ukbd__probe,
2132         .init = &ukbd_init,
2133         .term = &ukbd_term,
2134         .intr = &ukbd_intr,
2135         .test_if = &ukbd_test_if,
2136         .enable = &ukbd_enable,
2137         .disable = &ukbd_disable,
2138         .read = &ukbd_read,
2139         .check = &ukbd_check,
2140         .read_char = &ukbd_read_char,
2141         .check_char = &ukbd_check_char,
2142         .ioctl = &ukbd_ioctl,
2143         .lock = &ukbd_lock,
2144         .clear_state = &ukbd_clear_state,
2145         .get_state = &ukbd_get_state,
2146         .set_state = &ukbd_set_state,
2147         .poll = &ukbd_poll,
2148 };
2149
2150 KEYBOARD_DRIVER(ukbd, ukbdsw, ukbd_configure);
2151
2152 static int
2153 ukbd_driver_load(module_t mod, int what, void *arg)
2154 {
2155         switch (what) {
2156         case MOD_LOAD:
2157                 kbd_add_driver(&ukbd_kbd_driver);
2158                 break;
2159         case MOD_UNLOAD:
2160                 kbd_delete_driver(&ukbd_kbd_driver);
2161                 break;
2162         }
2163         return (0);
2164 }
2165
2166 static devclass_t ukbd_devclass;
2167
2168 static device_method_t ukbd_methods[] = {
2169         DEVMETHOD(device_probe, ukbd_probe),
2170         DEVMETHOD(device_attach, ukbd_attach),
2171         DEVMETHOD(device_detach, ukbd_detach),
2172         DEVMETHOD(device_resume, ukbd_resume),
2173
2174         DEVMETHOD_END
2175 };
2176
2177 static driver_t ukbd_driver = {
2178         .name = "ukbd",
2179         .methods = ukbd_methods,
2180         .size = sizeof(struct ukbd_softc),
2181 };
2182
2183 DRIVER_MODULE(ukbd, uhub, ukbd_driver, ukbd_devclass, ukbd_driver_load, 0);
2184 MODULE_DEPEND(ukbd, usb, 1, 1, 1);
2185 #ifdef EVDEV_SUPPORT
2186 MODULE_DEPEND(ukbd, evdev, 1, 1, 1);
2187 #endif
2188 MODULE_VERSION(ukbd, 1);
2189 USB_PNP_HOST_INFO(ukbd_devs);