]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/port/usbehci.c
kernel: fix fairshare formula in comment (thanks erik)
[plan9front.git] / sys / src / 9 / port / usbehci.c
1 /*
2  * USB Enhanced Host Controller Interface (EHCI) driver
3  * High speed USB 2.0.
4  *
5  * Note that all of our unlock routines call coherence.
6  *
7  * BUGS:
8  * - Too many delays and ilocks.
9  * - bandwidth admission control must be done per-frame.
10  * - requires polling (some controllers miss interrupts).
11  * - must warn of power overruns.
12  */
13
14 #include        "u.h"
15 #include        "../port/lib.h"
16 #include        "mem.h"
17 #include        "dat.h"
18 #include        "fns.h"
19 #include        "io.h"
20 #include        "../port/error.h"
21 #include        "../port/usb.h"
22 #include        "usbehci.h"
23 #include        "uncached.h"
24
25 #define diprint         if(ehcidebug || iso->debug)print
26 #define ddiprint        if(ehcidebug>1 || iso->debug>1)print
27 #define dqprint         if(ehcidebug || (qh->io && qh->io->debug))print
28 #define ddqprint        if(ehcidebug>1 || (qh->io && qh->io->debug>1))print
29
30 #define TRUNC(x, sz)    ((x) & ((sz)-1))
31 #define LPTR(q)         ((ulong*)KADDR((q) & ~0x1F))
32
33 typedef struct Ctlio Ctlio;
34 typedef union Ed Ed;
35 typedef struct Edpool Edpool;
36 typedef struct Itd Itd;
37 typedef struct Qio Qio;
38 typedef struct Qtd Qtd;
39 typedef struct Sitd Sitd;
40 typedef struct Td Td;
41
42 /*
43  * EHCI interface registers and bits
44  */
45 enum
46 {
47         /* Queue states (software) */
48         Qidle           = 0,
49         Qinstall,
50         Qrun,
51         Qdone,
52         Qclose,
53         Qfree,
54
55         Enabledelay     = 100,          /* waiting for a port to enable */
56         Abortdelay      = 10,           /* delay after cancelling Tds (ms) */
57
58         Incr            = 64,           /* for pools of Tds, Qhs, etc. */
59         Align           = 128,          /* in bytes for all those descriptors */
60
61         /* Keep them as a power of 2, lower than ctlr->nframes */
62         /* Also, keep Nisoframes >= Nintrleafs */
63         Nintrleafs      = 32,           /* nb. of leaf frames in intr. tree */
64         Nisoframes      = 64,           /* nb. of iso frames (in window) */
65
66         /*
67          * HW constants
68          */
69
70         /* Itd bits (csw[]) */
71         Itdactive       = 0x80000000,   /* execution enabled */
72         Itddberr        = 0x40000000,   /* data buffer error */
73         Itdbabble       = 0x20000000,   /* babble error */
74         Itdtrerr        = 0x10000000,   /* transaction error */
75         Itdlenshift     = 16,           /* transaction length */
76         Itdlenmask      = 0xFFF,
77         Itdioc          = 0x00008000,   /* interrupt on complete */
78         Itdpgshift      = 12,           /* page select field */
79         Itdoffshift     = 0,            /* transaction offset */
80         /* Itd bits, buffer[] */
81         Itdepshift      = 8,            /* endpoint address (buffer[0]) */
82         Itddevshift     = 0,            /* device address (buffer[0]) */
83         Itdin           = 0x800,        /* is input (buffer[1]) */
84         Itdout          = 0,
85         Itdmaxpktshift  = 0,            /* max packet (buffer[1]) */
86         Itdntdsshift    = 0,            /* nb. of tds per µframe (buffer[2]) */
87
88         Itderrors       = Itddberr|Itdbabble|Itdtrerr,
89
90         /* Sitd bits (epc) */
91         Stdin           = 0x80000000,   /* input direction */
92         Stdportshift    = 24,           /* hub port number */
93         Stdhubshift     = 16,           /* hub address */
94         Stdepshift      = 8,            /* endpoint address */
95         Stddevshift     = 0,            /* device address */
96         /* Sitd bits (mfs) */
97         Stdssmshift     = 0,            /* split start mask */
98         Stdscmshift     = 8,            /* split complete mask */
99         /* Sitd bits (csw) */
100         Stdioc          = 0x80000000,   /* interrupt on complete */
101         Stdpg           = 0x40000000,   /* page select */
102         Stdlenshift     = 16,           /* total bytes to transfer */
103         Stdlenmask      = 0x3FF,
104         Stdactive       = 0x00000080,   /* active */
105         Stderr          = 0x00000040,   /* tr. translator error */
106         Stddberr        = 0x00000020,   /* data buffer error */
107         Stdbabble       = 0x00000010,   /* babble error */
108         Stdtrerr        = 0x00000008,   /* transaction error */
109         Stdmmf          = 0x00000004,   /* missed µframe */
110         Stddcs          = 0x00000002,   /* do complete split */
111
112         Stderrors       = Stderr|Stddberr|Stdbabble|Stdtrerr|Stdmmf,
113
114         /* Sitd bits buffer[1] */
115         Stdtpall        = 0x00000000,   /* all payload here (188 bytes) */
116         Stdtpbegin      = 0x00000008,   /* first payload for fs trans. */
117         Stdtcntmask     = 0x00000007,   /* T-count */
118
119         /* Td bits (csw) */
120         Tddata1         = 0x80000000,   /* data toggle 1 */
121         Tddata0         = 0x00000000,   /* data toggle 0 */
122         Tdlenshift      = 16,           /* total bytes to transfer */
123         Tdlenmask       = 0x7FFF,
124         Tdmaxpkt        = 0x5000,       /* max buffer for a Td */
125         Tdioc           = 0x00008000,   /* interrupt on complete */
126         Tdpgshift       = 12,           /* current page */
127         Tdpgmask        = 7,
128         Tderr1          = 0x00000400,   /* bit 0 of error counter */
129         Tderr2          = 0x00000800,   /* bit 1 of error counter */
130         Tdtokout        = 0x00000000,   /* direction out */
131         Tdtokin         = 0x00000100,   /* direction in */
132         Tdtoksetup      = 0x00000200,   /* setup packet */
133         Tdtok           = 0x00000300,   /* token bits */
134         Tdactive                = 0x00000080,   /* active */
135         Tdhalt          = 0x00000040,   /* halted */
136         Tddberr         = 0x00000020,   /* data buffer error */
137         Tdbabble        = 0x00000010,   /* babble error */
138         Tdtrerr         = 0x00000008,   /* transaction error */
139         Tdmmf           = 0x00000004,   /* missed µframe */
140         Tddcs           = 0x00000002,   /* do complete split */
141         Tdping          = 0x00000001,   /* do ping */
142
143         Tderrors        = Tdhalt|Tddberr|Tdbabble|Tdtrerr|Tdmmf,
144
145         /* Qh bits (eps0) */
146         Qhrlcmask       = 0xF,          /* nak reload count */
147         Qhrlcshift      = 28,           /* nak reload count */
148         Qhnhctl         = 0x08000000,   /* not-high speed ctl */
149         Qhmplmask       = 0x7FF,        /* max packet */
150         Qhmplshift      = 16,
151         Qhhrl           = 0x00008000,   /* head of reclamation list */
152         Qhdtc           = 0x00004000,   /* data toggle ctl. */
153         Qhint           = 0x00000080,   /* inactivate on next transition */
154         Qhspeedmask     = 0x00003000,   /* speed bits */
155         Qhfull          = 0x00000000,   /* full speed */
156         Qhlow           = 0x00001000,   /* low speed */
157         Qhhigh          = 0x00002000,   /* high speed */
158
159         /* Qh bits (eps1) */
160         Qhmultshift     = 30,           /* multiple tds per µframe */
161         Qhmultmask      = 3,
162         Qhportshift     = 23,           /* hub port number */
163         Qhhubshift      = 16,           /* hub address */
164         Qhscmshift      = 8,            /* split completion mask bits */
165         Qhismshift      = 0,            /* interrupt sched. mask bits */
166 };
167
168 /*
169  * Endpoint tree (software)
170  */
171 struct Qtree
172 {
173         int     nel;
174         int     depth;
175         ulong*  bw;
176         Qh**    root;
177 };
178
179 /*
180  * One per endpoint per direction, to control I/O.
181  */
182 struct Qio
183 {
184         QLock;                  /* for the entire I/O process */
185         Rendez;                 /* wait for completion */
186         Qh*     qh;             /* Td list (field const after init) */
187         int     usbid;          /* usb address for endpoint/device */
188         int     toggle;         /* Tddata0/Tddata1 */
189         int     tok;            /* Tdtoksetup, Tdtokin, Tdtokout */
190         ulong   iotime;         /* last I/O time; to hold interrupt polls */
191         int     debug;          /* debug flag from the endpoint */
192         char*   err;            /* error string */
193         char*   tag;            /* debug (no room in Qh for this) */
194         ulong   bw;
195 };
196
197 struct Ctlio
198 {
199         Qio;                    /* a single Qio for each RPC */
200         uchar*  data;           /* read from last ctl req. */
201         int     ndata;          /* number of bytes read */
202 };
203
204 struct Isoio
205 {
206         QLock;
207         Rendez;                 /* wait for space/completion/errors */
208         int     usbid;          /* address used for device/endpoint */
209         int     tok;            /* Tdtokin or Tdtokout */
210         int     state;          /* Qrun -> Qdone -> Qrun... -> Qclose */
211         int     nframes;        /* number of frames ([S]Itds) used */
212         uchar*  data;           /* iso data buffers if not embedded */
213         char*   err;            /* error string */
214         int     nerrs;          /* nb of consecutive I/O errors */
215         ulong   maxsize;        /* ntds * ep->maxpkt */
216         long    nleft;          /* number of bytes left from last write */
217         int     debug;          /* debug flag from the endpoint */
218         int     delay;          /* max number of bytes to buffer */
219         int     hs;             /* is high speed? */
220         Isoio*  next;           /* in list of active Isoios */
221         ulong   td0frno;        /* first frame used in ctlr */
222         union{
223                 Itd*    tdi;    /* next td processed by interrupt */
224                 Sitd*   stdi;
225         };
226         union{
227                 Itd*    tdu;    /* next td for user I/O in tdps */
228                 Sitd*   stdu;
229         };
230         union{
231                 Itd**   itdps;  /* itdps[i]: ptr to Itd for i-th frame or nil */
232                 Sitd**  sitdps; /* sitdps[i]: ptr to Sitd for i-th frame or nil */
233                 ulong** tdps;   /* same thing, as seen by hw */
234         };
235 };
236
237 struct Edpool
238 {
239         Lock;
240         Ed*     free;
241         int     nalloc;
242         int     ninuse;
243         int     nfree;
244 };
245
246 /*
247  * We use the 64-bit version for Itd, Sitd, Td, and Qh.
248  * If the ehci is 64-bit capable it assumes we are using those
249  * structures even when the system is 32 bits.
250  */
251
252 /*
253  * Iso transfer descriptor.  hw: 92 bytes, 108 bytes total
254  * aligned to 32.
255  */
256 struct Itd
257 {
258         ulong   link;           /* to next hw struct */
259         ulong   csw[8];         /* sts/length/pg/off. updated by hw */
260         ulong   buffer[7];      /* buffer pointers, addrs, maxsz */
261         ulong   xbuffer[7];     /* high 32 bits of buffer for 64-bits */
262
263         ulong   _pad0;          /* pad to next cache line */
264         /* cache-line boundary here */
265
266         /* software */
267         Itd*    next;
268         ulong   ndata;          /* number of bytes in data */
269         ulong   mdata;          /* max number of bytes in data */
270         uchar*  data;
271 };
272
273 /*
274  * Split transaction iso transfer descriptor.
275  * hw: 36 bytes, 52 bytes total. aligned to 32.
276  */
277 struct Sitd
278 {
279         ulong   link;           /* to next hw struct */
280         ulong   epc;            /* static endpoint state. addrs */
281         ulong   mfs;            /* static endpoint state. µ-frame sched. */
282         ulong   csw;            /* transfer state. updated by hw */
283         ulong   buffer[2];      /* buf. ptr/offset. offset updated by hw */
284                                 /* buf ptr/TP/Tcnt. TP/Tcnt updated by hw */
285         ulong   blink;          /* back pointer */
286         /* cache-line boundary after xbuffer[0] */
287         ulong   xbuffer[2];     /* high 32 bits of buffer for 64-bits */
288
289         /* software */
290         Sitd*   next;
291         ulong   ndata;          /* number of bytes in data */
292         ulong   mdata;          /* max number of bytes in data */
293         uchar*  data;
294 };
295
296 /*
297  * Queue element transfer descriptor.
298  * hw: first 52 bytes, total 68+sbuff bytes.  aligned to 32 bytes.
299  */
300 struct Td
301 {
302         ulong   nlink;          /* to next Td */
303         ulong   alink;          /* alternate link to next Td */
304         ulong   csw;            /* cmd/sts. updated by hw */
305         ulong   buffer[5];      /* buf ptrs. offset updated by hw */
306         /* cache-line boundary here */
307         ulong   xbuffer[5];     /* high 32 bits of buffer for 64-bits */
308
309         /* software */
310         Td*     next;           /* in qh or Isoio or free list */
311         ulong   ndata;          /* bytes available/used at data */
312         uchar*  data;           /* pointer to actual data */
313         uchar*  buff;           /* allocated data buffer or nil */
314         uchar   sbuff[1];       /* first byte of embedded buffer */
315 };
316
317 /*
318  * Queue head. Aligned to 32 bytes.
319  * hw: first 68 bytes, 92 total.
320  */
321 struct Qh
322 {
323         ulong   link;           /* to next Qh in round robin */
324         ulong   eps0;           /* static endpoint state. addrs */
325         ulong   eps1;           /* static endpoint state. µ-frame sched. */
326
327         /* updated by hw */
328         ulong   tclink;         /* current Td (No Term bit here!) */
329         ulong   nlink;          /* to next Td */
330         ulong   alink;          /* alternate link to next Td */
331         ulong   csw;            /* cmd/sts. updated by hw */
332         /* cache-line boundary after buffer[0] */
333         ulong   buffer[5];      /* buf ptrs. offset updated by hw */
334         ulong   xbuffer[5];     /* high 32 bits of buffer for 64-bits */
335
336         /* software */
337         Qh*     next;           /* in controller list/tree of Qhs */
338         int     state;          /* Qidle -> Qinstall -> Qrun -> Qdone | Qclose */
339         Qio*    io;             /* for this queue */
340         Td*     tds;            /* for this queue */
341         int     sched;          /* slot for for intr. Qhs */
342         Qh*     inext;          /* next in list of intr. qhs */
343 };
344
345 /*
346  * We can avoid frame span traversal nodes if we don't span frames.
347  * Just schedule transfers that can fit on the current frame and
348  * wait a little bit otherwise.
349  */
350
351 /*
352  * Software. Ehci descriptors provided by pool.
353  * There are soo few because we avoid using Fstn.
354  */
355 union Ed
356 {
357         Ed*     next;           /* in free list */
358         Qh      qh;
359         Td      td;
360         Itd     itd;
361         Sitd    sitd;
362         uchar   align[Align];
363 };
364
365 int ehcidebug;
366
367 static Edpool edpool;
368 static char Ebug[] = "not yet implemented";
369 static char* qhsname[] = { "idle", "install", "run", "done", "close", "FREE" };
370
371 Ecapio* ehcidebugcapio;
372 int ehcidebugport;
373
374 void
375 ehcirun(Ctlr *ctlr, int on)
376 {
377         int i;
378         Eopio *opio;
379
380         ddprint("ehci %#p %s\n", ctlr->capio, on ? "starting" : "halting");
381         opio = ctlr->opio;
382         if(on)
383                 opio->cmd |= Crun;
384         else
385                 opio->cmd = Cstop;
386         coherence();
387         for(i = 0; i < 100; i++)
388                 if(on == 0 && (opio->sts & Shalted) != 0)
389                         break;
390                 else if(on != 0 && (opio->sts & Shalted) == 0)
391                         break;
392                 else
393                         delay(1);
394         if(i == 100)
395                 print("ehci %#p %s cmd timed out\n",
396                         ctlr->capio, on ? "run" : "halt");
397         ddprint("ehci %#p cmd %#lux sts %#lux\n",
398                 ctlr->capio, opio->cmd, opio->sts);
399 }
400
401 static void*
402 edalloc(void)
403 {
404         Ed *ed, *pool;
405         int i;
406
407         lock(&edpool);
408         if(edpool.free == nil){
409                 pool = xspanalloc(Incr*sizeof(Ed), Align, 0);
410                 if(pool == nil)
411                         panic("edalloc");
412                 for(i=Incr; --i>=0;){
413                         pool[i].next = edpool.free;
414                         edpool.free = &pool[i];
415                 }
416                 edpool.nalloc += Incr;
417                 edpool.nfree += Incr;
418                 dprint("ehci: edalloc: %d eds\n", edpool.nalloc);
419         }
420         ed = edpool.free;
421         edpool.free = ed->next;
422         edpool.ninuse++;
423         edpool.nfree--;
424         unlock(&edpool);
425
426         memset(ed, 0, sizeof(Ed));      /* safety */
427         assert(((ulong)ed & 0xF) == 0);
428         return ed;
429 }
430
431 static void
432 edfree(void *a)
433 {
434         Ed *ed;
435
436         ed = a;
437         lock(&edpool);
438         ed->next = edpool.free;
439         edpool.free = ed;
440         edpool.ninuse--;
441         edpool.nfree++;
442         unlock(&edpool);
443 }
444
445 /*
446  * Allocate and do some initialization.
447  * Free after releasing buffers used.
448  */
449
450 static Itd*
451 itdalloc(void)
452 {
453         Itd *td;
454
455         td = edalloc();
456         td->link = Lterm;
457         return td;
458 }
459
460 static void
461 itdfree(Itd *td)
462 {
463         edfree(td);
464 }
465
466 static Sitd*
467 sitdalloc(void)
468 {
469         Sitd *td;
470
471         td = edalloc();
472         td->link = td->blink = Lterm;
473         return td;
474 }
475
476 static void
477 sitdfree(Sitd *td)
478 {
479         edfree(td);
480 }
481
482 static Td*
483 tdalloc(void)
484 {
485         Td *td;
486
487         td = edalloc();
488         td->nlink = td->alink = Lterm;
489         return td;
490 }
491
492 static void
493 tdfree(Td *td)
494 {
495         if(td == nil)
496                 return;
497         free(td->buff);
498         edfree(td);
499 }
500
501 static void
502 tdlinktd(Td *td, Td *next)
503 {
504         td->next = next;
505         td->alink = Lterm;
506         if(next == nil)
507                 td->nlink = Lterm;
508         else
509                 td->nlink = PADDR(next);
510         coherence();
511 }
512
513 static Qh*
514 qhlinkqh(Qh *qh, Qh *next)
515 {
516         qh->next = next;
517         if(next == nil)
518                 qh->link = Lterm;
519         else
520                 qh->link = PADDR(next)|Lqh;
521         coherence();
522         return qh;
523 }
524
525 static void
526 qhsetaddr(Qh *qh, ulong addr)
527 {
528         ulong eps0;
529
530         eps0 = qh->eps0 & ~((Epmax<<8)|Devmax);
531         qh->eps0 = eps0 | addr & Devmax | ((addr >> 7) & Epmax) << 8;
532         coherence();
533 }
534
535 /*
536  * return smallest power of 2 <= n
537  */
538 static int
539 flog2lower(int n)
540 {
541         int i;
542
543         for(i = 0; (1 << (i + 1)) <= n; i++)
544                 ;
545         return i;
546 }
547
548 static int
549 pickschedq(Qtree *qt, int pollival, ulong bw, ulong limit)
550 {
551         int i, j, d, upperb, q;
552         ulong best, worst, total;
553
554         d = flog2lower(pollival);
555         if(d > qt->depth)
556                 d = qt->depth;
557         q = -1;
558         worst = 0;
559         best = ~0;
560         upperb = (1 << (d+1)) - 1;
561         for(i = (1 << d) - 1; i < upperb; i++){
562                 total = qt->bw[0];
563                 for(j = i; j > 0; j = (j - 1) / 2)
564                         total += qt->bw[j];
565                 if(total < best){
566                         best = total;
567                         q = i;
568                 }
569                 if(total > worst)
570                         worst = total;
571         }
572         if(worst + bw >= limit)
573                 return -1;
574         return q;
575 }
576
577 static int
578 schedq(Ctlr *ctlr, Qh *qh, int pollival)
579 {
580         int q;
581         Qh *tqh;
582         ulong bw;
583
584         bw = qh->io->bw;
585         q = pickschedq(ctlr->tree, pollival, 0, ~0);
586         ddqprint("ehci: sched %#p q %d, ival %d, bw %uld\n",
587                 qh->io, q, pollival, bw);
588         if(q < 0){
589                 print("ehci: no room for ed\n");
590                 return -1;
591         }
592         ctlr->tree->bw[q] += bw;
593         tqh = ctlr->tree->root[q];
594         qh->sched = q;
595         qhlinkqh(qh, tqh->next);
596         qhlinkqh(tqh, qh);
597         coherence();
598         qh->inext = ctlr->intrqhs;
599         ctlr->intrqhs = qh;
600         coherence();
601         return 0;
602 }
603
604 static void
605 unschedq(Ctlr *ctlr, Qh *qh)
606 {
607         int q;
608         Qh *prev, *this, *next;
609         Qh **l;
610         ulong bw;
611
612         bw = qh->io->bw;
613         q = qh->sched;
614         if(q < 0)
615                 return;
616         ctlr->tree->bw[q] -= bw;
617
618         prev = ctlr->tree->root[q];
619         this = prev->next;
620         while(this != nil && this != qh){
621                 prev = this;
622                 this = this->next;
623         }
624         if(this == nil)
625                 print("ehci: unschedq %d: not found\n", q);
626         else{
627                 next = this->next;
628                 qhlinkqh(prev, next);
629         }
630         for(l = &ctlr->intrqhs; *l != nil; l = &(*l)->inext)
631                 if(*l == qh){
632                         *l = (*l)->inext;
633                         return;
634                 }
635         print("ehci: unschedq: qh %#p not found\n", qh);
636 }
637
638 static ulong
639 qhmaxpkt(Qh *qh)
640 {
641         return (qh->eps0 >> Qhmplshift) & Qhmplmask;
642 }
643
644 static void
645 qhsetmaxpkt(Qh *qh, int maxpkt)
646 {
647         ulong eps0;
648
649         eps0 = qh->eps0 & ~(Qhmplmask << Qhmplshift);
650         qh->eps0 = eps0 | (maxpkt & Qhmplmask) << Qhmplshift;
651         coherence();
652 }
653
654 /*
655  * Initialize the round-robin circular list of ctl/bulk Qhs
656  * if ep is nil. Otherwise, allocate and link a new Qh in the ctlr.
657  */
658 static Qh*
659 qhalloc(Ctlr *ctlr, Ep *ep, Qio *io, char* tag)
660 {
661         Qh *qh;
662         int ttype;
663
664         qh = edalloc();
665         qh->nlink = Lterm;
666         qh->alink = Lterm;
667         qh->csw = Tdhalt;
668         qh->state = Qidle;
669         qh->sched = -1;
670         qh->io = io;
671         if(ep != nil){
672                 qh->eps0 = 0;
673                 qhsetmaxpkt(qh, ep->maxpkt);
674                 if(ep->dev->speed == Lowspeed)
675                         qh->eps0 |= Qhlow;
676                 if(ep->dev->speed == Highspeed)
677                         qh->eps0 |= Qhhigh;
678                 else if(ep->ttype == Tctl)
679                         qh->eps0 |= Qhnhctl;
680                 qh->eps0 |= Qhdtc | 8 << Qhrlcshift;    /* 8 naks max */
681                 coherence();
682                 qhsetaddr(qh, io->usbid);
683                 qh->eps1 = (ep->ntds & Qhmultmask) << Qhmultshift;
684                 qh->eps1 |= ep->dev->port << Qhportshift;
685                 qh->eps1 |= ep->dev->hub << Qhhubshift;
686                 qh->eps1 |= 034 << Qhscmshift;
687                 if(ep->ttype == Tintr)
688                         qh->eps1 |= 1 << Qhismshift;    /* intr. start µf. */
689                 coherence();
690                 if(io != nil)
691                         io->tag = tag;
692         }
693         ilock(ctlr);
694         ttype = Tctl;
695         if(ep != nil)
696                 ttype = ep->ttype;
697         switch(ttype){
698         case Tctl:
699         case Tbulk:
700                 if(ctlr->qhs == nil){
701                         ctlr->qhs = qhlinkqh(qh, qh);
702                         qh->eps0 |= Qhhigh | Qhhrl;
703                         coherence();
704                         ctlr->opio->link = PADDR(qh)|Lqh;
705                         coherence();
706                 }else{
707                         qhlinkqh(qh, ctlr->qhs->next);
708                         qhlinkqh(ctlr->qhs, qh);
709                 }
710                 break;
711         case Tintr:
712                 schedq(ctlr, qh, ep->pollival);
713                 break;
714         default:
715                 print("ehci: qhalloc called for ttype != ctl/bulk\n");
716         }
717         iunlock(ctlr);
718         return qh;
719 }
720
721 static int
722 qhadvanced(void *a)
723 {
724         Ctlr *ctlr;
725
726         ctlr = a;
727         return (ctlr->opio->cmd & Ciasync) == 0;
728 }
729
730 /*
731  * called when a qh is removed, to be sure the hw is not
732  * keeping pointers into it.
733  */
734 static void
735 qhcoherency(Ctlr *ctlr)
736 {
737         int i;
738
739         qlock(&ctlr->portlck);
740         ctlr->opio->cmd |= Ciasync;     /* ask for intr. on async advance */
741         coherence();
742         for(i = 0; i < 3 && qhadvanced(ctlr) == 0; i++){
743                 while(waserror())
744                         ;
745                 tsleep(ctlr, qhadvanced, ctlr, Abortdelay);
746                 poperror();
747         }
748         dprint("ehci: qhcoherency: doorbell %d\n", qhadvanced(ctlr));
749         if(i == 3)
750                 print("ehci: async advance doorbell did not ring\n");
751         ctlr->opio->cmd &= ~Ciasync;    /* try to clean */
752         qunlock(&ctlr->portlck);
753 }
754
755 static void
756 qhfree(Ctlr *ctlr, Qh *qh)
757 {
758         Td *td;
759         Qh *q;
760
761         ilock(ctlr);
762         if(qh->sched < 0){
763                 for(q = ctlr->qhs; q != nil; q = q->next)
764                         if(q->next == qh)
765                                 break;
766                 if(q == nil)
767                         panic("qhfree: nil q");
768                 q->next = qh->next;
769                 q->link = qh->link;
770                 coherence();
771         }else
772                 unschedq(ctlr, qh);
773         qh->state = Qfree;      /* paranoia */
774         iunlock(ctlr);
775
776         qhcoherency(ctlr);
777
778         while((td = qh->tds) != nil){
779                 qh->tds = td->next;
780                 tdfree(td);
781         }
782
783         edfree(qh);
784 }
785
786 static void
787 qhlinktd(Qh *qh, Td *td)
788 {
789         ulong csw;
790         int i;
791
792         csw = qh->csw;
793         qh->tds = td;
794         if(td == nil)
795                 qh->csw = (csw & ~Tdactive) | Tdhalt;
796         else{
797                 csw &= Tddata1 | Tdping;        /* save */
798                 qh->csw = Tdhalt;
799                 coherence();
800                 qh->tclink = 0;
801                 qh->alink = Lterm;
802                 qh->nlink = PADDR(td);
803                 for(i = 0; i < nelem(qh->buffer); i++)
804                         qh->buffer[i] = 0;
805                 coherence();
806                 qh->csw = csw & ~(Tdhalt|Tdactive);     /* activate next */
807         }
808         coherence();
809 }
810
811 static char*
812 seprintlink(char *s, char *se, char *name, ulong l, int typed)
813 {
814         s = seprint(s, se, "%s %ulx", name, l);
815         if((l & Lterm) != 0)
816                 return seprint(s, se, "T");
817         if(typed == 0)
818                 return s;
819         switch(l & (3<<1)){
820         case Litd:
821                 return seprint(s, se, "I");
822         case Lqh:
823                 return seprint(s, se, "Q");
824         case Lsitd:
825                 return seprint(s, se, "S");
826         default:
827                 return seprint(s, se, "F");
828         }
829 }
830
831 static char*
832 seprintitd(char *s, char *se, Itd *td)
833 {
834         int i;
835         ulong b0, b1;
836         char flags[6];
837         char *rw;
838
839         if(td == nil)
840                 return seprint(s, se, "<nil itd>\n");
841         b0 = td->buffer[0];
842         b1 = td->buffer[1];
843
844         s = seprint(s, se, "itd %#p", td);
845         rw = (b1 & Itdin) ? "in" : "out";
846         s = seprint(s, se, " %s ep %uld dev %uld max %uld mult %uld",
847                 rw, (b0>>8)&Epmax, (b0&Devmax),
848                 td->buffer[1] & 0x7ff, b1 & 3);
849         s = seprintlink(s, se, " link", td->link, 1);
850         s = seprint(s, se, "\n");
851         for(i = 0; i < nelem(td->csw); i++){
852                 memset(flags, '-', 5);
853                 if((td->csw[i] & Itdactive) != 0)
854                         flags[0] = 'a';
855                 if((td->csw[i] & Itdioc) != 0)
856                         flags[1] = 'i';
857                 if((td->csw[i] & Itddberr) != 0)
858                         flags[2] = 'd';
859                 if((td->csw[i] & Itdbabble) != 0)
860                         flags[3] = 'b';
861                 if((td->csw[i] & Itdtrerr) != 0)
862                         flags[4] = 't';
863                 flags[5] = 0;
864                 s = seprint(s, se, "\ttd%d %s", i, flags);
865                 s = seprint(s, se, " len %uld", (td->csw[i] >> 16) & 0x7ff);
866                 s = seprint(s, se, " pg %uld", (td->csw[i] >> 12) & 0x7);
867                 s = seprint(s, se, " off %uld\n", td->csw[i] & 0xfff);
868         }
869         s = seprint(s, se, "\tbuffs:");
870         for(i = 0; i < nelem(td->buffer); i++)
871                 s = seprint(s, se, " %#lux", td->buffer[i] >> 12);
872         return seprint(s, se, "\n");
873 }
874
875 static char*
876 seprintsitd(char *s, char *se, Sitd *td)
877 {
878         char rw, pg, ss;
879         char flags[8];
880         static char pc[4] = { 'a', 'b', 'm', 'e' };
881
882         if(td == nil)
883                 return seprint(s, se, "<nil sitd>\n");
884         s = seprint(s, se, "sitd %#p", td);
885         rw = (td->epc & Stdin) ? 'r' : 'w';
886         s = seprint(s, se, " %c ep %uld dev %uld",
887                 rw, (td->epc>>8)&0xf, td->epc&0x7f);
888         s = seprint(s, se, " max %uld", (td->csw >> 16) & 0x3ff);
889         s = seprint(s, se, " hub %uld", (td->epc >> 16) & 0x7f);
890         s = seprint(s, se, " port %uld\n", (td->epc >> 24) & 0x7f);
891         memset(flags, '-', 7);
892         if((td->csw & Stdactive) != 0)
893                 flags[0] = 'a';
894         if((td->csw & Stdioc) != 0)
895                 flags[1] = 'i';
896         if((td->csw & Stderr) != 0)
897                 flags[2] = 'e';
898         if((td->csw & Stddberr) != 0)
899                 flags[3] = 'd';
900         if((td->csw & Stdbabble) != 0)
901                 flags[4] = 'b';
902         if((td->csw & Stdtrerr) != 0)
903                 flags[5] = 't';
904         if((td->csw & Stdmmf) != 0)
905                 flags[6] = 'n';
906         flags[7] = 0;
907         ss = (td->csw & Stddcs) ? 'c' : 's';
908         pg = (td->csw & Stdpg) ? '1' : '0';
909         s = seprint(s, se, "\t%s %cs pg%c", flags, ss, pg);
910         s = seprint(s, se, " b0 %#lux b1 %#lux off %uld\n",
911                 td->buffer[0] >> 12, td->buffer[1] >> 12, td->buffer[0] & 0xfff);
912         s = seprint(s, se, "\ttpos %c tcnt %uld",
913                 pc[(td->buffer[0]>>3)&3], td->buffer[1] & 7);
914         s = seprint(s, se, " ssm %#lux csm %#lux cspm %#lux",
915                 td->mfs & 0xff, (td->mfs>>8) & 0xff, (td->csw>>8) & 0xff);
916         s = seprintlink(s, se, " link", td->link, 1);
917         s = seprintlink(s, se, " blink", td->blink, 0);
918         return seprint(s, se, "\n");
919 }
920
921 static long
922 maxtdlen(Td *td)
923 {
924         return (td->csw >> Tdlenshift) & Tdlenmask;
925 }
926
927 static long
928 tdlen(Td *td)
929 {
930         if(td->data == nil)
931                 return 0;
932         return td->ndata - maxtdlen(td);
933 }
934
935 static char*
936 seprinttd(char *s, char *se, Td *td, char *tag)
937 {
938         int i;
939         char t, ss;
940         char flags[9];
941         static char *tok[4] = { "out", "in", "setup", "BUG" };
942
943         if(td == nil)
944                 return seprint(s, se, "%s <nil td>\n", tag);
945         s = seprint(s, se, "%s %#p", tag, td);
946         s = seprintlink(s, se, " nlink", td->nlink, 0);
947         s = seprintlink(s, se, " alink", td->alink, 0);
948         s = seprint(s, se, " %s", tok[(td->csw & Tdtok) >> 8]);
949         if((td->csw & Tdping) != 0)
950                 s = seprint(s, se, " png");
951         memset(flags, '-', 8);
952         if((td->csw & Tdactive) != 0)
953                 flags[0] = 'a';
954         if((td->csw & Tdioc) != 0)
955                 flags[1] = 'i';
956         if((td->csw & Tdhalt) != 0)
957                 flags[2] = 'h';
958         if((td->csw & Tddberr) != 0)
959                 flags[3] = 'd';
960         if((td->csw & Tdbabble) != 0)
961                 flags[4] = 'b';
962         if((td->csw & Tdtrerr) != 0)
963                 flags[5] = 't';
964         if((td->csw & Tdmmf) != 0)
965                 flags[6] = 'n';
966         if((td->csw & (Tderr2|Tderr1)) == 0)
967                 flags[7] = 'z';
968         flags[8] = 0;
969         t = (td->csw & Tddata1) ? '1' : '0';
970         ss = (td->csw & Tddcs) ? 'c' : 's';
971         s = seprint(s, se, "\n\td%c %s %cs", t, flags, ss);
972         s = seprint(s, se, " max %uld", maxtdlen(td));
973         s = seprint(s, se, " pg %uld off %#lux\n",
974                 (td->csw >> Tdpgshift) & Tdpgmask, td->buffer[0] & 0xFFF);
975         s = seprint(s, se, "\tbuffs:");
976         for(i = 0; i < nelem(td->buffer); i++)
977                 s = seprint(s, se, " %#lux", td->buffer[i]>>12);
978         if(td->data != nil)
979                 s = seprintdata(s, se, td->data, td->ndata);
980         return seprint(s, se, "\n");
981 }
982
983 static void
984 dumptd(Td *td, char *pref)
985 {
986         char buf[256];
987         char *se;
988         int i;
989
990         i = 0;
991         se = buf+sizeof(buf);
992         for(; td != nil; td = td->next){
993                 seprinttd(buf, se, td, pref);
994                 print("%s", buf);
995                 if(i++ > 20){
996                         print("...more tds...\n");
997                         break;
998                 }
999         }
1000 }
1001
1002 static void
1003 qhdump(Qh *qh)
1004 {
1005         char buf[256];
1006         char *s, *se, *tag;
1007         Td td;
1008         static char *speed[] = {"full", "low", "high", "BUG"};
1009
1010         if(qh == nil){
1011                 print("<nil qh>\n");
1012                 return;
1013         }
1014         if(qh->io == nil)
1015                 tag = "qh";
1016         else
1017                 tag = qh->io->tag;
1018         se = buf+sizeof(buf);
1019         s = seprint(buf, se, "%s %#p", tag, qh);
1020         s = seprint(s, se, " ep %uld dev %uld",
1021                 (qh->eps0>>8)&0xf, qh->eps0&0x7f);
1022         s = seprint(s, se, " hub %uld", (qh->eps1 >> 16) & 0x7f);
1023         s = seprint(s, se, " port %uld", (qh->eps1 >> 23) & 0x7f);
1024         s = seprintlink(s, se, " link", qh->link, 1);
1025         seprint(s, se, "  clink %#lux", qh->tclink);
1026         print("%s\n", buf);
1027         s = seprint(buf, se, "\tnrld %uld", (qh->eps0 >> Qhrlcshift) & Qhrlcmask);
1028         s = seprint(s, se, " nak %uld", (qh->alink >> 1) & 0xf);
1029         s = seprint(s, se, " max %uld ", qhmaxpkt(qh));
1030         if((qh->eps0 & Qhnhctl) != 0)
1031                 s = seprint(s, se, "c");
1032         if((qh->eps0 & Qhhrl) != 0)
1033                 s = seprint(s, se, "h");
1034         if((qh->eps0 & Qhdtc) != 0)
1035                 s = seprint(s, se, "d");
1036         if((qh->eps0 & Qhint) != 0)
1037                 s = seprint(s, se, "i");
1038         s = seprint(s, se, " %s", speed[(qh->eps0 >> 12) & 3]);
1039         s = seprint(s, se, " mult %uld", (qh->eps1 >> Qhmultshift) & Qhmultmask);
1040         seprint(s, se, " scm %#lux ism %#lux\n",
1041                 (qh->eps1 >> 8 & 0xff), qh->eps1 & 0xff);
1042         print("%s\n", buf);
1043         memset(&td, 0, sizeof(td));
1044         memmove(&td, &qh->nlink, 32);   /* overlay area */
1045         seprinttd(buf, se, &td, "\tovl");
1046         print("%s", buf);
1047 }
1048
1049 static void
1050 isodump(Isoio* iso, int all)
1051 {
1052         Itd *td, *tdi, *tdu;
1053         Sitd *std, *stdi, *stdu;
1054         char buf[256];
1055         int i;
1056
1057         if(iso == nil){
1058                 print("<nil iso>\n");
1059                 return;
1060         }
1061         print("iso %#p %s %s speed state %d nframes %d maxsz %uld",
1062                 iso, iso->tok == Tdtokin ? "in" : "out",
1063                 iso->hs ? "high" : "full",
1064                 iso->state, iso->nframes, iso->maxsize);
1065         print(" td0 %uld tdi %#p tdu %#p data %#p\n",
1066                 iso->td0frno, iso->tdi, iso->tdu, iso->data);
1067         if(iso->err != nil)
1068                 print("\terr %s\n", iso->err);
1069         if(iso->err != nil)
1070                 print("\terr='%s'\n", iso->err);
1071         if(all == 0)
1072                 if(iso->hs != 0){
1073                         tdi = iso->tdi;
1074                         seprintitd(buf, buf+sizeof(buf), tdi);
1075                         print("\ttdi %s\n", buf);
1076                         tdu = iso->tdu;
1077                         seprintitd(buf, buf+sizeof(buf), tdu);
1078                         print("\ttdu %s\n", buf);
1079                 }else{
1080                         stdi = iso->stdi;
1081                         seprintsitd(buf, buf+sizeof(buf), stdi);
1082                         print("\tstdi %s\n", buf);
1083                         stdu = iso->stdu;
1084                         seprintsitd(buf, buf+sizeof(buf), stdu);
1085                         print("\tstdu %s\n", buf);
1086                 }
1087         else
1088                 for(i = 0; i < Nisoframes; i++)
1089                         if(iso->tdps[i] != nil)
1090                                 if(iso->hs != 0){
1091                                         td = iso->itdps[i];
1092                                         seprintitd(buf, buf+sizeof(buf), td);
1093                                         if(td == iso->tdi)
1094                                                 print("i->");
1095                                         if(td == iso->tdu)
1096                                                 print("i->");
1097                                         print("[%d]\t%s", i, buf);
1098                                 }else{
1099                                         std = iso->sitdps[i];
1100                                         seprintsitd(buf, buf+sizeof(buf), std);
1101                                         if(std == iso->stdi)
1102                                                 print("i->");
1103                                         if(std == iso->stdu)
1104                                                 print("u->");
1105                                         print("[%d]\t%s", i, buf);
1106                                 }
1107 }
1108
1109 static void
1110 dump(Hci *hp)
1111 {
1112         int i;
1113         char *s, *se;
1114         char buf[128];
1115         Ctlr *ctlr;
1116         Eopio *opio;
1117         Isoio *iso;
1118         Qh *qh;
1119
1120         ctlr = hp->aux;
1121         opio = ctlr->opio;
1122         ilock(ctlr);
1123         print("ehci port %#p frames %#p (%d fr.) nintr %d ntdintr %d",
1124                 ctlr->capio, ctlr->frames, ctlr->nframes,
1125                 ctlr->nintr, ctlr->ntdintr);
1126         print(" nqhintr %d nisointr %d\n", ctlr->nqhintr, ctlr->nisointr);
1127         print("\tcmd %#lux sts %#lux intr %#lux frno %uld",
1128                 opio->cmd, opio->sts, opio->intr, opio->frno);
1129         print(" base %#lux link %#lux fr0 %#lux\n",
1130                 opio->frbase, opio->link, ctlr->frames[0]);
1131         se = buf+sizeof(buf);
1132         s = seprint(buf, se, "\t");
1133         for(i = 0; i < hp->nports; i++){
1134                 s = seprint(s, se, "p%d %#lux ", i, opio->portsc[i]);
1135                 if(hp->nports > 4 && i == hp->nports/2 - 1)
1136                         s = seprint(s, se, "\n\t");
1137         }
1138         print("%s\n", buf);
1139         qh = ctlr->qhs;
1140         i = 0;
1141         do{
1142                 qhdump(qh);
1143                 qh = qh->next;
1144         }while(qh != ctlr->qhs && i++ < 100);
1145         if(i > 100)
1146                 print("...too many Qhs...\n");
1147         if(ctlr->intrqhs != nil)
1148                 print("intr qhs:\n");
1149         for(qh = ctlr->intrqhs; qh != nil; qh = qh->inext)
1150                 qhdump(qh);
1151         if(ctlr->iso != nil)
1152                 print("iso:\n");
1153         for(iso = ctlr->iso; iso != nil; iso = iso->next)
1154                 isodump(ctlr->iso, 0);
1155         print("%d eds in tree\n", ctlr->ntree);
1156         iunlock(ctlr);
1157         lock(&edpool);
1158         print("%d eds allocated = %d in use + %d free\n",
1159                 edpool.nalloc, edpool.ninuse, edpool.nfree);
1160         unlock(&edpool);
1161 }
1162
1163 static char*
1164 errmsg(int err)
1165 {
1166         if(err == 0)
1167                 return "ok";
1168         if(err & Tddberr)
1169                 return "data buffer error";
1170         if(err & Tdbabble)
1171                 return "babble detected";
1172         if(err & Tdtrerr)
1173                 return "transaction error";
1174         if(err & Tdmmf)
1175                 return "missed µframe";
1176         if(err & Tdhalt)
1177                 return Estalled;        /* [uo]hci report this error */
1178         return Eio;
1179 }
1180
1181 static char*
1182 ierrmsg(int err)
1183 {
1184         if(err == 0)
1185                 return "ok";
1186         if(err & Itddberr)
1187                 return "data buffer error";
1188         if(err & Itdbabble)
1189                 return "babble detected";
1190         if(err & Itdtrerr)
1191                 return "transaction error";
1192         return Eio;
1193 }
1194
1195 static char*
1196 serrmsg(int err)
1197 {
1198         if(err & Stderr)
1199                 return "translation translator error";
1200         /* other errors have same numbers than Td errors */
1201         return errmsg(err);
1202 }
1203
1204 static int
1205 isocanread(void *a)
1206 {
1207         Isoio *iso;
1208
1209         iso = a;
1210         if(iso->state == Qclose)
1211                 return 1;
1212         if(iso->state == Qrun && iso->tok == Tdtokin){
1213                 if(iso->hs != 0 && iso->tdi != iso->tdu)
1214                         return 1;
1215                 if(iso->hs == 0 && iso->stdi != iso->stdu)
1216                         return 1;
1217         }
1218         return 0;
1219 }
1220
1221 static int
1222 isocanwrite(void *a)
1223 {
1224         Isoio *iso;
1225
1226         iso = a;
1227         if(iso->state == Qclose)
1228                 return 1;
1229         if(iso->state == Qrun && iso->tok == Tdtokout){
1230                 if(iso->hs != 0 && iso->tdu->next != iso->tdi)
1231                         return 1;
1232                 if(iso->hs == 0 && iso->stdu->next != iso->stdi)
1233                         return 1;
1234         }
1235         return 0;
1236 }
1237
1238 static void
1239 itdinit(Isoio *iso, Itd *td)
1240 {
1241         int p, t;
1242         ulong pa, tsize, size;
1243
1244         /*
1245          * BUG: This does not put an integral number of samples
1246          * on each µframe unless samples per packet % 8 == 0
1247          * Also, all samples are packed early on each frame.
1248          */
1249         p = 0;
1250         size = td->ndata = td->mdata;
1251         pa = PADDR(td->data);
1252         for(t = 0; size > 0 && t < 8; t++){
1253                 tsize = size;
1254                 if(tsize > iso->maxsize)
1255                         tsize = iso->maxsize;
1256                 size -= tsize;
1257                 assert(p < nelem(td->buffer));
1258                 td->csw[t] = tsize << Itdlenshift | p << Itdpgshift |
1259                         (pa & 0xFFF) << Itdoffshift | Itdactive | Itdioc;
1260                 coherence();
1261                 if(((pa+tsize) & ~0xFFF) != (pa & ~0xFFF))
1262                         p++;
1263                 pa += tsize;
1264         }
1265 }
1266
1267 static void
1268 sitdinit(Isoio *iso, Sitd *td)
1269 {
1270         td->ndata = td->mdata & Stdlenmask;
1271         td->buffer[0] = PADDR(td->data);
1272         td->buffer[1] = (td->buffer[0] & ~0xFFF) + 0x1000;
1273         if(iso->tok == Tdtokin || td->ndata <= 188)
1274                 td->buffer[1] |= Stdtpall;
1275         else
1276                 td->buffer[1] |= Stdtpbegin;
1277         if(iso->tok == Tdtokin)
1278                 td->buffer[1] |= 1;
1279         else
1280                 td->buffer[1] |= ((td->ndata + 187) / 188) & Stdtcntmask;
1281         coherence();
1282         td->csw = td->ndata << Stdlenshift | Stdactive | Stdioc;
1283         coherence();
1284 }
1285
1286 static int
1287 itdactive(Itd *td)
1288 {
1289         int i;
1290
1291         for(i = 0; i < nelem(td->csw); i++)
1292                 if((td->csw[i] & Itdactive) != 0)
1293                         return 1;
1294         return 0;
1295 }
1296
1297 static int
1298 isodelay(void *a)
1299 {
1300         Isoio *iso;
1301         int delay;
1302
1303         iso = a;
1304         if(iso->state == Qclose || iso->err || iso->delay == 0)
1305                 return 1;
1306
1307         delay = 0;
1308         if(iso->hs){
1309                 Itd *i;
1310
1311                 for(i = iso->tdi; i->next != iso->tdu; i = i->next){
1312                         if(!itdactive(i))
1313                                 continue;
1314                         delay += i->mdata;
1315                         if(delay > iso->delay)
1316                                 break;
1317                 }
1318         } else {
1319                 Sitd *i;
1320
1321                 for(i = iso->stdi; i->next != iso->stdu; i = i->next){
1322                         if((i->csw & Stdactive) == 0)
1323                                 continue;
1324                         delay += i->mdata;
1325                         if(delay > iso->delay)
1326                                 break;
1327                 }
1328         }
1329
1330         return delay <= iso->delay;
1331 }
1332
1333
1334 static int
1335 isohsinterrupt(Ctlr *ctlr, Isoio *iso)
1336 {
1337         int err, i, nframes, t;
1338         Itd *tdi;
1339
1340         tdi = iso->tdi;
1341         if(tdi == nil || itdactive(tdi))                        /* not all tds are done */
1342                 return 0;
1343         ctlr->nisointr++;
1344         ddiprint("isohsintr: iso %#p: tdi %#p tdu %#p\n", iso, tdi, iso->tdu);
1345         if(iso->state != Qrun && iso->state != Qdone)
1346                 panic("isofsintr: iso state");
1347         if(ehcidebug > 1 || iso->debug > 1)
1348                 isodump(iso, 0);
1349
1350         nframes = iso->nframes / 2;             /* limit how many we look */
1351         if(nframes > Nisoframes)
1352                 nframes = Nisoframes;
1353
1354         if(iso->tok == Tdtokin)
1355                 tdi->ndata = 0;
1356         /* else, it has the number of bytes transferred */
1357
1358         for(i = 0; i < nframes && itdactive(tdi) == 0; i++){
1359                 if(iso->tok == Tdtokin)
1360                         tdi->ndata += (tdi->csw[i] >> Itdlenshift) & Itdlenmask;
1361                 err = 0;
1362                 coherence();
1363                 for(t = 0; t < nelem(tdi->csw); t++){
1364                         tdi->csw[t] &= ~Itdioc;
1365                         coherence();
1366                         err |= tdi->csw[t] & Itderrors;
1367                 }
1368                 if(err == 0)
1369                         iso->nerrs = 0;
1370                 else if(iso->nerrs++ > iso->nframes/2){
1371                         if(iso->err == nil){
1372                                 iso->err = ierrmsg(err);
1373                                 diprint("isohsintr: tdi %#p error %#ux %s\n",
1374                                         tdi, err, iso->err);
1375                                 diprint("ctlr load %uld\n", ctlr->load);
1376                         }
1377                         tdi->ndata = 0;
1378                 }else
1379                         tdi->ndata = 0;
1380                 if(tdi->next == iso->tdu || tdi->next->next == iso->tdu){
1381                         memset(iso->tdu->data, 0, iso->tdu->mdata);
1382                         itdinit(iso, iso->tdu);
1383                         iso->tdu = iso->tdu->next;
1384                         iso->nleft = 0;
1385                 }
1386                 tdi = tdi->next;
1387                 coherence();
1388         }
1389         ddiprint("isohsintr: %d frames processed\n", nframes);
1390         if(i == nframes){
1391                 tdi->csw[0] |= Itdioc;
1392                 coherence();
1393         }
1394         iso->tdi = tdi;
1395         coherence();
1396         if(isocanwrite(iso) || isocanread(iso)){
1397                 diprint("wakeup iso %#p tdi %#p tdu %#p\n", iso,
1398                         iso->tdi, iso->tdu);
1399                 wakeup(iso);
1400         }
1401         return 1;
1402 }
1403
1404 static int
1405 isofsinterrupt(Ctlr *ctlr, Isoio *iso)
1406 {
1407         int err, i, nframes;
1408         Sitd *stdi;
1409
1410         stdi = iso->stdi;
1411         if(stdi == nil || (stdi->csw & Stdactive) != 0)         /* nothing new done */
1412                 return 0;
1413         ctlr->nisointr++;
1414         ddiprint("isofsintr: iso %#p: tdi %#p tdu %#p\n", iso, stdi, iso->stdu);
1415         if(iso->state != Qrun && iso->state != Qdone)
1416                 panic("isofsintr: iso state");
1417         if(ehcidebug > 1 || iso->debug > 1)
1418                 isodump(iso, 0);
1419
1420         nframes = iso->nframes / 2;             /* limit how many we look */
1421         if(nframes > Nisoframes)
1422                 nframes = Nisoframes;
1423
1424         for(i = 0; i < nframes && (stdi->csw & Stdactive) == 0; i++){
1425                 stdi->csw &= ~Stdioc;
1426                 /* write back csw and see if it produces errors */
1427                 coherence();
1428                 err = stdi->csw & Stderrors;
1429                 if(err == 0){
1430                         iso->nerrs = 0;
1431                         if(iso->tok == Tdtokin)
1432                                 stdi->ndata = (stdi->csw>>Stdlenshift)&Stdlenmask;
1433                         /* else len is assumed correct */
1434                 }else if(iso->nerrs++ > iso->nframes/2){
1435                         if(iso->err == nil){
1436                                 iso->err = serrmsg(err);
1437                                 diprint("isofsintr: tdi %#p error %#ux %s\n",
1438                                         stdi, err, iso->err);
1439                                 diprint("ctlr load %uld\n", ctlr->load);
1440                         }
1441                         stdi->ndata = 0;
1442                 }else
1443                         stdi->ndata = 0;
1444
1445                 if(stdi->next == iso->stdu || stdi->next->next == iso->stdu){
1446                         memset(iso->stdu->data, 0, iso->stdu->mdata);
1447                         coherence();
1448                         sitdinit(iso, iso->stdu);
1449                         iso->stdu = iso->stdu->next;
1450                         iso->nleft = 0;
1451                 }
1452                 coherence();
1453                 stdi = stdi->next;
1454         }
1455         ddiprint("isofsintr: %d frames processed\n", nframes);
1456         if(i == nframes){
1457                 stdi->csw |= Stdioc;
1458                 coherence();
1459         }
1460         iso->stdi = stdi;
1461         coherence();
1462         if(isocanwrite(iso) || isocanread(iso)){
1463                 diprint("wakeup iso %#p tdi %#p tdu %#p\n", iso,
1464                         iso->stdi, iso->stdu);
1465                 wakeup(iso);
1466         }
1467         return 1;
1468 }
1469
1470 static int
1471 qhinterrupt(Ctlr *ctlr, Qh *qh)
1472 {
1473         Td *td;
1474         int err;
1475
1476         if(qh->state != Qrun)
1477                 panic("qhinterrupt: qh state");
1478         td = qh->tds;
1479         if(td == nil)
1480                 return 0;
1481         if((td->csw & Tdactive) == 0)
1482                 ddqprint("qhinterrupt port %#p qh %#p\n", ctlr->capio, qh);
1483         for(; td != nil; td = td->next){
1484                 if(td->csw & Tdactive)
1485                         return 0;
1486                 err = td->csw & Tderrors;
1487                 if(err != 0){
1488                         if(qh->io->err == nil){
1489                                 qh->io->err = errmsg(err);
1490                                 dqprint("qhintr: td %#p csw %#lux error %#ux %s\n",
1491                                         td, td->csw, err, qh->io->err);
1492                         }
1493                         break;
1494                 }
1495                 td->ndata = tdlen(td);
1496                 coherence();
1497                 if(td->ndata < maxtdlen(td)){   /* EOT */
1498                         td = td->next;
1499                         break;
1500                 }
1501         }
1502         /*
1503          * Done. Make void the Tds not used (errors or EOT) and wakeup epio.
1504          */
1505         for(; td != nil; td = td->next)
1506                 td->ndata = 0;
1507         coherence();
1508         qh->state = Qdone;
1509         coherence();
1510         wakeup(qh->io);
1511         return 1;
1512 }
1513
1514 static int
1515 ctlrinterrupt(Ctlr *ctlr)
1516 {
1517         Eopio *opio;
1518         Isoio *iso;
1519         ulong sts;
1520         Qh *qh;
1521         int i, some;
1522
1523         opio = ctlr->opio;
1524         /*
1525          * Will we know in USB 3.0 who the interrupt was for?.
1526          * Do they still teach indexing in CS?
1527          * This is Intel's doing.
1528          */
1529         sts = opio->sts & Sintrs;
1530         if(sts == 0)            /* not ours; shared intr. */
1531                 return 0;
1532         opio->sts = sts;
1533         coherence();
1534         ctlr->nintr++;
1535         if((sts & Sherr) != 0)
1536                 iprint("ehci: port %#p fatal host system error\n", ctlr->capio);
1537         if((sts & Shalted) != 0)
1538                 iprint("ehci: port %#p: halted\n", ctlr->capio);
1539         if((sts & Sasync) != 0){
1540                 dprint("ehci: doorbell\n");
1541                 wakeup(ctlr);
1542         }
1543         /*
1544          * We enter always this if, even if it seems the
1545          * interrupt does not report anything done/failed.
1546          * Some controllers don't post interrupts right.
1547          */
1548         some = 0;
1549         if((sts & (Serrintr|Sintr)) != 0){
1550                 ctlr->ntdintr++;
1551                 if(ehcidebug > 1){
1552                         iprint("ehci port %#p frames %#p nintr %d ntdintr %d",
1553                                 ctlr->capio, ctlr->frames,
1554                                 ctlr->nintr, ctlr->ntdintr);
1555                         iprint(" nqhintr %d nisointr %d\n",
1556                                 ctlr->nqhintr, ctlr->nisointr);
1557                         iprint("\tcmd %#lux sts %#lux intr %#lux frno %uld",
1558                                 opio->cmd, opio->sts, opio->intr, opio->frno);
1559                 }
1560
1561                 /* process the Iso transfers */
1562                 for(iso = ctlr->iso; iso != nil; iso = iso->next)
1563                         if(iso->state == Qrun || iso->state == Qdone)
1564                                 if(iso->hs != 0)
1565                                         some += isohsinterrupt(ctlr, iso);
1566                                 else
1567                                         some += isofsinterrupt(ctlr, iso);
1568
1569                 /* process the qhs in the periodic tree */
1570                 for(qh = ctlr->intrqhs; qh != nil; qh = qh->inext)
1571                         if(qh->state == Qrun)
1572                                 some += qhinterrupt(ctlr, qh);
1573
1574                 /* process the async Qh circular list */
1575                 qh = ctlr->qhs;
1576                 i = 0;
1577                 do{
1578                         if(qh == nil)
1579                                 break;
1580                         if(qh->state == Qrun)
1581                                 some += qhinterrupt(ctlr, qh);
1582                         qh = qh->next;
1583                 }while(qh != ctlr->qhs && i++ < 100);
1584                 if(i > 100)
1585                         iprint("echi: interrupt: qh loop?\n");
1586         }
1587         return some;
1588 }
1589
1590 static int
1591 ehciintr(Hci *hp)
1592 {
1593         Ctlr *ctlr;
1594         int some;
1595
1596         ctlr = hp->aux;
1597         ilock(ctlr);
1598         some = ctlrinterrupt(ctlr);
1599         iunlock(ctlr);
1600         return some;
1601 }
1602
1603 static void
1604 interrupt(Ureg*, void* a)
1605 {
1606         ehciintr(a);
1607 }
1608
1609 static int
1610 portenable(Hci *hp, int port, int on)
1611 {
1612         Ctlr *ctlr;
1613         Eopio *opio;
1614         int s;
1615
1616         ctlr = hp->aux;
1617         opio = ctlr->opio;
1618         s = opio->portsc[port-1];
1619         eqlock(&ctlr->portlck);
1620         if(waserror()){
1621                 qunlock(&ctlr->portlck);
1622                 nexterror();
1623         }
1624         dprint("ehci %#p port %d enable=%d; sts %#x\n",
1625                 ctlr->capio, port, on, s);
1626         ilock(ctlr);
1627         if(s & (Psstatuschg | Pschange))
1628                 opio->portsc[port-1] = s;
1629         if(on)
1630                 opio->portsc[port-1] |= Psenable;
1631         else
1632                 opio->portsc[port-1] &= ~Psenable;
1633         coherence();
1634         microdelay(64);
1635         iunlock(ctlr);
1636         tsleep(&up->sleep, return0, 0, Enabledelay);
1637         dprint("ehci %#p port %d enable=%d: sts %#lux\n",
1638                 ctlr->capio, port, on, opio->portsc[port-1]);
1639         qunlock(&ctlr->portlck);
1640         poperror();
1641         return 0;
1642 }
1643
1644 /*
1645  * If we detect during status that the port is low-speed or
1646  * during reset that it's full-speed, the device is not for
1647  * ourselves. The companion controller will take care.
1648  * Low-speed devices will not be seen by usbd. Full-speed
1649  * ones are seen because it's only after reset that we know what
1650  * they are (usbd may notice a device not enabled in this case).
1651  */
1652 static void
1653 portlend(Ctlr *ctlr, int port, char *ss)
1654 {
1655         Eopio *opio;
1656         ulong s;
1657
1658         opio = ctlr->opio;
1659
1660         dprint("ehci %#p port %d: %s speed device: no longer owned\n",
1661                 ctlr->capio, port, ss);
1662         s = opio->portsc[port-1] & ~(Pschange|Psstatuschg);
1663         opio->portsc[port-1] = s | Psowner;
1664         coherence();
1665 }
1666
1667 static int
1668 portreset(Hci *hp, int port, int on)
1669 {
1670         ulong *portscp;
1671         Eopio *opio;
1672         Ctlr *ctlr;
1673         int i;
1674
1675         if(on == 0)
1676                 return 0;
1677
1678         ctlr = hp->aux;
1679         opio = ctlr->opio;
1680         eqlock(&ctlr->portlck);
1681         if(waserror()){
1682                 iunlock(ctlr);
1683                 qunlock(&ctlr->portlck);
1684                 nexterror();
1685         }
1686         portscp = &opio->portsc[port-1];
1687         dprint("ehci %#p port %d reset; sts %#lux\n", ctlr->capio, port, *portscp);
1688         ilock(ctlr);
1689         /* Shalted must be zero, else Psreset will stay set */
1690         if (opio->sts & Shalted)
1691                 iprint("ehci %#p: halted yet trying to reset port\n",
1692                         ctlr->capio);
1693
1694         *portscp = (*portscp & ~Psenable) | Psreset;    /* initiate reset */
1695         /*
1696          * usb 2 spec: reset must finish within 20 ms.
1697          * linux says spec says it can take 50 ms. for hubs.
1698          */
1699         delay(50);
1700         *portscp &= ~Psreset;   /* terminate reset */
1701
1702         delay(10);
1703         for(i = 0; *portscp & Psreset && i < 10; i++)
1704                 delay(10);
1705
1706         if (*portscp & Psreset)
1707                 iprint("ehci %#p: port %d didn't reset; sts %#lux\n",
1708                         ctlr->capio, port, *portscp);
1709
1710         delay(10);                      /* ehci spec: enable within 2 ms. */
1711         if((*portscp & Psenable) == 0)
1712                 portlend(ctlr, port, "full");
1713
1714         iunlock(ctlr);
1715         dprint("ehci %#p after port %d reset; sts %#lux\n",
1716                 ctlr->capio, port, *portscp);
1717         qunlock(&ctlr->portlck);
1718         poperror();
1719         return 0;
1720 }
1721
1722 static int
1723 portstatus(Hci *hp, int port)
1724 {
1725         int s, r;
1726         Eopio *opio;
1727         Ctlr *ctlr;
1728
1729         ctlr = hp->aux;
1730         opio = ctlr->opio;
1731         eqlock(&ctlr->portlck);
1732         if(waserror()){
1733                 iunlock(ctlr);
1734                 qunlock(&ctlr->portlck);
1735                 nexterror();
1736         }
1737         ilock(ctlr);
1738         s = opio->portsc[port-1];
1739         if(s & (Psstatuschg | Pschange)){
1740                 opio->portsc[port-1] = s;
1741                 coherence();
1742                 ddprint("ehci %#p port %d status %#x\n", ctlr->capio, port, s);
1743         }
1744         /*
1745          * If the port is a low speed port we yield ownership now
1746          * to the [uo]hci companion controller and pretend it's not here.
1747          */
1748         if((s & Pspresent) != 0 && (s & Pslinemask) == Pslow){
1749                 portlend(ctlr, port, "low");
1750                 s &= ~Pspresent;                /* not for us this time */
1751         }
1752         iunlock(ctlr);
1753         qunlock(&ctlr->portlck);
1754         poperror();
1755
1756         /*
1757          * We must return status bits as a
1758          * get port status hub request would do.
1759          */
1760         r = 0;
1761         if(s & Pspresent)
1762                 r |= HPpresent|HPhigh;
1763         if(s & Psenable)
1764                 r |= HPenable;
1765         if(s & Pssuspend)
1766                 r |= HPsuspend;
1767         if(s & Psreset)
1768                 r |= HPreset;
1769         if(s & Psstatuschg)
1770                 r |= HPstatuschg;
1771         if(s & Pschange)
1772                 r |= HPchange;
1773         return r;
1774 }
1775
1776 static char*
1777 seprintio(char *s, char *e, Qio *io, char *pref)
1778 {
1779         s = seprint(s,e,"%s io %#p qh %#p id %#x", pref, io, io->qh, io->usbid);
1780         s = seprint(s,e," iot %ld", io->iotime);
1781         s = seprint(s,e," tog %#x tok %#x err %s", io->toggle, io->tok, io->err);
1782         return s;
1783 }
1784
1785 static char*
1786 seprintep(char *s, char *e, Ep *ep)
1787 {
1788         Qio *io;
1789         Ctlio *cio;
1790         Ctlr *ctlr;
1791
1792         ctlr = ep->hp->aux;
1793         ilock(ctlr);
1794         if(ep->aux == nil){
1795                 *s = 0;
1796                 iunlock(ctlr);
1797                 return s;
1798         }
1799         switch(ep->ttype){
1800         case Tctl:
1801                 cio = ep->aux;
1802                 s = seprintio(s, e, cio, "c");
1803                 s = seprint(s, e, "\trepl %d ndata %d\n", ep->rhrepl, cio->ndata);
1804                 break;
1805         case Tbulk:
1806         case Tintr:
1807                 io = ep->aux;
1808                 if(ep->mode != OWRITE)
1809                         s = seprintio(s, e, &io[OREAD], "r");
1810                 if(ep->mode != OREAD)
1811                         s = seprintio(s, e, &io[OWRITE], "w");
1812                 break;
1813         case Tiso:
1814                 *s = 0;
1815                 break;
1816         }
1817         iunlock(ctlr);
1818         return s;
1819 }
1820
1821 /*
1822  * halt condition was cleared on the endpoint. update our toggles.
1823  */
1824 static void
1825 clrhalt(Ep *ep)
1826 {
1827         Qio *io;
1828
1829         ep->clrhalt = 0;
1830         coherence();
1831         switch(ep->ttype){
1832         case Tintr:
1833         case Tbulk:
1834                 io = ep->aux;
1835                 if(ep->mode != OREAD){
1836                         qlock(&io[OWRITE]);
1837                         io[OWRITE].toggle = Tddata0;
1838                         deprint("ep clrhalt for io %#p\n", io+OWRITE);
1839                         qunlock(&io[OWRITE]);
1840                 }
1841                 if(ep->mode != OWRITE){
1842                         qlock(&io[OREAD]);
1843                         io[OREAD].toggle = Tddata0;
1844                         deprint("ep clrhalt for io %#p\n", io+OREAD);
1845                         qunlock(&io[OREAD]);
1846                 }
1847                 break;
1848         }
1849 }
1850
1851 static void
1852 xdump(char* pref, void *qh)
1853 {
1854         int i;
1855         ulong *u;
1856
1857         u = qh;
1858         print("%s %#p:", pref, u);
1859         for(i = 0; i < 16; i++)
1860                 if((i%4) == 0)
1861                         print("\n %#8.8ulx", u[i]);
1862                 else
1863                         print(" %#8.8ulx", u[i]);
1864         print("\n");
1865 }
1866
1867 static long
1868 episohscpy(Ctlr *ctlr, Ep *ep, Isoio* iso, uchar *b, long count)
1869 {
1870         int nr;
1871         long tot;
1872         Itd *tdu;
1873
1874         for(tot = 0; iso->tdi != iso->tdu && tot < count; tot += nr){
1875                 tdu = iso->tdu;
1876                 if(itdactive(tdu))
1877                         break;
1878                 nr = tdu->ndata;
1879                 if(tot + nr > count)
1880                         nr = count - tot;
1881                 if(nr == 0)
1882                         print("ehci: ep%d.%d: too many polls\n",
1883                                 ep->dev->nb, ep->nb);
1884                 else{
1885                         iunlock(ctlr);          /* We could page fault here */
1886                         memmove(b+tot, tdu->data, nr);
1887                         ilock(ctlr);
1888                         if(iso->tdu != tdu)
1889                                 continue;
1890                         if(nr < tdu->ndata)
1891                                 memmove(tdu->data, tdu->data+nr, tdu->ndata - nr);
1892                         tdu->ndata -= nr;
1893                         coherence();
1894                 }
1895                 if(tdu->ndata == 0){
1896                         itdinit(iso, tdu);
1897                         iso->tdu = tdu->next;
1898                 }
1899         }
1900         return tot;
1901 }
1902
1903 static long
1904 episofscpy(Ctlr *ctlr, Ep *ep, Isoio* iso, uchar *b, long count)
1905 {
1906         int nr;
1907         long tot;
1908         Sitd *stdu;
1909
1910         for(tot = 0; iso->stdi != iso->stdu && tot < count; tot += nr){
1911                 stdu = iso->stdu;
1912                 if(stdu->csw & Stdactive){
1913                         diprint("ehci: episoread: %#p tdu active\n", iso);
1914                         break;
1915                 }
1916                 nr = stdu->ndata;
1917                 if(tot + nr > count)
1918                         nr = count - tot;
1919                 if(nr == 0)
1920                         print("ehci: ep%d.%d: too many polls\n",
1921                                 ep->dev->nb, ep->nb);
1922                 else{
1923                         iunlock(ctlr);          /* We could page fault here */
1924                         memmove(b+tot, stdu->data, nr);
1925                         ilock(ctlr);
1926                         if(iso->stdu != stdu)
1927                                 continue;
1928                         if(nr < stdu->ndata)
1929                                 memmove(stdu->data, stdu->data+nr,
1930                                         stdu->ndata - nr);
1931                         stdu->ndata -= nr;
1932                         coherence();
1933                 }
1934                 if(stdu->ndata == 0){
1935                         sitdinit(iso, stdu);
1936                         iso->stdu = stdu->next;
1937                 }
1938         }
1939         return tot;
1940 }
1941
1942 static long
1943 episoread(Ep *ep, Isoio *iso, void *a, long count)
1944 {
1945         Ctlr *ctlr;
1946         uchar *b;
1947         long tot;
1948
1949         iso->debug = ep->debug;
1950         diprint("ehci: episoread: %#p ep%d.%d\n", iso, ep->dev->nb, ep->nb);
1951
1952         b = a;
1953         ctlr = ep->hp->aux;
1954         eqlock(iso);
1955         if(waserror()){
1956                 qunlock(iso);
1957                 nexterror();
1958         }
1959         iso->err = nil;
1960         iso->nerrs = 0;
1961         ilock(ctlr);
1962         if(iso->state == Qclose){
1963                 iunlock(ctlr);
1964                 error(iso->err ? iso->err : Eio);
1965         }
1966         iso->state = Qrun;
1967         coherence();
1968         while(isocanread(iso) == 0){
1969                 iunlock(ctlr);
1970                 diprint("ehci: episoread: %#p sleep\n", iso);
1971                 if(waserror()){
1972                         if(iso->err == nil)
1973                                 iso->err = "I/O timed out";
1974                         ilock(ctlr);
1975                         break;
1976                 }
1977                 tsleep(iso, isocanread, iso, ep->tmout);
1978                 poperror();
1979                 ilock(ctlr);
1980         }
1981         if(iso->state == Qclose){
1982                 iunlock(ctlr);
1983                 error(iso->err ? iso->err : Eio);
1984         }
1985         iso->state = Qdone;
1986         coherence();
1987         assert(iso->tdu != iso->tdi);
1988
1989         if(iso->hs != 0)
1990                 tot = episohscpy(ctlr, ep, iso, b, count);
1991         else
1992                 tot = episofscpy(ctlr, ep, iso, b, count);
1993         iunlock(ctlr);
1994         qunlock(iso);
1995         poperror();
1996         diprint("uhci: episoread: %#p %uld bytes err '%s'\n", iso, tot, iso->err);
1997         if(iso->err != nil)
1998                 error(iso->err);
1999         return tot;
2000 }
2001
2002 /*
2003  * iso->tdu is the next place to put data. When it gets full
2004  * it is activated and tdu advanced.
2005  */
2006 static long
2007 putsamples(Ctlr *ctlr, Isoio *iso, uchar *b, long count)
2008 {
2009         long left, tot, n;
2010         Sitd *stdu;
2011         Itd *tdu;
2012
2013         for(tot = 0; isocanwrite(iso) && tot < count; tot += n){
2014                 n = count-tot;
2015                 left = iso->nleft;
2016                 if(iso->hs != 0){
2017                         tdu = iso->tdu;
2018                         if(n > tdu->mdata - left)
2019                                 n = tdu->mdata - left;
2020                         iunlock(ctlr);          /* We could page fault here */
2021                         memmove(tdu->data + left, b + tot, n);
2022                         ilock(ctlr);
2023                         if(iso->tdu != tdu)
2024                                 continue;
2025                         iso->nleft += n;
2026                         if(iso->nleft == tdu->mdata){
2027                                 itdinit(iso, tdu);
2028                                 iso->tdu = tdu->next;
2029                                 iso->nleft = 0;
2030                         }
2031                 }else{
2032                         stdu = iso->stdu;
2033                         if(n > stdu->mdata - left)
2034                                 n = stdu->mdata - left;
2035                         iunlock(ctlr);          /* We could page fault here */
2036                         memmove(stdu->data + left, b + tot, n);
2037                         ilock(ctlr);
2038                         if(iso->stdu != stdu)
2039                                 continue;
2040                         iso->nleft += n;
2041                         if(iso->nleft == stdu->mdata){
2042                                 sitdinit(iso, stdu);
2043                                 iso->stdu = stdu->next;
2044                                 iso->nleft = 0;
2045                         }
2046                 }
2047         }
2048         return tot;
2049 }
2050
2051 /*
2052  * Queue data for writing and return error status from
2053  * last writes done, to maintain buffered data.
2054  */
2055 static long
2056 episowrite(Ep *ep, Isoio *iso, void *a, long count)
2057 {
2058         Ctlr *ctlr;
2059         uchar *b;
2060         int tot, nw;
2061         char *err;
2062
2063         iso->delay = ep->sampledelay * ep->samplesz;
2064         iso->debug = ep->debug;
2065         diprint("ehci: episowrite: %#p ep%d.%d\n", iso, ep->dev->nb, ep->nb);
2066
2067         ctlr = ep->hp->aux;
2068         eqlock(iso);
2069         if(waserror()){
2070                 qunlock(iso);
2071                 nexterror();
2072         }
2073         ilock(ctlr);
2074         if(iso->state == Qclose){
2075                 iunlock(ctlr);
2076                 error(iso->err ? iso->err : Eio);
2077         }
2078         iso->state = Qrun;
2079         coherence();
2080         b = a;
2081         for(tot = 0; tot < count; tot += nw){
2082                 while(isocanwrite(iso) == 0){
2083                         iunlock(ctlr);
2084                         diprint("ehci: episowrite: %#p sleep\n", iso);
2085                         if(waserror()){
2086                                 if(iso->err == nil)
2087                                         iso->err = "I/O timed out";
2088                                 ilock(ctlr);
2089                                 break;
2090                         }
2091                         tsleep(iso, isocanwrite, iso, ep->tmout);
2092                         poperror();
2093                         ilock(ctlr);
2094                 }
2095                 err = iso->err;
2096                 iso->err = nil;
2097                 if(iso->state == Qclose || err != nil){
2098                         iunlock(ctlr);
2099                         error(err ? err : Eio);
2100                 }
2101                 if(iso->state != Qrun)
2102                         panic("episowrite: iso not running");
2103                 nw = putsamples(ctlr, iso, b+tot, count-tot);
2104         }
2105         while(isodelay(iso) == 0){
2106                 iunlock(ctlr);
2107                 sleep(iso, isodelay, iso);
2108                 ilock(ctlr);
2109         }
2110         if(iso->state != Qclose)
2111                 iso->state = Qdone;
2112         iunlock(ctlr);
2113         err = iso->err;         /* in case it failed early */
2114         iso->err = nil;
2115         qunlock(iso);
2116         poperror();
2117         if(err != nil)
2118                 error(err);
2119         diprint("ehci: episowrite: %#p %d bytes\n", iso, tot);
2120         return tot;
2121 }
2122
2123 static int
2124 nexttoggle(int toggle, int count, int maxpkt)
2125 {
2126         int np;
2127
2128         np = count / maxpkt;
2129         if(np == 0)
2130                 np = 1;
2131         if((np % 2) == 0)
2132                 return toggle;
2133         if(toggle == Tddata1)
2134                 return Tddata0;
2135         else
2136                 return Tddata1;
2137 }
2138
2139 static Td*
2140 epgettd(Qio *io, int flags, void *a, int count, int maxpkt)
2141 {
2142         Td *td;
2143         ulong pa;
2144         int i;
2145
2146         if(count > Tdmaxpkt)
2147                 panic("ehci: epgettd: too many bytes");
2148         td = tdalloc();
2149         td->csw = flags | io->toggle | io->tok | count << Tdlenshift |
2150                 Tderr2 | Tderr1;
2151         coherence();
2152
2153         /*
2154          * use the space wasted by alignment as an
2155          * embedded buffer if count bytes fit in there.
2156          */
2157         assert(Align > sizeof(Td));
2158         if(count <= Align - sizeof(Td)){
2159                 td->data = td->sbuff;
2160                 td->buff = nil;
2161         } else if(count <= 0x4000){
2162                 td->buff = td->data = smalloc(count);
2163         } else {
2164                 td->buff = smalloc(count + 0x1000);
2165                 td->data = (uchar*)ROUND((uintptr)td->buff, 0x1000);
2166         }
2167
2168         pa = PADDR(td->data);
2169         for(i = 0; i < nelem(td->buffer); i++){
2170                 td->buffer[i] = pa;
2171                 pa &= ~0xFFF;
2172                 pa += 0x1000;
2173         }
2174         td->ndata = count;
2175         if(a != nil && count > 0)
2176                 memmove(td->data, a, count);
2177         coherence();
2178         io->toggle = nexttoggle(io->toggle, count, maxpkt);
2179         coherence();
2180         return td;
2181 }
2182
2183 /*
2184  * Try to get them idle
2185  */
2186 static void
2187 aborttds(Qh *qh)
2188 {
2189         Td *td;
2190
2191         if(qh->sched >= 0 && (qh->eps0 & Qhspeedmask) != Qhhigh)
2192                 qh->eps0 |= Qhint;      /* inactivate on next pass */
2193         qh->csw = (qh->csw & ~Tdactive) | Tdhalt;
2194         coherence();
2195         for(td = qh->tds; td != nil; td = td->next){
2196                 if(td->csw & Tdactive){
2197                         td->ndata = 0;
2198                         td->csw |= Tdhalt;
2199                         coherence();
2200                 }
2201         }
2202 }
2203
2204 /*
2205  * Some controllers do not post the usb/error interrupt after
2206  * the work has been done. It seems that we must poll for them.
2207  */
2208 static int
2209 workpending(void *a)
2210 {
2211         Ctlr *ctlr;
2212
2213         ctlr = a;
2214         return ctlr->nreqs > 0;
2215 }
2216
2217 static void
2218 ehcipoll(void* a)
2219 {
2220         Hci *hp;
2221         Ctlr *ctlr;
2222         Poll *poll;
2223         int i;
2224
2225         hp = a;
2226         ctlr = hp->aux;
2227         poll = &ctlr->poll;
2228         while(waserror())
2229                 ;
2230         for(;;){
2231                 if(ctlr->nreqs == 0){
2232                         if(0)ddprint("ehcipoll %#p sleep\n", ctlr->capio);
2233                         sleep(poll, workpending, ctlr);
2234                         if(0)ddprint("ehcipoll %#p awaken\n", ctlr->capio);
2235                 }
2236                 for(i = 0; i < 16 && ctlr->nreqs > 0; i++)
2237                         if(ehciintr(hp) == 0)
2238                                  break;
2239                 do{
2240                         tsleep(&up->sleep, return0, 0, 1);
2241                         ehciintr(hp);
2242                 }while(ctlr->nreqs > 0);
2243         }
2244 }
2245
2246 static void
2247 pollcheck(Hci *hp)
2248 {
2249         Ctlr *ctlr;
2250         Poll *poll;
2251
2252         ctlr = hp->aux;
2253         poll = &ctlr->poll;
2254
2255         if(poll->must != 0 && poll->does == 0){
2256                 lock(poll);
2257                 if(poll->must != 0 && poll->does == 0){
2258                         poll->does++;
2259                         print("ehci %#p: polling\n", ctlr->capio);
2260                         kproc("ehcipoll", ehcipoll, hp);
2261                 }
2262                 unlock(poll);
2263         }
2264 }
2265
2266 static int
2267 epiodone(void *a)
2268 {
2269         Qh *qh;
2270
2271         qh = a;
2272         return qh->state != Qrun;
2273 }
2274
2275 static void
2276 epiowait(Hci *hp, Qio *io, int tmout, ulong load)
2277 {
2278         Qh *qh;
2279         int timedout;
2280         Ctlr *ctlr;
2281
2282         ctlr = hp->aux;
2283         qh = io->qh;
2284         ddqprint("ehci io %#p sleep on qh %#p state %s\n",
2285                 io, qh, qhsname[qh->state]);
2286         timedout = 0;
2287         if(waserror()){
2288                 dqprint("ehci io %#p qh %#p timed out\n", io, qh);
2289                 timedout++;
2290         }else{
2291                 if(tmout == 0)
2292                         sleep(io, epiodone, qh);
2293                 else
2294                         tsleep(io, epiodone, qh, tmout);
2295                 poperror();
2296         }
2297
2298         ilock(ctlr);
2299         /* Are we missing interrupts? */
2300         if(qh->state == Qrun){
2301                 ctlrinterrupt(ctlr);
2302                 if(qh->state == Qdone){
2303                         dqprint("ehci %#p: polling required\n", ctlr->capio);
2304                         ctlr->poll.must = 1;
2305                         pollcheck(hp);
2306                 }
2307         }
2308
2309         if(qh->state == Qrun){
2310                 dqprint("ehci io %#p qh %#p timed out (no intr?)\n", io, qh);
2311                 timedout = 1;
2312         }else if(qh->state != Qdone && qh->state != Qclose)
2313                 panic("ehci: epio: queue state %d", qh->state);
2314         if(timedout){
2315                 aborttds(qh);
2316                 qh->state = Qdone;
2317                 if(io->err == nil)
2318                         io->err = "request timed out";
2319                 iunlock(ctlr);
2320                 while(waserror())
2321                         ;
2322                 tsleep(&up->sleep, return0, 0, Abortdelay);
2323                 poperror();
2324                 ilock(ctlr);
2325         }
2326         if(qh->state != Qclose)
2327                 qh->state = Qidle;
2328         qhlinktd(qh, nil);
2329         ctlr->load -= load;
2330         ctlr->nreqs--;
2331         iunlock(ctlr);
2332 }
2333
2334 /*
2335  * Non iso I/O.
2336  * To make it work for control transfers, the caller may
2337  * lock the Qio for the entire control transfer.
2338  */
2339 static long
2340 epio(Ep *ep, Qio *io, void *a, long count, int mustlock)
2341 {
2342         int saved, ntds, tmout;
2343         long n, tot;
2344         ulong load;
2345         char *err;
2346         char buf[128];
2347         uchar *c;
2348         Ctlr *ctlr;
2349         Qh* qh;
2350         Td *td, *ltd, *td0, *ntd;
2351
2352         ctlr = ep->hp->aux;
2353         io->debug = ep->debug;
2354         tmout = ep->tmout;
2355         ddeprint("epio: %s ep%d.%d io %#p count %ld load %uld\n",
2356                 io->tok == Tdtokin ? "in" : "out",
2357                 ep->dev->nb, ep->nb, io, count, ctlr->load);
2358         if((ehcidebug > 1 || ep->debug > 1) && io->tok != Tdtokin){
2359                 seprintdata(buf, buf+sizeof(buf), a, count);
2360                 print("echi epio: user data: %s\n", buf);
2361         }
2362         if(mustlock){
2363                 eqlock(io);
2364                 if(waserror()){
2365                         qunlock(io);
2366                         nexterror();
2367                 }
2368         }
2369         io->err = nil;
2370         ilock(ctlr);
2371         qh = io->qh;
2372         if(qh == nil || qh->state == Qclose){   /* Tds released by cancelio */
2373                 iunlock(ctlr);
2374                 error(io->err ? io->err : Eio);
2375         }
2376         if(qh->state != Qidle)
2377                 panic("epio: qh not idle");
2378         qh->state = Qinstall;
2379         iunlock(ctlr);
2380
2381         c = a;
2382         td0 = ltd = nil;
2383         load = tot = 0;
2384         do{
2385                 n = (Tdmaxpkt / ep->maxpkt) * ep->maxpkt;
2386                 if(count-tot < n)
2387                         n = count-tot;
2388                 if(c != nil && io->tok != Tdtokin)
2389                         td = epgettd(io, Tdactive, c+tot, n, ep->maxpkt);
2390                 else
2391                         td = epgettd(io, Tdactive, nil, n, ep->maxpkt);
2392                 if(td0 == nil)
2393                         td0 = td;
2394                 else
2395                         tdlinktd(ltd, td);
2396                 ltd = td;
2397                 tot += n;
2398                 load += ep->load;
2399         }while(tot < count);
2400         if(td0 == nil || ltd == nil)
2401                 panic("epio: no td");
2402
2403         ltd->csw |= Tdioc;              /* the last one interrupts */
2404         coherence();
2405
2406         ddeprint("ehci: load %uld ctlr load %uld\n", load, ctlr->load);
2407         if(ehcidebug > 1 || ep->debug > 1)
2408                 dumptd(td0, "epio: put: ");
2409
2410         ilock(ctlr);
2411         if(qh->state != Qclose){
2412                 io->iotime = TK2MS(MACHP(0)->ticks);
2413                 qh->state = Qrun;
2414                 coherence();
2415                 qhlinktd(qh, td0);
2416                 ctlr->nreqs++;
2417                 ctlr->load += load;
2418         }
2419         iunlock(ctlr);
2420
2421         if(ctlr->poll.does)
2422                 wakeup(&ctlr->poll);
2423
2424         epiowait(ep->hp, io, tmout, load);
2425         if(ehcidebug > 1 || ep->debug > 1){
2426                 dumptd(td0, "epio: got: ");
2427                 qhdump(qh);
2428         }
2429         err = io->err;
2430
2431         tot = 0;
2432         c = a;
2433         saved = 0;
2434         ntds = 0;
2435         for(td = td0; td != nil; td = ntd){
2436                 ntds++;
2437                 /*
2438                  * Use td tok, not io tok, because of setup packets.
2439                  * Also, we must save the next toggle value from the
2440                  * last completed Td (in case of a short packet, or
2441                  * fewer than the requested number of packets in the
2442                  * Td being transferred).
2443                  */
2444                 if(td->csw & (Tdhalt|Tdactive))
2445                         saved++;
2446                 else{
2447                         if(!saved){
2448                                 io->toggle = td->csw & Tddata1;
2449                                 coherence();
2450                         }
2451                         if(err == nil && (n = td->ndata) > 0 && tot < count){
2452                                 if((tot + n) > count)
2453                                         n = count - tot;
2454                                 if(c != nil && (td->csw & Tdtok) == Tdtokin){
2455                                         memmove(c, td->data, n);
2456                                         c += n;
2457                                 }
2458                                 tot += n;
2459                         }
2460                 }
2461                 ntd = td->next;
2462                 tdfree(td);
2463         }
2464         if(mustlock){
2465                 qunlock(io);
2466                 poperror();
2467         }
2468         ddeprint("epio: io %#p: %d tds: return %ld err '%s'\n",
2469                 io, ntds, tot, err);
2470         if(err == Estalled)
2471                 return 0;       /* that's our convention */
2472         if(err != nil)
2473                 error(err);
2474         return tot;
2475 }
2476
2477 static long
2478 epread(Ep *ep, void *a, long count)
2479 {
2480         Ctlio *cio;
2481         Qio *io;
2482         Isoio *iso;
2483         char buf[160];
2484         ulong delta;
2485
2486         ddeprint("ehci: epread\n");
2487         if(ep->aux == nil)
2488                 panic("epread: not open");
2489
2490         pollcheck(ep->hp);
2491
2492         switch(ep->ttype){
2493         case Tctl:
2494                 cio = ep->aux;
2495                 eqlock(cio);
2496                 if(waserror()){
2497                         qunlock(cio);
2498                         nexterror();
2499                 }
2500                 ddeprint("epread ctl ndata %d\n", cio->ndata);
2501                 if(cio->ndata < 0)
2502                         error("request expected");
2503                 else if(cio->ndata == 0){
2504                         cio->ndata = -1;
2505                         count = 0;
2506                 }else{
2507                         if(count > cio->ndata)
2508                                 count = cio->ndata;
2509                         if(count > 0)
2510                                 memmove(a, cio->data, count);
2511                         /* BUG for big transfers */
2512                         free(cio->data);
2513                         cio->data = nil;
2514                         cio->ndata = 0; /* signal EOF next time */
2515                 }
2516                 qunlock(cio);
2517                 poperror();
2518                 if(ehcidebug>1 || ep->debug){
2519                         seprintdata(buf, buf+sizeof(buf), a, count);
2520                         print("epread: %s\n", buf);
2521                 }
2522                 return count;
2523         case Tbulk:
2524                 io = ep->aux;
2525                 if(ep->clrhalt)
2526                         clrhalt(ep);
2527                 return epio(ep, &io[OREAD], a, count, 1);
2528         case Tintr:
2529                 io = ep->aux;
2530                 delta = TK2MS(MACHP(0)->ticks) - io[OREAD].iotime + 1;
2531                 if(delta < ep->pollival / 2)
2532                         tsleep(&up->sleep, return0, 0, ep->pollival/2 - delta);
2533                 if(ep->clrhalt)
2534                         clrhalt(ep);
2535                 return epio(ep, &io[OREAD], a, count, 1);
2536         case Tiso:
2537                 iso = ep->aux;
2538                 return episoread(ep, iso, a, count);
2539         }
2540         return -1;
2541 }
2542
2543 /*
2544  * Control transfers are one setup write (data0)
2545  * plus zero or more reads/writes (data1, data0, ...)
2546  * plus a final write/read with data1 to ack.
2547  * For both host to device and device to host we perform
2548  * the entire transfer when the user writes the request,
2549  * and keep any data read from the device for a later read.
2550  * We call epio three times instead of placing all Tds at
2551  * the same time because doing so leads to crc/tmout errors
2552  * for some devices.
2553  * Upon errors on the data phase we must still run the status
2554  * phase or the device may cease responding in the future.
2555  */
2556 static long
2557 epctlio(Ep *ep, Ctlio *cio, void *a, long count)
2558 {
2559         uchar *c;
2560         long len;
2561
2562         ddeprint("epctlio: cio %#p ep%d.%d count %ld\n",
2563                 cio, ep->dev->nb, ep->nb, count);
2564         if(count < Rsetuplen)
2565                 error("short usb comand");
2566         eqlock(cio);
2567         free(cio->data);
2568         cio->data = nil;
2569         cio->ndata = 0;
2570         if(waserror()){
2571                 free(cio->data);
2572                 cio->data = nil;
2573                 cio->ndata = 0;
2574                 qunlock(cio);
2575                 nexterror();
2576         }
2577
2578         /* set the address if unset and out of configuration state */
2579         if(ep->dev->state != Dconfig && ep->dev->state != Dreset)
2580                 if(cio->usbid == 0){
2581                         cio->usbid = (ep->nb&Epmax) << 7 | ep->dev->nb&Devmax;
2582                         coherence();
2583                         qhsetaddr(cio->qh, cio->usbid);
2584                 }
2585         /* adjust maxpkt if the user has learned a different one */
2586         if(qhmaxpkt(cio->qh) != ep->maxpkt)
2587                 qhsetmaxpkt(cio->qh, ep->maxpkt);
2588         c = a;
2589         cio->tok = Tdtoksetup;
2590         cio->toggle = Tddata0;
2591         coherence();
2592         if(epio(ep, cio, a, Rsetuplen, 0) < Rsetuplen)
2593                 error(Eio);
2594         a = c + Rsetuplen;
2595         count -= Rsetuplen;
2596
2597         cio->toggle = Tddata1;
2598         if(c[Rtype] & Rd2h){
2599                 cio->tok = Tdtokin;
2600                 len = GET2(c+Rcount);
2601                 if(len <= 0)
2602                         error("bad length in d2h request");
2603                 if(len > Maxctllen)
2604                         error("d2h data too large to fit in ehci");
2605                 a = cio->data = smalloc(len+1);
2606         }else{
2607                 cio->tok = Tdtokout;
2608                 len = count;
2609         }
2610         coherence();
2611         if(len > 0)
2612                 if(waserror())
2613                         len = -1;
2614                 else{
2615                         len = epio(ep, cio, a, len, 0);
2616                         poperror();
2617                 }
2618         if(c[Rtype] & Rd2h){
2619                 count = Rsetuplen;
2620                 cio->ndata = len;
2621                 cio->tok = Tdtokout;
2622         }else{
2623                 if(len < 0)
2624                         count = -1;
2625                 else
2626                         count = Rsetuplen + len;
2627                 cio->tok = Tdtokin;
2628         }
2629         cio->toggle = Tddata1;
2630         coherence();
2631         epio(ep, cio, nil, 0, 0);
2632         qunlock(cio);
2633         poperror();
2634         ddeprint("epctlio cio %#p return %ld\n", cio, count);
2635         return count;
2636 }
2637
2638 static long
2639 epwrite(Ep *ep, void *a, long count)
2640 {
2641         Qio *io;
2642         Ctlio *cio;
2643         Isoio *iso;
2644         ulong delta;
2645
2646         pollcheck(ep->hp);
2647
2648         ddeprint("ehci: epwrite ep%d.%d\n", ep->dev->nb, ep->nb);
2649         if(ep->aux == nil)
2650                 panic("ehci: epwrite: not open");
2651         switch(ep->ttype){
2652         case Tctl:
2653                 cio = ep->aux;
2654                 return epctlio(ep, cio, a, count);
2655         case Tbulk:
2656                 io = ep->aux;
2657                 if(ep->clrhalt)
2658                         clrhalt(ep);
2659                 return epio(ep, &io[OWRITE], a, count, 1);
2660         case Tintr:
2661                 io = ep->aux;
2662                 delta = TK2MS(MACHP(0)->ticks) - io[OWRITE].iotime + 1;
2663                 if(delta < ep->pollival)
2664                         tsleep(&up->sleep, return0, 0, ep->pollival - delta);
2665                 if(ep->clrhalt)
2666                         clrhalt(ep);
2667                 return epio(ep, &io[OWRITE], a, count, 1);
2668         case Tiso:
2669                 iso = ep->aux;
2670                 return episowrite(ep, iso, a, count);
2671         }
2672         return -1;
2673 }
2674
2675 static void
2676 isofsinit(Ep *ep, Isoio *iso)
2677 {
2678         long left;
2679         Sitd *td, *ltd;
2680         int i;
2681         ulong frno;
2682
2683         left = 0;
2684         ltd = nil;
2685         frno = iso->td0frno;
2686         for(i = 0; i < iso->nframes; i++){
2687                 td = sitdalloc();
2688                 td->data = iso->data + i * ep->maxpkt;
2689                 td->epc = ep->dev->port << Stdportshift;
2690                 td->epc |= ep->dev->hub << Stdhubshift;
2691                 td->epc |= ep->nb << Stdepshift;
2692                 td->epc |= ep->dev->nb << Stddevshift;
2693                 td->mfs = 034 << Stdscmshift | 1 << Stdssmshift;
2694                 if(ep->mode == OREAD){
2695                         td->epc |= Stdin;
2696                         td->mdata = ep->maxpkt;
2697                 }else{
2698                         td->mdata = (ep->hz+left) * ep->pollival / 1000;
2699                         td->mdata *= ep->samplesz;
2700                         left = (ep->hz+left) * ep->pollival % 1000;
2701                         if(td->mdata > ep->maxpkt){
2702                                 print("ehci: ep%d.%d: size > maxpkt\n",
2703                                         ep->dev->nb, ep->nb);
2704                                 print("size = %ld max = %ld\n",
2705                                         td->mdata,ep->maxpkt);
2706                                 td->mdata = ep->maxpkt;
2707                         }
2708                 }
2709                 coherence();
2710
2711                 iso->sitdps[frno] = td;
2712                 coherence();
2713                 sitdinit(iso, td);
2714                 if(ltd != nil)
2715                         ltd->next = td;
2716                 ltd = td;
2717                 frno = TRUNC(frno+ep->pollival, Nisoframes);
2718         }
2719         ltd->next = iso->sitdps[iso->td0frno];
2720         coherence();
2721 }
2722
2723 static void
2724 isohsinit(Ep *ep, Isoio *iso)
2725 {
2726         int ival, p;
2727         long left;
2728         ulong frno, i, pa;
2729         Itd *ltd, *td;
2730
2731         iso->hs = 1;
2732         ival = 1;
2733         if(ep->pollival > 8)
2734                 ival = ep->pollival/8;
2735         left = 0;
2736         ltd = nil;
2737         frno = iso->td0frno;
2738         for(i = 0; i < iso->nframes; i++){
2739                 td = itdalloc();
2740                 td->data = iso->data + i * 8 * iso->maxsize;
2741                 pa = PADDR(td->data) & ~0xFFF;
2742                 for(p = 0; p < nelem(td->buffer); p++){
2743                         td->buffer[p] = pa;
2744                         pa += 0x1000;
2745                 }
2746                 td->buffer[0] |= ep->nb << Itdepshift | ep->dev->nb << Itddevshift;
2747                 if(ep->mode == OREAD)
2748                         td->buffer[1] |= Itdin;
2749                 else
2750                         td->buffer[1] |= Itdout;
2751                 td->buffer[1] |= ep->maxpkt << Itdmaxpktshift;
2752                 td->buffer[2] |= ep->ntds << Itdntdsshift;
2753
2754                 if(ep->mode == OREAD)
2755                         td->mdata = 8 * iso->maxsize;
2756                 else{
2757                         td->mdata = (ep->hz + left) * ep->pollival / 1000;
2758                         td->mdata *= ep->samplesz;
2759                         left = (ep->hz + left) * ep->pollival % 1000;
2760                 }
2761                 coherence();
2762                 iso->itdps[frno] = td;
2763                 coherence();
2764                 itdinit(iso, td);
2765                 if(ltd != nil)
2766                         ltd->next = td;
2767                 ltd = td;
2768                 frno = TRUNC(frno + ival, Nisoframes);
2769         }
2770 }
2771
2772 static void
2773 isoopen(Ctlr *ctlr, Ep *ep)
2774 {
2775         int ival;               /* pollival in ms */
2776         int tpf;                /* tds per frame */
2777         int i, n, w, woff;
2778         ulong frno;
2779         Isoio *iso;
2780
2781         iso = ep->aux;
2782         switch(ep->mode){
2783         case OREAD:
2784                 iso->tok = Tdtokin;
2785                 break;
2786         case OWRITE:
2787                 iso->tok = Tdtokout;
2788                 break;
2789         default:
2790                 error("iso i/o is half-duplex");
2791         }
2792         iso->usbid = ep->nb << 7 | ep->dev->nb & Devmax;
2793         iso->state = Qidle;
2794         coherence();
2795         iso->debug = ep->debug;
2796         ival = ep->pollival;
2797         tpf = 1;
2798         if(ep->dev->speed == Highspeed){
2799                 tpf = 8;
2800                 if(ival <= 8)
2801                         ival = 1;
2802                 else
2803                         ival /= 8;
2804         }
2805         assert(ival != 0);
2806         iso->nframes = Nisoframes / ival;
2807         if(iso->nframes < 3)
2808                 error("uhci isoopen bug");      /* we need at least 3 tds */
2809         iso->maxsize = ep->ntds * ep->maxpkt;
2810         if(ctlr->load + ep->load > 800)
2811                 print("usb: ehci: bandwidth may be exceeded\n");
2812         ilock(ctlr);
2813         ctlr->load += ep->load;
2814         ctlr->isoload += ep->load;
2815         ctlr->nreqs++;
2816         dprint("ehci: load %uld isoload %uld\n", ctlr->load, ctlr->isoload);
2817         diprint("iso nframes %d pollival %uld ival %d maxpkt %uld ntds %d\n",
2818                 iso->nframes, ep->pollival, ival, ep->maxpkt, ep->ntds);
2819         iunlock(ctlr);
2820         if(ctlr->poll.does)
2821                 wakeup(&ctlr->poll);
2822
2823         /*
2824          * From here on this cannot raise errors
2825          * unless we catch them and release here all memory allocated.
2826          */
2827         assert(ep->maxpkt > 0 && ep->ntds > 0 && ep->ntds < 4);
2828         assert(ep->maxpkt <= 1024);
2829         iso->tdps = smalloc(sizeof(uintptr) * Nisoframes);
2830         iso->data = smalloc(iso->nframes * tpf * ep->ntds * ep->maxpkt);
2831         iso->td0frno = TRUNC(ctlr->opio->frno + 10, Nisoframes);
2832         /* read: now; write: 1s ahead */
2833
2834         if(ep->dev->speed == Highspeed)
2835                 isohsinit(ep, iso);
2836         else
2837                 isofsinit(ep, iso);
2838         iso->tdu = iso->tdi = iso->itdps[iso->td0frno];
2839         iso->stdu = iso->stdi = iso->sitdps[iso->td0frno];
2840         coherence();
2841
2842         ilock(ctlr);
2843         frno = iso->td0frno;
2844         for(i = 0; i < iso->nframes; i++){
2845                 *iso->tdps[frno] = ctlr->frames[frno];
2846                 frno = TRUNC(frno+ival, Nisoframes);
2847         }
2848
2849         /*
2850          * Iso uses a virtual frame window of Nisoframes, and we must
2851          * fill the actual ctlr frame array by placing ctlr->nframes/Nisoframes
2852          * copies of the window in the frame array.
2853          */
2854         assert(ctlr->nframes >= Nisoframes && Nisoframes >= iso->nframes);
2855         assert(Nisoframes >= Nintrleafs);
2856         n = ctlr->nframes / Nisoframes;
2857         for(w = 0; w < n; w++){
2858                 frno = iso->td0frno;
2859                 woff = w * Nisoframes;
2860                 for(i = 0; i < iso->nframes ; i++){
2861                         assert(woff+frno < ctlr->nframes);
2862                         assert(iso->tdps[frno] != nil);
2863                         if(ep->dev->speed == Highspeed)
2864                                 ctlr->frames[woff+frno] = PADDR(iso->tdps[frno])
2865                                         |Litd;
2866                         else
2867                                 ctlr->frames[woff+frno] = PADDR(iso->tdps[frno])
2868                                         |Lsitd;
2869                         coherence();
2870                         frno = TRUNC(frno+ep->pollival, Nisoframes);
2871                 }
2872         }
2873         coherence();
2874         iso->next = ctlr->iso;
2875         ctlr->iso = iso;
2876         coherence();
2877         iso->state = Qdone;
2878         iunlock(ctlr);
2879         if(ehcidebug > 1 || iso->debug >1)
2880                 isodump(iso, 0);
2881 }
2882
2883 /*
2884  * Allocate the endpoint and set it up for I/O
2885  * in the controller. This must follow what's said
2886  * in Ep regarding configuration, including perhaps
2887  * the saved toggles (saved on a previous close of
2888  * the endpoint data file by epclose).
2889  */
2890 static void
2891 epopen(Ep *ep)
2892 {
2893         Ctlr *ctlr;
2894         Ctlio *cio;
2895         Qio *io;
2896         int usbid;
2897
2898         ctlr = ep->hp->aux;
2899         deprint("ehci: epopen ep%d.%d\n", ep->dev->nb, ep->nb);
2900         if(ep->aux != nil)
2901                 panic("ehci: epopen called with open ep");
2902         if(waserror()){
2903                 free(ep->aux);
2904                 ep->aux = nil;
2905                 nexterror();
2906         }
2907         switch(ep->ttype){
2908         case Tnone:
2909                 error("endpoint not configured");
2910         case Tiso:
2911                 ep->aux = smalloc(sizeof(Isoio));
2912                 isoopen(ctlr, ep);
2913                 break;
2914         case Tctl:
2915                 cio = ep->aux = smalloc(sizeof(Ctlio));
2916                 cio->debug = ep->debug;
2917                 cio->ndata = -1;
2918                 cio->data = nil;
2919                 if(ep->dev->isroot != 0 && ep->nb == 0) /* root hub */
2920                         break;
2921                 cio->qh = qhalloc(ctlr, ep, cio, "epc");
2922                 break;
2923         case Tbulk:
2924                 ep->pollival = 1;       /* assume this; doesn't really matter */
2925                 /* and fall... */
2926         case Tintr:
2927                 io = ep->aux = smalloc(sizeof(Qio)*2);
2928                 io[OREAD].debug = io[OWRITE].debug = ep->debug;
2929                 usbid = (ep->nb&Epmax) << 7 | ep->dev->nb &Devmax;
2930                 assert(ep->pollival != 0);
2931                 if(ep->mode != OREAD){
2932                         if(ep->toggle[OWRITE] != 0)
2933                                 io[OWRITE].toggle = Tddata1;
2934                         else
2935                                 io[OWRITE].toggle = Tddata0;
2936                         io[OWRITE].tok = Tdtokout;
2937                         io[OWRITE].usbid = usbid;
2938                         io[OWRITE].bw = ep->maxpkt*1000/ep->pollival; /* bytes/s */
2939                         io[OWRITE].qh = qhalloc(ctlr, ep, io+OWRITE, "epw");
2940                 }
2941                 if(ep->mode != OWRITE){
2942                         if(ep->toggle[OREAD] != 0)
2943                                 io[OREAD].toggle = Tddata1;
2944                         else
2945                                 io[OREAD].toggle = Tddata0;
2946                         io[OREAD].tok = Tdtokin;
2947                         io[OREAD].usbid = usbid;
2948                         io[OREAD].bw = ep->maxpkt*1000/ep->pollival; /* bytes/s */
2949                         io[OREAD].qh = qhalloc(ctlr, ep, io+OREAD, "epr");
2950                 }
2951                 break;
2952         }
2953         coherence();
2954         if(ehcidebug>1 || ep->debug)
2955                 dump(ep->hp);
2956         deprint("ehci: epopen done\n");
2957         poperror();
2958 }
2959
2960 static void
2961 cancelio(Ctlr *ctlr, Qio *io)
2962 {
2963         Qh *qh;
2964
2965         ilock(ctlr);
2966         qh = io->qh;
2967         if(qh == nil || qh->state == Qclose){
2968                 iunlock(ctlr);
2969                 return;
2970         }
2971         dqprint("ehci: cancelio for qh %#p state %s\n",
2972                 qh, qhsname[qh->state]);
2973         aborttds(qh);
2974         qh->state = Qclose;
2975         iunlock(ctlr);
2976         while(waserror())
2977                 ;
2978         tsleep(&up->sleep, return0, 0, Abortdelay);
2979         poperror();
2980         wakeup(io);
2981         qlock(io);
2982         /* wait for epio if running */
2983         if(io->qh == qh)
2984                 io->qh = nil;
2985         qunlock(io);
2986
2987         qhfree(ctlr, qh);
2988 }
2989
2990 static void
2991 cancelisoio(Ctlr *ctlr, Isoio *iso, int pollival, ulong load)
2992 {
2993         int frno, i, n, t, w, woff;
2994         ulong *lp, *tp;
2995         Isoio **il;
2996         Itd *td;
2997         Sitd *std;
2998
2999         ilock(ctlr);
3000         if(iso->state == Qclose){
3001                 iunlock(ctlr);
3002                 return;
3003         }
3004         ctlr->nreqs--;
3005         if(iso->state != Qrun && iso->state != Qdone)
3006                 panic("bad iso state");
3007         iso->state = Qclose;
3008         coherence();
3009         if(ctlr->isoload < load)
3010                 panic("ehci: low isoload");
3011         ctlr->isoload -= load;
3012         ctlr->load -= load;
3013         for(il = &ctlr->iso; *il != nil; il = &(*il)->next)
3014                 if(*il == iso)
3015                         break;
3016         if(*il == nil)
3017                 panic("cancleiso: not found");
3018         *il = iso->next;
3019
3020         frno = iso->td0frno;
3021         for(i = 0; i < iso->nframes; i++){
3022                 tp = iso->tdps[frno];
3023                 if(iso->hs != 0){
3024                         td = iso->itdps[frno];
3025                         for(t = 0; t < nelem(td->csw); t++)
3026                                 td->csw[t] &= ~(Itdioc|Itdactive);
3027                 }else{
3028                         std = iso->sitdps[frno];
3029                         std->csw &= ~(Stdioc|Stdactive);
3030                 }
3031                 coherence();
3032                 for(lp = &ctlr->frames[frno]; !(*lp & Lterm);
3033                     lp = &LPTR(*lp)[0])
3034                         if(LPTR(*lp) == tp)
3035                                 break;
3036                 if(*lp & Lterm)
3037                         panic("cancelisoio: td not found");
3038                 *lp = tp[0];
3039                 /*
3040                  * Iso uses a virtual frame window of Nisoframes, and we must
3041                  * restore pointers in copies of the window kept at ctlr->frames.
3042                  */
3043                 if(lp == &ctlr->frames[frno]){
3044                         n = ctlr->nframes / Nisoframes;
3045                         for(w = 1; w < n; w++){
3046                                 woff = w * Nisoframes;
3047                                 ctlr->frames[woff+frno] = *lp;
3048                         }
3049                 }
3050                 coherence();
3051                 frno = TRUNC(frno+pollival, Nisoframes);
3052         }
3053         iunlock(ctlr);
3054
3055         /*
3056          * wakeup anyone waiting for I/O and
3057          * wait to be sure no I/O is in progress in the controller.
3058          * and then wait to be sure episo* is no longer running.
3059          */
3060         wakeup(iso);
3061         diprint("cancelisoio iso %#p waiting for I/O to cease\n", iso);
3062         tsleep(&up->sleep, return0, 0, 5);
3063         qlock(iso);
3064         qunlock(iso);
3065         diprint("cancelisoio iso %#p releasing iso\n", iso);
3066
3067         frno = iso->td0frno;
3068         for(i = 0; i < iso->nframes; i++){
3069                 if(iso->hs != 0)
3070                         itdfree(iso->itdps[frno]);
3071                 else
3072                         sitdfree(iso->sitdps[frno]);
3073                 iso->tdps[frno] = nil;
3074                 frno = TRUNC(frno+pollival, Nisoframes);
3075         }
3076         free(iso->tdps);
3077         iso->tdps = nil;
3078         free(iso->data);
3079         iso->data = nil;
3080         coherence();
3081 }
3082
3083 static void
3084 epclose(Ep *ep)
3085 {
3086         Qio *io;
3087         Ctlio *cio;
3088         Isoio *iso;
3089         Ctlr *ctlr;
3090
3091         ctlr = ep->hp->aux;
3092         deprint("ehci: epclose ep%d.%d\n", ep->dev->nb, ep->nb);
3093
3094         if(ep->aux == nil)
3095                 panic("ehci: epclose called with closed ep");
3096         switch(ep->ttype){
3097         case Tctl:
3098                 cio = ep->aux;
3099                 cancelio(ctlr, cio);
3100                 free(cio->data);
3101                 cio->data = nil;
3102                 break;
3103         case Tintr:
3104         case Tbulk:
3105                 io = ep->aux;
3106                 ep->toggle[OREAD] = ep->toggle[OWRITE] = 0;
3107                 if(ep->mode != OWRITE){
3108                         cancelio(ctlr, &io[OREAD]);
3109                         if(io[OREAD].toggle == Tddata1)
3110                                 ep->toggle[OREAD] = 1;
3111                 }
3112                 if(ep->mode != OREAD){
3113                         cancelio(ctlr, &io[OWRITE]);
3114                         if(io[OWRITE].toggle == Tddata1)
3115                                 ep->toggle[OWRITE] = 1;
3116                 }
3117                 coherence();
3118                 break;
3119         case Tiso:
3120                 iso = ep->aux;
3121                 cancelisoio(ctlr, iso, ep->pollival, ep->load);
3122                 break;
3123         default:
3124                 panic("epclose: bad ttype");
3125         }
3126         free(ep->aux);
3127         ep->aux = nil;
3128 }
3129
3130 /*
3131  * return smallest power of 2 >= n
3132  */
3133 static int
3134 flog2(int n)
3135 {
3136         int i;
3137
3138         for(i = 0; (1 << i) < n; i++)
3139                 ;
3140         return i;
3141 }
3142
3143 /*
3144  * build the periodic scheduling tree:
3145  * framesize must be a multiple of the tree size
3146  */
3147 static void
3148 mkqhtree(Ctlr *ctlr)
3149 {
3150         int i, n, d, o, leaf0, depth;
3151         ulong leafs[Nintrleafs];
3152         Qh *qh;
3153         Qh **tree;
3154         Qtree *qt;
3155
3156         depth = flog2(Nintrleafs);
3157         n = (1 << (depth+1)) - 1;
3158         qt = mallocz(sizeof(*qt), 1);
3159         if(qt == nil)
3160                 panic("ehci: mkqhtree: no memory");
3161         qt->nel = n;
3162         qt->depth = depth;
3163         qt->bw = mallocz(n * sizeof(qt->bw), 1);
3164         qt->root = tree = mallocz(n * sizeof(Qh *), 1);
3165         if(qt->bw == nil || tree == nil)
3166                 panic("ehci: mkqhtree: no memory");
3167         for(i = 0; i < n; i++){
3168                 tree[i] = qh = edalloc();
3169                 if(qh == nil)
3170                         panic("ehci: mkqhtree: no memory");
3171                 qh->nlink = qh->alink = qh->link = Lterm;
3172                 qh->csw = Tdhalt;
3173                 qh->state = Qidle;
3174                 coherence();
3175                 if(i > 0)
3176                         qhlinkqh(tree[i], tree[(i-1)/2]);
3177         }
3178         ctlr->ntree = i;
3179         dprint("ehci: tree: %d endpoints allocated\n", i);
3180
3181         /* distribute leaves evenly round the frame list */
3182         leaf0 = n / 2;
3183         for(i = 0; i < Nintrleafs; i++){
3184                 o = 0;
3185                 for(d = 0; d < depth; d++){
3186                         o <<= 1;
3187                         if(i & (1 << d))
3188                                 o |= 1;
3189                 }
3190                 if(leaf0 + o >= n){
3191                         print("leaf0=%d o=%d i=%d n=%d\n", leaf0, o, i, n);
3192                         break;
3193                 }
3194                 leafs[i] = PADDR(tree[leaf0 + o]) | Lqh;
3195         }
3196         assert((ctlr->nframes % Nintrleafs) == 0);
3197         for(i = 0; i < ctlr->nframes; i += Nintrleafs){
3198                 memmove(ctlr->frames + i, leafs, sizeof leafs);
3199                 coherence();
3200         }
3201         ctlr->tree = qt;
3202         coherence();
3203 }
3204
3205 void
3206 ehcimeminit(Ctlr *ctlr)
3207 {
3208         int i, frsize;
3209         Eopio *opio;
3210
3211         opio = ctlr->opio;
3212         frsize = ctlr->nframes * sizeof(ulong);
3213         assert((frsize & 0xFFF) == 0);          /* must be 4k aligned */
3214         ctlr->frames = xspanalloc(frsize, frsize, 0);
3215         if(ctlr->frames == nil)
3216                 panic("ehci reset: no memory");
3217
3218         for (i = 0; i < ctlr->nframes; i++)
3219                 ctlr->frames[i] = Lterm;
3220         opio->frbase = PADDR(ctlr->frames);
3221         opio->frno = 0;
3222         coherence();
3223
3224         qhalloc(ctlr, nil, nil, nil);   /* init async list */
3225         mkqhtree(ctlr);                 /* init sync list */
3226         edfree(edalloc());              /* try to get some ones pre-allocated */
3227
3228         dprint("ehci %#p flb %#lux frno %#lux\n",
3229                 ctlr->capio, opio->frbase, opio->frno);
3230 }
3231
3232 static void
3233 init(Hci *hp)
3234 {
3235         Ctlr *ctlr;
3236         Eopio *opio;
3237         static int ctlrno;
3238         int i;
3239
3240         hp->highspeed = 1;
3241         ctlr = hp->aux;
3242         opio = ctlr->opio;
3243         dprint("ehci %#p init\n", ctlr->capio);
3244
3245         ilock(ctlr);
3246         /*
3247          * Unless we activate frroll interrupt
3248          * some machines won't post other interrupts.
3249          */
3250         opio->intr = Iusb|Ierr|Iportchg|Ihcerr|Iasync;
3251         coherence();
3252         opio->cmd |= Cpse;
3253         coherence();
3254         opio->cmd |= Case;
3255         coherence();
3256         ehcirun(ctlr, 1);
3257
3258         /* route all ports to us */
3259         opio->config = Callmine;
3260         coherence();
3261
3262         for (i = 0; i < hp->nports; i++)
3263                 opio->portsc[i] = Pspower;
3264         iunlock(ctlr);
3265         if(ehcidebug > 1)
3266                 dump(hp);
3267         ctlrno++;
3268 }
3269
3270 void
3271 ehcilinkage(Hci *hp)
3272 {
3273         hp->init = init;
3274         hp->dump = dump;
3275         hp->interrupt = interrupt;
3276         hp->epopen = epopen;
3277         hp->epclose = epclose;
3278         hp->epread = epread;
3279         hp->epwrite = epwrite;
3280         hp->seprintep = seprintep;
3281         hp->portenable = portenable;
3282         hp->portreset = portreset;
3283         hp->portstatus = portstatus;
3284 //      hp->shutdown = shutdown;
3285 //      hp->debug = setdebug;
3286         hp->type = "ehci";
3287 }