xref: /plan9-contrib/sys/src/cmd/usb/kb/kb.c (revision b249590635b298a2b629c4458908d752eced8f6f)
1 /*
2  * USB Human Interaction Device: keyboard and mouse.
3  *
4  * If there's no usb keyboard, it tries to setup the mouse, if any.
5  * It should be started at boot time.
6  *
7  * Mouse events are converted to the format of mouse(3)'s
8  * mousein file.
9  * Keyboard keycodes are translated to scan codes and sent to kbin(3).
10  *
11  */
12 
13 #include <u.h>
14 #include <libc.h>
15 #include <thread.h>
16 #include "usb.h"
17 #include "hid.h"
18 
19 enum
20 {
21 	Awakemsg=0xdeaddead,
22 	Diemsg = 0xbeefbeef,
23 };
24 
25 typedef struct KDev KDev;
26 typedef struct Kin Kin;
27 
28 struct KDev
29 {
30 	Dev*	dev;		/* usb device*/
31 	Dev*	ep;		/* endpoint to get events */
32 	Kin*	in;		/* used to send events to kernel */
33 	Channel*repeatc;	/* only for keyboard */
34 	int	accel;		/* only for mouse */
35 };
36 
37 /*
38  * Kbdin and mousein files must be shared among all instances.
39  */
40 struct Kin
41 {
42 	int	ref;
43 	int	fd;
44 	char*	name;
45 };
46 
47 /*
48  * Map for the logitech bluetooth mouse with 8 buttons and wheels.
49  *	{ ptr ->mouse}
50  *	{ 0x01, 0x01 },	// left
51  *	{ 0x04, 0x02 },	// middle
52  *	{ 0x02, 0x04 },	// right
53  *	{ 0x40, 0x08 },	// up
54  *	{ 0x80, 0x10 },	// down
55  *	{ 0x10, 0x08 },	// side up
56  *	{ 0x08, 0x10 },	// side down
57  *	{ 0x20, 0x02 }, // page
58  * besides wheel and regular up/down report the 4th byte as 1/-1
59  */
60 
61 /*
62  * key code to scan code; for the page table used by
63  * the logitech bluetooth keyboard.
64  */
65 static char sctab[256] =
66 {
67 [0x00]	0x0,	0x0,	0x0,	0x0,	0x1e,	0x30,	0x2e,	0x20,
68 [0x08]	0x12,	0x21,	0x22,	0x23,	0x17,	0x24,	0x25,	0x26,
69 [0x10]	0x32,	0x31,	0x18,	0x19,	0x10,	0x13,	0x1f,	0x14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x0,	0x0,	0x0,	0x0,	0x0,
91 [0xc0]	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,
92 [0xc8]	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,
93 [0xd0]	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,
94 [0xd8]	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,
95 [0xe0]	0x1d,	0x2a,	0x38,	0x7d,	0x61,	0x36,	0x64,	0x7e,
96 [0xe8]	0x0,	0x0,	0x0,	0x0,	0x0,	0x73,	0x72,	0x71,
97 [0xf0]	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,
98 [0xf8]	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,	0x0,
99 };
100 
101 static QLock inlck;
102 static Kin kbdin =
103 {
104 	.ref = 0,
105 	.name = "#Ι/kbin",
106 	.fd = -1,
107 };
108 static Kin ptrin =
109 {
110 	.ref = 0,
111 	.name = "#m/mousein",
112 	.fd = -1,
113 };
114 
115 static int kbdebug;
116 
117 static void
118 kbfatal(KDev *kd, char *sts)
119 {
120 	Dev *dev;
121 
122 	if(sts != nil)
123 		fprint(2, "kb: fatal: %s\n", sts);
124 	else
125 		fprint(2, "kb: exiting\n");
126 	if(kd->repeatc != nil)
127 		nbsendul(kd->repeatc, Diemsg);
128 	dev = kd->dev;
129 	kd->dev = nil;
130 	if(kd->ep != nil)
131 		closedev(kd->ep);
132 	kd->ep = nil;
133 	devctl(dev, "detach");
134 	closedev(dev);
135 	/*
136 	 * free(kd); done by closedev.
137 	 */
138 	threadexits(sts);
139 }
140 
141 static int
142 scale(KDev *f, int x)
143 {
144 	int sign = 1;
145 
146 	if(x < 0){
147 		sign = -1;
148 		x = -x;
149 	}
150 	switch(x){
151 	case 0:
152 	case 1:
153 	case 2:
154 	case 3:
155 		break;
156 	case 4:
157 		x = 6 + (f->accel>>2);
158 		break;
159 	case 5:
160 		x = 9 + (f->accel>>1);
161 		break;
162 	default:
163 		x *= MaxAcc;
164 		break;
165 	}
166 	return sign*x;
167 }
168 
169 /*
170  * ps2 mouse is processed mostly at interrupt time.
171  * for usb we do what we can.
172  */
173 static void
174 sethipri(void)
175 {
176 	char fn[30];
177 	int fd;
178 
179 	snprint(fn, sizeof(fn), "/proc/%d/ctl", getpid());
180 	fd = open(fn, OWRITE);
181 	if(fd < 0)
182 		return;
183 	fprint(fd, "pri 13");
184 	close(fd);
185 }
186 
187 static void
188 ptrwork(void* a)
189 {
190 	static char maptab[] = {0x0, 0x1, 0x4, 0x5, 0x2, 0x3, 0x6, 0x7};
191 	int x, y, b, c, ptrfd;
192 	int	mfd;
193 	char	buf[32];
194 	char	mbuf[80];
195 	KDev*	f = a;
196 	int	hipri;
197 
198 	hipri = 0;
199 	ptrfd = f->ep->dfd;
200 	mfd = f->in->fd;
201 
202 	if(f->ep->maxpkt < 3 || f->ep->maxpkt > sizeof buf)
203 		kbfatal(f, "weird mouse maxpkt");
204 	for(;;){
205 		memset(buf, 0, sizeof buf);
206 		if(f->ep == nil)
207 			kbfatal(f, nil);
208 		c = read(ptrfd, buf, f->ep->maxpkt);
209 		assert(f->dev != nil);
210 		assert(f->ep != nil);
211 		if(c < 0)
212 			dprint(2, "kb: mouse: %s: read: %r\n", f->ep->dir);
213 		if(c <= 0)
214 			kbfatal(f, nil);
215 		if(c < 3)
216 			continue;
217 		if(f->accel){
218 			x = scale(f, buf[1]);
219 			y = scale(f, buf[2]);
220 		}else{
221 			x = buf[1];
222 			y = buf[2];
223 		}
224 		b = maptab[buf[0] & 0x7];
225 		if(c > 3 && buf[3] == 1)	/* up */
226 			b |= 0x08;
227 		if(c > 3 && buf[3] == -1)	/* down */
228 			b |= 0x10;
229 		if(kbdebug)
230 			fprint(2, "kb: m%11d %11d %11d\n", x, y, b);
231 		seprint(mbuf, mbuf+sizeof(mbuf), "m%11d %11d %11d", x, y,b);
232 		if(write(mfd, mbuf, strlen(mbuf)) < 0)
233 			kbfatal(f, "mousein i/o");
234 		if(hipri == 0){
235 			sethipri();
236 			hipri = 1;
237 		}
238 	}
239 }
240 
241 static void
242 stoprepeat(KDev *f)
243 {
244 	sendul(f->repeatc, Awakemsg);
245 }
246 
247 static void
248 startrepeat(KDev *f, uchar esc1, uchar sc)
249 {
250 	ulong c;
251 
252 	if(esc1)
253 		c = SCesc1 << 8 | (sc & 0xff);
254 	else
255 		c = sc;
256 	sendul(f->repeatc, c);
257 }
258 
259 static void
260 putscan(int kbinfd, uchar esc, uchar sc)
261 {
262 	uchar s[2] = {SCesc1, 0};
263 
264 	if(sc == 0x41){
265 		kbdebug++;
266 		return;
267 	}
268 	if(sc == 0x42){
269 		kbdebug = 0;
270 		return;
271 	}
272 	if(kbdebug)
273 		fprint(2, "sc: %x %x\n", (esc? SCesc1: 0), sc);
274 	s[1] = sc;
275 	if(esc && sc != 0)
276 		write(kbinfd, s, 2);
277 	else if(sc != 0)
278 		write(kbinfd, s+1, 1);
279 }
280 
281 static void
282 repeatproc(void* a)
283 {
284 	KDev *f;
285 	Channel *repeatc;
286 	int kbdinfd;
287 	ulong l, t, i;
288 	uchar esc1, sc;
289 
290 	/*
291 	 * too many jumps here.
292 	 * Rewrite instead of debug, if needed.
293 	 */
294 	f = a;
295 	repeatc = f->repeatc;
296 	kbdinfd = f->in->fd;
297 	l = Awakemsg;
298 Repeat:
299 	if(l == Diemsg)
300 		goto Abort;
301 	while(l == Awakemsg)
302 		l = recvul(repeatc);
303 	if(l == Diemsg)
304 		goto Abort;
305 	esc1 = l >> 8;
306 	sc = l;
307 	t = 160;
308 	for(;;){
309 		for(i = 0; i < t; i += 5){
310 			if(l = nbrecvul(repeatc))
311 				goto Repeat;
312 			sleep(5);
313 		}
314 		putscan(kbdinfd, esc1, sc);
315 		t = 30;
316 	}
317 Abort:
318 	chanfree(repeatc);
319 	threadexits("aborted");
320 
321 }
322 
323 
324 #define hasesc1(sc)	(((sc) > 0x47) || ((sc) == 0x38))
325 
326 static void
327 putmod(int fd, uchar mods, uchar omods, uchar mask, uchar esc, uchar sc)
328 {
329 	/* BUG: Should be a single write */
330 	if((mods&mask) && !(omods&mask))
331 		putscan(fd, esc, sc);
332 	if(!(mods&mask) && (omods&mask))
333 		putscan(fd, esc, Keyup|sc);
334 }
335 
336 /*
337  * This routine diffs the state with the last known state
338  * and invents the scan codes that would have been sent
339  * by a non-usb keyboard in that case. This also requires supplying
340  * the extra esc1 byte as well as keyup flags.
341  * The aim is to allow future addition of other keycode pages
342  * for other keyboards.
343  */
344 static uchar
345 putkeys(KDev *f, uchar buf[], uchar obuf[], int n, uchar dk)
346 {
347 	int i, j;
348 	uchar uk;
349 	int fd;
350 
351 	fd = f->in->fd;
352 	putmod(fd, buf[0], obuf[0], Mctrl, 0, SCctrl);
353 	putmod(fd, buf[0], obuf[0], (1<<Mlshift), 0, SClshift);
354 	putmod(fd, buf[0], obuf[0], (1<<Mrshift), 0, SCrshift);
355 	putmod(fd, buf[0], obuf[0], Mcompose, 0, SCcompose);
356 	putmod(fd, buf[0], obuf[0], Maltgr, 1, SCcompose);
357 
358 	/* Report key downs */
359 	for(i = 2; i < n; i++){
360 		for(j = 2; j < n; j++)
361 			if(buf[i] == obuf[j])
362 			 	break;
363 		if(j == n && buf[i] != 0){
364 			dk = sctab[buf[i]];
365 			putscan(fd, hasesc1(dk), dk);
366 			startrepeat(f, hasesc1(dk), dk);
367 		}
368 	}
369 
370 	/* Report key ups */
371 	uk = 0;
372 	for(i = 2; i < n; i++){
373 		for(j = 2; j < n; j++)
374 			if(obuf[i] == buf[j])
375 				break;
376 		if(j == n && obuf[i] != 0){
377 			uk = sctab[obuf[i]];
378 			putscan(fd, hasesc1(uk), uk|Keyup);
379 		}
380 	}
381 	if(uk && (dk == 0 || dk == uk)){
382 		stoprepeat(f);
383 		dk = 0;
384 	}
385 	return dk;
386 }
387 
388 static int
389 kbdbusy(uchar* buf, int n)
390 {
391 	int i;
392 
393 	for(i = 1; i < n; i++)
394 		if(buf[i] == 0 || buf[i] != buf[0])
395 			return 0;
396 	return 1;
397 }
398 
399 static int
400 setbootproto(KDev* f, int eid)
401 {
402 	int r, id;
403 
404 	r = Rh2d|Rclass|Riface;
405 	id = f->dev->usb->ep[eid]->iface->id;
406 	return usbcmd(f->dev, r, Setproto, Bootproto, id, nil, 0);
407 }
408 
409 /*
410  * Try to recover from a babble error. A port reset is the only way out.
411  * BUG: we should be careful not to reset a bundle with several devices.
412  */
413 static void
414 recoverkb(KDev *f)
415 {
416 	int i;
417 
418 	close(f->dev->dfd);		/* it's for usbd now */
419 	devctl(f->dev, "reset");
420 	for(i = 0; i < 10; i++){
421 		sleep(500);
422 		if(opendevdata(f->dev, ORDWR) >= 0){
423 			setbootproto(f, f->ep->id);
424 			break;
425 		}
426 		/* else usbd still working... */
427 	}
428 }
429 
430 static void
431 kbdwork(void *a)
432 {
433 	int c, i, kbdfd, nerrs;
434 	uchar dk, buf[64], lbuf[64];
435 	char err[128];
436 	KDev *f = a;
437 
438 	kbdfd = f->ep->dfd;
439 
440 	if(f->ep->maxpkt < 3 || f->ep->maxpkt > sizeof buf)
441 		kbfatal(f, "weird maxpkt");
442 
443 	f->repeatc = chancreate(sizeof(ulong), 0);
444 	if(f->repeatc == nil)
445 		kbfatal(f, "chancreate failed");
446 
447 	proccreate(repeatproc, f, Stack);
448 	memset(lbuf, 0, sizeof lbuf);
449 	dk = nerrs = 0;
450 	for(;;){
451 		memset(buf, 0, sizeof buf);
452 		c = read(kbdfd, buf, f->ep->maxpkt);
453 		assert(f->dev != nil);
454 		assert(f->ep != nil);
455 		if(c < 0){
456 			rerrstr(err, sizeof(err));
457 			dprint(2, "kb: %s: read: %s\n", f->ep->dir, err);
458 			if(strstr(err, "babble") != 0 && ++nerrs < 3){
459 				recoverkb(f);
460 				continue;
461 			}
462 		}
463 		if(c <= 0)
464 			kbfatal(f, nil);
465 		if(c < 3)
466 			continue;
467 		if(kbdbusy(buf + 2, c - 2))
468 			continue;
469 		if(usbdebug > 1 || kbdebug > 1){
470 			fprint(2, "kbd mod %x: ", buf[0]);
471 			for(i = 2; i < c; i++)
472 				fprint(2, "kc %x ", buf[i]);
473 			fprint(2, "\n");
474 		}
475 		dk = putkeys(f, buf, lbuf, f->ep->maxpkt, dk);
476 		memmove(lbuf, buf, c);
477 		nerrs = 0;
478 	}
479 }
480 
481 static void
482 freekdev(void *a)
483 {
484 	KDev *kd;
485 
486 	kd = a;
487 	if(kd->in != nil){
488 		qlock(&inlck);
489 		if(--kd->in->ref == 0){
490 			close(kd->in->fd);
491 			kd->in->fd = -1;
492 		}
493 		qunlock(&inlck);
494 	}
495 	dprint(2, "freekdev\n");
496 	free(kd);
497 }
498 
499 static void
500 kbstart(Dev *d, Ep *ep, Kin *in, void (*f)(void*), int accel)
501 {
502 	KDev *kd;
503 
504 	qlock(&inlck);
505 	if(in->fd < 0){
506 		in->fd = open(in->name, OWRITE);
507 		if(in->fd < 0){
508 			fprint(2, "kb: %s: %r\n", in->name);
509 			qunlock(&inlck);
510 			return;
511 		}
512 	}
513 	in->ref++;	/* for kd->in = in */
514 	qunlock(&inlck);
515 	kd = d->aux = emallocz(sizeof(KDev), 1);
516 	d->free = freekdev;
517 	kd->in = in;
518 	kd->dev = d;
519 	if(setbootproto(kd, ep->id) < 0){
520 		fprint(2, "kb: %s: bootproto: %r\n", d->dir);
521 		return;
522 	}
523 	kd->accel = accel;
524 	kd->ep = openep(d, ep->id);
525 	if(kd->ep == nil){
526 		fprint(2, "kb: %s: openep %d: %r\n", d->dir, ep->id);
527 		return;
528 	}
529 	if(opendevdata(kd->ep, OREAD) < 0){
530 		fprint(2, "kb: %s: opendevdata: %r\n", kd->ep->dir);
531 		closedev(kd->ep);
532 		kd->ep = nil;
533 		return;
534 	}
535 
536 	incref(d);
537 	proccreate(f, kd, Stack);
538 }
539 
540 static int
541 usage(void)
542 {
543 	werrstr("usage: usb/kb [-dkmn] [-a n]");
544 	return -1;
545 }
546 
547 int
548 kbmain(Dev *d, int argc, char* argv[])
549 {
550 	int i;
551 	int kena;
552 	int pena;
553 	int accel;
554 	char *as;
555 	Usbdev *ud;
556 	Ep *ep;
557 
558 	kena = pena = 1;
559 	accel = 0;
560 	ARGBEGIN{
561 	case 'a':
562 		as = ARGF();
563 		if(as == nil)
564 			return usage();
565 		accel = strtol(as, nil, 0);
566 		break;
567 	case 'd':
568 		kbdebug++;
569 		break;
570 	case 'k':
571 		kena = 1;
572 		pena = 0;
573 		break;
574 	case 'm':
575 		kena = 0;
576 		pena = 1;
577 		break;
578 	default:
579 		return usage();
580 	}ARGEND;
581 	if(argc != 0){
582 		return usage();
583 	}
584 	ud = d->usb;
585 	d->aux = nil;
586 	dprint(2, "kb: main: dev %s ref %ld\n", d->dir, d->ref);
587 	for(i = 0; i < nelem(ud->ep); i++){
588 		if((ep = ud->ep[i]) == nil)
589 			break;
590 		if(kena && ep->type == Eintr && ep->dir == Ein)
591 		if(ep->iface->csp == KbdCSP)
592 			kbstart(d, ep, &kbdin, kbdwork, accel);
593 		if(pena && ep->type == Eintr && ep->dir == Ein)
594 		if(ep->iface->csp == PtrCSP)
595 			kbstart(d, ep, &ptrin, ptrwork, accel);
596 	}
597 	closedev(d);
598 	return 0;
599 }
600