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