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