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