xref: /freebsd/sys/dev/hid/hkbd.c (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
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 #ifdef EVDEV_SUPPORT
602 	struct epoch_tracker et;
603 #endif
604 
605 	HKBD_LOCK_ASSERT(sc);
606 
607 	sc->sc_time_ms += sc->sc_delay;
608 	sc->sc_delay = 0;
609 
610 #ifdef EVDEV_SUPPORT
611 	epoch_enter_preempt(INPUT_EPOCH, &et);
612 #endif
613 	hkbd_interrupt(sc);
614 #ifdef EVDEV_SUPPORT
615 	epoch_exit_preempt(INPUT_EPOCH, &et);
616 #endif
617 
618 	/* Make sure any leftover key events gets read out */
619 	taskqueue_enqueue(taskqueue_swi_giant, &sc->sc_task);
620 
621 	if (hkbd_any_key_pressed(sc) ||
622 	    atomic_load_acq_32(&sc->sc_inputhead) != sc->sc_inputtail) {
623 		hkbd_start_timer(sc);
624 	}
625 }
626 
627 static uint32_t
628 hkbd_apple_fn(uint32_t keycode)
629 {
630 	switch (keycode) {
631 	case 0x28: return 0x49; /* RETURN -> INSERT */
632 	case 0x2a: return 0x4c; /* BACKSPACE -> DEL */
633 	case 0x50: return 0x4a; /* LEFT ARROW -> HOME */
634 	case 0x4f: return 0x4d; /* RIGHT ARROW -> END */
635 	case 0x52: return 0x4b; /* UP ARROW -> PGUP */
636 	case 0x51: return 0x4e; /* DOWN ARROW -> PGDN */
637 	default: return keycode;
638 	}
639 }
640 
641 static uint32_t
642 hkbd_apple_swap(uint32_t keycode)
643 {
644 	switch (keycode) {
645 	case 0x35: return 0x64;
646 	case 0x64: return 0x35;
647 	default: return keycode;
648 	}
649 }
650 
651 static void
652 hkbd_intr_callback(void *context, void *data, hid_size_t len)
653 {
654 	struct hkbd_softc *sc = context;
655 	uint8_t *buf = data;
656 	uint32_t i;
657 	uint8_t id = 0;
658 	uint8_t modifiers;
659 	int offset;
660 
661 	HKBD_LOCK_ASSERT(sc);
662 
663 	DPRINTF("actlen=%d bytes\n", len);
664 
665 	if (len == 0) {
666 		DPRINTF("zero length data\n");
667 		return;
668 	}
669 
670 	if (sc->sc_kbd_id != 0) {
671 		/* check and remove HID ID byte */
672 		id = buf[0];
673 		buf++;
674 		len--;
675 		if (len == 0) {
676 			DPRINTF("zero length data\n");
677 			return;
678 		}
679 	}
680 
681 	/* clear temporary storage */
682 	memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
683 
684 	/* clear modifiers */
685 	modifiers = 0;
686 
687 	/* scan through HID data */
688 	if ((sc->sc_flags & HKBD_FLAG_APPLE_EJECT) &&
689 	    (id == sc->sc_id_apple_eject)) {
690 		if (hid_get_data(buf, len, &sc->sc_loc_apple_eject))
691 			modifiers |= MOD_EJECT;
692 	}
693 	if ((sc->sc_flags & HKBD_FLAG_APPLE_FN) &&
694 	    (id == sc->sc_id_apple_fn)) {
695 		if (hid_get_data(buf, len, &sc->sc_loc_apple_fn))
696 			modifiers |= MOD_FN;
697 	}
698 
699 	for (i = 0; i != HKBD_NKEYCODE; i++) {
700 		const uint64_t valid = sc->sc_loc_key_valid[i / 64];
701 		const uint64_t mask = 1ULL << (i % 64);
702 
703 		if (mask == 1 && valid == 0) {
704 			i += 63;
705 			continue;	/* skip empty areas */
706 		} else if (~valid & mask) {
707 			continue;	/* location is not valid */
708 		} else if (id != sc->sc_id_loc_key[i]) {
709 			continue;	/* invalid HID ID */
710 		} else if (i == 0) {
711 			offset = sc->sc_loc_key[0].count;
712 			if (offset < 0 || offset > len)
713 				offset = len;
714 			while (offset--) {
715 				uint32_t key =
716 				    hid_get_data(buf + offset, len - offset,
717 				    &sc->sc_loc_key[i]);
718 				if (modifiers & MOD_FN)
719 					key = hkbd_apple_fn(key);
720 				if (sc->sc_flags & HKBD_FLAG_APPLE_SWAP)
721 					key = hkbd_apple_swap(key);
722 				if (key == KEY_NONE || key == KEY_ERROR || key >= HKBD_NKEYCODE)
723 					continue;
724 				/* set key in bitmap */
725 				sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
726 			}
727 		} else if (hid_get_data(buf, len, &sc->sc_loc_key[i])) {
728 			uint32_t key = i;
729 
730 			if (modifiers & MOD_FN)
731 				key = hkbd_apple_fn(key);
732 			if (sc->sc_flags & HKBD_FLAG_APPLE_SWAP)
733 				key = hkbd_apple_swap(key);
734 			if (key == KEY_NONE || key == KEY_ERROR || key >= HKBD_NKEYCODE)
735 				continue;
736 			/* set key in bitmap */
737 			sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
738 		}
739 	}
740 #ifdef HID_DEBUG
741 	DPRINTF("modifiers = 0x%04x\n", modifiers);
742 	for (i = 0; i != HKBD_NKEYCODE; i++) {
743 		const uint64_t valid = sc->sc_ndata.bitmap[i / 64];
744 		const uint64_t mask = 1ULL << (i % 64);
745 
746 		if (valid & mask)
747 			DPRINTF("Key 0x%02x pressed\n", i);
748 	}
749 #endif
750 	hkbd_interrupt(sc);
751 }
752 
753 /* A match on these entries will load ukbd */
754 static const struct hid_device_id __used hkbd_devs[] = {
755 	{ HID_TLC(HUP_GENERIC_DESKTOP, HUG_KEYBOARD) },
756 };
757 
758 static int
759 hkbd_probe(device_t dev)
760 {
761 	keyboard_switch_t *sw = kbd_get_switch(HKBD_DRIVER_NAME);
762 	int error;
763 
764 	DPRINTFN(11, "\n");
765 
766 	if (sw == NULL) {
767 		return (ENXIO);
768 	}
769 
770 	error = HIDBUS_LOOKUP_DRIVER_INFO(dev, hkbd_devs);
771 	if (error != 0)
772                 return (error);
773 
774 	hidbus_set_desc(dev, "Keyboard");
775 
776 	return (BUS_PROBE_DEFAULT);
777 }
778 
779 static void
780 hkbd_parse_hid(struct hkbd_softc *sc, const uint8_t *ptr, uint32_t len,
781     uint8_t tlc_index)
782 {
783 	uint32_t flags;
784 	uint32_t key;
785 	uint8_t id;
786 
787 	/* reset detected bits */
788 	sc->sc_flags &= ~HKBD_FLAG_HID_MASK;
789 
790 	/* reset detected keys */
791 	memset(sc->sc_loc_key_valid, 0, sizeof(sc->sc_loc_key_valid));
792 
793 	/* check if there is an ID byte */
794 	sc->sc_kbd_size = hid_report_size_max(ptr, len,
795 	    hid_input, &sc->sc_kbd_id);
796 
797 	/* investigate if this is an Apple Keyboard */
798 	if (hidbus_locate(ptr, len,
799 	    HID_USAGE2(HUP_CONSUMER, HUG_APPLE_EJECT),
800 	    hid_input, tlc_index, 0, &sc->sc_loc_apple_eject, &flags,
801 	    &sc->sc_id_apple_eject, NULL)) {
802 		if (flags & HIO_VARIABLE)
803 			sc->sc_flags |= HKBD_FLAG_APPLE_EJECT |
804 			    HKBD_FLAG_APPLE_SWAP;
805 		DPRINTFN(1, "Found Apple eject-key\n");
806 	}
807 	if (hidbus_locate(ptr, len,
808 	    HID_USAGE2(0xFFFF, 0x0003),
809 	    hid_input, tlc_index, 0, &sc->sc_loc_apple_fn, &flags,
810 	    &sc->sc_id_apple_fn, NULL)) {
811 		if (flags & HIO_VARIABLE)
812 			sc->sc_flags |= HKBD_FLAG_APPLE_FN;
813 		DPRINTFN(1, "Found Apple FN-key\n");
814 	}
815 
816 	/* figure out event buffer */
817 	if (hidbus_locate(ptr, len,
818 	    HID_USAGE2(HUP_KEYBOARD, 0x00),
819 	    hid_input, tlc_index, 0, &sc->sc_loc_key[0], &flags,
820 	    &sc->sc_id_loc_key[0], NULL)) {
821 		if (flags & HIO_VARIABLE) {
822 			DPRINTFN(1, "Ignoring keyboard event control\n");
823 		} else {
824 			sc->sc_loc_key_valid[0] |= 1;
825 			DPRINTFN(1, "Found keyboard event array\n");
826 		}
827 	}
828 
829 	/* figure out the keys */
830 	for (key = 1; key != HKBD_NKEYCODE; key++) {
831 		if (hidbus_locate(ptr, len,
832 		    HID_USAGE2(HUP_KEYBOARD, key),
833 		    hid_input, tlc_index, 0, &sc->sc_loc_key[key], &flags,
834 		    &sc->sc_id_loc_key[key], NULL)) {
835 			if (flags & HIO_VARIABLE) {
836 				sc->sc_loc_key_valid[key / 64] |=
837 				    1ULL << (key % 64);
838 				DPRINTFN(1, "Found key 0x%02x\n", key);
839 			}
840 		}
841 	}
842 
843 	/* figure out leds on keyboard */
844 	if (hidbus_locate(ptr, len,
845 	    HID_USAGE2(HUP_LEDS, 0x01),
846 	    hid_output, tlc_index, 0, &sc->sc_loc_numlock, &flags,
847 	    &sc->sc_id_leds, NULL)) {
848 		if (flags & HIO_VARIABLE)
849 			sc->sc_flags |= HKBD_FLAG_NUMLOCK;
850 		DPRINTFN(1, "Found keyboard numlock\n");
851 	}
852 	if (hidbus_locate(ptr, len,
853 	    HID_USAGE2(HUP_LEDS, 0x02),
854 	    hid_output, tlc_index, 0, &sc->sc_loc_capslock, &flags,
855 	    &id, NULL)) {
856 		if ((sc->sc_flags & HKBD_FLAG_NUMLOCK) == 0)
857 			sc->sc_id_leds = id;
858 		if (flags & HIO_VARIABLE && sc->sc_id_leds == id)
859 			sc->sc_flags |= HKBD_FLAG_CAPSLOCK;
860 		DPRINTFN(1, "Found keyboard capslock\n");
861 	}
862 	if (hidbus_locate(ptr, len,
863 	    HID_USAGE2(HUP_LEDS, 0x03),
864 	    hid_output, tlc_index, 0, &sc->sc_loc_scrolllock, &flags,
865 	    &id, NULL)) {
866 		if ((sc->sc_flags & (HKBD_FLAG_NUMLOCK | HKBD_FLAG_CAPSLOCK))
867 		    == 0)
868 			sc->sc_id_leds = id;
869 		if (flags & HIO_VARIABLE && sc->sc_id_leds == id)
870 			sc->sc_flags |= HKBD_FLAG_SCROLLLOCK;
871 		DPRINTFN(1, "Found keyboard scrolllock\n");
872 	}
873 
874 	if ((sc->sc_flags & (HKBD_FLAG_NUMLOCK | HKBD_FLAG_CAPSLOCK |
875 	    HKBD_FLAG_SCROLLLOCK)) != 0)
876 		sc->sc_led_size = hid_report_size(ptr, len,
877 		    hid_output, sc->sc_id_leds);
878 }
879 
880 static int
881 hkbd_attach(device_t dev)
882 {
883 	struct hkbd_softc *sc = device_get_softc(dev);
884 	const struct hid_device_info *hw = hid_get_device_info(dev);
885 	int unit = device_get_unit(dev);
886 	keyboard_t *kbd = &sc->sc_kbd;
887 	void *hid_ptr = NULL;
888 	int err;
889 	uint16_t n;
890 	hid_size_t hid_len;
891 	uint8_t tlc_index = hidbus_get_index(dev);
892 #ifdef EVDEV_SUPPORT
893 	struct evdev_dev *evdev;
894 	int i;
895 #endif
896 
897 	sc->sc_dev = dev;
898 	SYSCONS_LOCK_ASSERT();
899 
900 	kbd_init_struct(kbd, HKBD_DRIVER_NAME, KB_OTHER, unit, 0, 0, 0);
901 
902 	kbd->kb_data = (void *)sc;
903 
904 	sc->sc_mode = K_XLATE;
905 
906 	mtx_init(&sc->sc_mtx, "hkbd lock", NULL, MTX_DEF);
907 	TASK_INIT(&sc->sc_task, 0, hkbd_event_keyinput, sc);
908 	callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0);
909 
910 	hidbus_set_intr(dev, hkbd_intr_callback, sc);
911 	/* interrupt handler will be called with hkbd mutex taken */
912 	hidbus_set_lock(dev, &sc->sc_mtx);
913 	/* interrupt handler can be called during panic */
914 	hidbus_set_flags(dev, hidbus_get_flags(dev) & HIDBUS_FLAG_CAN_POLL);
915 
916 	/* setup default keyboard maps */
917 
918 	sc->sc_keymap = key_map;
919 	sc->sc_accmap = accent_map;
920 	for (n = 0; n < HKBD_NFKEY; n++) {
921 		sc->sc_fkeymap[n] = fkey_tab[n];
922 	}
923 
924 	kbd_set_maps(kbd, &sc->sc_keymap, &sc->sc_accmap,
925 	    sc->sc_fkeymap, HKBD_NFKEY);
926 
927 	KBD_FOUND_DEVICE(kbd);
928 
929 	hkbd_clear_state(kbd);
930 
931 	/*
932 	 * FIXME: set the initial value for lock keys in "sc_state"
933 	 * according to the BIOS data?
934 	 */
935 	KBD_PROBE_DONE(kbd);
936 
937 	/* get HID descriptor */
938 	err = hid_get_report_descr(dev, &hid_ptr, &hid_len);
939 
940 	if (err == 0) {
941 		DPRINTF("Parsing HID descriptor of %d bytes\n",
942 		    (int)hid_len);
943 
944 		hkbd_parse_hid(sc, hid_ptr, hid_len, tlc_index);
945 	}
946 
947 	/* check if we should use the boot protocol */
948 	if (hid_test_quirk(hw, HQ_KBD_BOOTPROTO) ||
949 	    (err != 0) || hkbd_any_key_valid(sc) == false) {
950 		DPRINTF("Forcing boot protocol\n");
951 
952 		err = hid_set_protocol(dev, 0);
953 
954 		if (err != 0) {
955 			DPRINTF("Set protocol error=%d (ignored)\n", err);
956 		}
957 
958 		hkbd_parse_hid(sc, hkbd_boot_desc, sizeof(hkbd_boot_desc), 0);
959 	}
960 
961 	/* ignore if SETIDLE fails, hence it is not crucial */
962 	hid_set_idle(dev, 0, 0);
963 
964 	hkbd_ioctl(kbd, KDSETLED, (caddr_t)&sc->sc_state);
965 
966 	KBD_INIT_DONE(kbd);
967 
968 	if (kbd_register(kbd) < 0) {
969 		goto detach;
970 	}
971 	KBD_CONFIG_DONE(kbd);
972 
973 	hkbd_enable(kbd);
974 
975 #ifdef KBD_INSTALL_CDEV
976 	if (kbd_attach(kbd)) {
977 		goto detach;
978 	}
979 #endif
980 
981 #ifdef EVDEV_SUPPORT
982 	evdev = evdev_alloc();
983 	evdev_set_name(evdev, device_get_desc(dev));
984 	evdev_set_phys(evdev, device_get_nameunit(dev));
985 	evdev_set_id(evdev, hw->idBus, hw->idVendor, hw->idProduct,
986 	    hw->idVersion);
987 	evdev_set_serial(evdev, hw->serial);
988 	evdev_set_methods(evdev, kbd, &hkbd_evdev_methods);
989 	evdev_set_flag(evdev, EVDEV_FLAG_EXT_EPOCH);	/* hidbus child */
990 	evdev_support_event(evdev, EV_SYN);
991 	evdev_support_event(evdev, EV_KEY);
992 	if (sc->sc_flags & (HKBD_FLAG_NUMLOCK | HKBD_FLAG_CAPSLOCK |
993 			    HKBD_FLAG_SCROLLLOCK))
994 		evdev_support_event(evdev, EV_LED);
995 	evdev_support_event(evdev, EV_REP);
996 
997 	for (i = 0x00; i <= 0xFF; i++)
998 		evdev_support_key(evdev, evdev_hid2key(i));
999 	if (sc->sc_flags & HKBD_FLAG_NUMLOCK)
1000 		evdev_support_led(evdev, LED_NUML);
1001 	if (sc->sc_flags & HKBD_FLAG_CAPSLOCK)
1002 		evdev_support_led(evdev, LED_CAPSL);
1003 	if (sc->sc_flags & HKBD_FLAG_SCROLLLOCK)
1004 		evdev_support_led(evdev, LED_SCROLLL);
1005 
1006 	if (evdev_register(evdev))
1007 		evdev_free(evdev);
1008 	else
1009 		sc->sc_evdev = evdev;
1010 #endif
1011 
1012 	sc->sc_flags |= HKBD_FLAG_ATTACHED;
1013 
1014 	if (bootverbose) {
1015 		kbdd_diag(kbd, bootverbose);
1016 	}
1017 
1018 	/* start the keyboard */
1019 	hidbus_intr_start(dev);
1020 
1021 	return (0);			/* success */
1022 
1023 detach:
1024 	hkbd_detach(dev);
1025 	return (ENXIO);			/* error */
1026 }
1027 
1028 static int
1029 hkbd_detach(device_t dev)
1030 {
1031 	struct hkbd_softc *sc = device_get_softc(dev);
1032 #ifdef EVDEV_SUPPORT
1033 	struct epoch_tracker et;
1034 #endif
1035 	int error;
1036 
1037 	SYSCONS_LOCK_ASSERT();
1038 
1039 	DPRINTF("\n");
1040 
1041 	sc->sc_flags |= HKBD_FLAG_GONE;
1042 
1043 	HKBD_LOCK(sc);
1044 	callout_stop(&sc->sc_callout);
1045 	HKBD_UNLOCK(sc);
1046 
1047 	/* kill any stuck keys */
1048 	if (sc->sc_flags & HKBD_FLAG_ATTACHED) {
1049 		/* stop receiving events from the USB keyboard */
1050 		hidbus_intr_stop(dev);
1051 
1052 		/* release all leftover keys, if any */
1053 		memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1054 
1055 		/* process releasing of all keys */
1056 		HKBD_LOCK(sc);
1057 #ifdef EVDEV_SUPPORT
1058 		epoch_enter_preempt(INPUT_EPOCH, &et);
1059 #endif
1060 		hkbd_interrupt(sc);
1061 #ifdef EVDEV_SUPPORT
1062 		epoch_exit_preempt(INPUT_EPOCH, &et);
1063 #endif
1064 		HKBD_UNLOCK(sc);
1065 		taskqueue_drain(taskqueue_swi_giant, &sc->sc_task);
1066 	}
1067 
1068 	mtx_destroy(&sc->sc_mtx);
1069 	hkbd_disable(&sc->sc_kbd);
1070 
1071 #ifdef KBD_INSTALL_CDEV
1072 	if (sc->sc_flags & HKBD_FLAG_ATTACHED) {
1073 		error = kbd_detach(&sc->sc_kbd);
1074 		if (error) {
1075 			/* usb attach cannot return an error */
1076 			device_printf(dev, "WARNING: kbd_detach() "
1077 			    "returned non-zero! (ignored)\n");
1078 		}
1079 	}
1080 #endif
1081 
1082 #ifdef EVDEV_SUPPORT
1083 	evdev_free(sc->sc_evdev);
1084 #endif
1085 
1086 	if (KBD_IS_CONFIGURED(&sc->sc_kbd)) {
1087 		error = kbd_unregister(&sc->sc_kbd);
1088 		if (error) {
1089 			/* usb attach cannot return an error */
1090 			device_printf(dev, "WARNING: kbd_unregister() "
1091 			    "returned non-zero! (ignored)\n");
1092 		}
1093 	}
1094 	sc->sc_kbd.kb_flags = 0;
1095 
1096 	DPRINTF("%s: disconnected\n",
1097 	    device_get_nameunit(dev));
1098 
1099 	return (0);
1100 }
1101 
1102 static int
1103 hkbd_resume(device_t dev)
1104 {
1105 	struct hkbd_softc *sc = device_get_softc(dev);
1106 
1107 	SYSCONS_LOCK_ASSERT();
1108 
1109 	hkbd_clear_state(&sc->sc_kbd);
1110 
1111 	return (0);
1112 }
1113 
1114 #ifdef EVDEV_SUPPORT
1115 static void
1116 hkbd_ev_event(struct evdev_dev *evdev, uint16_t type, uint16_t code,
1117     int32_t value)
1118 {
1119 	keyboard_t *kbd = evdev_get_softc(evdev);
1120 
1121 	if (evdev_rcpt_mask & EVDEV_RCPT_HW_KBD &&
1122 	    (type == EV_LED || type == EV_REP)) {
1123 		mtx_lock(&Giant);
1124 		kbd_ev_event(kbd, type, code, value);
1125 		mtx_unlock(&Giant);
1126 	}
1127 }
1128 #endif
1129 
1130 /* early keyboard probe, not supported */
1131 static int
1132 hkbd_configure(int flags)
1133 {
1134 	return (0);
1135 }
1136 
1137 /* detect a keyboard, not used */
1138 static int
1139 hkbd__probe(int unit, void *arg, int flags)
1140 {
1141 	return (ENXIO);
1142 }
1143 
1144 /* reset and initialize the device, not used */
1145 static int
1146 hkbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
1147 {
1148 	return (ENXIO);
1149 }
1150 
1151 /* test the interface to the device, not used */
1152 static int
1153 hkbd_test_if(keyboard_t *kbd)
1154 {
1155 	return (0);
1156 }
1157 
1158 /* finish using this keyboard, not used */
1159 static int
1160 hkbd_term(keyboard_t *kbd)
1161 {
1162 	return (ENXIO);
1163 }
1164 
1165 /* keyboard interrupt routine, not used */
1166 static int
1167 hkbd_intr(keyboard_t *kbd, void *arg)
1168 {
1169 	return (0);
1170 }
1171 
1172 /* lock the access to the keyboard, not used */
1173 static int
1174 hkbd_lock(keyboard_t *kbd, int lock)
1175 {
1176 	return (1);
1177 }
1178 
1179 /*
1180  * Enable the access to the device; until this function is called,
1181  * the client cannot read from the keyboard.
1182  */
1183 static int
1184 hkbd_enable(keyboard_t *kbd)
1185 {
1186 
1187 	SYSCONS_LOCK();
1188 	KBD_ACTIVATE(kbd);
1189 	SYSCONS_UNLOCK();
1190 
1191 	return (0);
1192 }
1193 
1194 /* disallow the access to the device */
1195 static int
1196 hkbd_disable(keyboard_t *kbd)
1197 {
1198 
1199 	SYSCONS_LOCK();
1200 	KBD_DEACTIVATE(kbd);
1201 	SYSCONS_UNLOCK();
1202 
1203 	return (0);
1204 }
1205 
1206 /* check if data is waiting */
1207 /* Currently unused. */
1208 static int
1209 hkbd_check(keyboard_t *kbd)
1210 {
1211 	struct hkbd_softc *sc = kbd->kb_data;
1212 
1213 	SYSCONS_LOCK_ASSERT();
1214 
1215 	if (!KBD_IS_ACTIVE(kbd))
1216 		return (0);
1217 
1218 	if (sc->sc_flags & HKBD_FLAG_POLLING)
1219 		hkbd_do_poll(sc, 0);
1220 
1221 #ifdef HKBD_EMULATE_ATSCANCODE
1222 	if (sc->sc_buffered_char[0]) {
1223 		return (1);
1224 	}
1225 #endif
1226 	if (sc->sc_inputhead != atomic_load_acq_32(&sc->sc_inputtail)) {
1227 		return (1);
1228 	}
1229 	return (0);
1230 }
1231 
1232 /* check if char is waiting */
1233 static int
1234 hkbd_check_char_locked(keyboard_t *kbd)
1235 {
1236 	struct hkbd_softc *sc = kbd->kb_data;
1237 
1238 	SYSCONS_LOCK_ASSERT();
1239 
1240 	if (!KBD_IS_ACTIVE(kbd))
1241 		return (0);
1242 
1243 	if ((sc->sc_composed_char > 0) &&
1244 	    (!(sc->sc_flags & HKBD_FLAG_COMPOSE))) {
1245 		return (1);
1246 	}
1247 	return (hkbd_check(kbd));
1248 }
1249 
1250 static int
1251 hkbd_check_char(keyboard_t *kbd)
1252 {
1253 	int result;
1254 
1255 	SYSCONS_LOCK();
1256 	result = hkbd_check_char_locked(kbd);
1257 	SYSCONS_UNLOCK();
1258 
1259 	return (result);
1260 }
1261 
1262 /* read one byte from the keyboard if it's allowed */
1263 /* Currently unused. */
1264 static int
1265 hkbd_read(keyboard_t *kbd, int wait)
1266 {
1267 	struct hkbd_softc *sc = kbd->kb_data;
1268 	int32_t usbcode;
1269 #ifdef HKBD_EMULATE_ATSCANCODE
1270 	uint32_t keycode;
1271 	uint32_t scancode;
1272 
1273 #endif
1274 
1275 	SYSCONS_LOCK_ASSERT();
1276 
1277 	if (!KBD_IS_ACTIVE(kbd))
1278 		return (-1);
1279 
1280 #ifdef HKBD_EMULATE_ATSCANCODE
1281 	if (sc->sc_buffered_char[0]) {
1282 		scancode = sc->sc_buffered_char[0];
1283 		if (scancode & SCAN_PREFIX) {
1284 			sc->sc_buffered_char[0] &= ~SCAN_PREFIX;
1285 			return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1286 		}
1287 		sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1288 		sc->sc_buffered_char[1] = 0;
1289 		return (scancode);
1290 	}
1291 #endif					/* HKBD_EMULATE_ATSCANCODE */
1292 
1293 	/* XXX */
1294 	usbcode = hkbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1295 	if (!KBD_IS_ACTIVE(kbd) || (usbcode == -1))
1296 		return (-1);
1297 
1298 	++(kbd->kb_count);
1299 
1300 #ifdef HKBD_EMULATE_ATSCANCODE
1301 	keycode = hkbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1302 	if (keycode == NN) {
1303 		return -1;
1304 	}
1305 	return (hkbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1306 	    (usbcode & KEY_RELEASE)));
1307 #else					/* !HKBD_EMULATE_ATSCANCODE */
1308 	return (usbcode);
1309 #endif					/* HKBD_EMULATE_ATSCANCODE */
1310 }
1311 
1312 /* read char from the keyboard */
1313 static uint32_t
1314 hkbd_read_char_locked(keyboard_t *kbd, int wait)
1315 {
1316 	struct hkbd_softc *sc = kbd->kb_data;
1317 	uint32_t action;
1318 	uint32_t keycode;
1319 	int32_t usbcode;
1320 #ifdef HKBD_EMULATE_ATSCANCODE
1321 	uint32_t scancode;
1322 #endif
1323 
1324 	SYSCONS_LOCK_ASSERT();
1325 
1326 	if (!KBD_IS_ACTIVE(kbd))
1327 		return (NOKEY);
1328 
1329 next_code:
1330 
1331 	/* do we have a composed char to return ? */
1332 
1333 	if ((sc->sc_composed_char > 0) &&
1334 	    (!(sc->sc_flags & HKBD_FLAG_COMPOSE))) {
1335 		action = sc->sc_composed_char;
1336 		sc->sc_composed_char = 0;
1337 
1338 		if (action > 0xFF) {
1339 			goto errkey;
1340 		}
1341 		goto done;
1342 	}
1343 #ifdef HKBD_EMULATE_ATSCANCODE
1344 
1345 	/* do we have a pending raw scan code? */
1346 
1347 	if (sc->sc_mode == K_RAW) {
1348 		scancode = sc->sc_buffered_char[0];
1349 		if (scancode) {
1350 			if (scancode & SCAN_PREFIX) {
1351 				sc->sc_buffered_char[0] = (scancode & ~SCAN_PREFIX);
1352 				return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1353 			}
1354 			sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1355 			sc->sc_buffered_char[1] = 0;
1356 			return (scancode);
1357 		}
1358 	}
1359 #endif					/* HKBD_EMULATE_ATSCANCODE */
1360 
1361 	/* see if there is something in the keyboard port */
1362 	/* XXX */
1363 	usbcode = hkbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1364 	if (usbcode == -1) {
1365 		return (NOKEY);
1366 	}
1367 	++kbd->kb_count;
1368 
1369 #ifdef HKBD_EMULATE_ATSCANCODE
1370 	/* USB key index -> key code -> AT scan code */
1371 	keycode = hkbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1372 	if (keycode == NN) {
1373 		return (NOKEY);
1374 	}
1375 	/* return an AT scan code for the K_RAW mode */
1376 	if (sc->sc_mode == K_RAW) {
1377 		return (hkbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1378 		    (usbcode & KEY_RELEASE)));
1379 	}
1380 #else					/* !HKBD_EMULATE_ATSCANCODE */
1381 
1382 	/* return the byte as is for the K_RAW mode */
1383 	if (sc->sc_mode == K_RAW) {
1384 		return (usbcode);
1385 	}
1386 	/* USB key index -> key code */
1387 	keycode = hkbd_trtab[KEY_INDEX(usbcode)];
1388 	if (keycode == NN) {
1389 		return (NOKEY);
1390 	}
1391 #endif					/* HKBD_EMULATE_ATSCANCODE */
1392 
1393 	switch (keycode) {
1394 	case 0x38:			/* left alt (compose key) */
1395 		if (usbcode & KEY_RELEASE) {
1396 			if (sc->sc_flags & HKBD_FLAG_COMPOSE) {
1397 				sc->sc_flags &= ~HKBD_FLAG_COMPOSE;
1398 
1399 				if (sc->sc_composed_char > 0xFF) {
1400 					sc->sc_composed_char = 0;
1401 				}
1402 			}
1403 		} else {
1404 			if (!(sc->sc_flags & HKBD_FLAG_COMPOSE)) {
1405 				sc->sc_flags |= HKBD_FLAG_COMPOSE;
1406 				sc->sc_composed_char = 0;
1407 			}
1408 		}
1409 		break;
1410 	}
1411 
1412 	/* return the key code in the K_CODE mode */
1413 	if (usbcode & KEY_RELEASE) {
1414 		keycode |= SCAN_RELEASE;
1415 	}
1416 	if (sc->sc_mode == K_CODE) {
1417 		return (keycode);
1418 	}
1419 	/* compose a character code */
1420 	if (sc->sc_flags & HKBD_FLAG_COMPOSE) {
1421 		switch (keycode) {
1422 			/* key pressed, process it */
1423 		case 0x47:
1424 		case 0x48:
1425 		case 0x49:		/* keypad 7,8,9 */
1426 			sc->sc_composed_char *= 10;
1427 			sc->sc_composed_char += keycode - 0x40;
1428 			goto check_composed;
1429 
1430 		case 0x4B:
1431 		case 0x4C:
1432 		case 0x4D:		/* keypad 4,5,6 */
1433 			sc->sc_composed_char *= 10;
1434 			sc->sc_composed_char += keycode - 0x47;
1435 			goto check_composed;
1436 
1437 		case 0x4F:
1438 		case 0x50:
1439 		case 0x51:		/* keypad 1,2,3 */
1440 			sc->sc_composed_char *= 10;
1441 			sc->sc_composed_char += keycode - 0x4E;
1442 			goto check_composed;
1443 
1444 		case 0x52:		/* keypad 0 */
1445 			sc->sc_composed_char *= 10;
1446 			goto check_composed;
1447 
1448 			/* key released, no interest here */
1449 		case SCAN_RELEASE | 0x47:
1450 		case SCAN_RELEASE | 0x48:
1451 		case SCAN_RELEASE | 0x49:	/* keypad 7,8,9 */
1452 		case SCAN_RELEASE | 0x4B:
1453 		case SCAN_RELEASE | 0x4C:
1454 		case SCAN_RELEASE | 0x4D:	/* keypad 4,5,6 */
1455 		case SCAN_RELEASE | 0x4F:
1456 		case SCAN_RELEASE | 0x50:
1457 		case SCAN_RELEASE | 0x51:	/* keypad 1,2,3 */
1458 		case SCAN_RELEASE | 0x52:	/* keypad 0 */
1459 			goto next_code;
1460 
1461 		case 0x38:		/* left alt key */
1462 			break;
1463 
1464 		default:
1465 			if (sc->sc_composed_char > 0) {
1466 				sc->sc_flags &= ~HKBD_FLAG_COMPOSE;
1467 				sc->sc_composed_char = 0;
1468 				goto errkey;
1469 			}
1470 			break;
1471 		}
1472 	}
1473 	/* keycode to key action */
1474 	action = genkbd_keyaction(kbd, SCAN_CHAR(keycode),
1475 	    (keycode & SCAN_RELEASE),
1476 	    &sc->sc_state, &sc->sc_accents);
1477 	if (action == NOKEY) {
1478 		goto next_code;
1479 	}
1480 done:
1481 	return (action);
1482 
1483 check_composed:
1484 	if (sc->sc_composed_char <= 0xFF) {
1485 		goto next_code;
1486 	}
1487 errkey:
1488 	return (ERRKEY);
1489 }
1490 
1491 /* Currently wait is always false. */
1492 static uint32_t
1493 hkbd_read_char(keyboard_t *kbd, int wait)
1494 {
1495 	uint32_t keycode;
1496 
1497 	SYSCONS_LOCK();
1498 	keycode = hkbd_read_char_locked(kbd, wait);
1499 	SYSCONS_UNLOCK();
1500 
1501 	return (keycode);
1502 }
1503 
1504 /* some useful control functions */
1505 static int
1506 hkbd_ioctl_locked(keyboard_t *kbd, u_long cmd, caddr_t arg)
1507 {
1508 	struct hkbd_softc *sc = kbd->kb_data;
1509 #ifdef EVDEV_SUPPORT
1510 	struct epoch_tracker et;
1511 #endif
1512 	int error;
1513 	int i;
1514 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1515     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1516 	int ival;
1517 
1518 #endif
1519 
1520 	SYSCONS_LOCK_ASSERT();
1521 
1522 	switch (cmd) {
1523 	case KDGKBMODE:		/* get keyboard mode */
1524 		*(int *)arg = sc->sc_mode;
1525 		break;
1526 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1527     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1528 	case _IO('K', 7):
1529 		ival = IOCPARM_IVAL(arg);
1530 		arg = (caddr_t)&ival;
1531 		/* FALLTHROUGH */
1532 #endif
1533 	case KDSKBMODE:		/* set keyboard mode */
1534 		switch (*(int *)arg) {
1535 		case K_XLATE:
1536 			if (sc->sc_mode != K_XLATE) {
1537 				/* make lock key state and LED state match */
1538 				sc->sc_state &= ~LOCK_MASK;
1539 				sc->sc_state |= KBD_LED_VAL(kbd);
1540 			}
1541 			/* FALLTHROUGH */
1542 		case K_RAW:
1543 		case K_CODE:
1544 			if (sc->sc_mode != *(int *)arg) {
1545 				if ((sc->sc_flags & HKBD_FLAG_POLLING) == 0)
1546 					hkbd_clear_state(kbd);
1547 				sc->sc_mode = *(int *)arg;
1548 			}
1549 			break;
1550 		default:
1551 			return (EINVAL);
1552 		}
1553 		break;
1554 
1555 	case KDGETLED:			/* get keyboard LED */
1556 		*(int *)arg = KBD_LED_VAL(kbd);
1557 		break;
1558 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1559     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1560 	case _IO('K', 66):
1561 		ival = IOCPARM_IVAL(arg);
1562 		arg = (caddr_t)&ival;
1563 		/* FALLTHROUGH */
1564 #endif
1565 	case KDSETLED:			/* set keyboard LED */
1566 		/* NOTE: lock key state in "sc_state" won't be changed */
1567 		if (*(int *)arg & ~LOCK_MASK)
1568 			return (EINVAL);
1569 
1570 		i = *(int *)arg;
1571 
1572 		/* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1573 		if (sc->sc_mode == K_XLATE &&
1574 		    kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1575 			if (i & ALKED)
1576 				i |= CLKED;
1577 			else
1578 				i &= ~CLKED;
1579 		}
1580 		if (KBD_HAS_DEVICE(kbd)) {
1581 			error = hkbd_set_leds(sc, i);
1582 			if (error)
1583 				return (error);
1584 		}
1585 #ifdef EVDEV_SUPPORT
1586 		if (sc->sc_evdev != NULL && !HID_IN_POLLING_MODE()) {
1587 			epoch_enter_preempt(INPUT_EPOCH, &et);
1588 			evdev_push_leds(sc->sc_evdev, i);
1589 			epoch_exit_preempt(INPUT_EPOCH, &et);
1590 		}
1591 #endif
1592 
1593 		KBD_LED_VAL(kbd) = *(int *)arg;
1594 		break;
1595 
1596 	case KDGKBSTATE:		/* get lock key state */
1597 		*(int *)arg = sc->sc_state & LOCK_MASK;
1598 		break;
1599 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1600     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1601 	case _IO('K', 20):
1602 		ival = IOCPARM_IVAL(arg);
1603 		arg = (caddr_t)&ival;
1604 		/* FALLTHROUGH */
1605 #endif
1606 	case KDSKBSTATE:		/* set lock key state */
1607 		if (*(int *)arg & ~LOCK_MASK) {
1608 			return (EINVAL);
1609 		}
1610 		sc->sc_state &= ~LOCK_MASK;
1611 		sc->sc_state |= *(int *)arg;
1612 
1613 		/* set LEDs and quit */
1614 		return (hkbd_ioctl_locked(kbd, KDSETLED, arg));
1615 
1616 	case KDSETREPEAT:		/* set keyboard repeat rate (new
1617 					 * interface) */
1618 		if (!KBD_HAS_DEVICE(kbd)) {
1619 			return (0);
1620 		}
1621 		/*
1622 		 * Convert negative, zero and tiny args to the same limits
1623 		 * as atkbd.  We could support delays of 1 msec, but
1624 		 * anything much shorter than the shortest atkbd value
1625 		 * of 250.34 is almost unusable as well as incompatible.
1626 		 */
1627 		kbd->kb_delay1 = imax(((int *)arg)[0], 250);
1628 		kbd->kb_delay2 = imax(((int *)arg)[1], 34);
1629 #ifdef EVDEV_SUPPORT
1630 		if (sc->sc_evdev != NULL && !HID_IN_POLLING_MODE()) {
1631 			epoch_enter_preempt(INPUT_EPOCH, &et);
1632 			evdev_push_repeats(sc->sc_evdev, kbd);
1633 			epoch_exit_preempt(INPUT_EPOCH, &et);
1634 		}
1635 #endif
1636 		return (0);
1637 
1638 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1639     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1640 	case _IO('K', 67):
1641 		ival = IOCPARM_IVAL(arg);
1642 		arg = (caddr_t)&ival;
1643 		/* FALLTHROUGH */
1644 #endif
1645 	case KDSETRAD:			/* set keyboard repeat rate (old
1646 					 * interface) */
1647 		return (hkbd_set_typematic(kbd, *(int *)arg));
1648 
1649 	case PIO_KEYMAP:		/* set keyboard translation table */
1650 	case OPIO_KEYMAP:		/* set keyboard translation table
1651 					 * (compat) */
1652 	case PIO_KEYMAPENT:		/* set keyboard translation table
1653 					 * entry */
1654 	case PIO_DEADKEYMAP:		/* set accent key translation table */
1655 		sc->sc_accents = 0;
1656 		/* FALLTHROUGH */
1657 	default:
1658 		return (genkbd_commonioctl(kbd, cmd, arg));
1659 	}
1660 
1661 	return (0);
1662 }
1663 
1664 static int
1665 hkbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
1666 {
1667 	int result;
1668 
1669 	/*
1670 	 * XXX Check if someone is calling us from a critical section:
1671 	 */
1672 	if (curthread->td_critnest != 0)
1673 		return (EDEADLK);
1674 
1675 	/*
1676 	 * XXX KDGKBSTATE, KDSKBSTATE and KDSETLED can be called from any
1677 	 * context where printf(9) can be called, which among other things
1678 	 * includes interrupt filters and threads with any kinds of locks
1679 	 * already held.  For this reason it would be dangerous to acquire
1680 	 * the Giant here unconditionally.  On the other hand we have to
1681 	 * have it to handle the ioctl.
1682 	 * So we make our best effort to auto-detect whether we can grab
1683 	 * the Giant or not.  Blame syscons(4) for this.
1684 	 */
1685 	switch (cmd) {
1686 	case KDGKBSTATE:
1687 	case KDSKBSTATE:
1688 	case KDSETLED:
1689 		if (!mtx_owned(&Giant) && !HID_IN_POLLING_MODE())
1690 			return (EDEADLK);	/* best I could come up with */
1691 		/* FALLTHROUGH */
1692 	default:
1693 		SYSCONS_LOCK();
1694 		result = hkbd_ioctl_locked(kbd, cmd, arg);
1695 		SYSCONS_UNLOCK();
1696 		return (result);
1697 	}
1698 }
1699 
1700 /* clear the internal state of the keyboard */
1701 static void
1702 hkbd_clear_state(keyboard_t *kbd)
1703 {
1704 	struct hkbd_softc *sc = kbd->kb_data;
1705 
1706 	SYSCONS_LOCK_ASSERT();
1707 
1708 	sc->sc_flags &= ~(HKBD_FLAG_COMPOSE | HKBD_FLAG_POLLING);
1709 	sc->sc_state &= LOCK_MASK;	/* preserve locking key state */
1710 	sc->sc_accents = 0;
1711 	sc->sc_composed_char = 0;
1712 #ifdef HKBD_EMULATE_ATSCANCODE
1713 	sc->sc_buffered_char[0] = 0;
1714 	sc->sc_buffered_char[1] = 0;
1715 #endif
1716 	memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1717 	memset(&sc->sc_odata, 0, sizeof(sc->sc_odata));
1718 	sc->sc_repeat_time = 0;
1719 	sc->sc_repeat_key = 0;
1720 }
1721 
1722 /* save the internal state, not used */
1723 static int
1724 hkbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1725 {
1726 	return (len == 0) ? 1 : -1;
1727 }
1728 
1729 /* set the internal state, not used */
1730 static int
1731 hkbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1732 {
1733 	return (EINVAL);
1734 }
1735 
1736 static int
1737 hkbd_poll(keyboard_t *kbd, int on)
1738 {
1739 	struct hkbd_softc *sc = kbd->kb_data;
1740 
1741 	SYSCONS_LOCK();
1742 	/*
1743 	 * Keep a reference count on polling to allow recursive
1744 	 * cngrab() during a panic for example.
1745 	 */
1746 	if (on)
1747 		sc->sc_polling++;
1748 	else if (sc->sc_polling > 0)
1749 		sc->sc_polling--;
1750 
1751 	if (sc->sc_polling != 0) {
1752 		sc->sc_flags |= HKBD_FLAG_POLLING;
1753 		sc->sc_poll_thread = curthread;
1754 	} else {
1755 		sc->sc_flags &= ~HKBD_FLAG_POLLING;
1756 		sc->sc_delay = 0;
1757 	}
1758 	SYSCONS_UNLOCK();
1759 
1760 	return (0);
1761 }
1762 
1763 /* local functions */
1764 
1765 static int
1766 hkbd_set_leds(struct hkbd_softc *sc, uint8_t leds)
1767 {
1768 	uint8_t id;
1769 	uint8_t any;
1770 	uint8_t *buf;
1771 	int len;
1772 	int error;
1773 
1774 	SYSCONS_LOCK_ASSERT();
1775 	DPRINTF("leds=0x%02x\n", leds);
1776 
1777 #ifdef HID_DEBUG
1778 	if (hkbd_no_leds)
1779 		return (0);
1780 #endif
1781 
1782 	memset(sc->sc_buffer, 0, HKBD_BUFFER_SIZE);
1783 
1784 	id = sc->sc_id_leds;
1785 	any = 0;
1786 
1787 	/* Assumption: All led bits must be in the same ID. */
1788 
1789 	if (sc->sc_flags & HKBD_FLAG_NUMLOCK) {
1790 		hid_put_udata(sc->sc_buffer + 1, HKBD_BUFFER_SIZE - 1,
1791 		    &sc->sc_loc_numlock, leds & NLKED ? 1 : 0);
1792 		any = 1;
1793 	}
1794 
1795 	if (sc->sc_flags & HKBD_FLAG_SCROLLLOCK) {
1796 		hid_put_udata(sc->sc_buffer + 1, HKBD_BUFFER_SIZE - 1,
1797 		    &sc->sc_loc_scrolllock, leds & SLKED ? 1 : 0);
1798 		any = 1;
1799 	}
1800 
1801 	if (sc->sc_flags & HKBD_FLAG_CAPSLOCK) {
1802 		hid_put_udata(sc->sc_buffer + 1, HKBD_BUFFER_SIZE - 1,
1803 		    &sc->sc_loc_capslock, leds & CLKED ? 1 : 0);
1804 		any = 1;
1805 	}
1806 
1807 	/* if no leds, nothing to do */
1808 	if (!any)
1809 		return (0);
1810 
1811 	/* range check output report length */
1812 	len = sc->sc_led_size;
1813 	if (len > (HKBD_BUFFER_SIZE - 1))
1814 		len = (HKBD_BUFFER_SIZE - 1);
1815 
1816 	/* check if we need to prefix an ID byte */
1817 
1818 	if (id != 0) {
1819 		sc->sc_buffer[0] = id;
1820 		buf = sc->sc_buffer;
1821 	} else {
1822 		buf = sc->sc_buffer + 1;
1823 	}
1824 
1825 	DPRINTF("len=%d, id=%d\n", len, id);
1826 
1827 	/* start data transfer */
1828 	SYSCONS_UNLOCK();
1829 	error = hid_write(sc->sc_dev, buf, len);
1830 	SYSCONS_LOCK();
1831 
1832 	return (error);
1833 }
1834 
1835 static int
1836 hkbd_set_typematic(keyboard_t *kbd, int code)
1837 {
1838 #ifdef EVDEV_SUPPORT
1839 	struct hkbd_softc *sc = kbd->kb_data;
1840 #endif
1841 	static const int delays[] = {250, 500, 750, 1000};
1842 	static const int rates[] = {34, 38, 42, 46, 50, 55, 59, 63,
1843 		68, 76, 84, 92, 100, 110, 118, 126,
1844 		136, 152, 168, 184, 200, 220, 236, 252,
1845 	272, 304, 336, 368, 400, 440, 472, 504};
1846 
1847 	if (code & ~0x7f) {
1848 		return (EINVAL);
1849 	}
1850 	kbd->kb_delay1 = delays[(code >> 5) & 3];
1851 	kbd->kb_delay2 = rates[code & 0x1f];
1852 #ifdef EVDEV_SUPPORT
1853 	if (sc->sc_evdev != NULL)
1854 		evdev_push_repeats(sc->sc_evdev, kbd);
1855 #endif
1856 	return (0);
1857 }
1858 
1859 #ifdef HKBD_EMULATE_ATSCANCODE
1860 static uint32_t
1861 hkbd_atkeycode(int usbcode, const uint64_t *bitmap)
1862 {
1863 	uint32_t keycode;
1864 
1865 	keycode = hkbd_trtab[KEY_INDEX(usbcode)];
1866 
1867 	/*
1868 	 * Translate Alt-PrintScreen to SysRq.
1869 	 *
1870 	 * Some or all AT keyboards connected through USB have already
1871 	 * mapped Alted PrintScreens to an unusual usbcode (0x8a).
1872 	 * hkbd_trtab translates this to 0x7e, and key2scan() would
1873 	 * translate that to 0x79 (Intl' 4).  Assume that if we have
1874 	 * an Alted 0x7e here then it actually is an Alted PrintScreen.
1875 	 *
1876 	 * The usual usbcode for all PrintScreens is 0x46.  hkbd_trtab
1877 	 * translates this to 0x5c, so the Alt check to classify 0x5c
1878 	 * is routine.
1879 	 */
1880 	if ((keycode == 0x5c || keycode == 0x7e) &&
1881 	    (HKBD_KEY_PRESSED(bitmap, 0xe2 /* ALT-L */) ||
1882 	     HKBD_KEY_PRESSED(bitmap, 0xe6 /* ALT-R */)))
1883 		return (0x54);
1884 	return (keycode);
1885 }
1886 
1887 static int
1888 hkbd_key2scan(struct hkbd_softc *sc, int code, const uint64_t *bitmap, int up)
1889 {
1890 	static const int scan[] = {
1891 		/* 89 */
1892 		0x11c,	/* Enter */
1893 		/* 90-99 */
1894 		0x11d,	/* Ctrl-R */
1895 		0x135,	/* Divide */
1896 		0x137,	/* PrintScreen */
1897 		0x138,	/* Alt-R */
1898 		0x147,	/* Home */
1899 		0x148,	/* Up */
1900 		0x149,	/* PageUp */
1901 		0x14b,	/* Left */
1902 		0x14d,	/* Right */
1903 		0x14f,	/* End */
1904 		/* 100-109 */
1905 		0x150,	/* Down */
1906 		0x151,	/* PageDown */
1907 		0x152,	/* Insert */
1908 		0x153,	/* Delete */
1909 		0x146,	/* Pause/Break */
1910 		0x15b,	/* Win_L(Super_L) */
1911 		0x15c,	/* Win_R(Super_R) */
1912 		0x15d,	/* Application(Menu) */
1913 
1914 		/* SUN TYPE 6 USB KEYBOARD */
1915 		0x168,	/* Sun Type 6 Help */
1916 		0x15e,	/* Sun Type 6 Stop */
1917 		/* 110 - 119 */
1918 		0x15f,	/* Sun Type 6 Again */
1919 		0x160,	/* Sun Type 6 Props */
1920 		0x161,	/* Sun Type 6 Undo */
1921 		0x162,	/* Sun Type 6 Front */
1922 		0x163,	/* Sun Type 6 Copy */
1923 		0x164,	/* Sun Type 6 Open */
1924 		0x165,	/* Sun Type 6 Paste */
1925 		0x166,	/* Sun Type 6 Find */
1926 		0x167,	/* Sun Type 6 Cut */
1927 		0x125,	/* Sun Type 6 Mute */
1928 		/* 120 - 130 */
1929 		0x11f,	/* Sun Type 6 VolumeDown */
1930 		0x11e,	/* Sun Type 6 VolumeUp */
1931 		0x120,	/* Sun Type 6 PowerDown */
1932 
1933 		/* Japanese 106/109 keyboard */
1934 		0x73,	/* Keyboard Intl' 1 (backslash / underscore) */
1935 		0x70,	/* Keyboard Intl' 2 (Katakana / Hiragana) */
1936 		0x7d,	/* Keyboard Intl' 3 (Yen sign) (Not using in jp106/109) */
1937 		0x79,	/* Keyboard Intl' 4 (Henkan) */
1938 		0x7b,	/* Keyboard Intl' 5 (Muhenkan) */
1939 		0x5c,	/* Keyboard Intl' 6 (Keypad ,) (For PC-9821 layout) */
1940 		0x71,   /* Apple Keyboard JIS (Kana) */
1941 		0x72,   /* Apple Keyboard JIS (Eisu) */
1942 	};
1943 
1944 	if ((code >= 89) && (code < (int)(89 + nitems(scan)))) {
1945 		code = scan[code - 89];
1946 	}
1947 	/* PrintScreen */
1948 	if (code == 0x137 && (!(
1949 	    HKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
1950 	    HKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */) ||
1951 	    HKBD_KEY_PRESSED(bitmap, 0xe1 /* SHIFT-L */) ||
1952 	    HKBD_KEY_PRESSED(bitmap, 0xe5 /* SHIFT-R */)))) {
1953 		code |= SCAN_PREFIX_SHIFT;
1954 	}
1955 	/* Pause/Break */
1956 	if ((code == 0x146) && (!(
1957 	    HKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
1958 	    HKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */)))) {
1959 		code = (0x45 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL);
1960 	}
1961 	code |= (up ? SCAN_RELEASE : SCAN_PRESS);
1962 
1963 	if (code & SCAN_PREFIX) {
1964 		if (code & SCAN_PREFIX_CTL) {
1965 			/* Ctrl */
1966 			sc->sc_buffered_char[0] = (0x1d | (code & SCAN_RELEASE));
1967 			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX);
1968 		} else if (code & SCAN_PREFIX_SHIFT) {
1969 			/* Shift */
1970 			sc->sc_buffered_char[0] = (0x2a | (code & SCAN_RELEASE));
1971 			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX_SHIFT);
1972 		} else {
1973 			sc->sc_buffered_char[0] = (code & ~SCAN_PREFIX);
1974 			sc->sc_buffered_char[1] = 0;
1975 		}
1976 		return ((code & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1977 	}
1978 	return (code);
1979 
1980 }
1981 
1982 #endif					/* HKBD_EMULATE_ATSCANCODE */
1983 
1984 static keyboard_switch_t hkbdsw = {
1985 	.probe = &hkbd__probe,
1986 	.init = &hkbd_init,
1987 	.term = &hkbd_term,
1988 	.intr = &hkbd_intr,
1989 	.test_if = &hkbd_test_if,
1990 	.enable = &hkbd_enable,
1991 	.disable = &hkbd_disable,
1992 	.read = &hkbd_read,
1993 	.check = &hkbd_check,
1994 	.read_char = &hkbd_read_char,
1995 	.check_char = &hkbd_check_char,
1996 	.ioctl = &hkbd_ioctl,
1997 	.lock = &hkbd_lock,
1998 	.clear_state = &hkbd_clear_state,
1999 	.get_state = &hkbd_get_state,
2000 	.set_state = &hkbd_set_state,
2001 	.poll = &hkbd_poll,
2002 };
2003 
2004 KEYBOARD_DRIVER(hkbd, hkbdsw, hkbd_configure);
2005 
2006 static int
2007 hkbd_driver_load(module_t mod, int what, void *arg)
2008 {
2009 	switch (what) {
2010 	case MOD_LOAD:
2011 		kbd_add_driver(&hkbd_kbd_driver);
2012 		break;
2013 	case MOD_UNLOAD:
2014 		kbd_delete_driver(&hkbd_kbd_driver);
2015 		break;
2016 	}
2017 	return (0);
2018 }
2019 
2020 static devclass_t hkbd_devclass;
2021 
2022 static device_method_t hkbd_methods[] = {
2023 	DEVMETHOD(device_probe, hkbd_probe),
2024 	DEVMETHOD(device_attach, hkbd_attach),
2025 	DEVMETHOD(device_detach, hkbd_detach),
2026 	DEVMETHOD(device_resume, hkbd_resume),
2027 
2028 	DEVMETHOD_END
2029 };
2030 
2031 static driver_t hkbd_driver = {
2032 	.name = "hkbd",
2033 	.methods = hkbd_methods,
2034 	.size = sizeof(struct hkbd_softc),
2035 };
2036 
2037 DRIVER_MODULE(hkbd, hidbus, hkbd_driver, hkbd_devclass, hkbd_driver_load, 0);
2038 MODULE_DEPEND(hkbd, hid, 1, 1, 1);
2039 MODULE_DEPEND(hkbd, hidbus, 1, 1, 1);
2040 #ifdef EVDEV_SUPPORT
2041 MODULE_DEPEND(hkbd, evdev, 1, 1, 1);
2042 #endif
2043 MODULE_VERSION(hkbd, 1);
2044 HID_PNP_INFO(hkbd_devs);
2045