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