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