1/*      $NetBSD: ukbd.c,v 1.164 2023/09/02 17:43:16 riastradh Exp $        */
2
3/*
4 * Copyright (c) 1998 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Lennart Augustsson (lennart@augustsson.net) at
9 * Carlstedt Research & Technology.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33/*
34 * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf
35 */
36
37#include <sys/cdefs.h>
38__KERNEL_RCSID(0, "$NetBSD: ukbd.c,v 1.164 2023/09/02 17:43:16 riastradh Exp $");
39
40#ifdef _KERNEL_OPT
41#include "opt_ddb.h"
42#include "opt_ukbd.h"
43#include "opt_ukbd_layout.h"
44#include "opt_usb.h"
45#include "opt_usbverbose.h"
46#include "opt_wsdisplay_compat.h"
47#endif /* _KERNEL_OPT */
48
49#include <sys/param.h>
50
51#include <sys/callout.h>
52#include <sys/device.h>
53#include <sys/file.h>
54#include <sys/ioctl.h>
55#include <sys/kernel.h>
56#include <sys/poll.h>
57#include <sys/proc.h>
58#include <sys/select.h>
59#include <sys/systm.h>
60#include <sys/vnode.h>
61
62#include <dev/hid/hid.h>
63
64#include <dev/usb/uhidev.h>
65#include <dev/usb/ukbdvar.h>
66#include <dev/usb/usb.h>
67#include <dev/usb/usb_quirks.h>
68#include <dev/usb/usbdevs.h>
69#include <dev/usb/usbdi.h>
70#include <dev/usb/usbdi_util.h>
71#include <dev/usb/usbdivar.h>
72#include <dev/usb/usbhid.h>
73
74#include <dev/wscons/wsconsio.h>
75#include <dev/wscons/wskbdvar.h>
76#include <dev/wscons/wsksymdef.h>
77#include <dev/wscons/wsksymvar.h>
78
79#ifdef UKBD_DEBUG
80#define DPRINTF(x)	if (ukbddebug) printf x
81#define DPRINTFN(n,x)	if (ukbddebug>(n)) printf x
82int	ukbddebug = 0;
83#else
84#define DPRINTF(x)
85#define DPRINTFN(n,x)
86#endif
87
88#define MAXKEYCODE 32
89#define MAXKEYS 256
90
91struct ukbd_data {
92	uint8_t		keys[MAXKEYS/NBBY];
93};
94
95#define PRESS    0x000
96#define RELEASE  0x100
97#define CODEMASK 0x0ff
98
99struct ukbd_keycodetrans {
100	uint16_t	from;
101	uint16_t	to;
102};
103
104#define IS_PMF	0x8000
105
106Static const struct ukbd_keycodetrans trtab_apple_fn[] = {
107	{ 0x0c, 0x5d },	/* i -> KP 5 */
108	{ 0x0d, 0x59 },	/* j -> KP 1 */
109	{ 0x0e, 0x5a },	/* k -> KP 2 */
110	{ 0x0f, 0x5b },	/* l -> KP 3 */
111	{ 0x10, 0x62 },	/* m -> KP 0 */
112	{ 0x12, 0x5e },	/* o -> KP 6 */
113	{ 0x13, 0x55 },	/* o -> KP * */
114	{ 0x18, 0x5c },	/* u -> KP 4 */
115	{ 0x0c, 0x5d },	/* i -> KP 5 */
116	{ 0x2a, 0x4c },	/* Backspace -> Delete */
117	{ 0x28, 0x49 },	/* Return -> Insert */
118	{ 0x24, 0x5f }, /* 7 -> KP 7 */
119	{ 0x25, 0x60 }, /* 8 -> KP 8 */
120	{ 0x26, 0x61 }, /* 9 -> KP 9 */
121	{ 0x27, 0x54 }, /* 0 -> KP / */
122	{ 0x2d, 0x67 }, /* - -> KP = */
123	{ 0x33, 0x56 },	/* ; -> KP - */
124	{ 0x37, 0x63 },	/* . -> KP . */
125	{ 0x38, 0x57 },	/* / -> KP + */
126	{ 0x3a, IS_PMF | PMFE_DISPLAY_BRIGHTNESS_DOWN },
127	{ 0x3b, IS_PMF | PMFE_DISPLAY_BRIGHTNESS_UP },
128	{ 0x3c, IS_PMF | PMFE_AUDIO_VOLUME_TOGGLE },
129	{ 0x3d, IS_PMF | PMFE_AUDIO_VOLUME_DOWN },
130	{ 0x3e, IS_PMF | PMFE_AUDIO_VOLUME_UP },
131	{ 0x3f, 0xd6 },	/* num lock */
132	{ 0x40, 0xd7 },
133	{ 0x41, IS_PMF | PMFE_KEYBOARD_BRIGHTNESS_TOGGLE },
134	{ 0x42, IS_PMF | PMFE_KEYBOARD_BRIGHTNESS_DOWN },
135	{ 0x43, IS_PMF | PMFE_KEYBOARD_BRIGHTNESS_UP },
136	{ 0x44, 0xdb },
137	{ 0x45, 0xdc },
138	{ 0x4f, 0x4d },	/* Right -> End */
139	{ 0x50, 0x4a },	/* Left -> Home */
140	{ 0x51, 0x4e },	/* Down -> PageDown */
141	{ 0x52, 0x4b },	/* Up -> PageUp */
142	{ 0x00, 0x00 }
143};
144
145Static const struct ukbd_keycodetrans trtab_apple_iso[] = {
146	{ 0x35, 0x64 },	/* swap the key above tab with key right of shift */
147	{ 0x64, 0x35 },
148	{ 0x31, 0x32 },	/* key left of return is Europe1, not "\|" */
149	{ 0x00, 0x00 }
150};
151
152#ifdef GDIUM_KEYBOARD_HACK
153Static const struct ukbd_keycodetrans trtab_gdium_fn[] = {
154#ifdef notyet
155	{ 58, 0 },	/* F1 -> toggle camera */
156	{ 59, 0 },	/* F2 -> toggle wireless */
157#endif
158	{ 60, IS_PMF | PMFE_AUDIO_VOLUME_TOGGLE },
159	{ 61, IS_PMF | PMFE_AUDIO_VOLUME_UP },
160	{ 62, IS_PMF | PMFE_AUDIO_VOLUME_DOWN },
161#ifdef notyet
162	{ 63, 0 },	/* F6 -> toggle ext. video */
163	{ 64, 0 },	/* F7 -> toggle mouse */
164#endif
165	{ 65, IS_PMF | PMFE_DISPLAY_BRIGHTNESS_UP },
166	{ 66, IS_PMF | PMFE_DISPLAY_BRIGHTNESS_DOWN },
167#ifdef notyet
168	{ 67, 0 },	/* F10 -> suspend */
169	{ 68, 0 },	/* F11 -> user1 */
170	{ 69, 0 },	/* F12 -> user2 */
171	{ 70, 0 },	/* print screen -> sysrq */
172#endif
173	{ 76, 71 },	/* delete -> scroll lock */
174	{ 81, 78 },	/* down -> page down */
175	{ 82, 75 },	/* up -> page up */
176	{  0, 0 }
177};
178#endif
179
180Static const struct ukbd_keycodetrans trtab_generic[] = {
181	{ 0x7f, IS_PMF | PMFE_AUDIO_VOLUME_TOGGLE },
182	{ 0x80, IS_PMF | PMFE_AUDIO_VOLUME_UP },
183	{ 0x81, IS_PMF | PMFE_AUDIO_VOLUME_DOWN },
184	{ 0x00, 0x00 }
185};
186
187#if defined(WSDISPLAY_COMPAT_RAWKBD)
188#define NN 0			/* no translation */
189/*
190 * Translate USB keycodes to US keyboard XT scancodes.
191 * Scancodes >= 0x80 represent EXTENDED keycodes.
192 *
193 * See http://www.microsoft.com/whdc/archive/scancode.mspx
194 *
195 * Note: a real pckbd(4) has more complexity in its
196 * protocol for some keys than this translation implements.
197 * For example, some keys generate Fake ShiftL events (e0 2a)
198 * before the actual key sequence.
199 */
200Static const uint8_t ukbd_trtab[256] = {
201      NN,   NN,   NN,   NN, 0x1e, 0x30, 0x2e, 0x20, /* 00 - 07 */
202    0x12, 0x21, 0x22, 0x23, 0x17, 0x24, 0x25, 0x26, /* 08 - 0f */
203    0x32, 0x31, 0x18, 0x19, 0x10, 0x13, 0x1f, 0x14, /* 10 - 17 */
204    0x16, 0x2f, 0x11, 0x2d, 0x15, 0x2c, 0x02, 0x03, /* 18 - 1f */
205    0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, /* 20 - 27 */
206    0x1c, 0x01, 0x0e, 0x0f, 0x39, 0x0c, 0x0d, 0x1a, /* 28 - 2f */
207    0x1b, 0x2b, 0x2b, 0x27, 0x28, 0x29, 0x33, 0x34, /* 30 - 37 */
208    0x35, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, /* 38 - 3f */
209    0x41, 0x42, 0x43, 0x44, 0x57, 0x58, 0xb7, 0x46, /* 40 - 47 */
210    0x7f, 0xd2, 0xc7, 0xc9, 0xd3, 0xcf, 0xd1, 0xcd, /* 48 - 4f */
211    0xcb, 0xd0, 0xc8, 0x45, 0xb5, 0x37, 0x4a, 0x4e, /* 50 - 57 */
212    0x9c, 0x4f, 0x50, 0x51, 0x4b, 0x4c, 0x4d, 0x47, /* 58 - 5f */
213    0x48, 0x49, 0x52, 0x53, 0x56, 0xdd, 0xdf, 0x59, /* 60 - 67 */
214    0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a,   NN, /* 68 - 6f */
215      NN,   NN,   NN,   NN, 0x84, 0x85, 0x87, 0x88, /* 70 - 77 */
216    0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,   NN, /* 78 - 7f */
217      NN,   NN,   NN,   NN,   NN, 0x7e,   NN, 0x73, /* 80 - 87 */
218    0x70, 0x7d, 0x79, 0x7b, 0x5c,   NN,   NN,   NN, /* 88 - 8f */
219      NN,   NN, 0x78, 0x77, 0x76,   NN,   NN,   NN, /* 90 - 97 */
220      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* 98 - 9f */
221      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* a0 - a7 */
222      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* a8 - af */
223      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* b0 - b7 */
224      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* b8 - bf */
225      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* c0 - c7 */
226      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* c8 - cf */
227      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* d0 - d7 */
228      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* d8 - df */
229    0x1d, 0x2a, 0x38, 0xdb, 0x9d, 0x36, 0xb8, 0xdc, /* e0 - e7 */
230      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* e8 - ef */
231      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* f0 - f7 */
232      NN,   NN,   NN,   NN,   NN,   NN,   NN,   NN, /* f8 - ff */
233};
234#endif /* defined(WSDISPLAY_COMPAT_RAWKBD) */
235
236#define KEY_ERROR 0x01
237
238struct ukbd_softc {
239	device_t sc_dev;
240	struct uhidev *sc_hdev;
241	struct usbd_device *sc_udev;
242	struct usbd_interface *sc_iface;
243	int sc_report_id;
244
245	struct ukbd_data sc_ndata;
246	struct ukbd_data sc_odata;
247	struct hid_location sc_keyloc[MAXKEYS];
248	uint8_t sc_keyuse[MAXKEYS];
249	u_int sc_nkeyloc;
250
251	struct hid_location sc_keycodeloc;
252	u_int sc_nkeycode;
253
254	u_int sc_flags;			/* flags */
255#define FLAG_ENABLED		0x0001
256#define FLAG_POLLING		0x0002
257#define FLAG_DEBOUNCE		0x0004	/* for quirk handling */
258#define FLAG_APPLE_FIX_ISO	0x0008
259#define FLAG_APPLE_FN		0x0010
260#define FLAG_GDIUM_FN		0x0020
261#define FLAG_FN_PRESSED		0x0100	/* FN key is held down */
262#define FLAG_FN_ALT		0x0200	/* Last Alt key was FN-Alt = AltGr */
263#define FLAG_NO_CONSOLE		0x0400	/* Don't attach as console */
264
265	int sc_console_keyboard;	/* we are the console keyboard */
266
267	struct callout sc_delay;	/* for quirk handling */
268#define MAXPENDING 32
269	struct ukbd_data sc_data[MAXPENDING];
270	size_t sc_data_w, sc_data_r;
271
272	struct hid_location sc_apple_fn;
273	struct hid_location sc_numloc;
274	struct hid_location sc_capsloc;
275	struct hid_location sc_scroloc;
276	struct hid_location sc_compose;
277	int sc_leds;
278	struct usb_task sc_ledtask;
279	struct callout sc_ledreset;
280	int sc_leds_set;
281	device_t sc_wskbddev;
282
283#if defined(WSDISPLAY_COMPAT_RAWKBD)
284	int sc_rawkbd;
285#if defined(UKBD_REPEAT)
286	struct callout sc_rawrepeat_ch;
287#define REP_DELAY1 400
288#define REP_DELAYN 100
289	int sc_nrep;
290	char sc_rep[MAXKEYS];
291#endif /* defined(UKBD_REPEAT) */
292#endif /* defined(WSDISPLAY_COMPAT_RAWKBD) */
293
294	int sc_spl;
295	int sc_npollchar;
296	uint16_t sc_pollchars[MAXKEYS];
297
298	bool sc_dying;
299	bool sc_attached;
300};
301
302#ifdef UKBD_DEBUG
303#define UKBDTRACESIZE 64
304struct ukbdtraceinfo {
305	int unit;
306	struct timeval tv;
307	struct ukbd_data ud;
308};
309struct ukbdtraceinfo ukbdtracedata[UKBDTRACESIZE];
310int ukbdtraceindex = 0;
311int ukbdtrace = 0;
312void ukbdtracedump(void);
313void
314ukbdtracedump(void)
315{
316	size_t i, j;
317	for (i = 0; i < UKBDTRACESIZE; i++) {
318		struct ukbdtraceinfo *p =
319		    &ukbdtracedata[(i+ukbdtraceindex)%UKBDTRACESIZE];
320		printf("%"PRIu64".%06"PRIu64":", p->tv.tv_sec,
321		    (uint64_t)p->tv.tv_usec);
322		for (j = 0; j < MAXKEYS; j++) {
323			if (isset(p->ud.keys, j))
324				printf(" %zu", j);
325		}
326		printf(".\n");
327	}
328}
329#endif
330
331#define	UKBDUNIT(dev)	(minor(dev))
332#define	UKBD_CHUNK	128	/* chunk size for read */
333#define	UKBD_BSIZE	1020	/* buffer size */
334
335Static int	ukbd_is_console;
336
337Static void	ukbd_cngetc(void *, u_int *, int *);
338Static void	ukbd_cnpollc(void *, int);
339
340const struct wskbd_consops ukbd_consops = {
341	.getc =  ukbd_cngetc,
342	.pollc = ukbd_cnpollc,
343	.bell =  NULL,
344};
345
346Static const char *ukbd_parse_desc(struct ukbd_softc *);
347
348Static void	ukbd_intr(void *, void *, u_int);
349Static void	ukbd_decode(struct ukbd_softc *, struct ukbd_data *);
350Static void	ukbd_delayed_decode(void *);
351
352Static int	ukbd_enable(void *, int);
353Static void	ukbd_set_leds(void *, int);
354Static void	ukbd_set_leds_task(void *);
355Static void	ukbd_delayed_leds_off(void *);
356
357Static int	ukbd_ioctl(void *, u_long, void *, int, struct lwp *);
358#if  defined(WSDISPLAY_COMPAT_RAWKBD) && defined(UKBD_REPEAT)
359Static void	ukbd_rawrepeat(void *v);
360#endif
361
362const struct wskbd_accessops ukbd_accessops = {
363	ukbd_enable,
364	ukbd_set_leds,
365	ukbd_ioctl,
366};
367
368extern const struct wscons_keydesc hidkbd_keydesctab[];
369
370const struct wskbd_mapdata ukbd_keymapdata = {
371	hidkbd_keydesctab,
372#if defined(UKBD_LAYOUT)
373	UKBD_LAYOUT,
374#elif defined(PCKBD_LAYOUT)
375	PCKBD_LAYOUT,
376#else
377	KB_US,
378#endif
379};
380
381static const struct ukbd_type {
382	struct usb_devno	dev;
383	int			flags;
384} ukbd_devs[] = {
385#define UKBD_DEV(v, p, f) \
386	{ { USB_VENDOR_##v, USB_PRODUCT_##v##_##p }, (f) }
387#ifdef GDIUM_KEYBOARD_HACK
388	UKBD_DEV(CYPRESS, LPRDK, FLAG_GDIUM_FN),
389#endif
390	UKBD_DEV(YUBICO, YUBIKEY4MODE1, FLAG_NO_CONSOLE),
391	UKBD_DEV(YUBICO, YUBIKEY4MODE2, FLAG_NO_CONSOLE),
392	UKBD_DEV(YUBICO, YUBIKEY4MODE6, FLAG_NO_CONSOLE)
393};
394#define ukbd_lookup(v, p) \
395	((const struct ukbd_type *)usb_lookup(ukbd_devs, v, p))
396
397static int ukbd_match(device_t, cfdata_t, void *);
398static void ukbd_attach(device_t, device_t, void *);
399static int ukbd_detach(device_t, int);
400static int ukbd_activate(device_t, enum devact);
401static void ukbd_childdet(device_t, device_t);
402
403
404
405CFATTACH_DECL2_NEW(ukbd, sizeof(struct ukbd_softc), ukbd_match, ukbd_attach,
406    ukbd_detach, ukbd_activate, NULL, ukbd_childdet);
407
408int
409ukbd_match(device_t parent, cfdata_t match, void *aux)
410{
411	struct uhidev_attach_arg *uha = aux;
412	int size;
413	void *desc;
414
415	uhidev_get_report_desc(uha->parent, &desc, &size);
416	if (!hid_is_collection(desc, size, uha->reportid,
417			       HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_KEYBOARD)))
418		return UMATCH_NONE;
419
420	return UMATCH_IFACECLASS;
421}
422
423void
424ukbd_attach(device_t parent, device_t self, void *aux)
425{
426	struct ukbd_softc *sc = device_private(self);
427	struct uhidev_attach_arg *uha = aux;
428	uint32_t qflags;
429	const char *parseerr;
430	struct wskbddev_attach_args a;
431	const struct ukbd_type *ukt;
432
433	sc->sc_dev = self;
434	sc->sc_hdev = uha->parent;
435	sc->sc_udev = uha->uiaa->uiaa_device;
436	sc->sc_iface = uha->uiaa->uiaa_iface;
437	sc->sc_report_id = uha->reportid;
438	sc->sc_flags = 0;
439
440	aprint_naive("\n");
441
442	if (!pmf_device_register(self, NULL, NULL)) {
443		aprint_normal("\n");
444		aprint_error_dev(self, "couldn't establish power handler\n");
445	}
446
447	parseerr = ukbd_parse_desc(sc);
448	if (parseerr != NULL) {
449		aprint_normal("\n");
450		aprint_error_dev(self, "attach failed, %s\n", parseerr);
451		return;
452	}
453
454	/* Quirks */
455	qflags = usbd_get_quirks(sc->sc_udev)->uq_flags;
456	if (qflags & UQ_SPUR_BUT_UP)
457		sc->sc_flags |= FLAG_DEBOUNCE;
458	if (qflags & UQ_APPLE_ISO)
459		sc->sc_flags |= FLAG_APPLE_FIX_ISO;
460
461	/* Other Quirks */
462	ukt = ukbd_lookup(uha->uiaa->uiaa_vendor, uha->uiaa->uiaa_product);
463	if (ukt)
464		sc->sc_flags |= ukt->flags;
465
466#ifdef USBVERBOSE
467	aprint_normal(": %d Variable keys, %d Array codes", sc->sc_nkeyloc,
468	       sc->sc_nkeycode);
469	if (sc->sc_flags & FLAG_APPLE_FN)
470		aprint_normal(", apple fn key");
471	if (sc->sc_flags & FLAG_APPLE_FIX_ISO)
472		aprint_normal(", fix apple iso");
473	if (sc->sc_flags & FLAG_GDIUM_FN)
474		aprint_normal(", Gdium fn key");
475#endif
476	aprint_normal("\n");
477
478	if ((sc->sc_flags & FLAG_NO_CONSOLE) == 0) {
479		/*
480		 * Remember if we're the console keyboard.
481		 *
482		 * XXX This always picks the first keyboard on the
483		 * first USB bus, but what else can we really do?
484		 */
485		if ((sc->sc_console_keyboard = ukbd_is_console) != 0) {
486			/* Don't let any other keyboard have it. */
487			ukbd_is_console = 0;
488		}
489	}
490
491	if (sc->sc_console_keyboard) {
492		DPRINTF(("%s: console keyboard sc=%p\n", __func__, sc));
493		wskbd_cnattach(&ukbd_consops, sc, &ukbd_keymapdata);
494		ukbd_enable(sc, 1);
495	}
496
497	a.console = sc->sc_console_keyboard;
498
499	a.keymap = &ukbd_keymapdata;
500
501	a.accessops = &ukbd_accessops;
502	a.accesscookie = sc;
503
504#ifdef UKBD_REPEAT
505	callout_init(&sc->sc_rawrepeat_ch, 0);
506#endif
507
508	callout_init(&sc->sc_delay, 0);
509
510	sc->sc_data_w = 0;
511	sc->sc_data_r = 0;
512
513	usb_init_task(&sc->sc_ledtask, ukbd_set_leds_task, sc, 0);
514	callout_init(&sc->sc_ledreset, 0);
515
516	/* Flash the leds; no real purpose, just shows we're alive. */
517	ukbd_set_leds(sc, WSKBD_LED_SCROLL | WSKBD_LED_NUM | WSKBD_LED_CAPS
518			| WSKBD_LED_COMPOSE);
519	sc->sc_leds_set = 0;	/* not explicitly set by wskbd yet */
520	callout_reset(&sc->sc_ledreset, mstohz(400), ukbd_delayed_leds_off,
521	    sc);
522
523	sc->sc_wskbddev = config_found(self, &a, wskbddevprint, CFARGS_NONE);
524
525	sc->sc_attached = true;
526
527	return;
528}
529
530int
531ukbd_enable(void *v, int on)
532{
533	struct ukbd_softc *sc = v;
534
535	if (on && sc->sc_dying)
536		return EIO;
537
538	/* Should only be called to change state */
539	if ((sc->sc_flags & FLAG_ENABLED) != 0 && on != 0) {
540#ifdef DIAGNOSTIC
541		aprint_error_dev(sc->sc_dev, "bad call on=%d\n", on);
542#endif
543		return EBUSY;
544	}
545
546	DPRINTF(("%s: sc=%p on=%d\n", __func__, sc, on));
547	if (on) {
548		sc->sc_flags |= FLAG_ENABLED;
549		return uhidev_open(sc->sc_hdev, &ukbd_intr, sc);
550	} else {
551		sc->sc_flags &= ~FLAG_ENABLED;
552		uhidev_close(sc->sc_hdev);
553		return 0;
554	}
555}
556
557
558static void
559ukbd_childdet(device_t self, device_t child)
560{
561	struct ukbd_softc *sc = device_private(self);
562
563	KASSERT(sc->sc_wskbddev == child);
564	sc->sc_wskbddev = NULL;
565}
566
567int
568ukbd_activate(device_t self, enum devact act)
569{
570	struct ukbd_softc *sc = device_private(self);
571
572	switch (act) {
573	case DVACT_DEACTIVATE:
574		sc->sc_dying = true;
575		return 0;
576	default:
577		return EOPNOTSUPP;
578	}
579}
580
581int
582ukbd_detach(device_t self, int flags)
583{
584	struct ukbd_softc *sc = device_private(self);
585	int rv = 0;
586
587	DPRINTF(("%s: sc=%p flags=%d\n", __func__, sc, flags));
588
589	pmf_device_deregister(self);
590
591	if (!sc->sc_attached)
592		return rv;
593
594	if (sc->sc_console_keyboard) {
595		/*
596		 * Disconnect our consops and set ukbd_is_console
597		 * back to 1 so that the next USB keyboard attached
598		 * to the system will get it.
599		 * XXX Should notify some other keyboard that it can be
600		 * XXX console, if there are any other keyboards.
601		 */
602		printf("%s: was console keyboard\n",
603		       device_xname(sc->sc_dev));
604		wskbd_cndetach();
605		ukbd_is_console = 1;
606	}
607	/* No need to do reference counting of ukbd, wskbd has all the goo. */
608	if (sc->sc_wskbddev != NULL)
609		rv = config_detach(sc->sc_wskbddev, flags);
610
611	callout_halt(&sc->sc_delay, NULL);
612	callout_halt(&sc->sc_ledreset, NULL);
613	usb_rem_task_wait(sc->sc_udev, &sc->sc_ledtask,
614	    USB_TASKQ_DRIVER, NULL);
615
616	/* The console keyboard does not get a disable call, so check pipe. */
617	if (sc->sc_flags & FLAG_ENABLED)
618		uhidev_close(sc->sc_hdev);
619
620	return rv;
621}
622
623static void
624ukbd_translate_keycodes(struct ukbd_softc *sc, struct ukbd_data *ud,
625    const struct ukbd_keycodetrans *tab)
626{
627	const struct ukbd_keycodetrans *tp;
628	struct ukbd_data oud;
629	int i;
630
631	oud = *ud;
632
633	for (i = 4; i < MAXKEYS; i++) {
634		if (isset(oud.keys, i))
635			for (tp = tab; tp->from; tp++)
636				if (tp->from == i) {
637					if (tp->to & IS_PMF) {
638						pmf_event_inject(sc->sc_dev,
639						    tp->to & 0xff);
640					} else
641						setbit(ud->keys, tp->to);
642					clrbit(ud->keys, i);
643					break;
644				}
645	}
646}
647
648static uint16_t
649ukbd_translate_modifier(struct ukbd_softc *sc, uint16_t key)
650{
651	if ((sc->sc_flags & FLAG_APPLE_FN) && (key & CODEMASK) == 0x00e2) {
652		if ((key & ~CODEMASK) == PRESS) {
653			if (sc->sc_flags & FLAG_FN_PRESSED) {
654				/* pressed FN-Alt, translate to AltGr */
655				key = 0x00e6 | PRESS;
656				sc->sc_flags |= FLAG_FN_ALT;
657			}
658		} else {
659			if (sc->sc_flags & FLAG_FN_ALT) {
660				/* released Alt, which was treated as FN-Alt */
661				key = 0x00e6 | RELEASE;
662				sc->sc_flags &= ~FLAG_FN_ALT;
663			}
664		}
665	}
666	return key;
667}
668
669void
670ukbd_intr(void *cookie, void *ibuf, u_int len)
671{
672	struct ukbd_softc *sc = cookie;
673	struct ukbd_data *ud = &sc->sc_ndata;
674	int i;
675
676#ifdef UKBD_DEBUG
677	if (ukbddebug > 5) {
678		printf("ukbd_intr: data");
679		for (i = 0; i < len; i++)
680			printf(" 0x%02x", ((u_char *)ibuf)[i]);
681		printf("\n");
682	}
683#endif
684
685	memset(ud->keys, 0, sizeof(ud->keys));
686
687	for (i = 0; i < sc->sc_nkeyloc; i++)
688		if (hid_get_data(ibuf, &sc->sc_keyloc[i]))
689			setbit(ud->keys, sc->sc_keyuse[i]);
690
691	const uint8_t * const scancode = (char *)ibuf + sc->sc_keycodeloc.pos / 8;
692	const uint16_t Keyboard_NoEvent = 0x0000;
693	for (i = 0; i < sc->sc_nkeycode; i++) {
694		if (scancode[i] != Keyboard_NoEvent)
695			setbit(ud->keys, scancode[i]);
696	}
697
698	if (sc->sc_flags & FLAG_APPLE_FN) {
699		if (hid_get_data(ibuf, &sc->sc_apple_fn)) {
700			sc->sc_flags |= FLAG_FN_PRESSED;
701			ukbd_translate_keycodes(sc, ud, trtab_apple_fn);
702		}
703		else
704			sc->sc_flags &= ~FLAG_FN_PRESSED;
705	}
706
707#ifdef GDIUM_KEYBOARD_HACK
708	if (sc->sc_flags & FLAG_GDIUM_FN) {
709		if (sc->sc_flags & FLAG_FN_PRESSED) {
710			ukbd_translate_keycodes(sc, ud, trtab_gdium_fn);
711		}
712	}
713#endif
714
715	ukbd_translate_keycodes(sc, ud, trtab_generic);
716
717	if ((sc->sc_flags & FLAG_DEBOUNCE) && !(sc->sc_flags & FLAG_POLLING)) {
718		/*
719		 * Some keyboards have a peculiar quirk.  They sometimes
720		 * generate a key up followed by a key down for the same
721		 * key after about 10 ms.
722		 * We avoid this bug by holding off decoding for 20 ms.
723		 * Note that this comes at a cost: we deliberately overwrite
724		 * the data for any keyboard event that is followed by
725		 * another one within this time window.
726		 */
727		if (sc->sc_data_w == sc->sc_data_r) {
728			sc->sc_data_w = (sc->sc_data_w + 1) % MAXPENDING;
729		}
730		sc->sc_data[sc->sc_data_w] = *ud;
731		callout_reset(&sc->sc_delay, hz / 50, ukbd_delayed_decode, sc);
732#ifdef DDB
733	} else if (sc->sc_console_keyboard && !(sc->sc_flags & FLAG_POLLING)) {
734		/*
735		 * For the console keyboard we can't deliver CTL-ALT-ESC
736		 * from the interrupt routine.  Doing so would start
737		 * polling from inside the interrupt routine and that
738		 * loses bigtime.
739		 */
740		sc->sc_data_w = (sc->sc_data_w + 1) % MAXPENDING;
741		sc->sc_data[sc->sc_data_w] = *ud;
742		callout_reset(&sc->sc_delay, 0, ukbd_delayed_decode, sc);
743#endif
744	} else {
745		ukbd_decode(sc, ud);
746	}
747}
748
749Static void
750ukbd_delayed_leds_off(void *addr)
751{
752	struct ukbd_softc *sc = addr;
753
754	/*
755	 * If the LEDs have already been set after attach, other than
756	 * by our initial flashing of them, leave them be.
757	 */
758	if (sc->sc_leds_set)
759		return;
760
761	ukbd_set_leds(sc, 0);
762}
763
764void
765ukbd_delayed_decode(void *addr)
766{
767	struct ukbd_softc *sc = addr;
768
769	while (sc->sc_data_r != sc->sc_data_w) {
770		sc->sc_data_r = (sc->sc_data_r + 1) % MAXPENDING;
771		ukbd_decode(sc, &sc->sc_data[sc->sc_data_r]);
772	}
773}
774
775void
776ukbd_decode(struct ukbd_softc *sc, struct ukbd_data *ud)
777{
778	uint16_t ibuf[MAXKEYS];	/* chars events */
779	int s;
780	int nkeys, i;
781#ifdef WSDISPLAY_COMPAT_RAWKBD
782	int j;
783#endif
784	int key;
785#define ADDKEY(c) do { \
786    KASSERT(nkeys < MAXKEYS); \
787    ibuf[nkeys++] = (c); \
788} while (0)
789
790#ifdef UKBD_DEBUG
791	/*
792	 * Keep a trace of the last events.  Using printf changes the
793	 * timing, so this can be useful sometimes.
794	 */
795	if (ukbdtrace) {
796		struct ukbdtraceinfo *p = &ukbdtracedata[ukbdtraceindex];
797		p->unit = device_unit(sc->sc_dev);
798		microtime(&p->tv);
799		p->ud = *ud;
800		if (++ukbdtraceindex >= UKBDTRACESIZE)
801			ukbdtraceindex = 0;
802	}
803	if (ukbddebug > 5) {
804		struct timeval tv;
805		microtime(&tv);
806		DPRINTF((" at %"PRIu64".%06"PRIu64":", tv.tv_sec,
807		    (uint64_t)tv.tv_usec));
808		for (size_t k = 0; k < MAXKEYS; k++) {
809			if (isset(ud->keys, k))
810				DPRINTF((" %zu", k));
811		}
812		DPRINTF((".\n"));
813	}
814#endif
815
816	if (isset(ud->keys, KEY_ERROR)) {
817		DPRINTF(("%s: KEY_ERROR\n", __func__));
818		return;		/* ignore  */
819	}
820
821	if (sc->sc_flags & FLAG_APPLE_FIX_ISO)
822		ukbd_translate_keycodes(sc, ud, trtab_apple_iso);
823
824	nkeys = 0;
825	for (i = 0; i < MAXKEYS; i++) {
826#ifdef GDIUM_KEYBOARD_HACK
827			if (sc->sc_flags & FLAG_GDIUM_FN && i == 0x82) {
828				if (isset(ud->keys, i))
829					sc->sc_flags |= FLAG_FN_PRESSED;
830				else
831					sc->sc_flags &= ~FLAG_FN_PRESSED;
832			}
833#endif
834			if (isset(ud->keys, i) != isset(sc->sc_odata.keys, i)) {
835				key = i | ((isset(ud->keys, i) ? PRESS : RELEASE));
836				ADDKEY(ukbd_translate_modifier(sc, key));
837			}
838	}
839	sc->sc_odata = *ud;
840
841	if (nkeys == 0)
842		return;
843
844	if (sc->sc_flags & FLAG_POLLING) {
845		DPRINTFN(1,("%s: pollchar = 0x%03x\n", __func__, ibuf[0]));
846		memcpy(sc->sc_pollchars, ibuf, nkeys * sizeof(uint16_t));
847		sc->sc_npollchar = nkeys;
848		return;
849	}
850#ifdef WSDISPLAY_COMPAT_RAWKBD
851	if (sc->sc_rawkbd) {
852		u_char cbuf[MAXKEYS * 2];
853		int c;
854#if defined(UKBD_REPEAT)
855		int npress = 0;
856#endif
857
858		for (i = j = 0; i < nkeys; i++) {
859			key = ibuf[i];
860			c = ukbd_trtab[key & CODEMASK];
861			if (c == NN)
862				continue;
863			if (c == 0x7f) {
864				/* pause key */
865				cbuf[j++] = 0xe1;
866				cbuf[j++] = 0x1d;
867				cbuf[j-1] |= (key & RELEASE) ? 0x80 : 0;
868				cbuf[j] = 0x45;
869			} else {
870				if (c & 0x80)
871					cbuf[j++] = 0xe0;
872				cbuf[j] = c & 0x7f;
873			}
874			if (key & RELEASE)
875				cbuf[j] |= 0x80;
876#if defined(UKBD_REPEAT)
877			else {
878				/* remember pressed keys for autorepeat */
879				if (c & 0x80)
880					sc->sc_rep[npress++] = 0xe0;
881				sc->sc_rep[npress++] = c & 0x7f;
882			}
883#endif
884			DPRINTFN(1,("%s: raw = %s0x%02x\n", __func__,
885				    c & 0x80 ? "0xe0 " : "",
886				    cbuf[j]));
887			j++;
888		}
889		s = spltty();
890		wskbd_rawinput(sc->sc_wskbddev, cbuf, j);
891		splx(s);
892#ifdef UKBD_REPEAT
893		callout_stop(&sc->sc_rawrepeat_ch);
894		if (npress != 0) {
895			sc->sc_nrep = npress;
896			callout_reset(&sc->sc_rawrepeat_ch,
897			    hz * REP_DELAY1 / 1000, ukbd_rawrepeat, sc);
898		}
899#endif
900		return;
901	}
902#endif
903
904	s = spltty();
905	for (i = 0; i < nkeys; i++) {
906		key = ibuf[i];
907		wskbd_input(sc->sc_wskbddev,
908		    key&RELEASE ? WSCONS_EVENT_KEY_UP : WSCONS_EVENT_KEY_DOWN,
909		    key&CODEMASK);
910	}
911	splx(s);
912}
913
914void
915ukbd_set_leds(void *v, int leds)
916{
917	struct ukbd_softc *sc = v;
918	struct usbd_device *udev = sc->sc_udev;
919
920	DPRINTF(("%s: sc=%p leds=%d, sc_leds=%d\n", __func__,
921		 sc, leds, sc->sc_leds));
922
923	if (sc->sc_dying)
924		return;
925
926	sc->sc_leds_set = 1;
927
928	if (sc->sc_leds == leds)
929		return;
930
931	sc->sc_leds = leds;
932	usb_add_task(udev, &sc->sc_ledtask, USB_TASKQ_DRIVER);
933}
934
935void
936ukbd_set_leds_task(void *v)
937{
938	struct ukbd_softc *sc = v;
939	int leds = sc->sc_leds;
940	uint8_t res = 0;
941
942	/* XXX not really right */
943	if ((leds & WSKBD_LED_COMPOSE) && sc->sc_compose.size == 1)
944		res |= 1 << sc->sc_compose.pos;
945	if ((leds & WSKBD_LED_SCROLL) && sc->sc_scroloc.size == 1)
946		res |= 1 << sc->sc_scroloc.pos;
947	if ((leds & WSKBD_LED_NUM) && sc->sc_numloc.size == 1)
948		res |= 1 << sc->sc_numloc.pos;
949	if ((leds & WSKBD_LED_CAPS) && sc->sc_capsloc.size == 1)
950		res |= 1 << sc->sc_capsloc.pos;
951
952	uhidev_set_report(sc->sc_hdev, UHID_OUTPUT_REPORT, &res, 1);
953}
954
955#if defined(WSDISPLAY_COMPAT_RAWKBD) && defined(UKBD_REPEAT)
956void
957ukbd_rawrepeat(void *v)
958{
959	struct ukbd_softc *sc = v;
960	int s;
961
962	s = spltty();
963	wskbd_rawinput(sc->sc_wskbddev, sc->sc_rep, sc->sc_nrep);
964	splx(s);
965	callout_reset(&sc->sc_rawrepeat_ch, hz * REP_DELAYN / 1000,
966	    ukbd_rawrepeat, sc);
967}
968#endif /* defined(WSDISPLAY_COMPAT_RAWKBD) && defined(UKBD_REPEAT) */
969
970int
971ukbd_ioctl(void *v, u_long cmd, void *data, int flag,
972    struct lwp *l)
973{
974	struct ukbd_softc *sc = v;
975
976	switch (cmd) {
977	case WSKBDIO_GTYPE:
978		*(int *)data = WSKBD_TYPE_USB;
979		return 0;
980	case WSKBDIO_SETLEDS:
981		ukbd_set_leds(v, *(int *)data);
982		return 0;
983	case WSKBDIO_GETLEDS:
984		*(int *)data = sc->sc_leds;
985		return 0;
986#if defined(WSDISPLAY_COMPAT_RAWKBD)
987	case WSKBDIO_SETMODE:
988		DPRINTF(("%s: set raw = %d\n", __func__, *(int *)data));
989		sc->sc_rawkbd = *(int *)data == WSKBD_RAW;
990#if defined(UKBD_REPEAT)
991		callout_stop(&sc->sc_rawrepeat_ch);
992#endif
993		return 0;
994#endif
995	}
996	return EPASSTHROUGH;
997}
998
999/*
1000 * This is a hack to work around some broken ports that don't call
1001 * cnpollc() before cngetc().
1002 */
1003static int pollenter, warned;
1004
1005/* Console interface. */
1006void
1007ukbd_cngetc(void *v, u_int *type, int *data)
1008{
1009	struct ukbd_softc *sc = v;
1010	int c;
1011	int broken;
1012
1013	if (pollenter == 0) {
1014		if (!warned) {
1015			printf("\n"
1016"This port is broken, it does not call cnpollc() before calling cngetc().\n"
1017"This should be fixed, but it will work anyway (for now).\n");
1018			warned = 1;
1019		}
1020		broken = 1;
1021		ukbd_cnpollc(v, 1);
1022	} else
1023		broken = 0;
1024
1025	DPRINTFN(0,("%s: enter\n", __func__));
1026	sc->sc_flags |= FLAG_POLLING;
1027	if (sc->sc_npollchar <= 0)
1028		usbd_dopoll(sc->sc_iface);
1029	sc->sc_flags &= ~FLAG_POLLING;
1030	if (sc->sc_npollchar > 0) {
1031		c = sc->sc_pollchars[0];
1032		sc->sc_npollchar--;
1033		memmove(sc->sc_pollchars, sc->sc_pollchars+1,
1034		       sc->sc_npollchar * sizeof(uint16_t));
1035		*type = c & RELEASE ? WSCONS_EVENT_KEY_UP : WSCONS_EVENT_KEY_DOWN;
1036		*data = c & CODEMASK;
1037		DPRINTFN(0,("%s: return 0x%02x\n", __func__, c));
1038	} else {
1039		*type = 0;
1040		*data = 0;
1041	}
1042	if (broken)
1043		ukbd_cnpollc(v, 0);
1044}
1045
1046void
1047ukbd_cnpollc(void *v, int on)
1048{
1049	struct ukbd_softc *sc = v;
1050	struct usbd_device *dev;
1051
1052	DPRINTFN(2,("%s: sc=%p on=%d\n", __func__, v, on));
1053
1054	/* XXX Can this just use sc->sc_udev, or am I mistaken?  */
1055	usbd_interface2device_handle(sc->sc_iface, &dev);
1056	if (on) {
1057		sc->sc_spl = splusb();
1058		pollenter++;
1059	}
1060	usbd_set_polling(dev, on);
1061	if (!on) {
1062		pollenter--;
1063		splx(sc->sc_spl);
1064	}
1065}
1066
1067int
1068ukbd_cnattach(void)
1069{
1070
1071	/*
1072	 * XXX USB requires too many parts of the kernel to be running
1073	 * XXX in order to work, so we can't do much for the console
1074	 * XXX keyboard until autoconfiguration has run its course.
1075	 */
1076	ukbd_is_console = 1;
1077	return 0;
1078}
1079
1080const char *
1081ukbd_parse_desc(struct ukbd_softc *sc)
1082{
1083	struct hid_data *d;
1084	struct hid_item h;
1085	int size;
1086	void *desc;
1087	int ikey;
1088
1089	uhidev_get_report_desc(sc->sc_hdev, &desc, &size);
1090	ikey = 0;
1091	sc->sc_nkeycode = 0;
1092	d = hid_start_parse(desc, size, hid_input);
1093	while (hid_get_item(d, &h)) {
1094		/* Check for special Apple notebook FN key */
1095		if (HID_GET_USAGE_PAGE(h.usage) == 0x00ff &&
1096		    HID_GET_USAGE(h.usage) == 0x0003 &&
1097		    h.kind == hid_input && (h.flags & HIO_VARIABLE)) {
1098			sc->sc_flags |= FLAG_APPLE_FN;
1099			sc->sc_apple_fn = h.loc;
1100		}
1101
1102		if (h.kind != hid_input || (h.flags & HIO_CONST) ||
1103		    HID_GET_USAGE_PAGE(h.usage) != HUP_KEYBOARD ||
1104		    h.report_ID != sc->sc_report_id)
1105			continue;
1106		DPRINTF(("%s: ikey=%d usage=%#x flags=%#x pos=%d size=%d "
1107		    "cnt=%d\n", __func__, ikey, h.usage, h.flags, h.loc.pos,
1108		    h.loc.size, h.loc.count));
1109		if (h.flags & HIO_VARIABLE) {
1110			if (h.loc.size != 1) {
1111				hid_end_parse(d);
1112				return "bad modifier size";
1113			}
1114			/* Single item */
1115			if (ikey < MAXKEYS) {
1116				sc->sc_keyloc[ikey] = h.loc;
1117				sc->sc_keyuse[ikey] = HID_GET_USAGE(h.usage);
1118				ikey++;
1119			} else {
1120				hid_end_parse(d);
1121				return "too many Variable keys";
1122			}
1123		} else {
1124			/* Array */
1125			if (h.loc.size != 8) {
1126				hid_end_parse(d);
1127				return "key code size != 8";
1128			}
1129			if (h.loc.count > MAXKEYCODE)
1130				h.loc.count = MAXKEYCODE;
1131			if (h.loc.pos % 8 != 0) {
1132				hid_end_parse(d);
1133				return "key codes not on byte boundary";
1134			}
1135			if (sc->sc_nkeycode != 0) {
1136				hid_end_parse(d);
1137				return "multiple key code arrays";
1138			}
1139			sc->sc_keycodeloc = h.loc;
1140			sc->sc_nkeycode = h.loc.count;
1141		}
1142	}
1143	sc->sc_nkeyloc = ikey;
1144	hid_end_parse(d);
1145
1146	hid_locate(desc, size, HID_USAGE2(HUP_LEDS, HUD_LED_NUM_LOCK),
1147	    sc->sc_report_id, hid_output, &sc->sc_numloc, NULL);
1148	hid_locate(desc, size, HID_USAGE2(HUP_LEDS, HUD_LED_CAPS_LOCK),
1149	    sc->sc_report_id, hid_output, &sc->sc_capsloc, NULL);
1150	hid_locate(desc, size, HID_USAGE2(HUP_LEDS, HUD_LED_SCROLL_LOCK),
1151	    sc->sc_report_id, hid_output, &sc->sc_scroloc, NULL);
1152	hid_locate(desc, size, HID_USAGE2(HUP_LEDS, HUD_LED_COMPOSE),
1153	    sc->sc_report_id, hid_output, &sc->sc_compose, NULL);
1154
1155	return NULL;
1156}
1157