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