]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/dev/usb/input/ukbd.c
Copy head to stable/8 as part of 8.0 Release cycle.
[FreeBSD/stable/8.git] / sys / dev / usb / input / ukbd.c
1 #include <sys/cdefs.h>
2 __FBSDID("$FreeBSD$");
3
4
5 /*-
6  * Copyright (c) 1998 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Lennart Augustsson (lennart@augustsson.net) at
11  * Carlstedt Research & Technology.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *        This product includes software developed by the NetBSD
24  *        Foundation, Inc. and its contributors.
25  * 4. Neither the name of The NetBSD Foundation nor the names of its
26  *    contributors may be used to endorse or promote products derived
27  *    from this software without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39  * POSSIBILITY OF SUCH DAMAGE.
40  *
41  */
42
43 /*
44  * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf
45  */
46
47 #include "opt_compat.h"
48 #include "opt_kbd.h"
49 #include "opt_ukbd.h"
50
51 #include <sys/stdint.h>
52 #include <sys/stddef.h>
53 #include <sys/param.h>
54 #include <sys/queue.h>
55 #include <sys/types.h>
56 #include <sys/systm.h>
57 #include <sys/kernel.h>
58 #include <sys/bus.h>
59 #include <sys/linker_set.h>
60 #include <sys/module.h>
61 #include <sys/lock.h>
62 #include <sys/mutex.h>
63 #include <sys/condvar.h>
64 #include <sys/sysctl.h>
65 #include <sys/sx.h>
66 #include <sys/unistd.h>
67 #include <sys/callout.h>
68 #include <sys/malloc.h>
69 #include <sys/priv.h>
70
71 #include <dev/usb/usb.h>
72 #include <dev/usb/usbdi.h>
73 #include <dev/usb/usbdi_util.h>
74 #include <dev/usb/usbhid.h>
75
76 #define USB_DEBUG_VAR ukbd_debug
77 #include <dev/usb/usb_debug.h>
78
79 #include <dev/usb/quirk/usb_quirk.h>
80
81 #include <sys/ioccom.h>
82 #include <sys/filio.h>
83 #include <sys/tty.h>
84 #include <sys/kbio.h>
85
86 #include <dev/kbd/kbdreg.h>
87
88 /* the initial key map, accent map and fkey strings */
89 #if defined(UKBD_DFLT_KEYMAP) && !defined(KLD_MODULE)
90 #define KBD_DFLT_KEYMAP
91 #include "ukbdmap.h"
92 #endif
93
94 /* the following file must be included after "ukbdmap.h" */
95 #include <dev/kbd/kbdtables.h>
96
97 #if USB_DEBUG
98 static int ukbd_debug = 0;
99
100 SYSCTL_NODE(_hw_usb, OID_AUTO, ukbd, CTLFLAG_RW, 0, "USB ukbd");
101 SYSCTL_INT(_hw_usb_ukbd, OID_AUTO, debug, CTLFLAG_RW,
102     &ukbd_debug, 0, "Debug level");
103 #endif
104
105 #define UPROTO_BOOT_KEYBOARD 1
106
107 #define UKBD_EMULATE_ATSCANCODE        1
108 #define UKBD_DRIVER_NAME          "ukbd"
109 #define UKBD_NMOD                     8 /* units */
110 #define UKBD_NKEYCODE                 6 /* units */
111 #define UKBD_IN_BUF_SIZE  (2*(UKBD_NMOD + (2*UKBD_NKEYCODE)))   /* bytes */
112 #define UKBD_IN_BUF_FULL  (UKBD_IN_BUF_SIZE / 2)        /* bytes */
113 #define UKBD_NFKEY        (sizeof(fkey_tab)/sizeof(fkey_tab[0]))        /* units */
114
115 struct ukbd_data {
116         uint8_t modifiers;
117 #define MOD_CONTROL_L   0x01
118 #define MOD_CONTROL_R   0x10
119 #define MOD_SHIFT_L     0x02
120 #define MOD_SHIFT_R     0x20
121 #define MOD_ALT_L       0x04
122 #define MOD_ALT_R       0x40
123 #define MOD_WIN_L       0x08
124 #define MOD_WIN_R       0x80
125         uint8_t reserved;
126         uint8_t keycode[UKBD_NKEYCODE];
127         uint8_t exten[8];
128 };
129
130 enum {
131         UKBD_INTR_DT,
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         struct hid_location sc_loc_apple_eject;
142         struct hid_location sc_loc_apple_fn;
143         struct usb_callout sc_callout;
144         struct ukbd_data sc_ndata;
145         struct ukbd_data sc_odata;
146
147         struct usb_device *sc_udev;
148         struct usb_interface *sc_iface;
149         struct usb_xfer *sc_xfer[UKBD_N_TRANSFER];
150
151         uint32_t sc_ntime[UKBD_NKEYCODE];
152         uint32_t sc_otime[UKBD_NKEYCODE];
153         uint32_t sc_input[UKBD_IN_BUF_SIZE];    /* input buffer */
154         uint32_t sc_time_ms;
155         uint32_t sc_composed_char;      /* composed char code, if non-zero */
156 #ifdef UKBD_EMULATE_ATSCANCODE
157         uint32_t sc_buffered_char[2];
158 #endif
159         uint32_t sc_flags;              /* flags */
160 #define UKBD_FLAG_COMPOSE       0x0001
161 #define UKBD_FLAG_POLLING       0x0002
162 #define UKBD_FLAG_SET_LEDS      0x0004
163 #define UKBD_FLAG_ATTACHED      0x0010
164 #define UKBD_FLAG_GONE          0x0020
165 #define UKBD_FLAG_APPLE_EJECT   0x0040
166 #define UKBD_FLAG_APPLE_FN      0x0080
167 #define UKBD_FLAG_APPLE_SWAP    0x0100
168
169         int32_t sc_mode;                /* input mode (K_XLATE,K_RAW,K_CODE) */
170         int32_t sc_state;               /* shift/lock key state */
171         int32_t sc_accents;             /* accent key index (> 0) */
172
173         uint16_t sc_inputs;
174         uint16_t sc_inputhead;
175         uint16_t sc_inputtail;
176
177         uint8_t sc_leds;                /* store for async led requests */
178         uint8_t sc_iface_index;
179         uint8_t sc_iface_no;
180         uint8_t sc_kbd_id;
181         uint8_t sc_led_id;
182 };
183
184 #define KEY_ERROR         0x01
185
186 #define KEY_PRESS         0
187 #define KEY_RELEASE       0x400
188 #define KEY_INDEX(c)      ((c) & 0xFF)
189
190 #define SCAN_PRESS        0
191 #define SCAN_RELEASE      0x80
192 #define SCAN_PREFIX_E0    0x100
193 #define SCAN_PREFIX_E1    0x200
194 #define SCAN_PREFIX_CTL   0x400
195 #define SCAN_PREFIX_SHIFT 0x800
196 #define SCAN_PREFIX     (SCAN_PREFIX_E0  | SCAN_PREFIX_E1 | \
197                          SCAN_PREFIX_CTL | SCAN_PREFIX_SHIFT)
198 #define SCAN_CHAR(c)    ((c) & 0x7f)
199
200 struct ukbd_mods {
201         uint32_t mask, key;
202 };
203
204 static const struct ukbd_mods ukbd_mods[UKBD_NMOD] = {
205         {MOD_CONTROL_L, 0xe0},
206         {MOD_CONTROL_R, 0xe4},
207         {MOD_SHIFT_L, 0xe1},
208         {MOD_SHIFT_R, 0xe5},
209         {MOD_ALT_L, 0xe2},
210         {MOD_ALT_R, 0xe6},
211         {MOD_WIN_L, 0xe3},
212         {MOD_WIN_R, 0xe7},
213 };
214
215 #define NN 0                            /* no translation */
216 /*
217  * Translate USB keycodes to AT keyboard scancodes.
218  */
219 /*
220  * FIXME: Mac USB keyboard generates:
221  * 0x53: keypad NumLock/Clear
222  * 0x66: Power
223  * 0x67: keypad =
224  * 0x68: F13
225  * 0x69: F14
226  * 0x6a: F15
227  */
228 static const uint8_t ukbd_trtab[256] = {
229         0, 0, 0, 0, 30, 48, 46, 32,     /* 00 - 07 */
230         18, 33, 34, 35, 23, 36, 37, 38, /* 08 - 0F */
231         50, 49, 24, 25, 16, 19, 31, 20, /* 10 - 17 */
232         22, 47, 17, 45, 21, 44, 2, 3,   /* 18 - 1F */
233         4, 5, 6, 7, 8, 9, 10, 11,       /* 20 - 27 */
234         28, 1, 14, 15, 57, 12, 13, 26,  /* 28 - 2F */
235         27, 43, 43, 39, 40, 41, 51, 52, /* 30 - 37 */
236         53, 58, 59, 60, 61, 62, 63, 64, /* 38 - 3F */
237         65, 66, 67, 68, 87, 88, 92, 70, /* 40 - 47 */
238         104, 102, 94, 96, 103, 99, 101, 98,     /* 48 - 4F */
239         97, 100, 95, 69, 91, 55, 74, 78,/* 50 - 57 */
240         89, 79, 80, 81, 75, 76, 77, 71, /* 58 - 5F */
241         72, 73, 82, 83, 86, 107, 122, NN,       /* 60 - 67 */
242         NN, NN, NN, NN, NN, NN, NN, NN, /* 68 - 6F */
243         NN, NN, NN, NN, 115, 108, 111, 113,     /* 70 - 77 */
244         109, 110, 112, 118, 114, 116, 117, 119, /* 78 - 7F */
245         121, 120, NN, NN, NN, NN, NN, 115,      /* 80 - 87 */
246         112, 125, 121, 123, NN, NN, NN, NN,     /* 88 - 8F */
247         NN, NN, NN, NN, NN, NN, NN, NN, /* 90 - 97 */
248         NN, NN, NN, NN, NN, NN, NN, NN, /* 98 - 9F */
249         NN, NN, NN, NN, NN, NN, NN, NN, /* A0 - A7 */
250         NN, NN, NN, NN, NN, NN, NN, NN, /* A8 - AF */
251         NN, NN, NN, NN, NN, NN, NN, NN, /* B0 - B7 */
252         NN, NN, NN, NN, NN, NN, NN, NN, /* B8 - BF */
253         NN, NN, NN, NN, NN, NN, NN, NN, /* C0 - C7 */
254         NN, NN, NN, NN, NN, NN, NN, NN, /* C8 - CF */
255         NN, NN, NN, NN, NN, NN, NN, NN, /* D0 - D7 */
256         NN, NN, NN, NN, NN, NN, NN, NN, /* D8 - DF */
257         29, 42, 56, 105, 90, 54, 93, 106,       /* E0 - E7 */
258         NN, NN, NN, NN, NN, NN, NN, NN, /* E8 - EF */
259         NN, NN, NN, NN, NN, NN, NN, NN, /* F0 - F7 */
260         NN, NN, NN, NN, NN, NN, NN, NN, /* F8 - FF */
261 };
262
263 /* prototypes */
264 static void     ukbd_timeout(void *);
265 static void     ukbd_set_leds(struct ukbd_softc *, uint8_t);
266 static int      ukbd_set_typematic(keyboard_t *, int);
267 #ifdef UKBD_EMULATE_ATSCANCODE
268 static int      ukbd_key2scan(struct ukbd_softc *, int, int, int);
269 #endif
270 static uint32_t ukbd_read_char(keyboard_t *, int);
271 static void     ukbd_clear_state(keyboard_t *);
272 static int      ukbd_ioctl(keyboard_t *, u_long, caddr_t);
273 static int      ukbd_enable(keyboard_t *);
274 static int      ukbd_disable(keyboard_t *);
275 static void     ukbd_interrupt(struct ukbd_softc *);
276
277 static device_probe_t ukbd_probe;
278 static device_attach_t ukbd_attach;
279 static device_detach_t ukbd_detach;
280 static device_resume_t ukbd_resume;
281
282 static void
283 ukbd_put_key(struct ukbd_softc *sc, uint32_t key)
284 {
285         mtx_assert(&Giant, MA_OWNED);
286
287         DPRINTF("0x%02x (%d) %s\n", key, key,
288             (key & KEY_RELEASE) ? "released" : "pressed");
289
290         if (sc->sc_inputs < UKBD_IN_BUF_SIZE) {
291                 sc->sc_input[sc->sc_inputtail] = key;
292                 ++(sc->sc_inputs);
293                 ++(sc->sc_inputtail);
294                 if (sc->sc_inputtail >= UKBD_IN_BUF_SIZE) {
295                         sc->sc_inputtail = 0;
296                 }
297         } else {
298                 DPRINTF("input buffer is full\n");
299         }
300 }
301
302 static void
303 ukbd_do_poll(struct ukbd_softc *sc, uint8_t wait)
304 {
305         DPRINTFN(2, "polling\n");
306
307         while (sc->sc_inputs == 0) {
308
309                 usbd_transfer_poll(sc->sc_xfer, UKBD_N_TRANSFER);
310
311                 DELAY(1000);    /* delay 1 ms */
312
313                 sc->sc_time_ms++;
314
315                 /* support repetition of keys: */
316
317                 ukbd_interrupt(sc);
318
319                 if (!wait)
320                         break;
321         }
322 }
323
324 static int32_t
325 ukbd_get_key(struct ukbd_softc *sc, uint8_t wait)
326 {
327         int32_t c;
328
329         mtx_assert(&Giant, MA_OWNED);
330
331         if (sc->sc_inputs == 0) {
332                 /* start transfer, if not already started */
333                 usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT]);
334         }
335         if (sc->sc_flags & UKBD_FLAG_POLLING) {
336                 ukbd_do_poll(sc, wait);
337         }
338         if (sc->sc_inputs == 0) {
339                 c = -1;
340         } else {
341                 c = sc->sc_input[sc->sc_inputhead];
342                 --(sc->sc_inputs);
343                 ++(sc->sc_inputhead);
344                 if (sc->sc_inputhead >= UKBD_IN_BUF_SIZE) {
345                         sc->sc_inputhead = 0;
346                 }
347         }
348         return (c);
349 }
350
351 static void
352 ukbd_interrupt(struct ukbd_softc *sc)
353 {
354         uint32_t n_mod;
355         uint32_t o_mod;
356         uint32_t now = sc->sc_time_ms;
357         uint32_t dtime;
358         uint32_t c;
359         uint8_t key;
360         uint8_t i;
361         uint8_t j;
362
363         if (sc->sc_ndata.keycode[0] == KEY_ERROR) {
364                 goto done;
365         }
366         n_mod = sc->sc_ndata.modifiers;
367         o_mod = sc->sc_odata.modifiers;
368         if (n_mod != o_mod) {
369                 for (i = 0; i < UKBD_NMOD; i++) {
370                         if ((n_mod & ukbd_mods[i].mask) !=
371                             (o_mod & ukbd_mods[i].mask)) {
372                                 ukbd_put_key(sc, ukbd_mods[i].key |
373                                     ((n_mod & ukbd_mods[i].mask) ?
374                                     KEY_PRESS : KEY_RELEASE));
375                         }
376                 }
377         }
378         /* Check for released keys. */
379         for (i = 0; i < UKBD_NKEYCODE; i++) {
380                 key = sc->sc_odata.keycode[i];
381                 if (key == 0) {
382                         continue;
383                 }
384                 for (j = 0; j < UKBD_NKEYCODE; j++) {
385                         if (sc->sc_ndata.keycode[j] == 0) {
386                                 continue;
387                         }
388                         if (key == sc->sc_ndata.keycode[j]) {
389                                 goto rfound;
390                         }
391                 }
392                 ukbd_put_key(sc, key | KEY_RELEASE);
393 rfound: ;
394         }
395
396         /* Check for pressed keys. */
397         for (i = 0; i < UKBD_NKEYCODE; i++) {
398                 key = sc->sc_ndata.keycode[i];
399                 if (key == 0) {
400                         continue;
401                 }
402                 sc->sc_ntime[i] = now + sc->sc_kbd.kb_delay1;
403                 for (j = 0; j < UKBD_NKEYCODE; j++) {
404                         if (sc->sc_odata.keycode[j] == 0) {
405                                 continue;
406                         }
407                         if (key == sc->sc_odata.keycode[j]) {
408
409                                 /* key is still pressed */
410
411                                 sc->sc_ntime[i] = sc->sc_otime[j];
412                                 dtime = (sc->sc_otime[j] - now);
413
414                                 if (!(dtime & 0x80000000)) {
415                                         /* time has not elapsed */
416                                         goto pfound;
417                                 }
418                                 sc->sc_ntime[i] = now + sc->sc_kbd.kb_delay2;
419                                 break;
420                         }
421                 }
422                 ukbd_put_key(sc, key | KEY_PRESS);
423
424                 /*
425                  * If any other key is presently down, force its repeat to be
426                  * well in the future (100s).  This makes the last key to be
427                  * pressed do the autorepeat.
428                  */
429                 for (j = 0; j != UKBD_NKEYCODE; j++) {
430                         if (j != i)
431                                 sc->sc_ntime[j] = now + (100 * 1000);
432                 }
433 pfound: ;
434         }
435
436         sc->sc_odata = sc->sc_ndata;
437
438         bcopy(sc->sc_ntime, sc->sc_otime, sizeof(sc->sc_otime));
439
440         if (sc->sc_inputs == 0) {
441                 goto done;
442         }
443         if (sc->sc_flags & UKBD_FLAG_POLLING) {
444                 goto done;
445         }
446         if (KBD_IS_ACTIVE(&sc->sc_kbd) &&
447             KBD_IS_BUSY(&sc->sc_kbd)) {
448                 /* let the callback function process the input */
449                 (sc->sc_kbd.kb_callback.kc_func) (&sc->sc_kbd, KBDIO_KEYINPUT,
450                     sc->sc_kbd.kb_callback.kc_arg);
451         } else {
452                 /* read and discard the input, no one is waiting for it */
453                 do {
454                         c = ukbd_read_char(&sc->sc_kbd, 0);
455                 } while (c != NOKEY);
456         }
457 done:
458         return;
459 }
460
461 static void
462 ukbd_timeout(void *arg)
463 {
464         struct ukbd_softc *sc = arg;
465
466         mtx_assert(&Giant, MA_OWNED);
467
468         if (!(sc->sc_flags & UKBD_FLAG_POLLING)) {
469                 sc->sc_time_ms += 25;   /* milliseconds */
470         }
471         ukbd_interrupt(sc);
472
473         usb_callout_reset(&sc->sc_callout, hz / 40, &ukbd_timeout, sc);
474 }
475
476 static uint8_t
477 ukbd_apple_fn(uint8_t keycode) {
478         switch (keycode) {
479         case 0x28: return 0x49; /* RETURN -> INSERT */
480         case 0x2a: return 0x4c; /* BACKSPACE -> DEL */
481         case 0x50: return 0x4a; /* LEFT ARROW -> HOME */
482         case 0x4f: return 0x4d; /* RIGHT ARROW -> END */
483         case 0x52: return 0x4b; /* UP ARROW -> PGUP */
484         case 0x51: return 0x4e; /* DOWN ARROW -> PGDN */
485         default: return keycode;
486         }
487 }
488
489 static uint8_t
490 ukbd_apple_swap(uint8_t keycode) {
491         switch (keycode) {
492         case 0x35: return 0x64;
493         case 0x64: return 0x35;
494         default: return keycode;
495         }
496 }
497
498 static void
499 ukbd_intr_callback(struct usb_xfer *xfer, usb_error_t error)
500 {
501         struct ukbd_softc *sc = usbd_xfer_softc(xfer);
502         struct usb_page_cache *pc;
503         uint8_t i;
504         uint8_t offset;
505         uint8_t id;
506         uint8_t apple_fn;
507         uint8_t apple_eject;
508         int len;
509
510         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
511         pc = usbd_xfer_get_frame(xfer, 0);
512
513         switch (USB_GET_STATE(xfer)) {
514         case USB_ST_TRANSFERRED:
515                 DPRINTF("actlen=%d bytes\n", len);
516
517                 if (len == 0) {
518                         DPRINTF("zero length data\n");
519                         goto tr_setup;
520                 }
521
522                 if (sc->sc_kbd_id != 0) {
523                         /* check and remove HID ID byte */
524                         usbd_copy_out(pc, 0, &id, 1);
525                         if (id != sc->sc_kbd_id) {
526                                 DPRINTF("wrong HID ID\n");
527                                 goto tr_setup;
528                         }
529                         offset = 1;
530                         len--;
531                 } else {
532                         offset = 0;
533                 }
534
535                 if (len > sizeof(sc->sc_ndata)) {
536                         len = sizeof(sc->sc_ndata);
537                 }
538
539                 if (len) {
540                         memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
541                         usbd_copy_out(pc, offset, &sc->sc_ndata, len);
542
543                         if ((sc->sc_flags & UKBD_FLAG_APPLE_EJECT) &&
544                             hid_get_data((uint8_t *)&sc->sc_ndata,
545                                 len, &sc->sc_loc_apple_eject))
546                                 apple_eject = 1;
547                         else
548                                 apple_eject = 0;
549
550                         if ((sc->sc_flags & UKBD_FLAG_APPLE_FN) &&
551                             hid_get_data((uint8_t *)&sc->sc_ndata,
552                                 len, &sc->sc_loc_apple_fn))
553                                 apple_fn = 1;
554                         else
555                                 apple_fn = 0;
556 #if USB_DEBUG
557                         DPRINTF("apple_eject=%u apple_fn=%u\n",
558                             apple_eject, apple_fn);
559
560                         if (sc->sc_ndata.modifiers) {
561                                 DPRINTF("mod: 0x%04x\n", sc->sc_ndata.modifiers);
562                         }
563                         for (i = 0; i < UKBD_NKEYCODE; i++) {
564                                 if (sc->sc_ndata.keycode[i]) {
565                                         DPRINTF("[%d] = %d\n", i, sc->sc_ndata.keycode[i]);
566                                 }
567                         }
568 #endif                                  /* USB_DEBUG */
569
570                         if (apple_fn) {
571                                 for (i = 0; i < UKBD_NKEYCODE; i++) {
572                                         sc->sc_ndata.keycode[i] = 
573                                             ukbd_apple_fn(sc->sc_ndata.keycode[i]);
574                                 }
575                         }
576
577                         if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP) {
578                                 for (i = 0; i < UKBD_NKEYCODE; i++) {
579                                         sc->sc_ndata.keycode[i] = 
580                                             ukbd_apple_swap(sc->sc_ndata.keycode[i]);
581                                 }
582                         }
583
584                         ukbd_interrupt(sc);
585                 }
586         case USB_ST_SETUP:
587 tr_setup:
588                 if (sc->sc_inputs < UKBD_IN_BUF_FULL) {
589                         usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
590                         usbd_transfer_submit(xfer);
591                 } else {
592                         DPRINTF("input queue is full!\n");
593                 }
594                 break;
595
596         default:                        /* Error */
597                 DPRINTF("error=%s\n", usbd_errstr(error));
598
599                 if (error != USB_ERR_CANCELLED) {
600                         /* try to clear stall first */
601                         usbd_xfer_set_stall(xfer);
602                         goto tr_setup;
603                 }
604                 break;
605         }
606 }
607
608 static void
609 ukbd_set_leds_callback(struct usb_xfer *xfer, usb_error_t error)
610 {
611         struct usb_device_request req;
612         struct usb_page_cache *pc;
613         uint8_t buf[2];
614         struct ukbd_softc *sc = usbd_xfer_softc(xfer);
615
616         switch (USB_GET_STATE(xfer)) {
617         case USB_ST_TRANSFERRED:
618         case USB_ST_SETUP:
619                 if (sc->sc_flags & UKBD_FLAG_SET_LEDS) {
620                         sc->sc_flags &= ~UKBD_FLAG_SET_LEDS;
621
622                         req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
623                         req.bRequest = UR_SET_REPORT;
624                         USETW2(req.wValue, UHID_OUTPUT_REPORT, 0);
625                         req.wIndex[0] = sc->sc_iface_no;
626                         req.wIndex[1] = 0;
627                         req.wLength[1] = 0;
628
629                         /* check if we need to prefix an ID byte */
630                         if (sc->sc_led_id != 0) {
631                                 req.wLength[0] = 2;
632                                 buf[0] = sc->sc_led_id;
633                                 buf[1] = sc->sc_leds;
634                         } else {
635                                 req.wLength[0] = 1;
636                                 buf[0] = sc->sc_leds;
637                                 buf[1] = 0;
638                         }
639
640                         pc = usbd_xfer_get_frame(xfer, 0);
641                         usbd_copy_in(pc, 0, &req, sizeof(req));
642                         pc = usbd_xfer_get_frame(xfer, 1);
643                         usbd_copy_in(pc, 0, buf, sizeof(buf));
644
645                         usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
646                         usbd_xfer_set_frame_len(xfer, 1, req.wLength[0]);
647                         usbd_xfer_set_frames(xfer, 2);
648                         usbd_transfer_submit(xfer);
649                 }
650                 return;
651
652         default:                        /* Error */
653                 DPRINTFN(0, "error=%s\n", usbd_errstr(error));
654                 return;
655         }
656 }
657
658 static const struct usb_config ukbd_config[UKBD_N_TRANSFER] = {
659
660         [UKBD_INTR_DT] = {
661                 .type = UE_INTERRUPT,
662                 .endpoint = UE_ADDR_ANY,
663                 .direction = UE_DIR_IN,
664                 .flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
665                 .bufsize = 0,   /* use wMaxPacketSize */
666                 .callback = &ukbd_intr_callback,
667         },
668
669         [UKBD_CTRL_LED] = {
670                 .type = UE_CONTROL,
671                 .endpoint = 0x00,       /* Control pipe */
672                 .direction = UE_DIR_ANY,
673                 .bufsize = sizeof(struct usb_device_request) + 8,
674                 .callback = &ukbd_set_leds_callback,
675                 .timeout = 1000,        /* 1 second */
676         },
677 };
678
679 static int
680 ukbd_probe(device_t dev)
681 {
682         keyboard_switch_t *sw = kbd_get_switch(UKBD_DRIVER_NAME);
683         struct usb_attach_arg *uaa = device_get_ivars(dev);
684         void *d_ptr;
685         int error;
686         uint16_t d_len;
687
688         DPRINTFN(11, "\n");
689
690         if (sw == NULL) {
691                 return (ENXIO);
692         }
693         if (uaa->usb_mode != USB_MODE_HOST) {
694                 return (ENXIO);
695         }
696
697         if (uaa->info.bInterfaceClass != UICLASS_HID)
698                 return (ENXIO);
699
700         if ((uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) &&
701             (uaa->info.bInterfaceProtocol == UPROTO_BOOT_KEYBOARD)) {
702                 if (usb_test_quirk(uaa, UQ_KBD_IGNORE))
703                         return (ENXIO);
704                 else
705                         return (0);
706         }
707
708         error = usbd_req_get_hid_desc(uaa->device, NULL,
709             &d_ptr, &d_len, M_TEMP, uaa->info.bIfaceIndex);
710
711         if (error)
712                 return (ENXIO);
713
714         /* 
715          * NOTE: we currently don't support USB mouse and USB keyboard
716          * on the same USB endpoint.
717          */
718         if (hid_is_collection(d_ptr, d_len,
719             HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_MOUSE))) {
720                 /* most likely a mouse */
721                 error = ENXIO;
722         } else if (hid_is_collection(d_ptr, d_len,
723             HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_KEYBOARD))) {
724                 if (usb_test_quirk(uaa, UQ_KBD_IGNORE))
725                         error = ENXIO;
726                 else
727                         error = 0;
728         } else
729                 error = ENXIO;
730
731         free(d_ptr, M_TEMP);
732         return (error);
733 }
734
735 static int
736 ukbd_attach(device_t dev)
737 {
738         struct ukbd_softc *sc = device_get_softc(dev);
739         struct usb_attach_arg *uaa = device_get_ivars(dev);
740         int32_t unit = device_get_unit(dev);
741         keyboard_t *kbd = &sc->sc_kbd;
742         void *hid_ptr = NULL;
743         usb_error_t err;
744         uint32_t flags;
745         uint16_t n;
746         uint16_t hid_len;
747
748         mtx_lock(&Giant);
749
750         kbd_init_struct(kbd, UKBD_DRIVER_NAME, KB_OTHER, unit, 0, 0, 0);
751
752         kbd->kb_data = (void *)sc;
753
754         device_set_usb_desc(dev);
755
756         sc->sc_udev = uaa->device;
757         sc->sc_iface = uaa->iface;
758         sc->sc_iface_index = uaa->info.bIfaceIndex;
759         sc->sc_iface_no = uaa->info.bIfaceNum;
760         sc->sc_mode = K_XLATE;
761
762         usb_callout_init_mtx(&sc->sc_callout, &Giant, 0);
763
764         err = usbd_transfer_setup(uaa->device,
765             &uaa->info.bIfaceIndex, sc->sc_xfer, ukbd_config,
766             UKBD_N_TRANSFER, sc, &Giant);
767
768         if (err) {
769                 DPRINTF("error=%s\n", usbd_errstr(err));
770                 goto detach;
771         }
772         /* setup default keyboard maps */
773
774         sc->sc_keymap = key_map;
775         sc->sc_accmap = accent_map;
776         for (n = 0; n < UKBD_NFKEY; n++) {
777                 sc->sc_fkeymap[n] = fkey_tab[n];
778         }
779
780         kbd_set_maps(kbd, &sc->sc_keymap, &sc->sc_accmap,
781             sc->sc_fkeymap, UKBD_NFKEY);
782
783         KBD_FOUND_DEVICE(kbd);
784
785         ukbd_clear_state(kbd);
786
787         /*
788          * FIXME: set the initial value for lock keys in "sc_state"
789          * according to the BIOS data?
790          */
791         KBD_PROBE_DONE(kbd);
792
793         /* figure out if there is an ID byte in the data */
794         err = usbd_req_get_hid_desc(uaa->device, NULL, &hid_ptr,
795             &hid_len, M_TEMP, uaa->info.bIfaceIndex);
796         if (err == 0) {
797                 uint8_t temp_id;
798
799                 /* investigate if this is an Apple Keyboard */
800                 if (hid_locate(hid_ptr, hid_len,
801                     HID_USAGE2(HUP_CONSUMER, HUG_APPLE_EJECT),
802                     hid_input, 0, &sc->sc_loc_apple_eject, &flags,
803                     &sc->sc_kbd_id)) {
804                         if (flags & HIO_VARIABLE)
805                                 sc->sc_flags |= UKBD_FLAG_APPLE_EJECT | 
806                                     UKBD_FLAG_APPLE_SWAP;
807                         if (hid_locate(hid_ptr, hid_len,
808                             HID_USAGE2(0xFFFF, 0x0003),
809                             hid_input, 0, &sc->sc_loc_apple_fn, &flags,
810                             &temp_id)) {
811                                 if (flags & HIO_VARIABLE)
812                                         sc->sc_flags |= UKBD_FLAG_APPLE_FN |
813                                             UKBD_FLAG_APPLE_SWAP;
814                                 if (temp_id != sc->sc_kbd_id) {
815                                         DPRINTF("HID IDs mismatch\n");
816                                 }
817                         }
818                 } else {
819                         /* 
820                          * Assume the first HID ID contains the
821                          * keyboard data
822                          */
823                         hid_report_size(hid_ptr, hid_len,
824                             hid_input, &sc->sc_kbd_id);
825                 }
826
827                 /* investigate if we need an ID-byte for the leds */
828                 hid_report_size(hid_ptr, hid_len, hid_output, &sc->sc_led_id);
829
830                 free(hid_ptr, M_TEMP);
831         }
832
833         /* ignore if SETIDLE fails, hence it is not crucial */
834         err = usbd_req_set_idle(sc->sc_udev, &Giant, sc->sc_iface_index, 0, 0);
835
836         ukbd_ioctl(kbd, KDSETLED, (caddr_t)&sc->sc_state);
837
838         KBD_INIT_DONE(kbd);
839
840         if (kbd_register(kbd) < 0) {
841                 goto detach;
842         }
843         KBD_CONFIG_DONE(kbd);
844
845         ukbd_enable(kbd);
846
847 #ifdef KBD_INSTALL_CDEV
848         if (kbd_attach(kbd)) {
849                 goto detach;
850         }
851 #endif
852         sc->sc_flags |= UKBD_FLAG_ATTACHED;
853
854         if (bootverbose) {
855                 genkbd_diag(kbd, bootverbose);
856         }
857
858         /* start the keyboard */
859
860         usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT]);
861
862         /* start the timer */
863
864         ukbd_timeout(sc);
865         mtx_unlock(&Giant);
866         return (0);                     /* success */
867
868 detach:
869         ukbd_detach(dev);
870         return (ENXIO);                 /* error */
871 }
872
873 static int
874 ukbd_detach(device_t dev)
875 {
876         struct ukbd_softc *sc = device_get_softc(dev);
877         int error;
878
879         mtx_lock(&Giant);
880
881         DPRINTF("\n");
882
883         if (sc->sc_flags & UKBD_FLAG_POLLING) {
884                 panic("cannot detach polled keyboard!\n");
885         }
886         sc->sc_flags |= UKBD_FLAG_GONE;
887
888         usb_callout_stop(&sc->sc_callout);
889
890         ukbd_disable(&sc->sc_kbd);
891
892 #ifdef KBD_INSTALL_CDEV
893         if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
894                 error = kbd_detach(&sc->sc_kbd);
895                 if (error) {
896                         /* usb attach cannot return an error */
897                         device_printf(dev, "WARNING: kbd_detach() "
898                             "returned non-zero! (ignored)\n");
899                 }
900         }
901 #endif
902         if (KBD_IS_CONFIGURED(&sc->sc_kbd)) {
903                 error = kbd_unregister(&sc->sc_kbd);
904                 if (error) {
905                         /* usb attach cannot return an error */
906                         device_printf(dev, "WARNING: kbd_unregister() "
907                             "returned non-zero! (ignored)\n");
908                 }
909         }
910         sc->sc_kbd.kb_flags = 0;
911
912         usbd_transfer_unsetup(sc->sc_xfer, UKBD_N_TRANSFER);
913
914         usb_callout_drain(&sc->sc_callout);
915
916         mtx_unlock(&Giant);
917
918         DPRINTF("%s: disconnected\n",
919             device_get_nameunit(dev));
920
921         return (0);
922 }
923
924 static int
925 ukbd_resume(device_t dev)
926 {
927         struct ukbd_softc *sc = device_get_softc(dev);
928
929         mtx_lock(&Giant);
930         ukbd_clear_state(&sc->sc_kbd);
931         mtx_unlock(&Giant);
932
933         return (0);
934 }
935
936 /* early keyboard probe, not supported */
937 static int
938 ukbd_configure(int flags)
939 {
940         return (0);
941 }
942
943 /* detect a keyboard, not used */
944 static int
945 ukbd__probe(int unit, void *arg, int flags)
946 {
947         mtx_assert(&Giant, MA_OWNED);
948         return (ENXIO);
949 }
950
951 /* reset and initialize the device, not used */
952 static int
953 ukbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
954 {
955         mtx_assert(&Giant, MA_OWNED);
956         return (ENXIO);
957 }
958
959 /* test the interface to the device, not used */
960 static int
961 ukbd_test_if(keyboard_t *kbd)
962 {
963         mtx_assert(&Giant, MA_OWNED);
964         return (0);
965 }
966
967 /* finish using this keyboard, not used */
968 static int
969 ukbd_term(keyboard_t *kbd)
970 {
971         mtx_assert(&Giant, MA_OWNED);
972         return (ENXIO);
973 }
974
975 /* keyboard interrupt routine, not used */
976 static int
977 ukbd_intr(keyboard_t *kbd, void *arg)
978 {
979         mtx_assert(&Giant, MA_OWNED);
980         return (0);
981 }
982
983 /* lock the access to the keyboard, not used */
984 static int
985 ukbd_lock(keyboard_t *kbd, int lock)
986 {
987         mtx_assert(&Giant, MA_OWNED);
988         return (1);
989 }
990
991 /*
992  * Enable the access to the device; until this function is called,
993  * the client cannot read from the keyboard.
994  */
995 static int
996 ukbd_enable(keyboard_t *kbd)
997 {
998         if (!mtx_owned(&Giant)) {
999                 /* XXX cludge */
1000                 int retval;
1001                 mtx_lock(&Giant);
1002                 retval = ukbd_enable(kbd);
1003                 mtx_unlock(&Giant);
1004                 return (retval);
1005         }
1006         mtx_assert(&Giant, MA_OWNED);
1007         KBD_ACTIVATE(kbd);
1008         return (0);
1009 }
1010
1011 /* disallow the access to the device */
1012 static int
1013 ukbd_disable(keyboard_t *kbd)
1014 {
1015         if (!mtx_owned(&Giant)) {
1016                 /* XXX cludge */
1017                 int retval;
1018                 mtx_lock(&Giant);
1019                 retval = ukbd_disable(kbd);
1020                 mtx_unlock(&Giant);
1021                 return (retval);
1022         }
1023         mtx_assert(&Giant, MA_OWNED);
1024         KBD_DEACTIVATE(kbd);
1025         return (0);
1026 }
1027
1028 /* check if data is waiting */
1029 static int
1030 ukbd_check(keyboard_t *kbd)
1031 {
1032         struct ukbd_softc *sc = kbd->kb_data;
1033
1034         if (!KBD_IS_ACTIVE(kbd))
1035                 return (0);
1036
1037         if (sc->sc_flags & UKBD_FLAG_POLLING) {
1038                 if (!mtx_owned(&Giant)) {
1039                         /* XXX cludge */
1040                         int retval;
1041                         mtx_lock(&Giant);
1042                         retval = ukbd_check(kbd);
1043                         mtx_unlock(&Giant);
1044                         return (retval);
1045                 }
1046                 ukbd_do_poll(sc, 0);
1047         } else {
1048                 /* XXX the keyboard layer requires Giant */
1049                 if (!mtx_owned(&Giant))
1050                         return (0);
1051         }
1052         mtx_assert(&Giant, MA_OWNED);
1053
1054 #ifdef UKBD_EMULATE_ATSCANCODE
1055         if (sc->sc_buffered_char[0]) {
1056                 return (1);
1057         }
1058 #endif
1059         if (sc->sc_inputs > 0) {
1060                 return (1);
1061         }
1062         return (0);
1063 }
1064
1065 /* check if char is waiting */
1066 static int
1067 ukbd_check_char(keyboard_t *kbd)
1068 {
1069         struct ukbd_softc *sc = kbd->kb_data;
1070
1071         if (!KBD_IS_ACTIVE(kbd))
1072                 return (0);
1073
1074         if (sc->sc_flags & UKBD_FLAG_POLLING) {
1075                 if (!mtx_owned(&Giant)) {
1076                         /* XXX cludge */
1077                         int retval;
1078                         mtx_lock(&Giant);
1079                         retval = ukbd_check_char(kbd);
1080                         mtx_unlock(&Giant);
1081                         return (retval);
1082                 }
1083         } else {
1084                 /* XXX the keyboard layer requires Giant */
1085                 if (!mtx_owned(&Giant))
1086                         return (0);
1087         }
1088         mtx_assert(&Giant, MA_OWNED);
1089
1090         if ((sc->sc_composed_char > 0) &&
1091             (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1092                 return (1);
1093         }
1094         return (ukbd_check(kbd));
1095 }
1096
1097
1098 /* read one byte from the keyboard if it's allowed */
1099 static int
1100 ukbd_read(keyboard_t *kbd, int wait)
1101 {
1102         struct ukbd_softc *sc = kbd->kb_data;
1103         int32_t usbcode;
1104
1105 #ifdef UKBD_EMULATE_ATSCANCODE
1106         uint32_t keycode;
1107         uint32_t scancode;
1108
1109 #endif
1110         if (!KBD_IS_ACTIVE(kbd))
1111                 return (-1);
1112
1113         if (sc->sc_flags & UKBD_FLAG_POLLING) {
1114                 if (!mtx_owned(&Giant)) {
1115                         /* XXX cludge */
1116                         int retval;
1117                         mtx_lock(&Giant);
1118                         retval = ukbd_read(kbd, wait);
1119                         mtx_unlock(&Giant);
1120                         return (retval);
1121                 }
1122         } else {
1123                 /* XXX the keyboard layer requires Giant */
1124                 if (!mtx_owned(&Giant))
1125                         return (-1);
1126         }
1127         mtx_assert(&Giant, MA_OWNED);
1128
1129 #ifdef UKBD_EMULATE_ATSCANCODE
1130         if (sc->sc_buffered_char[0]) {
1131                 scancode = sc->sc_buffered_char[0];
1132                 if (scancode & SCAN_PREFIX) {
1133                         sc->sc_buffered_char[0] &= ~SCAN_PREFIX;
1134                         return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1135                 }
1136                 sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1137                 sc->sc_buffered_char[1] = 0;
1138                 return (scancode);
1139         }
1140 #endif                                  /* UKBD_EMULATE_ATSCANCODE */
1141
1142         /* XXX */
1143         usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1144         if (!KBD_IS_ACTIVE(kbd) || (usbcode == -1))
1145                 return (-1);
1146
1147         ++(kbd->kb_count);
1148
1149 #ifdef UKBD_EMULATE_ATSCANCODE
1150         keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1151         if (keycode == NN) {
1152                 return -1;
1153         }
1154         return (ukbd_key2scan(sc, keycode, sc->sc_ndata.modifiers,
1155             (usbcode & KEY_RELEASE)));
1156 #else                                   /* !UKBD_EMULATE_ATSCANCODE */
1157         return (usbcode);
1158 #endif                                  /* UKBD_EMULATE_ATSCANCODE */
1159 }
1160
1161 /* read char from the keyboard */
1162 static uint32_t
1163 ukbd_read_char(keyboard_t *kbd, int wait)
1164 {
1165         struct ukbd_softc *sc = kbd->kb_data;
1166         uint32_t action;
1167         uint32_t keycode;
1168         int32_t usbcode;
1169
1170 #ifdef UKBD_EMULATE_ATSCANCODE
1171         uint32_t scancode;
1172
1173 #endif
1174
1175         if (!KBD_IS_ACTIVE(kbd))
1176                 return (NOKEY);
1177
1178         if (sc->sc_flags & UKBD_FLAG_POLLING) {
1179                 if (!mtx_owned(&Giant)) {
1180                         /* XXX cludge */
1181                         int retval;
1182                         mtx_lock(&Giant);
1183                         retval = ukbd_read_char(kbd, wait);
1184                         mtx_unlock(&Giant);
1185                         return (retval);
1186                 }
1187         } else {
1188                 /* XXX the keyboard layer requires Giant */
1189                 if (!mtx_owned(&Giant))
1190                         return (NOKEY);
1191         }
1192         mtx_assert(&Giant, MA_OWNED);
1193
1194 next_code:
1195
1196         /* do we have a composed char to return ? */
1197
1198         if ((sc->sc_composed_char > 0) &&
1199             (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1200
1201                 action = sc->sc_composed_char;
1202                 sc->sc_composed_char = 0;
1203
1204                 if (action > 0xFF) {
1205                         goto errkey;
1206                 }
1207                 goto done;
1208         }
1209 #ifdef UKBD_EMULATE_ATSCANCODE
1210
1211         /* do we have a pending raw scan code? */
1212
1213         if (sc->sc_mode == K_RAW) {
1214                 scancode = sc->sc_buffered_char[0];
1215                 if (scancode) {
1216                         if (scancode & SCAN_PREFIX) {
1217                                 sc->sc_buffered_char[0] = (scancode & ~SCAN_PREFIX);
1218                                 return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1219                         }
1220                         sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1221                         sc->sc_buffered_char[1] = 0;
1222                         return (scancode);
1223                 }
1224         }
1225 #endif                                  /* UKBD_EMULATE_ATSCANCODE */
1226
1227         /* see if there is something in the keyboard port */
1228         /* XXX */
1229         usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1230         if (usbcode == -1) {
1231                 return (NOKEY);
1232         }
1233         ++kbd->kb_count;
1234
1235 #ifdef UKBD_EMULATE_ATSCANCODE
1236         /* USB key index -> key code -> AT scan code */
1237         keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1238         if (keycode == NN) {
1239                 return (NOKEY);
1240         }
1241         /* return an AT scan code for the K_RAW mode */
1242         if (sc->sc_mode == K_RAW) {
1243                 return (ukbd_key2scan(sc, keycode, sc->sc_ndata.modifiers,
1244                     (usbcode & KEY_RELEASE)));
1245         }
1246 #else                                   /* !UKBD_EMULATE_ATSCANCODE */
1247
1248         /* return the byte as is for the K_RAW mode */
1249         if (sc->sc_mode == K_RAW) {
1250                 return (usbcode);
1251         }
1252         /* USB key index -> key code */
1253         keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1254         if (keycode == NN) {
1255                 return (NOKEY);
1256         }
1257 #endif                                  /* UKBD_EMULATE_ATSCANCODE */
1258
1259         switch (keycode) {
1260         case 0x38:                      /* left alt (compose key) */
1261                 if (usbcode & KEY_RELEASE) {
1262                         if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1263                                 sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1264
1265                                 if (sc->sc_composed_char > 0xFF) {
1266                                         sc->sc_composed_char = 0;
1267                                 }
1268                         }
1269                 } else {
1270                         if (!(sc->sc_flags & UKBD_FLAG_COMPOSE)) {
1271                                 sc->sc_flags |= UKBD_FLAG_COMPOSE;
1272                                 sc->sc_composed_char = 0;
1273                         }
1274                 }
1275                 break;
1276                 /* XXX: I don't like these... */
1277         case 0x5c:                      /* print screen */
1278                 if (sc->sc_flags & ALTS) {
1279                         keycode = 0x54; /* sysrq */
1280                 }
1281                 break;
1282         case 0x68:                      /* pause/break */
1283                 if (sc->sc_flags & CTLS) {
1284                         keycode = 0x6c; /* break */
1285                 }
1286                 break;
1287         }
1288
1289         /* return the key code in the K_CODE mode */
1290         if (usbcode & KEY_RELEASE) {
1291                 keycode |= SCAN_RELEASE;
1292         }
1293         if (sc->sc_mode == K_CODE) {
1294                 return (keycode);
1295         }
1296         /* compose a character code */
1297         if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1298                 switch (keycode) {
1299                         /* key pressed, process it */
1300                 case 0x47:
1301                 case 0x48:
1302                 case 0x49:              /* keypad 7,8,9 */
1303                         sc->sc_composed_char *= 10;
1304                         sc->sc_composed_char += keycode - 0x40;
1305                         goto check_composed;
1306
1307                 case 0x4B:
1308                 case 0x4C:
1309                 case 0x4D:              /* keypad 4,5,6 */
1310                         sc->sc_composed_char *= 10;
1311                         sc->sc_composed_char += keycode - 0x47;
1312                         goto check_composed;
1313
1314                 case 0x4F:
1315                 case 0x50:
1316                 case 0x51:              /* keypad 1,2,3 */
1317                         sc->sc_composed_char *= 10;
1318                         sc->sc_composed_char += keycode - 0x4E;
1319                         goto check_composed;
1320
1321                 case 0x52:              /* keypad 0 */
1322                         sc->sc_composed_char *= 10;
1323                         goto check_composed;
1324
1325                         /* key released, no interest here */
1326                 case SCAN_RELEASE | 0x47:
1327                 case SCAN_RELEASE | 0x48:
1328                 case SCAN_RELEASE | 0x49:       /* keypad 7,8,9 */
1329                 case SCAN_RELEASE | 0x4B:
1330                 case SCAN_RELEASE | 0x4C:
1331                 case SCAN_RELEASE | 0x4D:       /* keypad 4,5,6 */
1332                 case SCAN_RELEASE | 0x4F:
1333                 case SCAN_RELEASE | 0x50:
1334                 case SCAN_RELEASE | 0x51:       /* keypad 1,2,3 */
1335                 case SCAN_RELEASE | 0x52:       /* keypad 0 */
1336                         goto next_code;
1337
1338                 case 0x38:              /* left alt key */
1339                         break;
1340
1341                 default:
1342                         if (sc->sc_composed_char > 0) {
1343                                 sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1344                                 sc->sc_composed_char = 0;
1345                                 goto errkey;
1346                         }
1347                         break;
1348                 }
1349         }
1350         /* keycode to key action */
1351         action = genkbd_keyaction(kbd, SCAN_CHAR(keycode),
1352             (keycode & SCAN_RELEASE),
1353             &sc->sc_state, &sc->sc_accents);
1354         if (action == NOKEY) {
1355                 goto next_code;
1356         }
1357 done:
1358         return (action);
1359
1360 check_composed:
1361         if (sc->sc_composed_char <= 0xFF) {
1362                 goto next_code;
1363         }
1364 errkey:
1365         return (ERRKEY);
1366 }
1367
1368 /* some useful control functions */
1369 static int
1370 ukbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
1371 {
1372         /* translate LED_XXX bits into the device specific bits */
1373         static const uint8_t ledmap[8] = {
1374                 0, 2, 1, 3, 4, 6, 5, 7,
1375         };
1376         struct ukbd_softc *sc = kbd->kb_data;
1377         int i;
1378
1379 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1380     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1381         int ival;
1382
1383 #endif
1384         if (!mtx_owned(&Giant)) {
1385                 /*
1386                  * XXX big problem: If scroll lock is pressed and "printf()"
1387                  * is called, the CPU will get here, to un-scroll lock the
1388                  * keyboard. But if "printf()" acquires the "Giant" lock,
1389                  * there will be a locking order reversal problem, so the
1390                  * keyboard system must get out of "Giant" first, before the
1391                  * CPU can proceed here ...
1392                  */
1393                 return (EINVAL);
1394         }
1395         mtx_assert(&Giant, MA_OWNED);
1396
1397         switch (cmd) {
1398         case KDGKBMODE:         /* get keyboard mode */
1399                 *(int *)arg = sc->sc_mode;
1400                 break;
1401 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1402     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1403         case _IO('K', 7):
1404                 ival = IOCPARM_IVAL(arg);
1405                 arg = (caddr_t)&ival;
1406                 /* FALLTHROUGH */
1407 #endif
1408         case KDSKBMODE:         /* set keyboard mode */
1409                 switch (*(int *)arg) {
1410                 case K_XLATE:
1411                         if (sc->sc_mode != K_XLATE) {
1412                                 /* make lock key state and LED state match */
1413                                 sc->sc_state &= ~LOCK_MASK;
1414                                 sc->sc_state |= KBD_LED_VAL(kbd);
1415                         }
1416                         /* FALLTHROUGH */
1417                 case K_RAW:
1418                 case K_CODE:
1419                         if (sc->sc_mode != *(int *)arg) {
1420                                 ukbd_clear_state(kbd);
1421                                 sc->sc_mode = *(int *)arg;
1422                         }
1423                         break;
1424                 default:
1425                         return (EINVAL);
1426                 }
1427                 break;
1428
1429         case KDGETLED:                  /* get keyboard LED */
1430                 *(int *)arg = KBD_LED_VAL(kbd);
1431                 break;
1432 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1433     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1434         case _IO('K', 66):
1435                 ival = IOCPARM_IVAL(arg);
1436                 arg = (caddr_t)&ival;
1437                 /* FALLTHROUGH */
1438 #endif
1439         case KDSETLED:                  /* set keyboard LED */
1440                 /* NOTE: lock key state in "sc_state" won't be changed */
1441                 if (*(int *)arg & ~LOCK_MASK) {
1442                         return (EINVAL);
1443                 }
1444                 i = *(int *)arg;
1445                 /* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1446                 if (sc->sc_mode == K_XLATE &&
1447                     kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1448                         if (i & ALKED)
1449                                 i |= CLKED;
1450                         else
1451                                 i &= ~CLKED;
1452                 }
1453                 if (KBD_HAS_DEVICE(kbd)) {
1454                         ukbd_set_leds(sc, ledmap[i & LED_MASK]);
1455                 }
1456                 KBD_LED_VAL(kbd) = *(int *)arg;
1457                 break;
1458         case KDGKBSTATE:                /* get lock key state */
1459                 *(int *)arg = sc->sc_state & LOCK_MASK;
1460                 break;
1461 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1462     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1463         case _IO('K', 20):
1464                 ival = IOCPARM_IVAL(arg);
1465                 arg = (caddr_t)&ival;
1466                 /* FALLTHROUGH */
1467 #endif
1468         case KDSKBSTATE:                /* set lock key state */
1469                 if (*(int *)arg & ~LOCK_MASK) {
1470                         return (EINVAL);
1471                 }
1472                 sc->sc_state &= ~LOCK_MASK;
1473                 sc->sc_state |= *(int *)arg;
1474
1475                 /* set LEDs and quit */
1476                 return (ukbd_ioctl(kbd, KDSETLED, arg));
1477
1478         case KDSETREPEAT:               /* set keyboard repeat rate (new
1479                                          * interface) */
1480                 if (!KBD_HAS_DEVICE(kbd)) {
1481                         return (0);
1482                 }
1483                 if (((int *)arg)[1] < 0) {
1484                         return (EINVAL);
1485                 }
1486                 if (((int *)arg)[0] < 0) {
1487                         return (EINVAL);
1488                 }
1489                 if (((int *)arg)[0] < 200)      /* fastest possible value */
1490                         kbd->kb_delay1 = 200;
1491                 else
1492                         kbd->kb_delay1 = ((int *)arg)[0];
1493                 kbd->kb_delay2 = ((int *)arg)[1];
1494                 return (0);
1495
1496 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1497     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1498         case _IO('K', 67):
1499                 ival = IOCPARM_IVAL(arg);
1500                 arg = (caddr_t)&ival;
1501                 /* FALLTHROUGH */
1502 #endif
1503         case KDSETRAD:                  /* set keyboard repeat rate (old
1504                                          * interface) */
1505                 return (ukbd_set_typematic(kbd, *(int *)arg));
1506
1507         case PIO_KEYMAP:                /* set keyboard translation table */
1508         case PIO_KEYMAPENT:             /* set keyboard translation table
1509                                          * entry */
1510         case PIO_DEADKEYMAP:            /* set accent key translation table */
1511                 sc->sc_accents = 0;
1512                 /* FALLTHROUGH */
1513         default:
1514                 return (genkbd_commonioctl(kbd, cmd, arg));
1515         }
1516
1517         return (0);
1518 }
1519
1520 /* clear the internal state of the keyboard */
1521 static void
1522 ukbd_clear_state(keyboard_t *kbd)
1523 {
1524         struct ukbd_softc *sc = kbd->kb_data;
1525
1526         if (!mtx_owned(&Giant)) {
1527                 return;                 /* XXX */
1528         }
1529         mtx_assert(&Giant, MA_OWNED);
1530
1531         sc->sc_flags &= ~(UKBD_FLAG_COMPOSE | UKBD_FLAG_POLLING);
1532         sc->sc_state &= LOCK_MASK;      /* preserve locking key state */
1533         sc->sc_accents = 0;
1534         sc->sc_composed_char = 0;
1535 #ifdef UKBD_EMULATE_ATSCANCODE
1536         sc->sc_buffered_char[0] = 0;
1537         sc->sc_buffered_char[1] = 0;
1538 #endif
1539         bzero(&sc->sc_ndata, sizeof(sc->sc_ndata));
1540         bzero(&sc->sc_odata, sizeof(sc->sc_odata));
1541         bzero(&sc->sc_ntime, sizeof(sc->sc_ntime));
1542         bzero(&sc->sc_otime, sizeof(sc->sc_otime));
1543 }
1544
1545 /* save the internal state, not used */
1546 static int
1547 ukbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1548 {
1549         mtx_assert(&Giant, MA_OWNED);
1550         return (len == 0) ? 1 : -1;
1551 }
1552
1553 /* set the internal state, not used */
1554 static int
1555 ukbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1556 {
1557         mtx_assert(&Giant, MA_OWNED);
1558         return (EINVAL);
1559 }
1560
1561 static int
1562 ukbd_poll(keyboard_t *kbd, int on)
1563 {
1564         struct ukbd_softc *sc = kbd->kb_data;
1565
1566         if (!mtx_owned(&Giant)) {
1567                 /* XXX cludge */
1568                 int retval;
1569                 mtx_lock(&Giant);
1570                 retval = ukbd_poll(kbd, on);
1571                 mtx_unlock(&Giant);
1572                 return (retval);
1573         }
1574         mtx_assert(&Giant, MA_OWNED);
1575
1576         if (on) {
1577                 sc->sc_flags |= UKBD_FLAG_POLLING;
1578         } else {
1579                 sc->sc_flags &= ~UKBD_FLAG_POLLING;
1580         }
1581         return (0);
1582 }
1583
1584 /* local functions */
1585
1586 static void
1587 ukbd_set_leds(struct ukbd_softc *sc, uint8_t leds)
1588 {
1589         DPRINTF("leds=0x%02x\n", leds);
1590
1591         sc->sc_leds = leds;
1592         sc->sc_flags |= UKBD_FLAG_SET_LEDS;
1593
1594         /* start transfer, if not already started */
1595
1596         usbd_transfer_start(sc->sc_xfer[UKBD_CTRL_LED]);
1597 }
1598
1599 static int
1600 ukbd_set_typematic(keyboard_t *kbd, int code)
1601 {
1602         static const int delays[] = {250, 500, 750, 1000};
1603         static const int rates[] = {34, 38, 42, 46, 50, 55, 59, 63,
1604                 68, 76, 84, 92, 100, 110, 118, 126,
1605                 136, 152, 168, 184, 200, 220, 236, 252,
1606         272, 304, 336, 368, 400, 440, 472, 504};
1607
1608         if (code & ~0x7f) {
1609                 return (EINVAL);
1610         }
1611         kbd->kb_delay1 = delays[(code >> 5) & 3];
1612         kbd->kb_delay2 = rates[code & 0x1f];
1613         return (0);
1614 }
1615
1616 #ifdef UKBD_EMULATE_ATSCANCODE
1617 static int
1618 ukbd_key2scan(struct ukbd_softc *sc, int code, int shift, int up)
1619 {
1620         static const int scan[] = {
1621                 0x1c, 0x1d, 0x35,
1622                 0x37 | SCAN_PREFIX_SHIFT,       /* PrintScreen */
1623                 0x38, 0x47, 0x48, 0x49, 0x4b, 0x4d, 0x4f,
1624                 0x50, 0x51, 0x52, 0x53,
1625                 0x46,                   /* XXX Pause/Break */
1626                 0x5b, 0x5c, 0x5d,
1627                 /* SUN TYPE 6 USB KEYBOARD */
1628                 0x68, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63,
1629                 0x64, 0x65, 0x66, 0x67, 0x25, 0x1f, 0x1e,
1630                 0x20,
1631         };
1632
1633         if ((code >= 89) && (code < (89 + (sizeof(scan) / sizeof(scan[0]))))) {
1634                 code = scan[code - 89] | SCAN_PREFIX_E0;
1635         }
1636         /* Pause/Break */
1637         if ((code == 104) && (!(shift & (MOD_CONTROL_L | MOD_CONTROL_R)))) {
1638                 code = (0x45 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL);
1639         }
1640         if (shift & (MOD_SHIFT_L | MOD_SHIFT_R)) {
1641                 code &= ~SCAN_PREFIX_SHIFT;
1642         }
1643         code |= (up ? SCAN_RELEASE : SCAN_PRESS);
1644
1645         if (code & SCAN_PREFIX) {
1646                 if (code & SCAN_PREFIX_CTL) {
1647                         /* Ctrl */
1648                         sc->sc_buffered_char[0] = (0x1d | (code & SCAN_RELEASE));
1649                         sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX);
1650                 } else if (code & SCAN_PREFIX_SHIFT) {
1651                         /* Shift */
1652                         sc->sc_buffered_char[0] = (0x2a | (code & SCAN_RELEASE));
1653                         sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX_SHIFT);
1654                 } else {
1655                         sc->sc_buffered_char[0] = (code & ~SCAN_PREFIX);
1656                         sc->sc_buffered_char[1] = 0;
1657                 }
1658                 return ((code & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1659         }
1660         return (code);
1661
1662 }
1663
1664 #endif                                  /* UKBD_EMULATE_ATSCANCODE */
1665
1666 static keyboard_switch_t ukbdsw = {
1667         .probe = &ukbd__probe,
1668         .init = &ukbd_init,
1669         .term = &ukbd_term,
1670         .intr = &ukbd_intr,
1671         .test_if = &ukbd_test_if,
1672         .enable = &ukbd_enable,
1673         .disable = &ukbd_disable,
1674         .read = &ukbd_read,
1675         .check = &ukbd_check,
1676         .read_char = &ukbd_read_char,
1677         .check_char = &ukbd_check_char,
1678         .ioctl = &ukbd_ioctl,
1679         .lock = &ukbd_lock,
1680         .clear_state = &ukbd_clear_state,
1681         .get_state = &ukbd_get_state,
1682         .set_state = &ukbd_set_state,
1683         .get_fkeystr = &genkbd_get_fkeystr,
1684         .poll = &ukbd_poll,
1685         .diag = &genkbd_diag,
1686 };
1687
1688 KEYBOARD_DRIVER(ukbd, ukbdsw, ukbd_configure);
1689
1690 static int
1691 ukbd_driver_load(module_t mod, int what, void *arg)
1692 {
1693         switch (what) {
1694         case MOD_LOAD:
1695                 kbd_add_driver(&ukbd_kbd_driver);
1696                 break;
1697         case MOD_UNLOAD:
1698                 kbd_delete_driver(&ukbd_kbd_driver);
1699                 break;
1700         }
1701         return (0);
1702 }
1703
1704 static devclass_t ukbd_devclass;
1705
1706 static device_method_t ukbd_methods[] = {
1707         DEVMETHOD(device_probe, ukbd_probe),
1708         DEVMETHOD(device_attach, ukbd_attach),
1709         DEVMETHOD(device_detach, ukbd_detach),
1710         DEVMETHOD(device_resume, ukbd_resume),
1711         {0, 0}
1712 };
1713
1714 static driver_t ukbd_driver = {
1715         .name = "ukbd",
1716         .methods = ukbd_methods,
1717         .size = sizeof(struct ukbd_softc),
1718 };
1719
1720 DRIVER_MODULE(ukbd, uhub, ukbd_driver, ukbd_devclass, ukbd_driver_load, 0);
1721 MODULE_DEPEND(ukbd, usb, 1, 1, 1);