xref: /plan9/sys/src/9/omap/devusb.c (revision 3468a4915d661daa200976acc4f80f51aae144b2)
1 /*
2  * USB device driver.
3  *
4  * This is in charge of providing access to actual HCIs
5  * and providing I/O to the various endpoints of devices.
6  * A separate user program (usbd) is in charge of
7  * enumerating the bus, setting up endpoints and
8  * starting devices (also user programs).
9  *
10  * The interface provided is a violation of the standard:
11  * you're welcome.
12  *
13  * The interface consists of a root directory with several files
14  * plus a directory (epN.M) with two files per endpoint.
15  * A device is represented by its first endpoint, which
16  * is a control endpoint automatically allocated for each device.
17  * Device control endpoints may be used to create new endpoints.
18  * Devices corresponding to hubs may also allocate new devices,
19  * perhaps also hubs. Initially, a hub device is allocated for
20  * each controller present, to represent its root hub. Those can
21  * never be removed.
22  *
23  * All endpoints refer to the first endpoint (epN.0) of the device,
24  * which keeps per-device information, and also to the HCI used
25  * to reach them. Although all endpoints cache that information.
26  *
27  * epN.M/data files permit I/O and are considered DMEXCL.
28  * epN.M/ctl files provide status info and accept control requests.
29  *
30  * Endpoints may be given file names to be listed also at #u,
31  * for those drivers that have nothing to do after configuring the
32  * device and its endpoints.
33  *
34  * Drivers for different controllers are kept at usb[oue]hci.c
35  * It's likely we could factor out much from controllers into
36  * a generic controller driver, the problem is that details
37  * regarding how to handle toggles, tokens, Tds, etc. will
38  * get in the way. Thus, code is probably easier the way it is.
39  *
40  */
41 
42 #include	"u.h"
43 #include	"../port/lib.h"
44 #include	"mem.h"
45 #include	"dat.h"
46 #include	"fns.h"
47 #include	"io.h"
48 #include	"../port/error.h"
49 #include	"usb.h"
50 
51 typedef struct Hcitype Hcitype;
52 
53 enum
54 {
55 	/* Qid numbers */
56 	Qdir = 0,		/* #u */
57 	Qusbdir,			/* #u/usb */
58 	Qctl,			/* #u/usb/ctl - control requests */
59 
60 	Qep0dir,			/* #u/usb/ep0.0 - endpoint 0 dir */
61 	Qep0io,			/* #u/usb/ep0.0/data - endpoint 0 I/O */
62 	Qep0ctl,		/* #u/usb/ep0.0/ctl - endpoint 0 ctl. */
63 	Qep0dummy,		/* give 4 qids to each endpoint */
64 
65 	Qepdir = 0,		/* (qid-qep0dir)&3 is one of these */
66 	Qepio,			/* to identify which file for the endpoint */
67 	Qepctl,
68 
69 	/* ... */
70 
71 	/* Usb ctls. */
72 	CMdebug = 0,		/* debug on|off */
73 	CMdump,			/* dump (data structures for debug) */
74 
75 	/* Ep. ctls */
76 	CMnew = 0,		/* new nb ctl|bulk|intr|iso r|w|rw (endpoint) */
77 	CMnewdev,		/* newdev full|low|high portnb (allocate new devices) */
78 	CMhub,			/* hub (set the device as a hub) */
79 	CMspeed,		/* speed full|low|high|no */
80 	CMmaxpkt,		/* maxpkt size */
81 	CMntds,			/* ntds nb (max nb. of tds per µframe) */
82 	CMclrhalt,		/* clrhalt (halt was cleared on endpoint) */
83 	CMpollival,		/* pollival interval (interrupt/iso) */
84 	CMhz,			/* hz n (samples/sec; iso) */
85 	CMsamplesz,		/* samplesz n (sample size; iso) */
86 	CMinfo,			/* info infostr (ke.ep info for humans) */
87 	CMdetach,		/* detach (abort I/O forever on this ep). */
88 	CMaddress,		/* address (address is assigned) */
89 	CMdebugep,		/* debug n (set/clear debug for this ep) */
90 	CMname,			/* name str (show up as #u/name as well) */
91 	CMtmout,		/* timeout n (activate timeouts for ep) */
92 	CMpreset,		/* reset the port */
93 
94 	/* Hub feature selectors */
95 	Rportenable	= 1,
96 	Rportreset	= 4,
97 
98 };
99 
100 struct Hcitype
101 {
102 	char*	type;
103 	int	(*reset)(Hci*);
104 };
105 
106 #define QID(q)	((int)(q).path)
107 
108 static char Edetach[] = "device is detached";
109 static char Enotconf[] = "endpoint not configured";
110 char Estalled[] = "endpoint stalled";
111 
112 static Cmdtab usbctls[] =
113 {
114 	{CMdebug,	"debug",	2},
115 	{CMdump,	"dump",		1},
116 };
117 
118 static Cmdtab epctls[] =
119 {
120 	{CMnew,		"new",		4},
121 	{CMnewdev,	"newdev",	3},
122 	{CMhub,		"hub",		1},
123 	{CMspeed,	"speed",	2},
124 	{CMmaxpkt,	"maxpkt",	2},
125 	{CMntds,	"ntds",		2},
126 	{CMpollival,	"pollival",	2},
127 	{CMsamplesz,	"samplesz",	2},
128 	{CMhz,		"hz",		2},
129 	{CMinfo,		"info",		0},
130 	{CMdetach,	"detach",	1},
131 	{CMaddress,	"address",	1},
132 	{CMdebugep,	"debug",	2},
133 	{CMclrhalt,	"clrhalt",	1},
134 	{CMname,	"name",		2},
135 	{CMtmout,	"timeout",	2},
136 	{CMpreset,	"reset",	1},
137 };
138 
139 static Dirtab usbdir[] =
140 {
141 	"ctl",		{Qctl},		0,	0666,
142 };
143 
144 char *usbmodename[] =
145 {
146 	[OREAD]	"r",
147 	[OWRITE]	"w",
148 	[ORDWR]	"rw",
149 };
150 
151 static char *ttname[] =
152 {
153 	[Tnone]	"none",
154 	[Tctl]	"control",
155 	[Tiso]	"iso",
156 	[Tintr]	"interrupt",
157 	[Tbulk]	"bulk",
158 };
159 
160 static char *spname[] =
161 {
162 	[Fullspeed]	"full",
163 	[Lowspeed]	"low",
164 	[Highspeed]	"high",
165 	[Nospeed]	"no",
166 };
167 
168 static int	debug = 0;
169 static Hcitype	hcitypes[Nhcis];
170 static Hci*	hcis[Nhcis];
171 static QLock	epslck;		/* add, del, lookup endpoints */
172 static Ep*	eps[Neps];	/* all endpoints known */
173 static int	epmax;		/* 1 + last endpoint index used  */
174 static int	usbidgen;	/* device address generator */
175 
176 /*
177  * Is there something like this in a library? should it be?
178  */
179 char*
180 seprintdata(char *s, char *se, uchar *d, int n)
181 {
182 	int i, l;
183 
184 	s = seprint(s, se, " %#p[%d]: ", d, n);
185 	l = n;
186 	if(l > 10)
187 		l = 10;
188 	for(i=0; i<l; i++)
189 		s = seprint(s, se, " %2.2ux", d[i]);
190 	if(l < n)
191 		s = seprint(s, se, "...");
192 	return s;
193 }
194 
195 static int
196 name2speed(char *name)
197 {
198 	int i;
199 
200 	for(i = 0; i < nelem(spname); i++)
201 		if(strcmp(name, spname[i]) == 0)
202 			return i;
203 	return Nospeed;
204 }
205 
206 static int
207 name2ttype(char *name)
208 {
209 	int i;
210 
211 	for(i = 0; i < nelem(ttname); i++)
212 		if(strcmp(name, ttname[i]) == 0)
213 			return i;
214 	/* may be a std. USB ep. type */
215 	i = strtol(name, nil, 0);
216 	switch(i+1){
217 	case Tctl:
218 	case Tiso:
219 	case Tbulk:
220 	case Tintr:
221 		return i+1;
222 	default:
223 		return Tnone;
224 	}
225 }
226 
227 static int
228 name2mode(char *mode)
229 {
230 	int i;
231 
232 	for(i = 0; i < nelem(usbmodename); i++)
233 		if(strcmp(mode, usbmodename[i]) == 0)
234 			return i;
235 	return -1;
236 }
237 
238 static int
239 qid2epidx(int q)
240 {
241 	q = (q-Qep0dir)/4;
242 	if(q < 0 || q >= epmax || eps[q] == nil)
243 		return -1;
244 	return q;
245 }
246 
247 static int
248 isqtype(int q, int type)
249 {
250 	if(q < Qep0dir)
251 		return 0;
252 	q -= Qep0dir;
253 	return (q & 3) == type;
254 }
255 
256 void
257 addhcitype(char* t, int (*r)(Hci*))
258 {
259 	static int ntype;
260 
261 	if(ntype == Nhcis)
262 		panic("too many USB host interface types");
263 	hcitypes[ntype].type = t;
264 	hcitypes[ntype].reset = r;
265 	ntype++;
266 }
267 
268 static char*
269 seprintep(char *s, char *se, Ep *ep, int all)
270 {
271 	static char* dsnames[] = { "config", "enabled", "detached", "reset" };
272 	Udev *d;
273 	int i;
274 	int di;
275 
276 	d = ep->dev;
277 
278 	qlock(ep);
279 	if(waserror()){
280 		qunlock(ep);
281 		nexterror();
282 	}
283 	di = ep->dev->nb;
284 	if(all)
285 		s = seprint(s, se, "dev %d ep %d ", di, ep->nb);
286 	s = seprint(s, se, "%s", dsnames[ep->dev->state]);
287 	s = seprint(s, se, " %s", ttname[ep->ttype]);
288 	assert(ep->mode == OREAD || ep->mode == OWRITE || ep->mode == ORDWR);
289 	s = seprint(s, se, " %s", usbmodename[ep->mode]);
290 	s = seprint(s, se, " speed %s", spname[d->speed]);
291 	s = seprint(s, se, " maxpkt %ld", ep->maxpkt);
292 	s = seprint(s, se, " pollival %ld", ep->pollival);
293 	s = seprint(s, se, " samplesz %ld", ep->samplesz);
294 	s = seprint(s, se, " hz %ld", ep->hz);
295 	s = seprint(s, se, " hub %d", ep->dev->hub);
296 	s = seprint(s, se, " port %d", ep->dev->port);
297 	if(ep->inuse)
298 		s = seprint(s, se, " busy");
299 	else
300 		s = seprint(s, se, " idle");
301 	if(all){
302 		s = seprint(s, se, " load %uld", ep->load);
303 		s = seprint(s, se, " ref %ld addr %#p", ep->ref, ep);
304 		s = seprint(s, se, " idx %d", ep->idx);
305 		if(ep->name != nil)
306 			s = seprint(s, se, " name '%s'", ep->name);
307 		if(ep->tmout != 0)
308 			s = seprint(s, se, " tmout");
309 		if(ep == ep->ep0){
310 			s = seprint(s, se, " ctlrno %#x", ep->hp->ctlrno);
311 			s = seprint(s, se, " eps:");
312 			for(i = 0; i < nelem(d->eps); i++)
313 				if(d->eps[i] != nil)
314 					s = seprint(s, se, " ep%d.%d", di, i);
315 		}
316 	}
317 	if(ep->info != nil)
318 		s = seprint(s, se, "\n%s %s\n", ep->info, ep->hp->type);
319 	else
320 		s = seprint(s, se, "\n");
321 	qunlock(ep);
322 	poperror();
323 	return s;
324 }
325 
326 static Ep*
327 epalloc(Hci *hp)
328 {
329 	Ep *ep;
330 	int i;
331 
332 	ep = mallocz(sizeof(Ep), 1);
333 	ep->ref = 1;
334 	qlock(&epslck);
335 	for(i = 0; i < Neps; i++)
336 		if(eps[i] == nil)
337 			break;
338 	if(i == Neps){
339 		qunlock(&epslck);
340 		free(ep);
341 		print("usb: bug: too few endpoints.\n");
342 		return nil;
343 	}
344 	ep->idx = i;
345 	if(epmax <= i)
346 		epmax = i+1;
347 	eps[i] = ep;
348 	ep->hp = hp;
349 	ep->maxpkt = 8;
350 	ep->ntds = 1;
351 	ep->samplesz = ep->pollival = ep->hz = 0; /* make them void */
352 	qunlock(&epslck);
353 	return ep;
354 }
355 
356 static Ep*
357 getep(int i)
358 {
359 	Ep *ep;
360 
361 	if(i < 0 || i >= epmax || eps[i] == nil)
362 		return nil;
363 	qlock(&epslck);
364 	ep = eps[i];
365 	if(ep != nil)
366 		incref(ep);
367 	qunlock(&epslck);
368 	return ep;
369 }
370 
371 static void
372 putep(Ep *ep)
373 {
374 	Udev *d;
375 
376 	if(ep != nil && decref(ep) == 0){
377 		d = ep->dev;
378 		deprint("usb: ep%d.%d %#p released\n", d->nb, ep->nb, ep);
379 		qlock(&epslck);
380 		eps[ep->idx] = nil;
381 		if(ep->idx == epmax-1)
382 			epmax--;
383 		if(ep == ep->ep0 && ep->dev != nil && ep->dev->nb == usbidgen)
384 			usbidgen--;
385 		qunlock(&epslck);
386 		if(d != nil){
387 			qlock(ep->ep0);
388 			d->eps[ep->nb] = nil;
389 			qunlock(ep->ep0);
390 		}
391 		if(ep->ep0 != ep){
392 			putep(ep->ep0);
393 			ep->ep0 = nil;
394 		}
395 		free(ep->info);
396 		free(ep->name);
397 		free(ep);
398 	}
399 }
400 
401 static void
402 dumpeps(void)
403 {
404 	int i;
405 	static char buf[512];
406 	char *s;
407 	char *e;
408 	Ep *ep;
409 
410 	print("usb dump eps: epmax %d Neps %d (ref=1+ for dump):\n", epmax, Neps);
411 	for(i = 0; i < epmax; i++){
412 		s = buf;
413 		e = buf+sizeof(buf);
414 		ep = getep(i);
415 		if(ep != nil){
416 			if(waserror()){
417 				putep(ep);
418 				nexterror();
419 			}
420 			s = seprint(s, e, "ep%d.%d ", ep->dev->nb, ep->nb);
421 			seprintep(s, e, ep, 1);
422 			print("%s", buf);
423 			ep->hp->seprintep(buf, e, ep);
424 			print("%s", buf);
425 			poperror();
426 			putep(ep);
427 		}
428 	}
429 	print("usb dump hcis:\n");
430 	for(i = 0; i < Nhcis; i++)
431 		if(hcis[i] != nil)
432 			hcis[i]->dump(hcis[i]);
433 }
434 
435 static int
436 newusbid(Hci *)
437 {
438 	int id;
439 
440 	qlock(&epslck);
441 	id = ++usbidgen;
442 	if(id >= 0x7F)
443 		print("#u: too many device addresses; reuse them more\n");
444 	qunlock(&epslck);
445 	return id;
446 }
447 
448 /*
449  * Create endpoint 0 for a new device
450  */
451 static Ep*
452 newdev(Hci *hp, int ishub, int isroot)
453 {
454 	Ep *ep;
455 	Udev *d;
456 
457 	ep = epalloc(hp);
458 	d = ep->dev = mallocz(sizeof(Udev), 1);
459 	d->nb = newusbid(hp);
460 	d->eps[0] = ep;
461 	ep->nb = 0;
462 	ep->toggle[0] = ep->toggle[1] = 0;
463 	d->ishub = ishub;
464 	d->isroot = isroot;
465 	if(hp->highspeed != 0)
466 		d->speed = Highspeed;
467 	else
468 		d->speed = Fullspeed;
469 	d->state = Dconfig;		/* address not yet set */
470 	ep->dev = d;
471 	ep->ep0 = ep;			/* no ref counted here */
472 	ep->ttype = Tctl;
473 	ep->tmout = Xfertmout;
474 	ep->mode = ORDWR;
475 	dprint("newdev %#p ep%d.%d %#p\n", d, d->nb, ep->nb, ep);
476 	return ep;
477 }
478 
479 /*
480  * Create a new endpoint for the device
481  * accessed via the given endpoint 0.
482  */
483 static Ep*
484 newdevep(Ep *ep, int i, int tt, int mode)
485 {
486 	Ep *nep;
487 	Udev *d;
488 
489 	d = ep->dev;
490 	if(d->eps[i] != nil)
491 		error("endpoint already in use");
492 	nep = epalloc(ep->hp);
493 	incref(ep);
494 	d->eps[i] = nep;
495 	nep->nb = i;
496 	nep->toggle[0] = nep->toggle[1] = 0;
497 	nep->ep0 = ep;
498 	nep->dev = ep->dev;
499 	nep->mode = mode;
500 	nep->ttype = tt;
501 	nep->debug = ep->debug;
502 	/* set defaults */
503 	switch(tt){
504 	case Tctl:
505 		nep->tmout = Xfertmout;
506 		break;
507 	case Tintr:
508 		nep->pollival = 10;
509 		break;
510 	case Tiso:
511 		nep->tmout = Xfertmout;
512 		nep->pollival = 10;
513 		nep->samplesz = 4;
514 		nep->hz = 44100;
515 		break;
516 	}
517 	deprint("newdevep ep%d.%d %#p\n", d->nb, nep->nb, nep);
518 	return ep;
519 }
520 
521 static int
522 epdataperm(int mode)
523 {
524 
525 	switch(mode){
526 	case OREAD:
527 		return 0440|DMEXCL;
528 		break;
529 	case OWRITE:
530 		return 0220|DMEXCL;
531 		break;
532 	default:
533 		return 0660|DMEXCL;
534 	}
535 }
536 
537 static int
538 usbgen(Chan *c, char *, Dirtab*, int, int s, Dir *dp)
539 {
540 	Qid q;
541 	Dirtab *dir;
542 	int perm;
543 	char *se;
544 	Ep *ep;
545 	int nb;
546 	int mode;
547 
548 	if(0)ddprint("usbgen q %#x s %d...", QID(c->qid), s);
549 	if(s == DEVDOTDOT){
550 		if(QID(c->qid) <= Qusbdir){
551 			mkqid(&q, Qdir, 0, QTDIR);
552 			devdir(c, q, "#u", 0, eve, 0555, dp);
553 		}else{
554 			mkqid(&q, Qusbdir, 0, QTDIR);
555 			devdir(c, q, "usb", 0, eve, 0555, dp);
556 		}
557 		if(0)ddprint("ok\n");
558 		return 1;
559 	}
560 
561 	switch(QID(c->qid)){
562 	case Qdir:				/* list #u */
563 		if(s == 0){
564 			mkqid(&q, Qusbdir, 0, QTDIR);
565 			devdir(c, q, "usb", 0, eve, 0555, dp);
566 			if(0)ddprint("ok\n");
567 			return 1;
568 		}
569 		s--;
570 		if(s < 0 || s >= epmax)
571 			goto Fail;
572 		ep = getep(s);
573 		if(ep == nil || ep->name == nil){
574 			if(ep != nil)
575 				putep(ep);
576 			if(0)ddprint("skip\n");
577 			return 0;
578 		}
579 		if(waserror()){
580 			putep(ep);
581 			nexterror();
582 		}
583 		mkqid(&q, Qep0io+s*4, 0, QTFILE);
584 		devdir(c, q, ep->name, 0, eve, epdataperm(ep->mode), dp);
585 		putep(ep);
586 		poperror();
587 		if(0)ddprint("ok\n");
588 		return 1;
589 
590 	case Qusbdir:				/* list #u/usb */
591 	Usbdir:
592 		if(s < nelem(usbdir)){
593 			dir = &usbdir[s];
594 			mkqid(&q, dir->qid.path, 0, QTFILE);
595 			devdir(c, q, dir->name, dir->length, eve, dir->perm, dp);
596 			if(0)ddprint("ok\n");
597 			return 1;
598 		}
599 		s -= nelem(usbdir);
600 		if(s < 0 || s >= epmax)
601 			goto Fail;
602 		ep = getep(s);
603 		if(ep == nil){
604 			if(0)ddprint("skip\n");
605 			return 0;
606 		}
607 		if(waserror()){
608 			putep(ep);
609 			nexterror();
610 		}
611 		se = up->genbuf+sizeof(up->genbuf);
612 		seprint(up->genbuf, se, "ep%d.%d", ep->dev->nb, ep->nb);
613 		mkqid(&q, Qep0dir+4*s, 0, QTDIR);
614 		putep(ep);
615 		poperror();
616 		devdir(c, q, up->genbuf, 0, eve, 0755, dp);
617 		if(0)ddprint("ok\n");
618 		return 1;
619 
620 	case Qctl:
621 		s = 0;
622 		goto Usbdir;
623 
624 	default:				/* list #u/usb/epN.M */
625 		nb = qid2epidx(QID(c->qid));
626 		ep = getep(nb);
627 		if(ep == nil)
628 			goto Fail;
629 		mode = ep->mode;
630 		putep(ep);
631 		if(isqtype(QID(c->qid), Qepdir)){
632 		Epdir:
633 			switch(s){
634 			case 0:
635 				mkqid(&q, Qep0io+nb*4, 0, QTFILE);
636 				perm = epdataperm(mode);
637 				devdir(c, q, "data", 0, eve, perm, dp);
638 				break;
639 			case 1:
640 				mkqid(&q, Qep0ctl+nb*4, 0, QTFILE);
641 				devdir(c, q, "ctl", 0, eve, 0664, dp);
642 				break;
643 			default:
644 				goto Fail;
645 			}
646 		}else if(isqtype(QID(c->qid), Qepctl)){
647 			s = 1;
648 			goto Epdir;
649 		}else{
650 			s = 0;
651 			goto Epdir;
652 		}
653 		if(0)ddprint("ok\n");
654 		return 1;
655 	}
656 Fail:
657 	if(0)ddprint("fail\n");
658 	return -1;
659 }
660 
661 static Hci*
662 hciprobe(int cardno, int ctlrno)
663 {
664 	Hci *hp;
665 	char *type;
666 	char name[64];
667 	static int epnb = 1;	/* guess the endpoint nb. for the controller */
668 
669 	ddprint("hciprobe %d %d\n", cardno, ctlrno);
670 	hp = mallocz(sizeof(Hci), 1);
671 	hp->ctlrno = ctlrno;
672 
673 	if(cardno < 0){
674 		for(cardno = 0; cardno < Nhcis; cardno++){
675 			if(hcitypes[cardno].type == nil)
676 				break;
677 			type = hp->type;
678 			if(type==nil || *type==0)
679 				type = "uhci";
680 			if(cistrcmp(hcitypes[cardno].type, type) == 0)
681 				break;
682 		}
683 	}
684 
685 	if(cardno >= Nhcis || hcitypes[cardno].type == nil){
686 		free(hp);
687 		return nil;
688 	}
689 	dprint("%s...", hcitypes[cardno].type);
690 	if(hcitypes[cardno].reset(hp) < 0){
691 		free(hp);
692 		return nil;
693 	}
694 
695 	snprint(name, sizeof(name), "usb%s", hcitypes[cardno].type);
696 	intrenable(hp->irq, hp->interrupt, hp, UNKNOWN, name);
697 
698 	print("#u/usb/ep%d.0: %s: port %#luX irq %d\n",
699 		epnb, hcitypes[cardno].type, hp->port, hp->irq);
700 	epnb++;
701 
702 	return hp;
703 }
704 
705 static void
706 usbreset(void)
707 {
708 	int cardno, ctlrno;
709 	Hci *hp;
710 
711 	dprint("usbreset\n");
712 
713 	for(ctlrno = 0; ctlrno < Nhcis; ctlrno++)
714 		if((hp = hciprobe(-1, ctlrno)) != nil)
715 			hcis[ctlrno] = hp;
716 	cardno = ctlrno = 0;
717 	while(cardno < Nhcis && ctlrno < Nhcis && hcitypes[cardno].type != nil)
718 		if(hcis[ctlrno] != nil)
719 			ctlrno++;
720 		else{
721 			hp = hciprobe(cardno, ctlrno);
722 			if(hp == nil)
723 				cardno++;
724 			hcis[ctlrno++] = hp;
725 		}
726 	if(hcis[Nhcis-1] != nil)
727 		print("usbreset: bug: Nhcis too small\n");
728 }
729 
730 static void
731 usbinit(void)
732 {
733 	Hci *hp;
734 	int ctlrno;
735 	Ep *d;
736 	char info[40];
737 
738 	dprint("usbinit\n");
739 	for(ctlrno = 0; ctlrno < Nhcis; ctlrno++){
740 		hp = hcis[ctlrno];
741 		if(hp != nil){
742 			if(hp->init != nil)
743 				hp->init(hp);
744 			d = newdev(hp, 1, 1);		/* new root hub */
745 			d->dev->state = Denabled;	/* although addr == 0 */
746 			d->maxpkt = 64;
747 			snprint(info, sizeof(info), "ports %d", hp->nports);
748 			kstrdup(&d->info, info);
749 		}
750 	}
751 }
752 
753 static Chan*
754 usbattach(char *spec)
755 {
756 	return devattach(L'u', spec);
757 }
758 
759 static Walkqid*
760 usbwalk(Chan *c, Chan *nc, char **name, int nname)
761 {
762 	return devwalk(c, nc, name, nname, nil, 0, usbgen);
763 }
764 
765 static int
766 usbstat(Chan *c, uchar *db, int n)
767 {
768 	return devstat(c, db, n, nil, 0, usbgen);
769 }
770 
771 /*
772  * µs for the given transfer, for bandwidth allocation.
773  * This is a very rough worst case for what 5.11.3
774  * of the usb 2.0 spec says.
775  * Also, we are using maxpkt and not actual transfer sizes.
776  * Only when we are sure we
777  * are not exceeding b/w might we consider adjusting it.
778  */
779 static ulong
780 usbload(int speed, int maxpkt)
781 {
782 	enum{ Hostns = 1000, Hubns = 333 };
783 	ulong l;
784 	ulong bs;
785 
786 	l = 0;
787 	bs = 10UL * maxpkt;
788 	switch(speed){
789 	case Highspeed:
790 		l = 55*8*2 + 2 * (3 + bs) + Hostns;
791 		break;
792 	case Fullspeed:
793 		l = 9107 + 84 * (4 + bs) + Hostns;
794 		break;
795 	case Lowspeed:
796 		l = 64107 + 2 * Hubns + 667 * (3 + bs) + Hostns;
797 		break;
798 	default:
799 		print("usbload: bad speed %d\n", speed);
800 		/* let it run */
801 	}
802 	return l / 1000UL;	/* in µs */
803 }
804 
805 static Chan*
806 usbopen(Chan *c, int omode)
807 {
808 	int q;
809 	Ep *ep;
810 	int mode;
811 
812 	mode = openmode(omode);
813 	q = QID(c->qid);
814 
815 	if(q >= Qep0dir && qid2epidx(q) < 0)
816 		error(Eio);
817 	if(q < Qep0dir || isqtype(q, Qepctl) || isqtype(q, Qepdir))
818 		return devopen(c, omode, nil, 0, usbgen);
819 
820 	ep = getep(qid2epidx(q));
821 	if(ep == nil)
822 		error(Eio);
823 	deprint("usbopen q %#x fid %d omode %d\n", q, c->fid, mode);
824 	if(waserror()){
825 		putep(ep);
826 		nexterror();
827 	}
828 	qlock(ep);
829 	if(ep->inuse){
830 		qunlock(ep);
831 		error(Einuse);
832 	}
833 	ep->inuse = 1;
834 	qunlock(ep);
835 	if(waserror()){
836 		ep->inuse = 0;
837 		nexterror();
838 	}
839 	if(mode != OREAD && ep->mode == OREAD)
840 		error(Eperm);
841 	if(mode != OWRITE && ep->mode == OWRITE)
842 		error(Eperm);
843 	if(ep->ttype == Tnone)
844 		error(Enotconf);
845 	ep->clrhalt = 0;
846 	ep->rhrepl = -1;
847 	if(ep->load == 0)
848 		ep->load = usbload(ep->dev->speed, ep->maxpkt);
849 	ep->hp->epopen(ep);
850 
851 	poperror();	/* ep->inuse */
852 	poperror();	/* don't putep(): ref kept for fid using the ep. */
853 
854 	c->mode = mode;
855 	c->flag |= COPEN;
856 	c->offset = 0;
857 	c->aux = nil;	/* paranoia */
858 	return c;
859 }
860 
861 static void
862 epclose(Ep *ep)
863 {
864 	qlock(ep);
865 	if(waserror()){
866 		qunlock(ep);
867 		nexterror();
868 	}
869 	if(ep->inuse){
870 		ep->hp->epclose(ep);
871 		ep->inuse = 0;
872 	}
873 	qunlock(ep);
874 	poperror();
875 }
876 
877 static void
878 usbclose(Chan *c)
879 {
880 	int q;
881 	Ep *ep;
882 
883 	q = QID(c->qid);
884 	if(q < Qep0dir || isqtype(q, Qepctl) || isqtype(q, Qepdir))
885 		return;
886 
887 	ep = getep(qid2epidx(q));
888 	if(ep == nil)
889 		return;
890 	deprint("usbclose q %#x fid %d ref %ld\n", q, c->fid, ep->ref);
891 	if(waserror()){
892 		putep(ep);
893 		nexterror();
894 	}
895 	if(c->flag & COPEN){
896 		free(c->aux);
897 		c->aux = nil;
898 		epclose(ep);
899 		putep(ep);	/* release ref kept since usbopen */
900 		c->flag &= ~COPEN;
901 	}
902 	poperror();
903 	putep(ep);
904 }
905 
906 static long
907 ctlread(Chan *c, void *a, long n, vlong offset)
908 {
909 	int q;
910 	char *s;
911 	char *us;
912 	char *se;
913 	Ep *ep;
914 	int i;
915 
916 	q = QID(c->qid);
917 	us = s = smalloc(READSTR);
918 	se = s + READSTR;
919 	if(waserror()){
920 		free(us);
921 		nexterror();
922 	}
923 	if(q == Qctl)
924 		for(i = 0; i < epmax; i++){
925 			ep = getep(i);
926 			if(ep != nil){
927 				if(waserror()){
928 					putep(ep);
929 					nexterror();
930 				}
931 				s = seprint(s, se, "ep%d.%d ", ep->dev->nb, ep->nb);
932 				s = seprintep(s, se, ep, 0);
933 				poperror();
934 			}
935 			putep(ep);
936 		}
937 	else{
938 		ep = getep(qid2epidx(q));
939 		if(ep == nil)
940 			error(Eio);
941 		if(waserror()){
942 			putep(ep);
943 			nexterror();
944 		}
945 		if(c->aux != nil){
946 			/* After a new endpoint request we read
947 			 * the new endpoint name back.
948 			 */
949 			strecpy(s, se, c->aux);
950 			free(c->aux);
951 			c->aux = nil;
952 		}else
953 			seprintep(s, se, ep, 0);
954 		poperror();
955 		putep(ep);
956 	}
957 	n = readstr(offset, a, n, us);
958 	poperror();
959 	free(us);
960 	return n;
961 }
962 
963 /*
964  * Fake root hub emulation.
965  */
966 static long
967 rhubread(Ep *ep, void *a, long n)
968 {
969 	char *b;
970 
971 	if(ep->dev->isroot == 0 || ep->nb != 0 || n < 2)
972 		return -1;
973 	if(ep->rhrepl < 0)
974 		return -1;
975 
976 	b = a;
977 	memset(b, 0, n);
978 	PUT2(b, ep->rhrepl);
979 	ep->rhrepl = -1;
980 	return n;
981 }
982 
983 static long
984 rhubwrite(Ep *ep, void *a, long n)
985 {
986 	uchar *s;
987 	int cmd;
988 	int feature;
989 	int port;
990 	Hci *hp;
991 
992 	if(ep->dev == nil || ep->dev->isroot == 0 || ep->nb != 0)
993 		return -1;
994 	if(n != Rsetuplen)
995 		error("root hub is a toy hub");
996 	ep->rhrepl = -1;
997 	s = a;
998 	if(s[Rtype] != (Rh2d|Rclass|Rother) && s[Rtype] != (Rd2h|Rclass|Rother))
999 		error("root hub is a toy hub");
1000 	hp = ep->hp;
1001 	cmd = s[Rreq];
1002 	feature = GET2(s+Rvalue);
1003 	port = GET2(s+Rindex);
1004 	if(port < 1 || port > hp->nports)
1005 		error("bad hub port number");
1006 	switch(feature){
1007 	case Rportenable:
1008 		ep->rhrepl = hp->portenable(hp, port, cmd == Rsetfeature);
1009 		break;
1010 	case Rportreset:
1011 		ep->rhrepl = hp->portreset(hp, port, cmd == Rsetfeature);
1012 		break;
1013 	case Rgetstatus:
1014 		ep->rhrepl = hp->portstatus(hp, port);
1015 		break;
1016 	default:
1017 		ep->rhrepl = 0;
1018 	}
1019 	return n;
1020 }
1021 
1022 static long
1023 usbread(Chan *c, void *a, long n, vlong offset)
1024 {
1025 	int q;
1026 	Ep *ep;
1027 	int nr;
1028 
1029 	q = QID(c->qid);
1030 
1031 	if(c->qid.type == QTDIR)
1032 		return devdirread(c, a, n, nil, 0, usbgen);
1033 
1034 	if(q == Qctl || isqtype(q, Qepctl))
1035 		return ctlread(c, a, n, offset);
1036 
1037 	ep = getep(qid2epidx(q));
1038 	if(ep == nil)
1039 		error(Eio);
1040 	if(waserror()){
1041 		putep(ep);
1042 		nexterror();
1043 	}
1044 	if(ep->dev->state == Ddetach)
1045 		error(Edetach);
1046 	if(ep->mode == OWRITE || ep->inuse == 0)
1047 		error(Ebadusefd);
1048 	switch(ep->ttype){
1049 	case Tnone:
1050 		error("endpoint not configured");
1051 	case Tctl:
1052 		nr = rhubread(ep, a, n);
1053 		if(nr >= 0){
1054 			n = nr;
1055 			break;
1056 		}
1057 		/* else fall */
1058 	default:
1059 		ddeprint("\nusbread q %#x fid %d cnt %ld off %lld\n",q,c->fid,n,offset);
1060 		n = ep->hp->epread(ep, a, n);
1061 		break;
1062 	}
1063 	poperror();
1064 	putep(ep);
1065 	return n;
1066 }
1067 
1068 static long
1069 pow2(int n)
1070 {
1071 	long v;
1072 
1073 	for(v = 1; n > 0; n--)
1074 		v *= 2;
1075 	return v;
1076 }
1077 
1078 static void
1079 setmaxpkt(Ep *ep, char* s)
1080 {
1081 	long spp;	/* samples per packet */
1082 
1083 	if(ep->dev->speed == Highspeed)
1084 		spp = (ep->hz * ep->pollival * ep->ntds + 7999) / 8000;
1085 	else
1086 		spp = (ep->hz * ep->pollival + 999) / 1000;
1087 	ep->maxpkt = spp * ep->samplesz;
1088 	deprint("usb: %s: setmaxpkt: hz %ld poll %ld"
1089 		" ntds %d %s speed -> spp %ld maxpkt %ld\n", s,
1090 		ep->hz, ep->pollival, ep->ntds, spname[ep->dev->speed],
1091 		spp, ep->maxpkt);
1092 	if(ep->maxpkt > 1024){
1093 		print("usb: %s: maxpkt %ld > 1024. truncating\n", s, ep->maxpkt);
1094 		ep->maxpkt = 1024;
1095 	}
1096 }
1097 
1098 /*
1099  * Many endpoint ctls. simply update the portable representation
1100  * of the endpoint. The actual controller driver will look
1101  * at them to setup the endpoints as dictated.
1102  */
1103 static long
1104 epctl(Ep *ep, Chan *c, void *a, long n)
1105 {
1106 	static char *Info = "info ";
1107 	Ep *nep;
1108 	Udev *d;
1109 	int l;
1110 	char *s;
1111 	char *b;
1112 	int tt;
1113 	int i;
1114 	int mode;
1115 	int nb;
1116 	Cmdtab *ct;
1117 	Cmdbuf *cb;
1118 
1119 	d = ep->dev;
1120 
1121 	cb = parsecmd(a, n);
1122 	if(waserror()){
1123 		free(cb);
1124 		nexterror();
1125 	}
1126 	ct = lookupcmd(cb, epctls, nelem(epctls));
1127 	if(ct == nil)
1128 		error(Ebadctl);
1129 	i = ct->index;
1130 	if(i == CMnew || i == CMspeed || i == CMhub || i == CMpreset)
1131 		if(ep != ep->ep0)
1132 			error("allowed only on a setup endpoint");
1133 	if(i != CMclrhalt && i != CMdetach && i != CMdebugep && i != CMname)
1134 		if(ep != ep->ep0 && ep->inuse != 0)
1135 			error("must configure before using");
1136 	switch(i){
1137 	case CMnew:
1138 		deprint("usb epctl %s\n", cb->f[0]);
1139 		nb = strtol(cb->f[1], nil, 0);
1140 		if(nb < 0 || nb >= Ndeveps)
1141 			error("bad endpoint number");
1142 		tt = name2ttype(cb->f[2]);
1143 		if(tt == Tnone)
1144 			error("unknown endpoint type");
1145 		mode = name2mode(cb->f[3]);
1146 		if(mode < 0)
1147 			error("unknown i/o mode");
1148 		newdevep(ep, nb, tt, mode);
1149 		break;
1150 	case CMnewdev:
1151 		deprint("usb epctl %s\n", cb->f[0]);
1152 		if(ep != ep->ep0 || d->ishub == 0)
1153 			error("not a hub setup endpoint");
1154 		l = name2speed(cb->f[1]);
1155 		if(l == Nospeed)
1156 			error("speed must be full|low|high");
1157 		nep = newdev(ep->hp, 0, 0);
1158 		nep->dev->speed = l;
1159 		if(nep->dev->speed  != Lowspeed)
1160 			nep->maxpkt = 64;	/* assume full speed */
1161 		nep->dev->hub = d->nb;
1162 		nep->dev->port = atoi(cb->f[2]);
1163 		/* next read request will read
1164 		 * the name for the new endpoint
1165 		 */
1166 		l = sizeof(up->genbuf);
1167 		snprint(up->genbuf, l, "ep%d.%d", nep->dev->nb, nep->nb);
1168 		kstrdup(&c->aux, up->genbuf);
1169 		break;
1170 	case CMhub:
1171 		deprint("usb epctl %s\n", cb->f[0]);
1172 		d->ishub = 1;
1173 		break;
1174 	case CMspeed:
1175 		l = name2speed(cb->f[1]);
1176 		deprint("usb epctl %s %d\n", cb->f[0], l);
1177 		if(l == Nospeed)
1178 			error("speed must be full|low|high");
1179 		qlock(ep->ep0);
1180 		d->speed = l;
1181 		qunlock(ep->ep0);
1182 		break;
1183 	case CMmaxpkt:
1184 		l = strtoul(cb->f[1], nil, 0);
1185 		deprint("usb epctl %s %d\n", cb->f[0], l);
1186 		if(l < 1 || l > 1024)
1187 			error("maxpkt not in [1:1024]");
1188 		qlock(ep);
1189 		ep->maxpkt = l;
1190 		qunlock(ep);
1191 		break;
1192 	case CMntds:
1193 		l = strtoul(cb->f[1], nil, 0);
1194 		deprint("usb epctl %s %d\n", cb->f[0], l);
1195 		if(l < 1 || l > 3)
1196 			error("ntds not in [1:3]");
1197 		qlock(ep);
1198 		ep->ntds = l;
1199 		qunlock(ep);
1200 		break;
1201 	case CMpollival:
1202 		if(ep->ttype != Tintr && ep->ttype != Tiso)
1203 			error("not an intr or iso endpoint");
1204 		l = strtoul(cb->f[1], nil, 0);
1205 		deprint("usb epctl %s %d\n", cb->f[0], l);
1206 		if(ep->ttype == Tiso ||
1207 		   (ep->ttype == Tintr && ep->dev->speed == Highspeed)){
1208 			if(l < 1 || l > 16)
1209 				error("pollival power not in [1:16]");
1210 			l = pow2(l-1);
1211 		}else
1212 			if(l < 1 || l > 255)
1213 				error("pollival not in [1:255]");
1214 		qlock(ep);
1215 		ep->pollival = l;
1216 		if(ep->ttype == Tiso)
1217 			setmaxpkt(ep, "pollival");
1218 		qunlock(ep);
1219 		break;
1220 	case CMsamplesz:
1221 		if(ep->ttype != Tiso)
1222 			error("not an iso endpoint");
1223 		l = strtoul(cb->f[1], nil, 0);
1224 		deprint("usb epctl %s %d\n", cb->f[0], l);
1225 		if(l <= 0 || l > 8)
1226 			error("samplesz not in [1:8]");
1227 		qlock(ep);
1228 		ep->samplesz = l;
1229 		setmaxpkt(ep, "samplesz");
1230 		qunlock(ep);
1231 		break;
1232 	case CMhz:
1233 		if(ep->ttype != Tiso)
1234 			error("not an iso endpoint");
1235 		l = strtoul(cb->f[1], nil, 0);
1236 		deprint("usb epctl %s %d\n", cb->f[0], l);
1237 		if(l <= 0 || l > 100000)
1238 			error("hz not in [1:100000]");
1239 		qlock(ep);
1240 		ep->hz = l;
1241 		setmaxpkt(ep, "hz");
1242 		qunlock(ep);
1243 		break;
1244 	case CMclrhalt:
1245 		qlock(ep);
1246 		deprint("usb epctl %s\n", cb->f[0]);
1247 		ep->clrhalt = 1;
1248 		qunlock(ep);
1249 		break;
1250 	case CMinfo:
1251 		deprint("usb epctl %s\n", cb->f[0]);
1252 		l = strlen(Info);
1253 		s = a;
1254 		if(n < l+2 || strncmp(Info, s, l) != 0)
1255 			error(Ebadctl);
1256 		if(n > 1024)
1257 			n = 1024;
1258 		b = smalloc(n);
1259 		memmove(b, s+l, n-l);
1260 		b[n-l] = 0;
1261 		if(b[n-l-1] == '\n')
1262 			b[n-l-1] = 0;
1263 		qlock(ep);
1264 		free(ep->info);
1265 		ep->info = b;
1266 		qunlock(ep);
1267 		break;
1268 	case CMaddress:
1269 		deprint("usb epctl %s\n", cb->f[0]);
1270 		ep->dev->state = Denabled;
1271 		break;
1272 	case CMdetach:
1273 		if(ep->dev->isroot != 0)
1274 			error("can't detach a root hub");
1275 		deprint("usb epctl %s ep%d.%d\n",
1276 			cb->f[0], ep->dev->nb, ep->nb);
1277 		ep->dev->state = Ddetach;
1278 		/* Release file system ref. for its endpoints */
1279 		for(i = 0; i < nelem(ep->dev->eps); i++)
1280 			putep(ep->dev->eps[i]);
1281 		break;
1282 	case CMdebugep:
1283 		if(strcmp(cb->f[1], "on") == 0)
1284 			ep->debug = 1;
1285 		else if(strcmp(cb->f[1], "off") == 0)
1286 			ep->debug = 0;
1287 		else
1288 			ep->debug = strtoul(cb->f[1], nil, 0);
1289 		print("usb: ep%d.%d debug %d\n",
1290 			ep->dev->nb, ep->nb, ep->debug);
1291 		break;
1292 	case CMname:
1293 		deprint("usb epctl %s %s\n", cb->f[0], cb->f[1]);
1294 		validname(cb->f[1], 0);
1295 		kstrdup(&ep->name, cb->f[1]);
1296 		break;
1297 	case CMtmout:
1298 		deprint("usb epctl %s\n", cb->f[0]);
1299 		if(ep->ttype == Tiso || ep->ttype == Tctl)
1300 			error("ctl ignored for this endpoint type");
1301 		ep->tmout = strtoul(cb->f[1], nil, 0);
1302 		if(ep->tmout != 0 && ep->tmout < Xfertmout)
1303 			ep->tmout = Xfertmout;
1304 		break;
1305 	case CMpreset:
1306 		deprint("usb epctl %s\n", cb->f[0]);
1307 		if(ep->ttype != Tctl)
1308 			error("not a control endpoint");
1309 		if(ep->dev->state != Denabled)
1310 			error("forbidden on devices not enabled");
1311 		ep->dev->state = Dreset;
1312 		break;
1313 	default:
1314 		panic("usb: unknown epctl %d", ct->index);
1315 	}
1316 	free(cb);
1317 	poperror();
1318 	return n;
1319 }
1320 
1321 static long
1322 usbctl(void *a, long n)
1323 {
1324 	Cmdtab *ct;
1325 	Cmdbuf *cb;
1326 	Ep *ep;
1327 	int i;
1328 
1329 	cb = parsecmd(a, n);
1330 	if(waserror()){
1331 		free(cb);
1332 		nexterror();
1333 	}
1334 	ct = lookupcmd(cb, usbctls, nelem(usbctls));
1335 	dprint("usb ctl %s\n", cb->f[0]);
1336 	switch(ct->index){
1337 	case CMdebug:
1338 		if(strcmp(cb->f[1], "on") == 0)
1339 			debug = 1;
1340 		else if(strcmp(cb->f[1], "off") == 0)
1341 			debug = 0;
1342 		else
1343 			debug = strtol(cb->f[1], nil, 0);
1344 		print("usb: debug %d\n", debug);
1345 		for(i = 0; i < epmax; i++)
1346 			if((ep = getep(i)) != nil){
1347 				ep->hp->debug(ep->hp, debug);
1348 				putep(ep);
1349 			}
1350 		break;
1351 	case CMdump:
1352 		dumpeps();
1353 		break;
1354 	}
1355 	free(cb);
1356 	poperror();
1357 	return n;
1358 }
1359 
1360 static long
1361 ctlwrite(Chan *c, void *a, long n)
1362 {
1363 	int q;
1364 	Ep *ep;
1365 
1366 	q = QID(c->qid);
1367 	if(q == Qctl)
1368 		return usbctl(a, n);
1369 
1370 	ep = getep(qid2epidx(q));
1371 	if(ep == nil)
1372 		error(Eio);
1373 	if(waserror()){
1374 		putep(ep);
1375 		nexterror();
1376 	}
1377 	if(ep->dev->state == Ddetach)
1378 		error(Edetach);
1379 	if(isqtype(q, Qepctl) && c->aux != nil){
1380 		/* Be sure we don't keep a cloned ep name */
1381 		free(c->aux);
1382 		c->aux = nil;
1383 		error("read, not write, expected");
1384 	}
1385 	n = epctl(ep, c, a, n);
1386 	putep(ep);
1387 	poperror();
1388 	return n;
1389 }
1390 
1391 static long
1392 usbwrite(Chan *c, void *a, long n, vlong off)
1393 {
1394 	int q;
1395 	Ep *ep;
1396 	int nr;
1397 
1398 	if(c->qid.type == QTDIR)
1399 		error(Eisdir);
1400 
1401 	q = QID(c->qid);
1402 
1403 	if(q == Qctl || isqtype(q, Qepctl))
1404 		return ctlwrite(c, a, n);
1405 
1406 	ep = getep(qid2epidx(q));
1407 	if(ep == nil)
1408 		error(Eio);
1409 	if(waserror()){
1410 		putep(ep);
1411 		nexterror();
1412 	}
1413 	if(ep->dev->state == Ddetach)
1414 		error(Edetach);
1415 	if(ep->mode == OREAD || ep->inuse == 0)
1416 		error(Ebadusefd);
1417 
1418 	switch(ep->ttype){
1419 	case Tnone:
1420 		error("endpoint not configured");
1421 	case Tctl:
1422 		nr = rhubwrite(ep, a, n);
1423 		if(nr >= 0){
1424 			n = nr;
1425 			break;
1426 		}
1427 		/* else fall */
1428 	default:
1429 		ddeprint("\nusbwrite q %#x fid %d cnt %ld off %lld\n",q, c->fid, n, off);
1430 		ep->hp->epwrite(ep, a, n);
1431 	}
1432 	putep(ep);
1433 	poperror();
1434 	return n;
1435 }
1436 
1437 void
1438 usbshutdown(void)
1439 {
1440 	Hci *hp;
1441 	int i;
1442 
1443 	for(i = 0; i < Nhcis; i++){
1444 		hp = hcis[i];
1445 		if(hp == nil)
1446 			continue;
1447 		if(hp->shutdown == nil)
1448 			print("#u: no shutdown function for %s\n", hp->type);
1449 		else
1450 			hp->shutdown(hp);
1451 	}
1452 }
1453 
1454 Dev usbdevtab = {
1455 	L'u',
1456 	"usb",
1457 
1458 	usbreset,
1459 	usbinit,
1460 	usbshutdown,
1461 	usbattach,
1462 	usbwalk,
1463 	usbstat,
1464 	usbopen,
1465 	devcreate,
1466 	usbclose,
1467 	usbread,
1468 	devbread,
1469 	usbwrite,
1470 	devbwrite,
1471 	devremove,
1472 	devwstat,
1473 };
1474