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