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