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