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