ukbd.c revision 358216
1#include <sys/cdefs.h>
2__FBSDID("$FreeBSD: stable/11/sys/dev/usb/input/ukbd.c 358216 2020-02-21 09:07:01Z 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 key changes */
524	for (key = 0; key != UKBD_NKEYCODE; 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 (mask == 1 && delta == 0) {
531			key += 63;
532			continue;	/* skip empty areas */
533		} else if (delta & mask) {
534			if (sc->sc_odata.bitmap[key / 64] & mask) {
535				ukbd_put_key(sc, key | KEY_RELEASE);
536
537				/* clear repeating key, if any */
538				if (sc->sc_repeat_key == key)
539					sc->sc_repeat_key = 0;
540			} else {
541				ukbd_put_key(sc, key | KEY_PRESS);
542
543				if (ukbd_is_modifier_key(key))
544					continue;
545
546				/*
547				 * Check for first new key and set
548				 * initial delay and [re]start timer:
549				 */
550				if (sc->sc_repeat_key == 0) {
551					sc->sc_co_basetime = sbinuptime();
552					sc->sc_delay = sc->sc_kbd.kb_delay1;
553					ukbd_start_timer(sc);
554				}
555
556				/* set repeat time for last key */
557				sc->sc_repeat_time = now + sc->sc_kbd.kb_delay1;
558				sc->sc_repeat_key = key;
559			}
560		}
561	}
562
563	/* synchronize old data with new data */
564	sc->sc_odata = sc->sc_ndata;
565
566	/* check if last key is still pressed */
567	if (sc->sc_repeat_key != 0) {
568		const int32_t dtime = (sc->sc_repeat_time - now);
569
570		/* check if time has elapsed */
571		if (dtime <= 0) {
572			ukbd_put_key(sc, sc->sc_repeat_key | KEY_PRESS);
573			sc->sc_repeat_time = now + sc->sc_kbd.kb_delay2;
574		}
575	}
576
577	/* wakeup keyboard system */
578	ukbd_event_keyinput(sc);
579}
580
581static void
582ukbd_event_keyinput(struct ukbd_softc *sc)
583{
584	int c;
585
586	UKBD_CTX_LOCK_ASSERT();
587
588	if ((sc->sc_flags & UKBD_FLAG_POLLING) != 0)
589		return;
590
591	if (sc->sc_inputs == 0)
592		return;
593
594	if (KBD_IS_ACTIVE(&sc->sc_kbd) &&
595	    KBD_IS_BUSY(&sc->sc_kbd)) {
596		/* let the callback function process the input */
597		(sc->sc_kbd.kb_callback.kc_func) (&sc->sc_kbd, KBDIO_KEYINPUT,
598		    sc->sc_kbd.kb_callback.kc_arg);
599	} else {
600		/* read and discard the input, no one is waiting for it */
601		do {
602			c = ukbd_read_char(&sc->sc_kbd, 0);
603		} while (c != NOKEY);
604	}
605}
606
607static void
608ukbd_timeout(void *arg)
609{
610	struct ukbd_softc *sc = arg;
611
612	UKBD_LOCK_ASSERT();
613
614	sc->sc_time_ms += sc->sc_delay;
615	sc->sc_delay = 0;
616
617	ukbd_interrupt(sc);
618
619	/* Make sure any leftover key events gets read out */
620	ukbd_event_keyinput(sc);
621
622	if (ukbd_any_key_pressed(sc) || (sc->sc_inputs != 0)) {
623		ukbd_start_timer(sc);
624	}
625}
626
627static uint32_t
628ukbd_apple_fn(uint32_t keycode)
629{
630	switch (keycode) {
631	case 0x28: return 0x49; /* RETURN -> INSERT */
632	case 0x2a: return 0x4c; /* BACKSPACE -> DEL */
633	case 0x50: return 0x4a; /* LEFT ARROW -> HOME */
634	case 0x4f: return 0x4d; /* RIGHT ARROW -> END */
635	case 0x52: return 0x4b; /* UP ARROW -> PGUP */
636	case 0x51: return 0x4e; /* DOWN ARROW -> PGDN */
637	default: return keycode;
638	}
639}
640
641static uint32_t
642ukbd_apple_swap(uint32_t keycode)
643{
644	switch (keycode) {
645	case 0x35: return 0x64;
646	case 0x64: return 0x35;
647	default: return keycode;
648	}
649}
650
651static void
652ukbd_intr_callback(struct usb_xfer *xfer, usb_error_t error)
653{
654	struct ukbd_softc *sc = usbd_xfer_softc(xfer);
655	struct usb_page_cache *pc;
656	uint32_t i;
657	uint8_t id;
658	uint8_t modifiers;
659	int offset;
660	int len;
661
662	UKBD_LOCK_ASSERT();
663
664	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
665	pc = usbd_xfer_get_frame(xfer, 0);
666
667	switch (USB_GET_STATE(xfer)) {
668	case USB_ST_TRANSFERRED:
669		DPRINTF("actlen=%d bytes\n", len);
670
671		if (len == 0) {
672			DPRINTF("zero length data\n");
673			goto tr_setup;
674		}
675
676		if (sc->sc_kbd_id != 0) {
677			/* check and remove HID ID byte */
678			usbd_copy_out(pc, 0, &id, 1);
679			offset = 1;
680			len--;
681			if (len == 0) {
682				DPRINTF("zero length data\n");
683				goto tr_setup;
684			}
685		} else {
686			offset = 0;
687			id = 0;
688		}
689
690		if (len > UKBD_BUFFER_SIZE)
691			len = UKBD_BUFFER_SIZE;
692
693		/* get data */
694		usbd_copy_out(pc, offset, sc->sc_buffer, len);
695
696		/* clear temporary storage */
697		memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
698
699		/* clear modifiers */
700		modifiers = 0;
701
702		/* scan through HID data */
703		if ((sc->sc_flags & UKBD_FLAG_APPLE_EJECT) &&
704		    (id == sc->sc_id_apple_eject)) {
705			if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_apple_eject))
706				modifiers |= MOD_EJECT;
707		}
708		if ((sc->sc_flags & UKBD_FLAG_APPLE_FN) &&
709		    (id == sc->sc_id_apple_fn)) {
710			if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_apple_fn))
711				modifiers |= MOD_FN;
712		}
713
714		for (i = 0; i != UKBD_NKEYCODE; i++) {
715			const uint64_t valid = sc->sc_loc_key_valid[i / 64];
716			const uint64_t mask = 1ULL << (i % 64);
717
718			if (mask == 1 && valid == 0) {
719				i += 63;
720				continue;	/* skip empty areas */
721			} else if (~valid & mask) {
722				continue;	/* location is not valid */
723			} else if (id != sc->sc_id_loc_key[i]) {
724				continue;	/* invalid HID ID */
725			} else if (i == 0) {
726				offset = sc->sc_loc_key[0].count;
727				if (offset < 0 || offset > len)
728					offset = len;
729				while (offset--) {
730					uint32_t key =
731					    hid_get_data(sc->sc_buffer + offset, len - offset,
732					    &sc->sc_loc_key[i]);
733					if (modifiers & MOD_FN)
734						key = ukbd_apple_fn(key);
735					if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP)
736						key = ukbd_apple_swap(key);
737					if (key == KEY_NONE || key == KEY_ERROR || key >= UKBD_NKEYCODE)
738						continue;
739					/* set key in bitmap */
740					sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
741				}
742			} else if (hid_get_data(sc->sc_buffer, len, &sc->sc_loc_key[i])) {
743				uint32_t key = i;
744
745				if (modifiers & MOD_FN)
746					key = ukbd_apple_fn(key);
747				if (sc->sc_flags & UKBD_FLAG_APPLE_SWAP)
748					key = ukbd_apple_swap(key);
749				if (key == KEY_NONE || key == KEY_ERROR || key >= UKBD_NKEYCODE)
750					continue;
751				/* set key in bitmap */
752				sc->sc_ndata.bitmap[key / 64] |= 1ULL << (key % 64);
753			}
754		}
755#ifdef USB_DEBUG
756		DPRINTF("modifiers = 0x%04x\n", modifiers);
757		for (i = 0; i != UKBD_NKEYCODE; i++) {
758			const uint64_t valid = sc->sc_ndata.bitmap[i / 64];
759			const uint64_t mask = 1ULL << (i % 64);
760
761			if (valid & mask)
762				DPRINTF("Key 0x%02x pressed\n", i);
763		}
764#endif
765		ukbd_interrupt(sc);
766
767	case USB_ST_SETUP:
768tr_setup:
769		if (sc->sc_inputs < UKBD_IN_BUF_FULL) {
770			usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
771			usbd_transfer_submit(xfer);
772		} else {
773			DPRINTF("input queue is full!\n");
774		}
775		break;
776
777	default:			/* Error */
778		DPRINTF("error=%s\n", usbd_errstr(error));
779
780		if (error != USB_ERR_CANCELLED) {
781			/* try to clear stall first */
782			usbd_xfer_set_stall(xfer);
783			goto tr_setup;
784		}
785		break;
786	}
787}
788
789static void
790ukbd_set_leds_callback(struct usb_xfer *xfer, usb_error_t error)
791{
792	struct ukbd_softc *sc = usbd_xfer_softc(xfer);
793	struct usb_device_request req;
794	struct usb_page_cache *pc;
795	uint8_t id;
796	uint8_t any;
797	int len;
798
799	UKBD_LOCK_ASSERT();
800
801#ifdef USB_DEBUG
802	if (ukbd_no_leds)
803		return;
804#endif
805
806	switch (USB_GET_STATE(xfer)) {
807	case USB_ST_TRANSFERRED:
808	case USB_ST_SETUP:
809		if (!(sc->sc_flags & UKBD_FLAG_SET_LEDS))
810			break;
811		sc->sc_flags &= ~UKBD_FLAG_SET_LEDS;
812
813		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
814		req.bRequest = UR_SET_REPORT;
815		USETW2(req.wValue, UHID_OUTPUT_REPORT, 0);
816		req.wIndex[0] = sc->sc_iface_no;
817		req.wIndex[1] = 0;
818		req.wLength[1] = 0;
819
820		memset(sc->sc_buffer, 0, UKBD_BUFFER_SIZE);
821
822		id = 0;
823		any = 0;
824
825		/* Assumption: All led bits must be in the same ID. */
826
827		if (sc->sc_flags & UKBD_FLAG_NUMLOCK) {
828			if (sc->sc_leds & NLKED) {
829				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
830				    &sc->sc_loc_numlock, 1);
831			}
832			id = sc->sc_id_numlock;
833			any = 1;
834		}
835
836		if (sc->sc_flags & UKBD_FLAG_SCROLLLOCK) {
837			if (sc->sc_leds & SLKED) {
838				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
839				    &sc->sc_loc_scrolllock, 1);
840			}
841			id = sc->sc_id_scrolllock;
842			any = 1;
843		}
844
845		if (sc->sc_flags & UKBD_FLAG_CAPSLOCK) {
846			if (sc->sc_leds & CLKED) {
847				hid_put_data_unsigned(sc->sc_buffer + 1, UKBD_BUFFER_SIZE - 1,
848				    &sc->sc_loc_capslock, 1);
849			}
850			id = sc->sc_id_capslock;
851			any = 1;
852		}
853
854		/* if no leds, nothing to do */
855		if (!any)
856			break;
857
858#ifdef EVDEV_SUPPORT
859		if (sc->sc_evdev != NULL)
860			evdev_push_leds(sc->sc_evdev, sc->sc_leds);
861#endif
862
863		/* range check output report length */
864		len = sc->sc_led_size;
865		if (len > (UKBD_BUFFER_SIZE - 1))
866			len = (UKBD_BUFFER_SIZE - 1);
867
868		/* check if we need to prefix an ID byte */
869		sc->sc_buffer[0] = id;
870
871		pc = usbd_xfer_get_frame(xfer, 1);
872		if (id != 0) {
873			len++;
874			usbd_copy_in(pc, 0, sc->sc_buffer, len);
875		} else {
876			usbd_copy_in(pc, 0, sc->sc_buffer + 1, len);
877		}
878		req.wLength[0] = len;
879		usbd_xfer_set_frame_len(xfer, 1, len);
880
881		DPRINTF("len=%d, id=%d\n", len, id);
882
883		/* setup control request last */
884		pc = usbd_xfer_get_frame(xfer, 0);
885		usbd_copy_in(pc, 0, &req, sizeof(req));
886		usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
887
888		/* start data transfer */
889		usbd_xfer_set_frames(xfer, 2);
890		usbd_transfer_submit(xfer);
891		break;
892
893	default:			/* Error */
894		DPRINTFN(1, "error=%s\n", usbd_errstr(error));
895		break;
896	}
897}
898
899static const struct usb_config ukbd_config[UKBD_N_TRANSFER] = {
900
901	[UKBD_INTR_DT_0] = {
902		.type = UE_INTERRUPT,
903		.endpoint = UE_ADDR_ANY,
904		.direction = UE_DIR_IN,
905		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
906		.bufsize = 0,	/* use wMaxPacketSize */
907		.callback = &ukbd_intr_callback,
908	},
909
910	[UKBD_INTR_DT_1] = {
911		.type = UE_INTERRUPT,
912		.endpoint = UE_ADDR_ANY,
913		.direction = UE_DIR_IN,
914		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
915		.bufsize = 0,	/* use wMaxPacketSize */
916		.callback = &ukbd_intr_callback,
917	},
918
919	[UKBD_CTRL_LED] = {
920		.type = UE_CONTROL,
921		.endpoint = 0x00,	/* Control pipe */
922		.direction = UE_DIR_ANY,
923		.bufsize = sizeof(struct usb_device_request) + UKBD_BUFFER_SIZE,
924		.callback = &ukbd_set_leds_callback,
925		.timeout = 1000,	/* 1 second */
926	},
927};
928
929/* A match on these entries will load ukbd */
930static const STRUCT_USB_HOST_ID __used ukbd_devs[] = {
931	{USB_IFACE_CLASS(UICLASS_HID),
932	 USB_IFACE_SUBCLASS(UISUBCLASS_BOOT),
933	 USB_IFACE_PROTOCOL(UIPROTO_BOOT_KEYBOARD),},
934};
935
936static int
937ukbd_probe(device_t dev)
938{
939	keyboard_switch_t *sw = kbd_get_switch(UKBD_DRIVER_NAME);
940	struct usb_attach_arg *uaa = device_get_ivars(dev);
941	void *d_ptr;
942	int error;
943	uint16_t d_len;
944
945	UKBD_LOCK_ASSERT();
946	DPRINTFN(11, "\n");
947
948	if (sw == NULL) {
949		return (ENXIO);
950	}
951	if (uaa->usb_mode != USB_MODE_HOST) {
952		return (ENXIO);
953	}
954
955	if (uaa->info.bInterfaceClass != UICLASS_HID)
956		return (ENXIO);
957
958	if (usb_test_quirk(uaa, UQ_KBD_IGNORE))
959		return (ENXIO);
960
961	if ((uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) &&
962	    (uaa->info.bInterfaceProtocol == UIPROTO_BOOT_KEYBOARD))
963		return (BUS_PROBE_DEFAULT);
964
965	error = usbd_req_get_hid_desc(uaa->device, NULL,
966	    &d_ptr, &d_len, M_TEMP, uaa->info.bIfaceIndex);
967
968	if (error)
969		return (ENXIO);
970
971	if (hid_is_keyboard(d_ptr, d_len)) {
972		if (hid_is_mouse(d_ptr, d_len)) {
973			/*
974			 * NOTE: We currently don't support USB mouse
975			 * and USB keyboard on the same USB endpoint.
976			 * Let "ums" driver win.
977			 */
978			error = ENXIO;
979		} else {
980			error = BUS_PROBE_DEFAULT;
981		}
982	} else {
983		error = ENXIO;
984	}
985	free(d_ptr, M_TEMP);
986	return (error);
987}
988
989static void
990ukbd_parse_hid(struct ukbd_softc *sc, const uint8_t *ptr, uint32_t len)
991{
992	uint32_t flags;
993	uint32_t key;
994
995	/* reset detected bits */
996	sc->sc_flags &= ~UKBD_FLAG_HID_MASK;
997
998	/* reset detected keys */
999	memset(sc->sc_loc_key_valid, 0, sizeof(sc->sc_loc_key_valid));
1000
1001	/* check if there is an ID byte */
1002	sc->sc_kbd_size = hid_report_size(ptr, len,
1003	    hid_input, &sc->sc_kbd_id);
1004
1005	/* investigate if this is an Apple Keyboard */
1006	if (hid_locate(ptr, len,
1007	    HID_USAGE2(HUP_CONSUMER, HUG_APPLE_EJECT),
1008	    hid_input, 0, &sc->sc_loc_apple_eject, &flags,
1009	    &sc->sc_id_apple_eject)) {
1010		if (flags & HIO_VARIABLE)
1011			sc->sc_flags |= UKBD_FLAG_APPLE_EJECT |
1012			    UKBD_FLAG_APPLE_SWAP;
1013		DPRINTFN(1, "Found Apple eject-key\n");
1014	}
1015	if (hid_locate(ptr, len,
1016	    HID_USAGE2(0xFFFF, 0x0003),
1017	    hid_input, 0, &sc->sc_loc_apple_fn, &flags,
1018	    &sc->sc_id_apple_fn)) {
1019		if (flags & HIO_VARIABLE)
1020			sc->sc_flags |= UKBD_FLAG_APPLE_FN;
1021		DPRINTFN(1, "Found Apple FN-key\n");
1022	}
1023
1024	/* figure out event buffer */
1025	if (hid_locate(ptr, len,
1026	    HID_USAGE2(HUP_KEYBOARD, 0x00),
1027	    hid_input, 0, &sc->sc_loc_key[0], &flags,
1028	    &sc->sc_id_loc_key[0])) {
1029		if (flags & HIO_VARIABLE) {
1030			DPRINTFN(1, "Ignoring keyboard event control\n");
1031		} else {
1032			sc->sc_loc_key_valid[0] |= 1;
1033			DPRINTFN(1, "Found keyboard event array\n");
1034		}
1035	}
1036
1037	/* figure out the keys */
1038	for (key = 1; key != UKBD_NKEYCODE; key++) {
1039		if (hid_locate(ptr, len,
1040		    HID_USAGE2(HUP_KEYBOARD, key),
1041		    hid_input, 0, &sc->sc_loc_key[key], &flags,
1042		    &sc->sc_id_loc_key[key])) {
1043			if (flags & HIO_VARIABLE) {
1044				sc->sc_loc_key_valid[key / 64] |=
1045				    1ULL << (key % 64);
1046				DPRINTFN(1, "Found key 0x%02x\n", key);
1047			}
1048		}
1049	}
1050
1051	/* figure out leds on keyboard */
1052	sc->sc_led_size = hid_report_size(ptr, len,
1053	    hid_output, NULL);
1054
1055	if (hid_locate(ptr, len,
1056	    HID_USAGE2(HUP_LEDS, 0x01),
1057	    hid_output, 0, &sc->sc_loc_numlock, &flags,
1058	    &sc->sc_id_numlock)) {
1059		if (flags & HIO_VARIABLE)
1060			sc->sc_flags |= UKBD_FLAG_NUMLOCK;
1061		DPRINTFN(1, "Found keyboard numlock\n");
1062	}
1063	if (hid_locate(ptr, len,
1064	    HID_USAGE2(HUP_LEDS, 0x02),
1065	    hid_output, 0, &sc->sc_loc_capslock, &flags,
1066	    &sc->sc_id_capslock)) {
1067		if (flags & HIO_VARIABLE)
1068			sc->sc_flags |= UKBD_FLAG_CAPSLOCK;
1069		DPRINTFN(1, "Found keyboard capslock\n");
1070	}
1071	if (hid_locate(ptr, len,
1072	    HID_USAGE2(HUP_LEDS, 0x03),
1073	    hid_output, 0, &sc->sc_loc_scrolllock, &flags,
1074	    &sc->sc_id_scrolllock)) {
1075		if (flags & HIO_VARIABLE)
1076			sc->sc_flags |= UKBD_FLAG_SCROLLLOCK;
1077		DPRINTFN(1, "Found keyboard scrolllock\n");
1078	}
1079}
1080
1081static int
1082ukbd_attach(device_t dev)
1083{
1084	struct ukbd_softc *sc = device_get_softc(dev);
1085	struct usb_attach_arg *uaa = device_get_ivars(dev);
1086	int unit = device_get_unit(dev);
1087	keyboard_t *kbd = &sc->sc_kbd;
1088	void *hid_ptr = NULL;
1089	usb_error_t err;
1090	uint16_t n;
1091	uint16_t hid_len;
1092#ifdef EVDEV_SUPPORT
1093	struct evdev_dev *evdev;
1094	int i;
1095#endif
1096#ifdef USB_DEBUG
1097	int rate;
1098#endif
1099	UKBD_LOCK_ASSERT();
1100
1101	kbd_init_struct(kbd, UKBD_DRIVER_NAME, KB_OTHER, unit, 0, 0, 0);
1102
1103	kbd->kb_data = (void *)sc;
1104
1105	device_set_usb_desc(dev);
1106
1107	sc->sc_udev = uaa->device;
1108	sc->sc_iface = uaa->iface;
1109	sc->sc_iface_index = uaa->info.bIfaceIndex;
1110	sc->sc_iface_no = uaa->info.bIfaceNum;
1111	sc->sc_mode = K_XLATE;
1112
1113	usb_callout_init_mtx(&sc->sc_callout, &Giant, 0);
1114
1115#ifdef UKBD_NO_POLLING
1116	err = usbd_transfer_setup(uaa->device,
1117	    &uaa->info.bIfaceIndex, sc->sc_xfer, ukbd_config,
1118	    UKBD_N_TRANSFER, sc, &Giant);
1119#else
1120	/*
1121	 * Setup the UKBD USB transfers one by one, so they are memory
1122	 * independent which allows for handling panics triggered by
1123	 * the keyboard driver itself, typically via CTRL+ALT+ESC
1124	 * sequences. Or if the USB keyboard driver was processing a
1125	 * key at the moment of panic.
1126	 */
1127	for (n = 0; n != UKBD_N_TRANSFER; n++) {
1128		err = usbd_transfer_setup(uaa->device,
1129		    &uaa->info.bIfaceIndex, sc->sc_xfer + n, ukbd_config + n,
1130		    1, sc, &Giant);
1131		if (err)
1132			break;
1133	}
1134#endif
1135
1136	if (err) {
1137		DPRINTF("error=%s\n", usbd_errstr(err));
1138		goto detach;
1139	}
1140	/* setup default keyboard maps */
1141
1142	sc->sc_keymap = key_map;
1143	sc->sc_accmap = accent_map;
1144	for (n = 0; n < UKBD_NFKEY; n++) {
1145		sc->sc_fkeymap[n] = fkey_tab[n];
1146	}
1147
1148	kbd_set_maps(kbd, &sc->sc_keymap, &sc->sc_accmap,
1149	    sc->sc_fkeymap, UKBD_NFKEY);
1150
1151	KBD_FOUND_DEVICE(kbd);
1152
1153	ukbd_clear_state(kbd);
1154
1155	/*
1156	 * FIXME: set the initial value for lock keys in "sc_state"
1157	 * according to the BIOS data?
1158	 */
1159	KBD_PROBE_DONE(kbd);
1160
1161	/* get HID descriptor */
1162	err = usbd_req_get_hid_desc(uaa->device, NULL, &hid_ptr,
1163	    &hid_len, M_TEMP, uaa->info.bIfaceIndex);
1164
1165	if (err == 0) {
1166		DPRINTF("Parsing HID descriptor of %d bytes\n",
1167		    (int)hid_len);
1168
1169		ukbd_parse_hid(sc, hid_ptr, hid_len);
1170
1171		free(hid_ptr, M_TEMP);
1172	}
1173
1174	/* check if we should use the boot protocol */
1175	if (usb_test_quirk(uaa, UQ_KBD_BOOTPROTO) ||
1176	    (err != 0) || ukbd_any_key_valid(sc) == false) {
1177
1178		DPRINTF("Forcing boot protocol\n");
1179
1180		err = usbd_req_set_protocol(sc->sc_udev, NULL,
1181			sc->sc_iface_index, 0);
1182
1183		if (err != 0) {
1184			DPRINTF("Set protocol error=%s (ignored)\n",
1185			    usbd_errstr(err));
1186		}
1187
1188		ukbd_parse_hid(sc, ukbd_boot_desc, sizeof(ukbd_boot_desc));
1189	}
1190
1191	/* ignore if SETIDLE fails, hence it is not crucial */
1192	usbd_req_set_idle(sc->sc_udev, NULL, sc->sc_iface_index, 0, 0);
1193
1194	ukbd_ioctl(kbd, KDSETLED, (caddr_t)&sc->sc_state);
1195
1196	KBD_INIT_DONE(kbd);
1197
1198	if (kbd_register(kbd) < 0) {
1199		goto detach;
1200	}
1201	KBD_CONFIG_DONE(kbd);
1202
1203	ukbd_enable(kbd);
1204
1205#ifdef KBD_INSTALL_CDEV
1206	if (kbd_attach(kbd)) {
1207		goto detach;
1208	}
1209#endif
1210
1211#ifdef EVDEV_SUPPORT
1212	evdev = evdev_alloc();
1213	evdev_set_name(evdev, device_get_desc(dev));
1214	evdev_set_phys(evdev, device_get_nameunit(dev));
1215	evdev_set_id(evdev, BUS_USB, uaa->info.idVendor,
1216	   uaa->info.idProduct, 0);
1217	evdev_set_serial(evdev, usb_get_serial(uaa->device));
1218	evdev_set_methods(evdev, kbd, &ukbd_evdev_methods);
1219	evdev_support_event(evdev, EV_SYN);
1220	evdev_support_event(evdev, EV_KEY);
1221	if (sc->sc_flags & (UKBD_FLAG_NUMLOCK | UKBD_FLAG_CAPSLOCK |
1222			    UKBD_FLAG_SCROLLLOCK))
1223		evdev_support_event(evdev, EV_LED);
1224	evdev_support_event(evdev, EV_REP);
1225
1226	for (i = 0x00; i <= 0xFF; i++)
1227		evdev_support_key(evdev, evdev_hid2key(i));
1228	if (sc->sc_flags & UKBD_FLAG_NUMLOCK)
1229		evdev_support_led(evdev, LED_NUML);
1230	if (sc->sc_flags & UKBD_FLAG_CAPSLOCK)
1231		evdev_support_led(evdev, LED_CAPSL);
1232	if (sc->sc_flags & UKBD_FLAG_SCROLLLOCK)
1233		evdev_support_led(evdev, LED_SCROLLL);
1234
1235	if (evdev_register(evdev))
1236		evdev_free(evdev);
1237	else
1238		sc->sc_evdev = evdev;
1239#endif
1240
1241	sc->sc_flags |= UKBD_FLAG_ATTACHED;
1242
1243	if (bootverbose) {
1244		kbdd_diag(kbd, bootverbose);
1245	}
1246
1247#ifdef USB_DEBUG
1248	/* check for polling rate override */
1249	rate = ukbd_pollrate;
1250	if (rate > 0) {
1251		if (rate > 1000)
1252			rate = 1;
1253		else
1254			rate = 1000 / rate;
1255
1256		/* set new polling interval in ms */
1257		usbd_xfer_set_interval(sc->sc_xfer[UKBD_INTR_DT_0], rate);
1258		usbd_xfer_set_interval(sc->sc_xfer[UKBD_INTR_DT_1], rate);
1259	}
1260#endif
1261	/* start the keyboard */
1262	usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_0]);
1263	usbd_transfer_start(sc->sc_xfer[UKBD_INTR_DT_1]);
1264
1265	return (0);			/* success */
1266
1267detach:
1268	ukbd_detach(dev);
1269	return (ENXIO);			/* error */
1270}
1271
1272static int
1273ukbd_detach(device_t dev)
1274{
1275	struct ukbd_softc *sc = device_get_softc(dev);
1276	int error;
1277
1278	UKBD_LOCK_ASSERT();
1279
1280	DPRINTF("\n");
1281
1282	sc->sc_flags |= UKBD_FLAG_GONE;
1283
1284	usb_callout_stop(&sc->sc_callout);
1285
1286	/* kill any stuck keys */
1287	if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
1288		/* stop receiving events from the USB keyboard */
1289		usbd_transfer_stop(sc->sc_xfer[UKBD_INTR_DT_0]);
1290		usbd_transfer_stop(sc->sc_xfer[UKBD_INTR_DT_1]);
1291
1292		/* release all leftover keys, if any */
1293		memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1294
1295		/* process releasing of all keys */
1296		ukbd_interrupt(sc);
1297	}
1298
1299	ukbd_disable(&sc->sc_kbd);
1300
1301#ifdef KBD_INSTALL_CDEV
1302	if (sc->sc_flags & UKBD_FLAG_ATTACHED) {
1303		error = kbd_detach(&sc->sc_kbd);
1304		if (error) {
1305			/* usb attach cannot return an error */
1306			device_printf(dev, "WARNING: kbd_detach() "
1307			    "returned non-zero! (ignored)\n");
1308		}
1309	}
1310#endif
1311
1312#ifdef EVDEV_SUPPORT
1313	evdev_free(sc->sc_evdev);
1314#endif
1315
1316	if (KBD_IS_CONFIGURED(&sc->sc_kbd)) {
1317		error = kbd_unregister(&sc->sc_kbd);
1318		if (error) {
1319			/* usb attach cannot return an error */
1320			device_printf(dev, "WARNING: kbd_unregister() "
1321			    "returned non-zero! (ignored)\n");
1322		}
1323	}
1324	sc->sc_kbd.kb_flags = 0;
1325
1326	usbd_transfer_unsetup(sc->sc_xfer, UKBD_N_TRANSFER);
1327
1328	usb_callout_drain(&sc->sc_callout);
1329
1330	DPRINTF("%s: disconnected\n",
1331	    device_get_nameunit(dev));
1332
1333	return (0);
1334}
1335
1336static int
1337ukbd_resume(device_t dev)
1338{
1339	struct ukbd_softc *sc = device_get_softc(dev);
1340
1341	UKBD_LOCK_ASSERT();
1342
1343	ukbd_clear_state(&sc->sc_kbd);
1344
1345	return (0);
1346}
1347
1348/* early keyboard probe, not supported */
1349static int
1350ukbd_configure(int flags)
1351{
1352	return (0);
1353}
1354
1355/* detect a keyboard, not used */
1356static int
1357ukbd__probe(int unit, void *arg, int flags)
1358{
1359	return (ENXIO);
1360}
1361
1362/* reset and initialize the device, not used */
1363static int
1364ukbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
1365{
1366	return (ENXIO);
1367}
1368
1369/* test the interface to the device, not used */
1370static int
1371ukbd_test_if(keyboard_t *kbd)
1372{
1373	return (0);
1374}
1375
1376/* finish using this keyboard, not used */
1377static int
1378ukbd_term(keyboard_t *kbd)
1379{
1380	return (ENXIO);
1381}
1382
1383/* keyboard interrupt routine, not used */
1384static int
1385ukbd_intr(keyboard_t *kbd, void *arg)
1386{
1387	return (0);
1388}
1389
1390/* lock the access to the keyboard, not used */
1391static int
1392ukbd_lock(keyboard_t *kbd, int lock)
1393{
1394	return (1);
1395}
1396
1397/*
1398 * Enable the access to the device; until this function is called,
1399 * the client cannot read from the keyboard.
1400 */
1401static int
1402ukbd_enable(keyboard_t *kbd)
1403{
1404
1405	UKBD_LOCK();
1406	KBD_ACTIVATE(kbd);
1407	UKBD_UNLOCK();
1408
1409	return (0);
1410}
1411
1412/* disallow the access to the device */
1413static int
1414ukbd_disable(keyboard_t *kbd)
1415{
1416
1417	UKBD_LOCK();
1418	KBD_DEACTIVATE(kbd);
1419	UKBD_UNLOCK();
1420
1421	return (0);
1422}
1423
1424/* check if data is waiting */
1425/* Currently unused. */
1426static int
1427ukbd_check(keyboard_t *kbd)
1428{
1429	struct ukbd_softc *sc = kbd->kb_data;
1430
1431	UKBD_CTX_LOCK_ASSERT();
1432
1433	if (!KBD_IS_ACTIVE(kbd))
1434		return (0);
1435
1436	if (sc->sc_flags & UKBD_FLAG_POLLING)
1437		ukbd_do_poll(sc, 0);
1438
1439#ifdef UKBD_EMULATE_ATSCANCODE
1440	if (sc->sc_buffered_char[0]) {
1441		return (1);
1442	}
1443#endif
1444	if (sc->sc_inputs > 0) {
1445		return (1);
1446	}
1447	return (0);
1448}
1449
1450/* check if char is waiting */
1451static int
1452ukbd_check_char_locked(keyboard_t *kbd)
1453{
1454	struct ukbd_softc *sc = kbd->kb_data;
1455
1456	UKBD_CTX_LOCK_ASSERT();
1457
1458	if (!KBD_IS_ACTIVE(kbd))
1459		return (0);
1460
1461	if ((sc->sc_composed_char > 0) &&
1462	    (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1463		return (1);
1464	}
1465	return (ukbd_check(kbd));
1466}
1467
1468static int
1469ukbd_check_char(keyboard_t *kbd)
1470{
1471	int result;
1472
1473	UKBD_LOCK();
1474	result = ukbd_check_char_locked(kbd);
1475	UKBD_UNLOCK();
1476
1477	return (result);
1478}
1479
1480/* read one byte from the keyboard if it's allowed */
1481/* Currently unused. */
1482static int
1483ukbd_read(keyboard_t *kbd, int wait)
1484{
1485	struct ukbd_softc *sc = kbd->kb_data;
1486	int32_t usbcode;
1487#ifdef UKBD_EMULATE_ATSCANCODE
1488	uint32_t keycode;
1489	uint32_t scancode;
1490
1491#endif
1492
1493	UKBD_CTX_LOCK_ASSERT();
1494
1495	if (!KBD_IS_ACTIVE(kbd))
1496		return (-1);
1497
1498#ifdef UKBD_EMULATE_ATSCANCODE
1499	if (sc->sc_buffered_char[0]) {
1500		scancode = sc->sc_buffered_char[0];
1501		if (scancode & SCAN_PREFIX) {
1502			sc->sc_buffered_char[0] &= ~SCAN_PREFIX;
1503			return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1504		}
1505		sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1506		sc->sc_buffered_char[1] = 0;
1507		return (scancode);
1508	}
1509#endif					/* UKBD_EMULATE_ATSCANCODE */
1510
1511	/* XXX */
1512	usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1513	if (!KBD_IS_ACTIVE(kbd) || (usbcode == -1))
1514		return (-1);
1515
1516	++(kbd->kb_count);
1517
1518#ifdef UKBD_EMULATE_ATSCANCODE
1519	keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1520	if (keycode == NN) {
1521		return -1;
1522	}
1523	return (ukbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1524	    (usbcode & KEY_RELEASE)));
1525#else					/* !UKBD_EMULATE_ATSCANCODE */
1526	return (usbcode);
1527#endif					/* UKBD_EMULATE_ATSCANCODE */
1528}
1529
1530/* read char from the keyboard */
1531static uint32_t
1532ukbd_read_char_locked(keyboard_t *kbd, int wait)
1533{
1534	struct ukbd_softc *sc = kbd->kb_data;
1535	uint32_t action;
1536	uint32_t keycode;
1537	int32_t usbcode;
1538#ifdef UKBD_EMULATE_ATSCANCODE
1539	uint32_t scancode;
1540#endif
1541
1542	UKBD_CTX_LOCK_ASSERT();
1543
1544	if (!KBD_IS_ACTIVE(kbd))
1545		return (NOKEY);
1546
1547next_code:
1548
1549	/* do we have a composed char to return ? */
1550
1551	if ((sc->sc_composed_char > 0) &&
1552	    (!(sc->sc_flags & UKBD_FLAG_COMPOSE))) {
1553
1554		action = sc->sc_composed_char;
1555		sc->sc_composed_char = 0;
1556
1557		if (action > 0xFF) {
1558			goto errkey;
1559		}
1560		goto done;
1561	}
1562#ifdef UKBD_EMULATE_ATSCANCODE
1563
1564	/* do we have a pending raw scan code? */
1565
1566	if (sc->sc_mode == K_RAW) {
1567		scancode = sc->sc_buffered_char[0];
1568		if (scancode) {
1569			if (scancode & SCAN_PREFIX) {
1570				sc->sc_buffered_char[0] = (scancode & ~SCAN_PREFIX);
1571				return ((scancode & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
1572			}
1573			sc->sc_buffered_char[0] = sc->sc_buffered_char[1];
1574			sc->sc_buffered_char[1] = 0;
1575			return (scancode);
1576		}
1577	}
1578#endif					/* UKBD_EMULATE_ATSCANCODE */
1579
1580	/* see if there is something in the keyboard port */
1581	/* XXX */
1582	usbcode = ukbd_get_key(sc, (wait == FALSE) ? 0 : 1);
1583	if (usbcode == -1) {
1584		return (NOKEY);
1585	}
1586	++kbd->kb_count;
1587
1588#ifdef UKBD_EMULATE_ATSCANCODE
1589	/* USB key index -> key code -> AT scan code */
1590	keycode = ukbd_atkeycode(usbcode, sc->sc_ndata.bitmap);
1591	if (keycode == NN) {
1592		return (NOKEY);
1593	}
1594	/* return an AT scan code for the K_RAW mode */
1595	if (sc->sc_mode == K_RAW) {
1596		return (ukbd_key2scan(sc, keycode, sc->sc_ndata.bitmap,
1597		    (usbcode & KEY_RELEASE)));
1598	}
1599#else					/* !UKBD_EMULATE_ATSCANCODE */
1600
1601	/* return the byte as is for the K_RAW mode */
1602	if (sc->sc_mode == K_RAW) {
1603		return (usbcode);
1604	}
1605	/* USB key index -> key code */
1606	keycode = ukbd_trtab[KEY_INDEX(usbcode)];
1607	if (keycode == NN) {
1608		return (NOKEY);
1609	}
1610#endif					/* UKBD_EMULATE_ATSCANCODE */
1611
1612	switch (keycode) {
1613	case 0x38:			/* left alt (compose key) */
1614		if (usbcode & KEY_RELEASE) {
1615			if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1616				sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1617
1618				if (sc->sc_composed_char > 0xFF) {
1619					sc->sc_composed_char = 0;
1620				}
1621			}
1622		} else {
1623			if (!(sc->sc_flags & UKBD_FLAG_COMPOSE)) {
1624				sc->sc_flags |= UKBD_FLAG_COMPOSE;
1625				sc->sc_composed_char = 0;
1626			}
1627		}
1628		break;
1629	}
1630
1631	/* return the key code in the K_CODE mode */
1632	if (usbcode & KEY_RELEASE) {
1633		keycode |= SCAN_RELEASE;
1634	}
1635	if (sc->sc_mode == K_CODE) {
1636		return (keycode);
1637	}
1638	/* compose a character code */
1639	if (sc->sc_flags & UKBD_FLAG_COMPOSE) {
1640		switch (keycode) {
1641			/* key pressed, process it */
1642		case 0x47:
1643		case 0x48:
1644		case 0x49:		/* keypad 7,8,9 */
1645			sc->sc_composed_char *= 10;
1646			sc->sc_composed_char += keycode - 0x40;
1647			goto check_composed;
1648
1649		case 0x4B:
1650		case 0x4C:
1651		case 0x4D:		/* keypad 4,5,6 */
1652			sc->sc_composed_char *= 10;
1653			sc->sc_composed_char += keycode - 0x47;
1654			goto check_composed;
1655
1656		case 0x4F:
1657		case 0x50:
1658		case 0x51:		/* keypad 1,2,3 */
1659			sc->sc_composed_char *= 10;
1660			sc->sc_composed_char += keycode - 0x4E;
1661			goto check_composed;
1662
1663		case 0x52:		/* keypad 0 */
1664			sc->sc_composed_char *= 10;
1665			goto check_composed;
1666
1667			/* key released, no interest here */
1668		case SCAN_RELEASE | 0x47:
1669		case SCAN_RELEASE | 0x48:
1670		case SCAN_RELEASE | 0x49:	/* keypad 7,8,9 */
1671		case SCAN_RELEASE | 0x4B:
1672		case SCAN_RELEASE | 0x4C:
1673		case SCAN_RELEASE | 0x4D:	/* keypad 4,5,6 */
1674		case SCAN_RELEASE | 0x4F:
1675		case SCAN_RELEASE | 0x50:
1676		case SCAN_RELEASE | 0x51:	/* keypad 1,2,3 */
1677		case SCAN_RELEASE | 0x52:	/* keypad 0 */
1678			goto next_code;
1679
1680		case 0x38:		/* left alt key */
1681			break;
1682
1683		default:
1684			if (sc->sc_composed_char > 0) {
1685				sc->sc_flags &= ~UKBD_FLAG_COMPOSE;
1686				sc->sc_composed_char = 0;
1687				goto errkey;
1688			}
1689			break;
1690		}
1691	}
1692	/* keycode to key action */
1693	action = genkbd_keyaction(kbd, SCAN_CHAR(keycode),
1694	    (keycode & SCAN_RELEASE),
1695	    &sc->sc_state, &sc->sc_accents);
1696	if (action == NOKEY) {
1697		goto next_code;
1698	}
1699done:
1700	return (action);
1701
1702check_composed:
1703	if (sc->sc_composed_char <= 0xFF) {
1704		goto next_code;
1705	}
1706errkey:
1707	return (ERRKEY);
1708}
1709
1710/* Currently wait is always false. */
1711static uint32_t
1712ukbd_read_char(keyboard_t *kbd, int wait)
1713{
1714	uint32_t keycode;
1715
1716	UKBD_LOCK();
1717	keycode = ukbd_read_char_locked(kbd, wait);
1718	UKBD_UNLOCK();
1719
1720	return (keycode);
1721}
1722
1723/* some useful control functions */
1724static int
1725ukbd_ioctl_locked(keyboard_t *kbd, u_long cmd, caddr_t arg)
1726{
1727	struct ukbd_softc *sc = kbd->kb_data;
1728	int i;
1729#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1730    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1731	int ival;
1732
1733#endif
1734
1735	UKBD_LOCK_ASSERT();
1736
1737	switch (cmd) {
1738	case KDGKBMODE:		/* get keyboard mode */
1739		*(int *)arg = sc->sc_mode;
1740		break;
1741#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1742    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1743	case _IO('K', 7):
1744		ival = IOCPARM_IVAL(arg);
1745		arg = (caddr_t)&ival;
1746		/* FALLTHROUGH */
1747#endif
1748	case KDSKBMODE:		/* set keyboard mode */
1749		switch (*(int *)arg) {
1750		case K_XLATE:
1751			if (sc->sc_mode != K_XLATE) {
1752				/* make lock key state and LED state match */
1753				sc->sc_state &= ~LOCK_MASK;
1754				sc->sc_state |= KBD_LED_VAL(kbd);
1755			}
1756			/* FALLTHROUGH */
1757		case K_RAW:
1758		case K_CODE:
1759			if (sc->sc_mode != *(int *)arg) {
1760				if ((sc->sc_flags & UKBD_FLAG_POLLING) == 0)
1761					ukbd_clear_state(kbd);
1762				sc->sc_mode = *(int *)arg;
1763			}
1764			break;
1765		default:
1766			return (EINVAL);
1767		}
1768		break;
1769
1770	case KDGETLED:			/* get keyboard LED */
1771		*(int *)arg = KBD_LED_VAL(kbd);
1772		break;
1773#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1774    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1775	case _IO('K', 66):
1776		ival = IOCPARM_IVAL(arg);
1777		arg = (caddr_t)&ival;
1778		/* FALLTHROUGH */
1779#endif
1780	case KDSETLED:			/* set keyboard LED */
1781		/* NOTE: lock key state in "sc_state" won't be changed */
1782		if (*(int *)arg & ~LOCK_MASK)
1783			return (EINVAL);
1784
1785		i = *(int *)arg;
1786
1787		/* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1788		if (sc->sc_mode == K_XLATE &&
1789		    kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1790			if (i & ALKED)
1791				i |= CLKED;
1792			else
1793				i &= ~CLKED;
1794		}
1795		if (KBD_HAS_DEVICE(kbd))
1796			ukbd_set_leds(sc, i);
1797
1798		KBD_LED_VAL(kbd) = *(int *)arg;
1799		break;
1800	case KDGKBSTATE:		/* get lock key state */
1801		*(int *)arg = sc->sc_state & LOCK_MASK;
1802		break;
1803#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1804    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1805	case _IO('K', 20):
1806		ival = IOCPARM_IVAL(arg);
1807		arg = (caddr_t)&ival;
1808		/* FALLTHROUGH */
1809#endif
1810	case KDSKBSTATE:		/* set lock key state */
1811		if (*(int *)arg & ~LOCK_MASK) {
1812			return (EINVAL);
1813		}
1814		sc->sc_state &= ~LOCK_MASK;
1815		sc->sc_state |= *(int *)arg;
1816
1817		/* set LEDs and quit */
1818		return (ukbd_ioctl(kbd, KDSETLED, arg));
1819
1820	case KDSETREPEAT:		/* set keyboard repeat rate (new
1821					 * interface) */
1822		if (!KBD_HAS_DEVICE(kbd)) {
1823			return (0);
1824		}
1825		/*
1826		 * Convert negative, zero and tiny args to the same limits
1827		 * as atkbd.  We could support delays of 1 msec, but
1828		 * anything much shorter than the shortest atkbd value
1829		 * of 250.34 is almost unusable as well as incompatible.
1830		 */
1831		kbd->kb_delay1 = imax(((int *)arg)[0], 250);
1832		kbd->kb_delay2 = imax(((int *)arg)[1], 34);
1833#ifdef EVDEV_SUPPORT
1834		if (sc->sc_evdev != NULL)
1835			evdev_push_repeats(sc->sc_evdev, kbd);
1836#endif
1837		return (0);
1838
1839#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1840    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1841	case _IO('K', 67):
1842		ival = IOCPARM_IVAL(arg);
1843		arg = (caddr_t)&ival;
1844		/* FALLTHROUGH */
1845#endif
1846	case KDSETRAD:			/* set keyboard repeat rate (old
1847					 * interface) */
1848		return (ukbd_set_typematic(kbd, *(int *)arg));
1849
1850	case PIO_KEYMAP:		/* set keyboard translation table */
1851	case OPIO_KEYMAP:		/* set keyboard translation table
1852					 * (compat) */
1853	case PIO_KEYMAPENT:		/* set keyboard translation table
1854					 * entry */
1855	case PIO_DEADKEYMAP:		/* set accent key translation table */
1856		sc->sc_accents = 0;
1857		/* FALLTHROUGH */
1858	default:
1859		return (genkbd_commonioctl(kbd, cmd, arg));
1860	}
1861
1862	return (0);
1863}
1864
1865static int
1866ukbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
1867{
1868	int result;
1869
1870	/*
1871	 * XXX Check if someone is calling us from a critical section:
1872	 */
1873	if (curthread->td_critnest != 0)
1874		return (EDEADLK);
1875
1876	/*
1877	 * XXX KDGKBSTATE, KDSKBSTATE and KDSETLED can be called from any
1878	 * context where printf(9) can be called, which among other things
1879	 * includes interrupt filters and threads with any kinds of locks
1880	 * already held.  For this reason it would be dangerous to acquire
1881	 * the Giant here unconditionally.  On the other hand we have to
1882	 * have it to handle the ioctl.
1883	 * So we make our best effort to auto-detect whether we can grab
1884	 * the Giant or not.  Blame syscons(4) for this.
1885	 */
1886	switch (cmd) {
1887	case KDGKBSTATE:
1888	case KDSKBSTATE:
1889	case KDSETLED:
1890		if (!mtx_owned(&Giant) && !SCHEDULER_STOPPED())
1891			return (EDEADLK);	/* best I could come up with */
1892		/* FALLTHROUGH */
1893	default:
1894		UKBD_LOCK();
1895		result = ukbd_ioctl_locked(kbd, cmd, arg);
1896		UKBD_UNLOCK();
1897		return (result);
1898	}
1899}
1900
1901
1902/* clear the internal state of the keyboard */
1903static void
1904ukbd_clear_state(keyboard_t *kbd)
1905{
1906	struct ukbd_softc *sc = kbd->kb_data;
1907
1908	UKBD_CTX_LOCK_ASSERT();
1909
1910	sc->sc_flags &= ~(UKBD_FLAG_COMPOSE | UKBD_FLAG_POLLING);
1911	sc->sc_state &= LOCK_MASK;	/* preserve locking key state */
1912	sc->sc_accents = 0;
1913	sc->sc_composed_char = 0;
1914#ifdef UKBD_EMULATE_ATSCANCODE
1915	sc->sc_buffered_char[0] = 0;
1916	sc->sc_buffered_char[1] = 0;
1917#endif
1918	memset(&sc->sc_ndata, 0, sizeof(sc->sc_ndata));
1919	memset(&sc->sc_odata, 0, sizeof(sc->sc_odata));
1920	sc->sc_repeat_time = 0;
1921	sc->sc_repeat_key = 0;
1922}
1923
1924/* save the internal state, not used */
1925static int
1926ukbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1927{
1928	return (len == 0) ? 1 : -1;
1929}
1930
1931/* set the internal state, not used */
1932static int
1933ukbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1934{
1935	return (EINVAL);
1936}
1937
1938static int
1939ukbd_poll(keyboard_t *kbd, int on)
1940{
1941	struct ukbd_softc *sc = kbd->kb_data;
1942
1943	UKBD_LOCK();
1944	/*
1945	 * Keep a reference count on polling to allow recursive
1946	 * cngrab() during a panic for example.
1947	 */
1948	if (on)
1949		sc->sc_polling++;
1950	else if (sc->sc_polling > 0)
1951		sc->sc_polling--;
1952
1953	if (sc->sc_polling != 0) {
1954		sc->sc_flags |= UKBD_FLAG_POLLING;
1955		sc->sc_poll_thread = curthread;
1956	} else {
1957		sc->sc_flags &= ~UKBD_FLAG_POLLING;
1958		sc->sc_delay = 0;
1959	}
1960	UKBD_UNLOCK();
1961
1962	return (0);
1963}
1964
1965/* local functions */
1966
1967static void
1968ukbd_set_leds(struct ukbd_softc *sc, uint8_t leds)
1969{
1970
1971	UKBD_LOCK_ASSERT();
1972	DPRINTF("leds=0x%02x\n", leds);
1973
1974	sc->sc_leds = leds;
1975	sc->sc_flags |= UKBD_FLAG_SET_LEDS;
1976
1977	/* start transfer, if not already started */
1978
1979	usbd_transfer_start(sc->sc_xfer[UKBD_CTRL_LED]);
1980}
1981
1982static int
1983ukbd_set_typematic(keyboard_t *kbd, int code)
1984{
1985#ifdef EVDEV_SUPPORT
1986	struct ukbd_softc *sc = kbd->kb_data;
1987#endif
1988	static const int delays[] = {250, 500, 750, 1000};
1989	static const int rates[] = {34, 38, 42, 46, 50, 55, 59, 63,
1990		68, 76, 84, 92, 100, 110, 118, 126,
1991		136, 152, 168, 184, 200, 220, 236, 252,
1992	272, 304, 336, 368, 400, 440, 472, 504};
1993
1994	if (code & ~0x7f) {
1995		return (EINVAL);
1996	}
1997	kbd->kb_delay1 = delays[(code >> 5) & 3];
1998	kbd->kb_delay2 = rates[code & 0x1f];
1999#ifdef EVDEV_SUPPORT
2000	if (sc->sc_evdev != NULL)
2001		evdev_push_repeats(sc->sc_evdev, kbd);
2002#endif
2003	return (0);
2004}
2005
2006#ifdef UKBD_EMULATE_ATSCANCODE
2007static uint32_t
2008ukbd_atkeycode(int usbcode, const uint64_t *bitmap)
2009{
2010	uint32_t keycode;
2011
2012	keycode = ukbd_trtab[KEY_INDEX(usbcode)];
2013
2014	/*
2015	 * Translate Alt-PrintScreen to SysRq.
2016	 *
2017	 * Some or all AT keyboards connected through USB have already
2018	 * mapped Alted PrintScreens to an unusual usbcode (0x8a).
2019	 * ukbd_trtab translates this to 0x7e, and key2scan() would
2020	 * translate that to 0x79 (Intl' 4).  Assume that if we have
2021	 * an Alted 0x7e here then it actually is an Alted PrintScreen.
2022	 *
2023	 * The usual usbcode for all PrintScreens is 0x46.  ukbd_trtab
2024	 * translates this to 0x5c, so the Alt check to classify 0x5c
2025	 * is routine.
2026	 */
2027	if ((keycode == 0x5c || keycode == 0x7e) &&
2028	    (UKBD_KEY_PRESSED(bitmap, 0xe2 /* ALT-L */) ||
2029	     UKBD_KEY_PRESSED(bitmap, 0xe6 /* ALT-R */)))
2030		return (0x54);
2031	return (keycode);
2032}
2033
2034static int
2035ukbd_key2scan(struct ukbd_softc *sc, int code, const uint64_t *bitmap, int up)
2036{
2037	static const int scan[] = {
2038		/* 89 */
2039		0x11c,	/* Enter */
2040		/* 90-99 */
2041		0x11d,	/* Ctrl-R */
2042		0x135,	/* Divide */
2043		0x137,	/* PrintScreen */
2044		0x138,	/* Alt-R */
2045		0x147,	/* Home */
2046		0x148,	/* Up */
2047		0x149,	/* PageUp */
2048		0x14b,	/* Left */
2049		0x14d,	/* Right */
2050		0x14f,	/* End */
2051		/* 100-109 */
2052		0x150,	/* Down */
2053		0x151,	/* PageDown */
2054		0x152,	/* Insert */
2055		0x153,	/* Delete */
2056		0x146,	/* Pause/Break */
2057		0x15b,	/* Win_L(Super_L) */
2058		0x15c,	/* Win_R(Super_R) */
2059		0x15d,	/* Application(Menu) */
2060
2061		/* SUN TYPE 6 USB KEYBOARD */
2062		0x168,	/* Sun Type 6 Help */
2063		0x15e,	/* Sun Type 6 Stop */
2064		/* 110 - 119 */
2065		0x15f,	/* Sun Type 6 Again */
2066		0x160,	/* Sun Type 6 Props */
2067		0x161,	/* Sun Type 6 Undo */
2068		0x162,	/* Sun Type 6 Front */
2069		0x163,	/* Sun Type 6 Copy */
2070		0x164,	/* Sun Type 6 Open */
2071		0x165,	/* Sun Type 6 Paste */
2072		0x166,	/* Sun Type 6 Find */
2073		0x167,	/* Sun Type 6 Cut */
2074		0x125,	/* Sun Type 6 Mute */
2075		/* 120 - 130 */
2076		0x11f,	/* Sun Type 6 VolumeDown */
2077		0x11e,	/* Sun Type 6 VolumeUp */
2078		0x120,	/* Sun Type 6 PowerDown */
2079
2080		/* Japanese 106/109 keyboard */
2081		0x73,	/* Keyboard Intl' 1 (backslash / underscore) */
2082		0x70,	/* Keyboard Intl' 2 (Katakana / Hiragana) */
2083		0x7d,	/* Keyboard Intl' 3 (Yen sign) (Not using in jp106/109) */
2084		0x79,	/* Keyboard Intl' 4 (Henkan) */
2085		0x7b,	/* Keyboard Intl' 5 (Muhenkan) */
2086		0x5c,	/* Keyboard Intl' 6 (Keypad ,) (For PC-9821 layout) */
2087		0x71,   /* Apple Keyboard JIS (Kana) */
2088		0x72,   /* Apple Keyboard JIS (Eisu) */
2089	};
2090
2091	if ((code >= 89) && (code < (int)(89 + nitems(scan)))) {
2092		code = scan[code - 89];
2093	}
2094	/* PrintScreen */
2095	if (code == 0x137 && (!(
2096	    UKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
2097	    UKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */) ||
2098	    UKBD_KEY_PRESSED(bitmap, 0xe1 /* SHIFT-L */) ||
2099	    UKBD_KEY_PRESSED(bitmap, 0xe5 /* SHIFT-R */)))) {
2100		code |= SCAN_PREFIX_SHIFT;
2101	}
2102	/* Pause/Break */
2103	if ((code == 0x146) && (!(
2104	    UKBD_KEY_PRESSED(bitmap, 0xe0 /* CTRL-L */) ||
2105	    UKBD_KEY_PRESSED(bitmap, 0xe4 /* CTRL-R */)))) {
2106		code = (0x45 | SCAN_PREFIX_E1 | SCAN_PREFIX_CTL);
2107	}
2108	code |= (up ? SCAN_RELEASE : SCAN_PRESS);
2109
2110	if (code & SCAN_PREFIX) {
2111		if (code & SCAN_PREFIX_CTL) {
2112			/* Ctrl */
2113			sc->sc_buffered_char[0] = (0x1d | (code & SCAN_RELEASE));
2114			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX);
2115		} else if (code & SCAN_PREFIX_SHIFT) {
2116			/* Shift */
2117			sc->sc_buffered_char[0] = (0x2a | (code & SCAN_RELEASE));
2118			sc->sc_buffered_char[1] = (code & ~SCAN_PREFIX_SHIFT);
2119		} else {
2120			sc->sc_buffered_char[0] = (code & ~SCAN_PREFIX);
2121			sc->sc_buffered_char[1] = 0;
2122		}
2123		return ((code & SCAN_PREFIX_E0) ? 0xe0 : 0xe1);
2124	}
2125	return (code);
2126
2127}
2128
2129#endif					/* UKBD_EMULATE_ATSCANCODE */
2130
2131static keyboard_switch_t ukbdsw = {
2132	.probe = &ukbd__probe,
2133	.init = &ukbd_init,
2134	.term = &ukbd_term,
2135	.intr = &ukbd_intr,
2136	.test_if = &ukbd_test_if,
2137	.enable = &ukbd_enable,
2138	.disable = &ukbd_disable,
2139	.read = &ukbd_read,
2140	.check = &ukbd_check,
2141	.read_char = &ukbd_read_char,
2142	.check_char = &ukbd_check_char,
2143	.ioctl = &ukbd_ioctl,
2144	.lock = &ukbd_lock,
2145	.clear_state = &ukbd_clear_state,
2146	.get_state = &ukbd_get_state,
2147	.set_state = &ukbd_set_state,
2148	.poll = &ukbd_poll,
2149};
2150
2151KEYBOARD_DRIVER(ukbd, ukbdsw, ukbd_configure);
2152
2153static int
2154ukbd_driver_load(module_t mod, int what, void *arg)
2155{
2156	switch (what) {
2157	case MOD_LOAD:
2158		kbd_add_driver(&ukbd_kbd_driver);
2159		break;
2160	case MOD_UNLOAD:
2161		kbd_delete_driver(&ukbd_kbd_driver);
2162		break;
2163	}
2164	return (0);
2165}
2166
2167static devclass_t ukbd_devclass;
2168
2169static device_method_t ukbd_methods[] = {
2170	DEVMETHOD(device_probe, ukbd_probe),
2171	DEVMETHOD(device_attach, ukbd_attach),
2172	DEVMETHOD(device_detach, ukbd_detach),
2173	DEVMETHOD(device_resume, ukbd_resume),
2174
2175	DEVMETHOD_END
2176};
2177
2178static driver_t ukbd_driver = {
2179	.name = "ukbd",
2180	.methods = ukbd_methods,
2181	.size = sizeof(struct ukbd_softc),
2182};
2183
2184DRIVER_MODULE(ukbd, uhub, ukbd_driver, ukbd_devclass, ukbd_driver_load, 0);
2185MODULE_DEPEND(ukbd, usb, 1, 1, 1);
2186#ifdef EVDEV_SUPPORT
2187MODULE_DEPEND(ukbd, evdev, 1, 1, 1);
2188#endif
2189MODULE_VERSION(ukbd, 1);
2190USB_PNP_HOST_INFO(ukbd_devs);
2191