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