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