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