]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/port/usbehci.c
usb: fix potential isoread overruns, error instead of panic on isoread in ohci
[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      = 5,            /* 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                 if(!waserror()){
744                         tsleep(ctlr, qhadvanced, ctlr, Abortdelay);
745                         poperror();
746                 }
747         dprint("ehci: qhcoherency: doorbell %d\n", qhadvanced(ctlr));
748         if(i == 3)
749                 print("ehci: async advance doorbell did not ring\n");
750         ctlr->opio->cmd &= ~Ciasync;    /* try to clean */
751         qunlock(&ctlr->portlck);
752 }
753
754 static void
755 qhfree(Ctlr *ctlr, Qh *qh)
756 {
757         Td *td, *ltd;
758         Qh *q;
759
760         if(qh == nil)
761                 return;
762         ilock(ctlr);
763         if(qh->sched < 0){
764                 for(q = ctlr->qhs; q != nil; q = q->next)
765                         if(q->next == qh)
766                                 break;
767                 if(q == nil)
768                         panic("qhfree: nil q");
769                 q->next = qh->next;
770                 q->link = qh->link;
771                 coherence();
772         }else
773                 unschedq(ctlr, qh);
774         iunlock(ctlr);
775
776         qhcoherency(ctlr);
777
778         for(td = qh->tds; td != nil; td = ltd){
779                 ltd = 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         assert(tdi != nil);
1342         if(itdactive(tdi))                      /* not all tds are done */
1343                 return 0;
1344         ctlr->nisointr++;
1345         ddiprint("isohsintr: iso %#p: tdi %#p tdu %#p\n", iso, tdi, iso->tdu);
1346         if(iso->state != Qrun && iso->state != Qdone)
1347                 panic("isofsintr: iso state");
1348         if(ehcidebug > 1 || iso->debug > 1)
1349                 isodump(iso, 0);
1350
1351         nframes = iso->nframes / 2;             /* limit how many we look */
1352         if(nframes > Nisoframes)
1353                 nframes = Nisoframes;
1354
1355         if(iso->tok == Tdtokin)
1356                 tdi->ndata = 0;
1357         /* else, it has the number of bytes transferred */
1358
1359         for(i = 0; i < nframes && itdactive(tdi) == 0; i++){
1360                 if(iso->tok == Tdtokin)
1361                         tdi->ndata += (tdi->csw[i] >> Itdlenshift) & Itdlenmask;
1362                 err = 0;
1363                 coherence();
1364                 for(t = 0; t < nelem(tdi->csw); t++){
1365                         tdi->csw[t] &= ~Itdioc;
1366                         coherence();
1367                         err |= tdi->csw[t] & Itderrors;
1368                 }
1369                 if(err == 0)
1370                         iso->nerrs = 0;
1371                 else if(iso->nerrs++ > iso->nframes/2){
1372                         if(iso->err == nil){
1373                                 iso->err = ierrmsg(err);
1374                                 diprint("isohsintr: tdi %#p error %#ux %s\n",
1375                                         tdi, err, iso->err);
1376                                 diprint("ctlr load %uld\n", ctlr->load);
1377                         }
1378                         tdi->ndata = 0;
1379                 }else
1380                         tdi->ndata = 0;
1381                 if(tdi->next == iso->tdu || tdi->next->next == iso->tdu){
1382                         memset(iso->tdu->data, 0, iso->tdu->mdata);
1383                         itdinit(iso, iso->tdu);
1384                         iso->tdu = iso->tdu->next;
1385                         iso->nleft = 0;
1386                 }
1387                 tdi = tdi->next;
1388                 coherence();
1389         }
1390         ddiprint("isohsintr: %d frames processed\n", nframes);
1391         if(i == nframes){
1392                 tdi->csw[0] |= Itdioc;
1393                 coherence();
1394         }
1395         iso->tdi = tdi;
1396         coherence();
1397         if(isocanwrite(iso) || isocanread(iso)){
1398                 diprint("wakeup iso %#p tdi %#p tdu %#p\n", iso,
1399                         iso->tdi, iso->tdu);
1400                 wakeup(iso);
1401         }
1402         return 1;
1403 }
1404
1405 static int
1406 isofsinterrupt(Ctlr *ctlr, Isoio *iso)
1407 {
1408         int err, i, nframes;
1409         Sitd *stdi;
1410
1411         stdi = iso->stdi;
1412         assert(stdi != nil);
1413         if((stdi->csw & Stdactive) != 0)                /* nothing new done */
1414                 return 0;
1415         ctlr->nisointr++;
1416         ddiprint("isofsintr: iso %#p: tdi %#p tdu %#p\n", iso, stdi, iso->stdu);
1417         if(iso->state != Qrun && iso->state != Qdone)
1418                 panic("isofsintr: iso state");
1419         if(ehcidebug > 1 || iso->debug > 1)
1420                 isodump(iso, 0);
1421
1422         nframes = iso->nframes / 2;             /* limit how many we look */
1423         if(nframes > Nisoframes)
1424                 nframes = Nisoframes;
1425
1426         for(i = 0; i < nframes && (stdi->csw & Stdactive) == 0; i++){
1427                 stdi->csw &= ~Stdioc;
1428                 /* write back csw and see if it produces errors */
1429                 coherence();
1430                 err = stdi->csw & Stderrors;
1431                 if(err == 0){
1432                         iso->nerrs = 0;
1433                         if(iso->tok == Tdtokin)
1434                                 stdi->ndata = (stdi->csw>>Stdlenshift)&Stdlenmask;
1435                         /* else len is assumed correct */
1436                 }else if(iso->nerrs++ > iso->nframes/2){
1437                         if(iso->err == nil){
1438                                 iso->err = serrmsg(err);
1439                                 diprint("isofsintr: tdi %#p error %#ux %s\n",
1440                                         stdi, err, iso->err);
1441                                 diprint("ctlr load %uld\n", ctlr->load);
1442                         }
1443                         stdi->ndata = 0;
1444                 }else
1445                         stdi->ndata = 0;
1446
1447                 if(stdi->next == iso->stdu || stdi->next->next == iso->stdu){
1448                         memset(iso->stdu->data, 0, iso->stdu->mdata);
1449                         coherence();
1450                         sitdinit(iso, iso->stdu);
1451                         iso->stdu = iso->stdu->next;
1452                         iso->nleft = 0;
1453                 }
1454                 coherence();
1455                 stdi = stdi->next;
1456         }
1457         ddiprint("isofsintr: %d frames processed\n", nframes);
1458         if(i == nframes){
1459                 stdi->csw |= Stdioc;
1460                 coherence();
1461         }
1462         iso->stdi = stdi;
1463         coherence();
1464         if(isocanwrite(iso) || isocanread(iso)){
1465                 diprint("wakeup iso %#p tdi %#p tdu %#p\n", iso,
1466                         iso->stdi, iso->stdu);
1467                 wakeup(iso);
1468         }
1469         return 1;
1470 }
1471
1472 static int
1473 qhinterrupt(Ctlr *ctlr, Qh *qh)
1474 {
1475         Td *td;
1476         int err;
1477
1478         if(qh->state != Qrun)
1479                 panic("qhinterrupt: qh state");
1480         td = qh->tds;
1481         if(td == nil)
1482                 panic("qhinterrupt: no tds");
1483         if((td->csw & Tdactive) == 0)
1484                 ddqprint("qhinterrupt port %#p qh %#p\n", ctlr->capio, qh);
1485         for(; td != nil; td = td->next){
1486                 if(td->csw & Tdactive)
1487                         return 0;
1488                 err = td->csw & Tderrors;
1489                 if(err != 0){
1490                         if(qh->io->err == nil){
1491                                 qh->io->err = errmsg(err);
1492                                 dqprint("qhintr: td %#p csw %#lux error %#ux %s\n",
1493                                         td, td->csw, err, qh->io->err);
1494                         }
1495                         break;
1496                 }
1497                 td->ndata = tdlen(td);
1498                 coherence();
1499                 if(td->ndata < maxtdlen(td)){   /* EOT */
1500                         td = td->next;
1501                         break;
1502                 }
1503         }
1504         /*
1505          * Done. Make void the Tds not used (errors or EOT) and wakeup epio.
1506          */
1507         for(; td != nil; td = td->next)
1508                 td->ndata = 0;
1509         coherence();
1510         qh->state = Qdone;
1511         coherence();
1512         wakeup(qh->io);
1513         return 1;
1514 }
1515
1516 static int
1517 ehciintr(Hci *hp)
1518 {
1519         Ctlr *ctlr;
1520         Eopio *opio;
1521         Isoio *iso;
1522         ulong sts;
1523         Qh *qh;
1524         int i, some;
1525
1526         ctlr = hp->aux;
1527         opio = ctlr->opio;
1528
1529         /*
1530          * Will we know in USB 3.0 who the interrupt was for?.
1531          * Do they still teach indexing in CS?
1532          * This is Intel's doing.
1533          */
1534         ilock(ctlr);
1535         ctlr->nintr++;
1536         sts = opio->sts & Sintrs;
1537         if(sts == 0){           /* not ours; shared intr. */
1538                 iunlock(ctlr);
1539                 return 0;
1540         }
1541         opio->sts = sts;
1542         coherence();
1543         if((sts & Sherr) != 0)
1544                 print("ehci: port %#p fatal host system error\n", ctlr->capio);
1545         if((sts & Shalted) != 0)
1546                 print("ehci: port %#p: halted\n", ctlr->capio);
1547         if((sts & Sasync) != 0){
1548                 dprint("ehci: doorbell\n");
1549                 wakeup(ctlr);
1550         }
1551         /*
1552          * We enter always this if, even if it seems the
1553          * interrupt does not report anything done/failed.
1554          * Some controllers don't post interrupts right.
1555          */
1556         some = 0;
1557         if((sts & (Serrintr|Sintr)) != 0){
1558                 ctlr->ntdintr++;
1559                 if(ehcidebug > 1){
1560                         print("ehci port %#p frames %#p nintr %d ntdintr %d",
1561                                 ctlr->capio, ctlr->frames,
1562                                 ctlr->nintr, ctlr->ntdintr);
1563                         print(" nqhintr %d nisointr %d\n",
1564                                 ctlr->nqhintr, ctlr->nisointr);
1565                         print("\tcmd %#lux sts %#lux intr %#lux frno %uld",
1566                                 opio->cmd, opio->sts, opio->intr, opio->frno);
1567                 }
1568
1569                 /* process the Iso transfers */
1570                 for(iso = ctlr->iso; iso != nil; iso = iso->next)
1571                         if(iso->state == Qrun || iso->state == Qdone)
1572                                 if(iso->hs != 0)
1573                                         some += isohsinterrupt(ctlr, iso);
1574                                 else
1575                                         some += isofsinterrupt(ctlr, iso);
1576
1577                 /* process the qhs in the periodic tree */
1578                 for(qh = ctlr->intrqhs; qh != nil; qh = qh->inext)
1579                         if(qh->state == Qrun)
1580                                 some += qhinterrupt(ctlr, qh);
1581
1582                 /* process the async Qh circular list */
1583                 qh = ctlr->qhs;
1584                 i = 0;
1585                 do{
1586                         if (qh == nil)
1587                                 panic("ehciintr: nil qh");
1588                         if(qh->state == Qrun)
1589                                 some += qhinterrupt(ctlr, qh);
1590                         qh = qh->next;
1591                 }while(qh != ctlr->qhs && i++ < 100);
1592                 if(i > 100)
1593                         print("echi: interrupt: qh loop?\n");
1594         }
1595 //      if (some == 0)
1596 //              panic("ehciintr: no work");
1597         iunlock(ctlr);
1598         return some;
1599 }
1600
1601 static void
1602 interrupt(Ureg*, void* a)
1603 {
1604         ehciintr(a);
1605 }
1606
1607 static int
1608 portenable(Hci *hp, int port, int on)
1609 {
1610         Ctlr *ctlr;
1611         Eopio *opio;
1612         int s;
1613
1614         ctlr = hp->aux;
1615         opio = ctlr->opio;
1616         s = opio->portsc[port-1];
1617         eqlock(&ctlr->portlck);
1618         if(waserror()){
1619                 qunlock(&ctlr->portlck);
1620                 nexterror();
1621         }
1622         dprint("ehci %#p port %d enable=%d; sts %#x\n",
1623                 ctlr->capio, port, on, s);
1624         ilock(ctlr);
1625         if(s & (Psstatuschg | Pschange))
1626                 opio->portsc[port-1] = s;
1627         if(on)
1628                 opio->portsc[port-1] |= Psenable;
1629         else
1630                 opio->portsc[port-1] &= ~Psenable;
1631         coherence();
1632         microdelay(64);
1633         iunlock(ctlr);
1634         tsleep(&up->sleep, return0, 0, Enabledelay);
1635         dprint("ehci %#p port %d enable=%d: sts %#lux\n",
1636                 ctlr->capio, port, on, opio->portsc[port-1]);
1637         qunlock(&ctlr->portlck);
1638         poperror();
1639         return 0;
1640 }
1641
1642 /*
1643  * If we detect during status that the port is low-speed or
1644  * during reset that it's full-speed, the device is not for
1645  * ourselves. The companion controller will take care.
1646  * Low-speed devices will not be seen by usbd. Full-speed
1647  * ones are seen because it's only after reset that we know what
1648  * they are (usbd may notice a device not enabled in this case).
1649  */
1650 static void
1651 portlend(Ctlr *ctlr, int port, char *ss)
1652 {
1653         Eopio *opio;
1654         ulong s;
1655
1656         opio = ctlr->opio;
1657
1658         dprint("ehci %#p port %d: %s speed device: no longer owned\n",
1659                 ctlr->capio, port, ss);
1660         s = opio->portsc[port-1] & ~(Pschange|Psstatuschg);
1661         opio->portsc[port-1] = s | Psowner;
1662         coherence();
1663 }
1664
1665 static int
1666 portreset(Hci *hp, int port, int on)
1667 {
1668         ulong *portscp;
1669         Eopio *opio;
1670         Ctlr *ctlr;
1671         int i;
1672
1673         if(on == 0)
1674                 return 0;
1675
1676         ctlr = hp->aux;
1677         opio = ctlr->opio;
1678         eqlock(&ctlr->portlck);
1679         if(waserror()){
1680                 iunlock(ctlr);
1681                 qunlock(&ctlr->portlck);
1682                 nexterror();
1683         }
1684         portscp = &opio->portsc[port-1];
1685         dprint("ehci %#p port %d reset; sts %#lux\n", ctlr->capio, port, *portscp);
1686         ilock(ctlr);
1687         /* Shalted must be zero, else Psreset will stay set */
1688         if (opio->sts & Shalted)
1689                 iprint("ehci %#p: halted yet trying to reset port\n",
1690                         ctlr->capio);
1691         *portscp = (*portscp & ~Psenable) | Psreset;    /* initiate reset */
1692         coherence();
1693
1694         /*
1695          * usb 2 spec: reset must finish within 20 ms.
1696          * linux says spec says it can take 50 ms. for hubs.
1697          */
1698         for(i = 0; *portscp & Psreset && i < 10; i++)
1699                 delay(10);
1700         if (*portscp & Psreset)
1701                 iprint("ehci %#p: port %d didn't reset within %d ms; sts %#lux\n",
1702                         ctlr->capio, port, i * 10, *portscp);
1703         *portscp &= ~Psreset;           /* force appearance of reset done */
1704         coherence();
1705         delay(10);                      /* ehci spec: enable within 2 ms. */
1706
1707         if((*portscp & Psenable) == 0)
1708                 portlend(ctlr, port, "full");
1709
1710         iunlock(ctlr);
1711         dprint("ehci %#p after port %d reset; sts %#lux\n",
1712                 ctlr->capio, port, *portscp);
1713         qunlock(&ctlr->portlck);
1714         poperror();
1715         return 0;
1716 }
1717
1718 static int
1719 portstatus(Hci *hp, int port)
1720 {
1721         int s, r;
1722         Eopio *opio;
1723         Ctlr *ctlr;
1724
1725         ctlr = hp->aux;
1726         opio = ctlr->opio;
1727         eqlock(&ctlr->portlck);
1728         if(waserror()){
1729                 iunlock(ctlr);
1730                 qunlock(&ctlr->portlck);
1731                 nexterror();
1732         }
1733         ilock(ctlr);
1734         s = opio->portsc[port-1];
1735         if(s & (Psstatuschg | Pschange)){
1736                 opio->portsc[port-1] = s;
1737                 coherence();
1738                 ddprint("ehci %#p port %d status %#x\n", ctlr->capio, port, s);
1739         }
1740         /*
1741          * If the port is a low speed port we yield ownership now
1742          * to the [uo]hci companion controller and pretend it's not here.
1743          */
1744         if((s & Pspresent) != 0 && (s & Pslinemask) == Pslow){
1745                 portlend(ctlr, port, "low");
1746                 s &= ~Pspresent;                /* not for us this time */
1747         }
1748         iunlock(ctlr);
1749         qunlock(&ctlr->portlck);
1750         poperror();
1751
1752         /*
1753          * We must return status bits as a
1754          * get port status hub request would do.
1755          */
1756         r = 0;
1757         if(s & Pspresent)
1758                 r |= HPpresent|HPhigh;
1759         if(s & Psenable)
1760                 r |= HPenable;
1761         if(s & Pssuspend)
1762                 r |= HPsuspend;
1763         if(s & Psreset)
1764                 r |= HPreset;
1765         if(s & Psstatuschg)
1766                 r |= HPstatuschg;
1767         if(s & Pschange)
1768                 r |= HPchange;
1769         return r;
1770 }
1771
1772 static char*
1773 seprintio(char *s, char *e, Qio *io, char *pref)
1774 {
1775         s = seprint(s,e,"%s io %#p qh %#p id %#x", pref, io, io->qh, io->usbid);
1776         s = seprint(s,e," iot %ld", io->iotime);
1777         s = seprint(s,e," tog %#x tok %#x err %s", io->toggle, io->tok, io->err);
1778         return s;
1779 }
1780
1781 static char*
1782 seprintep(char *s, char *e, Ep *ep)
1783 {
1784         Qio *io;
1785         Ctlio *cio;
1786         Ctlr *ctlr;
1787
1788         ctlr = ep->hp->aux;
1789         ilock(ctlr);
1790         if(ep->aux == nil){
1791                 *s = 0;
1792                 iunlock(ctlr);
1793                 return s;
1794         }
1795         switch(ep->ttype){
1796         case Tctl:
1797                 cio = ep->aux;
1798                 s = seprintio(s, e, cio, "c");
1799                 s = seprint(s, e, "\trepl %d ndata %d\n", ep->rhrepl, cio->ndata);
1800                 break;
1801         case Tbulk:
1802         case Tintr:
1803                 io = ep->aux;
1804                 if(ep->mode != OWRITE)
1805                         s = seprintio(s, e, &io[OREAD], "r");
1806                 if(ep->mode != OREAD)
1807                         s = seprintio(s, e, &io[OWRITE], "w");
1808                 break;
1809         case Tiso:
1810                 *s = 0;
1811                 break;
1812         }
1813         iunlock(ctlr);
1814         return s;
1815 }
1816
1817 /*
1818  * halt condition was cleared on the endpoint. update our toggles.
1819  */
1820 static void
1821 clrhalt(Ep *ep)
1822 {
1823         Qio *io;
1824
1825         ep->clrhalt = 0;
1826         coherence();
1827         switch(ep->ttype){
1828         case Tintr:
1829         case Tbulk:
1830                 io = ep->aux;
1831                 if(ep->mode != OREAD){
1832                         qlock(&io[OWRITE]);
1833                         io[OWRITE].toggle = Tddata0;
1834                         deprint("ep clrhalt for io %#p\n", io+OWRITE);
1835                         qunlock(&io[OWRITE]);
1836                 }
1837                 if(ep->mode != OWRITE){
1838                         qlock(&io[OREAD]);
1839                         io[OREAD].toggle = Tddata0;
1840                         deprint("ep clrhalt for io %#p\n", io+OREAD);
1841                         qunlock(&io[OREAD]);
1842                 }
1843                 break;
1844         }
1845 }
1846
1847 static void
1848 xdump(char* pref, void *qh)
1849 {
1850         int i;
1851         ulong *u;
1852
1853         u = qh;
1854         print("%s %#p:", pref, u);
1855         for(i = 0; i < 16; i++)
1856                 if((i%4) == 0)
1857                         print("\n %#8.8ulx", u[i]);
1858                 else
1859                         print(" %#8.8ulx", u[i]);
1860         print("\n");
1861 }
1862
1863 static long
1864 episohscpy(Ctlr *ctlr, Ep *ep, Isoio* iso, uchar *b, long count)
1865 {
1866         int nr;
1867         long tot;
1868         Itd *tdu;
1869
1870         for(tot = 0; iso->tdi != iso->tdu && tot < count; tot += nr){
1871                 tdu = iso->tdu;
1872                 if(itdactive(tdu))
1873                         break;
1874                 nr = tdu->ndata;
1875                 if(tot + nr > count)
1876                         nr = count - tot;
1877                 if(nr == 0)
1878                         print("ehci: ep%d.%d: too many polls\n",
1879                                 ep->dev->nb, ep->nb);
1880                 else{
1881                         iunlock(ctlr);          /* We could page fault here */
1882                         memmove(b+tot, tdu->data, nr);
1883                         ilock(ctlr);
1884                         if(iso->tdu != tdu)
1885                                 continue;
1886                         if(nr < tdu->ndata)
1887                                 memmove(tdu->data, tdu->data+nr, tdu->ndata - nr);
1888                         tdu->ndata -= nr;
1889                         coherence();
1890                 }
1891                 if(tdu->ndata == 0){
1892                         itdinit(iso, tdu);
1893                         iso->tdu = tdu->next;
1894                 }
1895         }
1896         return tot;
1897 }
1898
1899 static long
1900 episofscpy(Ctlr *ctlr, Ep *ep, Isoio* iso, uchar *b, long count)
1901 {
1902         int nr;
1903         long tot;
1904         Sitd *stdu;
1905
1906         for(tot = 0; iso->stdi != iso->stdu && tot < count; tot += nr){
1907                 stdu = iso->stdu;
1908                 if(stdu->csw & Stdactive){
1909                         diprint("ehci: episoread: %#p tdu active\n", iso);
1910                         break;
1911                 }
1912                 nr = stdu->ndata;
1913                 if(tot + nr > count)
1914                         nr = count - tot;
1915                 if(nr == 0)
1916                         print("ehci: ep%d.%d: too many polls\n",
1917                                 ep->dev->nb, ep->nb);
1918                 else{
1919                         iunlock(ctlr);          /* We could page fault here */
1920                         memmove(b+tot, stdu->data, nr);
1921                         ilock(ctlr);
1922                         if(iso->stdu != stdu)
1923                                 continue;
1924                         if(nr < stdu->ndata)
1925                                 memmove(stdu->data, stdu->data+nr,
1926                                         stdu->ndata - nr);
1927                         stdu->ndata -= nr;
1928                         coherence();
1929                 }
1930                 if(stdu->ndata == 0){
1931                         sitdinit(iso, stdu);
1932                         iso->stdu = stdu->next;
1933                 }
1934         }
1935         return tot;
1936 }
1937
1938 static long
1939 episoread(Ep *ep, Isoio *iso, void *a, long count)
1940 {
1941         Ctlr *ctlr;
1942         uchar *b;
1943         long tot;
1944
1945         iso->debug = ep->debug;
1946         diprint("ehci: episoread: %#p ep%d.%d\n", iso, ep->dev->nb, ep->nb);
1947
1948         b = a;
1949         ctlr = ep->hp->aux;
1950         eqlock(iso);
1951         if(waserror()){
1952                 qunlock(iso);
1953                 nexterror();
1954         }
1955         iso->err = nil;
1956         iso->nerrs = 0;
1957         ilock(ctlr);
1958         if(iso->state == Qclose){
1959                 iunlock(ctlr);
1960                 error(iso->err ? iso->err : Eio);
1961         }
1962         iso->state = Qrun;
1963         coherence();
1964         while(isocanread(iso) == 0){
1965                 iunlock(ctlr);
1966                 diprint("ehci: episoread: %#p sleep\n", iso);
1967                 if(waserror()){
1968                         if(iso->err == nil)
1969                                 iso->err = "I/O timed out";
1970                         ilock(ctlr);
1971                         break;
1972                 }
1973                 tsleep(iso, isocanread, iso, ep->tmout);
1974                 poperror();
1975                 ilock(ctlr);
1976         }
1977         if(iso->state == Qclose){
1978                 iunlock(ctlr);
1979                 error(iso->err ? iso->err : Eio);
1980         }
1981         iso->state = Qdone;
1982         coherence();
1983         assert(iso->tdu != iso->tdi);
1984
1985         if(iso->hs != 0)
1986                 tot = episohscpy(ctlr, ep, iso, b, count);
1987         else
1988                 tot = episofscpy(ctlr, ep, iso, b, count);
1989         iunlock(ctlr);
1990         qunlock(iso);
1991         poperror();
1992         diprint("uhci: episoread: %#p %uld bytes err '%s'\n", iso, tot, iso->err);
1993         if(iso->err != nil)
1994                 error(iso->err);
1995         return tot;
1996 }
1997
1998 /*
1999  * iso->tdu is the next place to put data. When it gets full
2000  * it is activated and tdu advanced.
2001  */
2002 static long
2003 putsamples(Ctlr *ctlr, Isoio *iso, uchar *b, long count)
2004 {
2005         long left, tot, n;
2006         Sitd *stdu;
2007         Itd *tdu;
2008
2009         for(tot = 0; isocanwrite(iso) && tot < count; tot += n){
2010                 n = count-tot;
2011                 left = iso->nleft;
2012                 if(iso->hs != 0){
2013                         tdu = iso->tdu;
2014                         if(n > tdu->mdata - left)
2015                                 n = tdu->mdata - left;
2016                         iunlock(ctlr);          /* We could page fault here */
2017                         memmove(tdu->data + left, b + tot, n);
2018                         ilock(ctlr);
2019                         if(iso->tdu != tdu)
2020                                 continue;
2021                         iso->nleft += n;
2022                         if(iso->nleft == tdu->mdata){
2023                                 itdinit(iso, tdu);
2024                                 iso->tdu = tdu->next;
2025                                 iso->nleft = 0;
2026                         }
2027                 }else{
2028                         stdu = iso->stdu;
2029                         if(n > stdu->mdata - left)
2030                                 n = stdu->mdata - left;
2031                         iunlock(ctlr);          /* We could page fault here */
2032                         memmove(stdu->data + left, b + tot, n);
2033                         ilock(ctlr);
2034                         if(iso->stdu != stdu)
2035                                 continue;
2036                         iso->nleft += n;
2037                         if(iso->nleft == stdu->mdata){
2038                                 sitdinit(iso, stdu);
2039                                 iso->stdu = stdu->next;
2040                                 iso->nleft = 0;
2041                         }
2042                 }
2043         }
2044         return tot;
2045 }
2046
2047 /*
2048  * Queue data for writing and return error status from
2049  * last writes done, to maintain buffered data.
2050  */
2051 static long
2052 episowrite(Ep *ep, Isoio *iso, void *a, long count)
2053 {
2054         Ctlr *ctlr;
2055         uchar *b;
2056         int tot, nw;
2057         char *err;
2058
2059         iso->delay = ep->sampledelay * ep->samplesz;
2060         iso->debug = ep->debug;
2061         diprint("ehci: episowrite: %#p ep%d.%d\n", iso, ep->dev->nb, ep->nb);
2062
2063         ctlr = ep->hp->aux;
2064         eqlock(iso);
2065         if(waserror()){
2066                 qunlock(iso);
2067                 nexterror();
2068         }
2069         ilock(ctlr);
2070         if(iso->state == Qclose){
2071                 iunlock(ctlr);
2072                 error(iso->err ? iso->err : Eio);
2073         }
2074         iso->state = Qrun;
2075         coherence();
2076         b = a;
2077         for(tot = 0; tot < count; tot += nw){
2078                 while(isocanwrite(iso) == 0){
2079                         iunlock(ctlr);
2080                         diprint("ehci: episowrite: %#p sleep\n", iso);
2081                         if(waserror()){
2082                                 if(iso->err == nil)
2083                                         iso->err = "I/O timed out";
2084                                 ilock(ctlr);
2085                                 break;
2086                         }
2087                         tsleep(iso, isocanwrite, iso, ep->tmout);
2088                         poperror();
2089                         ilock(ctlr);
2090                 }
2091                 err = iso->err;
2092                 iso->err = nil;
2093                 if(iso->state == Qclose || err != nil){
2094                         iunlock(ctlr);
2095                         error(err ? err : Eio);
2096                 }
2097                 if(iso->state != Qrun)
2098                         panic("episowrite: iso not running");
2099                 nw = putsamples(ctlr, iso, b+tot, count-tot);
2100         }
2101         while(isodelay(iso) == 0){
2102                 iunlock(ctlr);
2103                 sleep(iso, isodelay, iso);
2104                 ilock(ctlr);
2105         }
2106         if(iso->state != Qclose)
2107                 iso->state = Qdone;
2108         iunlock(ctlr);
2109         err = iso->err;         /* in case it failed early */
2110         iso->err = nil;
2111         qunlock(iso);
2112         poperror();
2113         if(err != nil)
2114                 error(err);
2115         diprint("ehci: episowrite: %#p %d bytes\n", iso, tot);
2116         return tot;
2117 }
2118
2119 static int
2120 nexttoggle(int toggle, int count, int maxpkt)
2121 {
2122         int np;
2123
2124         np = count / maxpkt;
2125         if(np == 0)
2126                 np = 1;
2127         if((np % 2) == 0)
2128                 return toggle;
2129         if(toggle == Tddata1)
2130                 return Tddata0;
2131         else
2132                 return Tddata1;
2133 }
2134
2135 static Td*
2136 epgettd(Qio *io, int flags, void *a, int count, int maxpkt)
2137 {
2138         Td *td;
2139         ulong pa;
2140         int i;
2141
2142         if(count > Tdmaxpkt)
2143                 panic("ehci: epgettd: too many bytes");
2144         td = tdalloc();
2145         td->csw = flags | io->toggle | io->tok | count << Tdlenshift |
2146                 Tderr2 | Tderr1;
2147         coherence();
2148
2149         /*
2150          * use the space wasted by alignment as an
2151          * embedded buffer if count bytes fit in there.
2152          */
2153         assert(Align > sizeof(Td));
2154         if(count <= Align - sizeof(Td)){
2155                 td->data = td->sbuff;
2156                 td->buff = nil;
2157         }else
2158                 td->data = td->buff = smalloc(Tdmaxpkt);
2159
2160         pa = PADDR(td->data);
2161         for(i = 0; i < nelem(td->buffer); i++){
2162                 td->buffer[i] = pa;
2163                 if(i > 0)
2164                         td->buffer[i] &= ~0xFFF;
2165                 pa += 0x1000;
2166         }
2167         td->ndata = count;
2168         if(a != nil && count > 0)
2169                 memmove(td->data, a, count);
2170         coherence();
2171         io->toggle = nexttoggle(io->toggle, count, maxpkt);
2172         coherence();
2173         return td;
2174 }
2175
2176 /*
2177  * Try to get them idle
2178  */
2179 static void
2180 aborttds(Qh *qh)
2181 {
2182         Td *td;
2183
2184         qh->state = Qdone;
2185         coherence();
2186         if(qh->sched >= 0 && (qh->eps0 & Qhspeedmask) != Qhhigh)
2187                 qh->eps0 |= Qhint;      /* inactivate on next pass */
2188         coherence();
2189         for(td = qh->tds; td != nil; td = td->next){
2190                 if(td->csw & Tdactive)
2191                         td->ndata = 0;
2192                 td->csw |= Tdhalt;
2193                 coherence();
2194         }
2195 }
2196
2197 /*
2198  * Some controllers do not post the usb/error interrupt after
2199  * the work has been done. It seems that we must poll for them.
2200  */
2201 static int
2202 workpending(void *a)
2203 {
2204         Ctlr *ctlr;
2205
2206         ctlr = a;
2207         return ctlr->nreqs > 0;
2208 }
2209
2210 static void
2211 ehcipoll(void* a)
2212 {
2213         Hci *hp;
2214         Ctlr *ctlr;
2215         Poll *poll;
2216         int i;
2217
2218         hp = a;
2219         ctlr = hp->aux;
2220         poll = &ctlr->poll;
2221         for(;;){
2222                 if(ctlr->nreqs == 0){
2223                         if(0)ddprint("ehcipoll %#p sleep\n", ctlr->capio);
2224                         sleep(poll, workpending, ctlr);
2225                         if(0)ddprint("ehcipoll %#p awaken\n", ctlr->capio);
2226                 }
2227                 for(i = 0; i < 16 && ctlr->nreqs > 0; i++)
2228                         if(ehciintr(hp) == 0)
2229                                  break;
2230                 do{
2231                         tsleep(&up->sleep, return0, 0, 1);
2232                         ehciintr(hp);
2233                 }while(ctlr->nreqs > 0);
2234         }
2235 }
2236
2237 static void
2238 pollcheck(Hci *hp)
2239 {
2240         Ctlr *ctlr;
2241         Poll *poll;
2242
2243         ctlr = hp->aux;
2244         poll = &ctlr->poll;
2245
2246         if(poll->must != 0 && poll->does == 0){
2247                 lock(poll);
2248                 if(poll->must != 0 && poll->does == 0){
2249                         poll->does++;
2250                         print("ehci %#p: polling\n", ctlr->capio);
2251                         kproc("ehcipoll", ehcipoll, hp);
2252                 }
2253                 unlock(poll);
2254         }
2255 }
2256
2257 static int
2258 epiodone(void *a)
2259 {
2260         Qh *qh;
2261
2262         qh = a;
2263         return qh->state != Qrun;
2264 }
2265
2266 static void
2267 epiowait(Hci *hp, Qio *io, int tmout, ulong load)
2268 {
2269         Qh *qh;
2270         int timedout;
2271         Ctlr *ctlr;
2272
2273         ctlr = hp->aux;
2274         qh = io->qh;
2275         ddqprint("ehci io %#p sleep on qh %#p state %s\n",
2276                 io, qh, qhsname[qh->state]);
2277         timedout = 0;
2278         if(waserror()){
2279                 dqprint("ehci io %#p qh %#p timed out\n", io, qh);
2280                 timedout++;
2281         }else{
2282                 if(tmout == 0)
2283                         sleep(io, epiodone, qh);
2284                 else
2285                         tsleep(io, epiodone, qh, tmout);
2286                 poperror();
2287         }
2288
2289         ilock(ctlr);
2290         /* Are we missing interrupts? */
2291         if(qh->state == Qrun){
2292                 iunlock(ctlr);
2293                 ehciintr(hp);
2294                 ilock(ctlr);
2295                 if(qh->state == Qdone){
2296                         dqprint("ehci %#p: polling required\n", ctlr->capio);
2297                         ctlr->poll.must = 1;
2298                         pollcheck(hp);
2299                 }
2300         }
2301
2302         if(qh->state == Qrun){
2303                 dqprint("ehci io %#p qh %#p timed out (no intr?)\n", io, qh);
2304                 timedout = 1;
2305         }else if(qh->state != Qdone && qh->state != Qclose)
2306                 panic("ehci: epio: queue state %d", qh->state);
2307         if(timedout){
2308                 aborttds(io->qh);
2309                 io->err = "request timed out";
2310                 iunlock(ctlr);
2311                 if(!waserror()){
2312                         tsleep(&up->sleep, return0, 0, Abortdelay);
2313                         poperror();
2314                 }
2315                 ilock(ctlr);
2316         }
2317         if(qh->state != Qclose)
2318                 qh->state = Qidle;
2319         coherence();
2320         qhlinktd(qh, nil);
2321         ctlr->load -= load;
2322         ctlr->nreqs--;
2323         iunlock(ctlr);
2324 }
2325
2326 /*
2327  * Non iso I/O.
2328  * To make it work for control transfers, the caller may
2329  * lock the Qio for the entire control transfer.
2330  */
2331 static long
2332 epio(Ep *ep, Qio *io, void *a, long count, int mustlock)
2333 {
2334         int saved, ntds, tmout;
2335         long n, tot;
2336         ulong load;
2337         char *err;
2338         char buf[128];
2339         uchar *c;
2340         Ctlr *ctlr;
2341         Qh* qh;
2342         Td *td, *ltd, *td0, *ntd;
2343
2344         qh = io->qh;
2345         ctlr = ep->hp->aux;
2346         io->debug = ep->debug;
2347         tmout = ep->tmout;
2348         ddeprint("epio: %s ep%d.%d io %#p count %ld load %uld\n",
2349                 io->tok == Tdtokin ? "in" : "out",
2350                 ep->dev->nb, ep->nb, io, count, ctlr->load);
2351         if((ehcidebug > 1 || ep->debug > 1) && io->tok != Tdtokin){
2352                 seprintdata(buf, buf+sizeof(buf), a, count);
2353                 print("echi epio: user data: %s\n", buf);
2354         }
2355         if(mustlock){
2356                 eqlock(io);
2357                 if(waserror()){
2358                         qunlock(io);
2359                         nexterror();
2360                 }
2361         }
2362         io->err = nil;
2363         ilock(ctlr);
2364         if(qh->state == Qclose){        /* Tds released by cancelio */
2365                 iunlock(ctlr);
2366                 error(io->err ? io->err : Eio);
2367         }
2368         if(qh->state != Qidle)
2369                 panic("epio: qh not idle");
2370         qh->state = Qinstall;
2371         iunlock(ctlr);
2372
2373         c = a;
2374         td0 = ltd = nil;
2375         load = tot = 0;
2376         do{
2377                 n = (Tdmaxpkt / ep->maxpkt) * ep->maxpkt;
2378                 if(count-tot < n)
2379                         n = count-tot;
2380                 if(c != nil && io->tok != Tdtokin)
2381                         td = epgettd(io, Tdactive, c+tot, n, ep->maxpkt);
2382                 else
2383                         td = epgettd(io, Tdactive, nil, n, ep->maxpkt);
2384                 if(td0 == nil)
2385                         td0 = td;
2386                 else
2387                         tdlinktd(ltd, td);
2388                 ltd = td;
2389                 tot += n;
2390                 load += ep->load;
2391         }while(tot < count);
2392         if(td0 == nil || ltd == nil)
2393                 panic("epio: no td");
2394
2395         ltd->csw |= Tdioc;              /* the last one interrupts */
2396         coherence();
2397
2398         ddeprint("ehci: load %uld ctlr load %uld\n", load, ctlr->load);
2399         if(ehcidebug > 1 || ep->debug > 1)
2400                 dumptd(td0, "epio: put: ");
2401
2402         ilock(ctlr);
2403         if(qh->state != Qclose){
2404                 io->iotime = TK2MS(MACHP(0)->ticks);
2405                 qh->state = Qrun;
2406                 coherence();
2407                 qhlinktd(qh, td0);
2408                 ctlr->nreqs++;
2409                 ctlr->load += load;
2410         }
2411         iunlock(ctlr);
2412
2413         if(ctlr->poll.does)
2414                 wakeup(&ctlr->poll);
2415
2416         epiowait(ep->hp, io, tmout, load);
2417         if(ehcidebug > 1 || ep->debug > 1){
2418                 dumptd(td0, "epio: got: ");
2419                 qhdump(qh);
2420         }
2421
2422         tot = 0;
2423         c = a;
2424         saved = 0;
2425         ntds = 0;
2426         for(td = td0; td != nil; td = ntd){
2427                 ntds++;
2428                 /*
2429                  * Use td tok, not io tok, because of setup packets.
2430                  * Also, we must save the next toggle value from the
2431                  * last completed Td (in case of a short packet, or
2432                  * fewer than the requested number of packets in the
2433                  * Td being transferred).
2434                  */
2435                 if(td->csw & (Tdhalt|Tdactive))
2436                         saved++;
2437                 else{
2438                         if(!saved){
2439                                 io->toggle = td->csw & Tddata1;
2440                                 coherence();
2441                         }
2442                         tot += td->ndata;
2443                         if(c != nil && (td->csw & Tdtok) == Tdtokin && td->ndata > 0){
2444                                 memmove(c, td->data, td->ndata);
2445                                 c += td->ndata;
2446                         }
2447                 }
2448                 ntd = td->next;
2449                 tdfree(td);
2450         }
2451         err = io->err;
2452         if(mustlock){
2453                 qunlock(io);
2454                 poperror();
2455         }
2456         ddeprint("epio: io %#p: %d tds: return %ld err '%s'\n",
2457                 io, ntds, tot, err);
2458         if(err == Estalled)
2459                 return 0;       /* that's our convention */
2460         if(err != nil)
2461                 error(err);
2462         if(tot < 0)
2463                 error(Eio);
2464         return tot;
2465 }
2466
2467 static long
2468 epread(Ep *ep, void *a, long count)
2469 {
2470         Ctlio *cio;
2471         Qio *io;
2472         Isoio *iso;
2473         char buf[160];
2474         ulong delta;
2475
2476         ddeprint("ehci: epread\n");
2477         if(ep->aux == nil)
2478                 panic("epread: not open");
2479
2480         pollcheck(ep->hp);
2481
2482         switch(ep->ttype){
2483         case Tctl:
2484                 cio = ep->aux;
2485                 eqlock(cio);
2486                 if(waserror()){
2487                         qunlock(cio);
2488                         nexterror();
2489                 }
2490                 ddeprint("epread ctl ndata %d\n", cio->ndata);
2491                 if(cio->ndata < 0)
2492                         error("request expected");
2493                 else if(cio->ndata == 0){
2494                         cio->ndata = -1;
2495                         count = 0;
2496                 }else{
2497                         if(count > cio->ndata)
2498                                 count = cio->ndata;
2499                         if(count > 0)
2500                                 memmove(a, cio->data, count);
2501                         /* BUG for big transfers */
2502                         free(cio->data);
2503                         cio->data = nil;
2504                         cio->ndata = 0; /* signal EOF next time */
2505                 }
2506                 qunlock(cio);
2507                 poperror();
2508                 if(ehcidebug>1 || ep->debug){
2509                         seprintdata(buf, buf+sizeof(buf), a, count);
2510                         print("epread: %s\n", buf);
2511                 }
2512                 return count;
2513         case Tbulk:
2514                 io = ep->aux;
2515                 if(ep->clrhalt)
2516                         clrhalt(ep);
2517                 return epio(ep, &io[OREAD], a, count, 1);
2518         case Tintr:
2519                 io = ep->aux;
2520                 delta = TK2MS(MACHP(0)->ticks) - io[OREAD].iotime + 1;
2521                 if(delta < ep->pollival / 2)
2522                         tsleep(&up->sleep, return0, 0, ep->pollival/2 - delta);
2523                 if(ep->clrhalt)
2524                         clrhalt(ep);
2525                 return epio(ep, &io[OREAD], a, count, 1);
2526         case Tiso:
2527                 iso = ep->aux;
2528                 return episoread(ep, iso, a, count);
2529         }
2530         return -1;
2531 }
2532
2533 /*
2534  * Control transfers are one setup write (data0)
2535  * plus zero or more reads/writes (data1, data0, ...)
2536  * plus a final write/read with data1 to ack.
2537  * For both host to device and device to host we perform
2538  * the entire transfer when the user writes the request,
2539  * and keep any data read from the device for a later read.
2540  * We call epio three times instead of placing all Tds at
2541  * the same time because doing so leads to crc/tmout errors
2542  * for some devices.
2543  * Upon errors on the data phase we must still run the status
2544  * phase or the device may cease responding in the future.
2545  */
2546 static long
2547 epctlio(Ep *ep, Ctlio *cio, void *a, long count)
2548 {
2549         uchar *c;
2550         long len;
2551
2552         ddeprint("epctlio: cio %#p ep%d.%d count %ld\n",
2553                 cio, ep->dev->nb, ep->nb, count);
2554         if(count < Rsetuplen)
2555                 error("short usb comand");
2556         eqlock(cio);
2557         free(cio->data);
2558         cio->data = nil;
2559         cio->ndata = 0;
2560         if(waserror()){
2561                 free(cio->data);
2562                 cio->data = nil;
2563                 cio->ndata = 0;
2564                 qunlock(cio);
2565                 nexterror();
2566         }
2567
2568         /* set the address if unset and out of configuration state */
2569         if(ep->dev->state != Dconfig && ep->dev->state != Dreset)
2570                 if(cio->usbid == 0){
2571                         cio->usbid = (ep->nb&Epmax) << 7 | ep->dev->nb&Devmax;
2572                         coherence();
2573                         qhsetaddr(cio->qh, cio->usbid);
2574                 }
2575         /* adjust maxpkt if the user has learned a different one */
2576         if(qhmaxpkt(cio->qh) != ep->maxpkt)
2577                 qhsetmaxpkt(cio->qh, ep->maxpkt);
2578         c = a;
2579         cio->tok = Tdtoksetup;
2580         cio->toggle = Tddata0;
2581         coherence();
2582         if(epio(ep, cio, a, Rsetuplen, 0) < Rsetuplen)
2583                 error(Eio);
2584         a = c + Rsetuplen;
2585         count -= Rsetuplen;
2586
2587         cio->toggle = Tddata1;
2588         if(c[Rtype] & Rd2h){
2589                 cio->tok = Tdtokin;
2590                 len = GET2(c+Rcount);
2591                 if(len <= 0)
2592                         error("bad length in d2h request");
2593                 if(len > Maxctllen)
2594                         error("d2h data too large to fit in ehci");
2595                 a = cio->data = smalloc(len+1);
2596         }else{
2597                 cio->tok = Tdtokout;
2598                 len = count;
2599         }
2600         coherence();
2601         if(len > 0)
2602                 if(waserror())
2603                         len = -1;
2604                 else{
2605                         len = epio(ep, cio, a, len, 0);
2606                         poperror();
2607                 }
2608         if(c[Rtype] & Rd2h){
2609                 count = Rsetuplen;
2610                 cio->ndata = len;
2611                 cio->tok = Tdtokout;
2612         }else{
2613                 if(len < 0)
2614                         count = -1;
2615                 else
2616                         count = Rsetuplen + len;
2617                 cio->tok = Tdtokin;
2618         }
2619         cio->toggle = Tddata1;
2620         coherence();
2621         epio(ep, cio, nil, 0, 0);
2622         qunlock(cio);
2623         poperror();
2624         ddeprint("epctlio cio %#p return %ld\n", cio, count);
2625         return count;
2626 }
2627
2628 static long
2629 epwrite(Ep *ep, void *a, long count)
2630 {
2631         Qio *io;
2632         Ctlio *cio;
2633         Isoio *iso;
2634         ulong delta;
2635
2636         pollcheck(ep->hp);
2637
2638         ddeprint("ehci: epwrite ep%d.%d\n", ep->dev->nb, ep->nb);
2639         if(ep->aux == nil)
2640                 panic("ehci: epwrite: not open");
2641         switch(ep->ttype){
2642         case Tctl:
2643                 cio = ep->aux;
2644                 return epctlio(ep, cio, a, count);
2645         case Tbulk:
2646                 io = ep->aux;
2647                 if(ep->clrhalt)
2648                         clrhalt(ep);
2649                 return epio(ep, &io[OWRITE], a, count, 1);
2650         case Tintr:
2651                 io = ep->aux;
2652                 delta = TK2MS(MACHP(0)->ticks) - io[OWRITE].iotime + 1;
2653                 if(delta < ep->pollival)
2654                         tsleep(&up->sleep, return0, 0, ep->pollival - delta);
2655                 if(ep->clrhalt)
2656                         clrhalt(ep);
2657                 return epio(ep, &io[OWRITE], a, count, 1);
2658         case Tiso:
2659                 iso = ep->aux;
2660                 return episowrite(ep, iso, a, count);
2661         }
2662         return -1;
2663 }
2664
2665 static void
2666 isofsinit(Ep *ep, Isoio *iso)
2667 {
2668         long left;
2669         Sitd *td, *ltd;
2670         int i;
2671         ulong frno;
2672
2673         left = 0;
2674         ltd = nil;
2675         frno = iso->td0frno;
2676         for(i = 0; i < iso->nframes; i++){
2677                 td = sitdalloc();
2678                 td->data = iso->data + i * ep->maxpkt;
2679                 td->epc = ep->dev->port << Stdportshift;
2680                 td->epc |= ep->dev->hub << Stdhubshift;
2681                 td->epc |= ep->nb << Stdepshift;
2682                 td->epc |= ep->dev->nb << Stddevshift;
2683                 td->mfs = 034 << Stdscmshift | 1 << Stdssmshift;
2684                 if(ep->mode == OREAD){
2685                         td->epc |= Stdin;
2686                         td->mdata = ep->maxpkt;
2687                 }else{
2688                         td->mdata = (ep->hz+left) * ep->pollival / 1000;
2689                         td->mdata *= ep->samplesz;
2690                         left = (ep->hz+left) * ep->pollival % 1000;
2691                         if(td->mdata > ep->maxpkt){
2692                                 print("ehci: ep%d.%d: size > maxpkt\n",
2693                                         ep->dev->nb, ep->nb);
2694                                 print("size = %ld max = %ld\n",
2695                                         td->mdata,ep->maxpkt);
2696                                 td->mdata = ep->maxpkt;
2697                         }
2698                 }
2699                 coherence();
2700
2701                 iso->sitdps[frno] = td;
2702                 coherence();
2703                 sitdinit(iso, td);
2704                 if(ltd != nil)
2705                         ltd->next = td;
2706                 ltd = td;
2707                 frno = TRUNC(frno+ep->pollival, Nisoframes);
2708         }
2709         ltd->next = iso->sitdps[iso->td0frno];
2710         coherence();
2711 }
2712
2713 static void
2714 isohsinit(Ep *ep, Isoio *iso)
2715 {
2716         int ival, p;
2717         long left;
2718         ulong frno, i, pa;
2719         Itd *ltd, *td;
2720
2721         iso->hs = 1;
2722         ival = 1;
2723         if(ep->pollival > 8)
2724                 ival = ep->pollival/8;
2725         left = 0;
2726         ltd = nil;
2727         frno = iso->td0frno;
2728         for(i = 0; i < iso->nframes; i++){
2729                 td = itdalloc();
2730                 td->data = iso->data + i * 8 * iso->maxsize;
2731                 pa = PADDR(td->data) & ~0xFFF;
2732                 for(p = 0; p < 8; p++)
2733                         td->buffer[i] = pa + p * 0x1000;
2734                 td->buffer[0] = PADDR(iso->data) & ~0xFFF |
2735                         ep->nb << Itdepshift | ep->dev->nb << Itddevshift;
2736                 if(ep->mode == OREAD)
2737                         td->buffer[1] |= Itdin;
2738                 else
2739                         td->buffer[1] |= Itdout;
2740                 td->buffer[1] |= ep->maxpkt << Itdmaxpktshift;
2741                 td->buffer[2] |= ep->ntds << Itdntdsshift;
2742
2743                 if(ep->mode == OREAD)
2744                         td->mdata = 8 * iso->maxsize;
2745                 else{
2746                         td->mdata = (ep->hz + left) * ep->pollival / 1000;
2747                         td->mdata *= ep->samplesz;
2748                         left = (ep->hz + left) * ep->pollival % 1000;
2749                 }
2750                 coherence();
2751                 iso->itdps[frno] = td;
2752                 coherence();
2753                 itdinit(iso, td);
2754                 if(ltd != nil)
2755                         ltd->next = td;
2756                 ltd = td;
2757                 frno = TRUNC(frno + ival, Nisoframes);
2758         }
2759 }
2760
2761 static void
2762 isoopen(Ctlr *ctlr, Ep *ep)
2763 {
2764         int ival;               /* pollival in ms */
2765         int tpf;                /* tds per frame */
2766         int i, n, w, woff;
2767         ulong frno;
2768         Isoio *iso;
2769
2770         iso = ep->aux;
2771         switch(ep->mode){
2772         case OREAD:
2773                 iso->tok = Tdtokin;
2774                 break;
2775         case OWRITE:
2776                 iso->tok = Tdtokout;
2777                 break;
2778         default:
2779                 error("iso i/o is half-duplex");
2780         }
2781         iso->usbid = ep->nb << 7 | ep->dev->nb & Devmax;
2782         iso->state = Qidle;
2783         coherence();
2784         iso->debug = ep->debug;
2785         ival = ep->pollival;
2786         tpf = 1;
2787         if(ep->dev->speed == Highspeed){
2788                 tpf = 8;
2789                 if(ival <= 8)
2790                         ival = 1;
2791                 else
2792                         ival /= 8;
2793         }
2794         assert(ival != 0);
2795         iso->nframes = Nisoframes / ival;
2796         if(iso->nframes < 3)
2797                 error("uhci isoopen bug");      /* we need at least 3 tds */
2798         iso->maxsize = ep->ntds * ep->maxpkt;
2799         if(ctlr->load + ep->load > 800)
2800                 print("usb: ehci: bandwidth may be exceeded\n");
2801         ilock(ctlr);
2802         ctlr->load += ep->load;
2803         ctlr->isoload += ep->load;
2804         ctlr->nreqs++;
2805         dprint("ehci: load %uld isoload %uld\n", ctlr->load, ctlr->isoload);
2806         diprint("iso nframes %d pollival %uld ival %d maxpkt %uld ntds %d\n",
2807                 iso->nframes, ep->pollival, ival, ep->maxpkt, ep->ntds);
2808         iunlock(ctlr);
2809         if(ctlr->poll.does)
2810                 wakeup(&ctlr->poll);
2811
2812         /*
2813          * From here on this cannot raise errors
2814          * unless we catch them and release here all memory allocated.
2815          */
2816         assert(ep->maxpkt > 0 && ep->ntds > 0 && ep->ntds < 4);
2817         assert(ep->maxpkt <= 1024);
2818         iso->tdps = smalloc(sizeof(uintptr) * Nisoframes);
2819         iso->data = smalloc(iso->nframes * tpf * ep->ntds * ep->maxpkt);
2820         iso->td0frno = TRUNC(ctlr->opio->frno + 10, Nisoframes);
2821         /* read: now; write: 1s ahead */
2822
2823         if(ep->dev->speed == Highspeed)
2824                 isohsinit(ep, iso);
2825         else
2826                 isofsinit(ep, iso);
2827         iso->tdu = iso->tdi = iso->itdps[iso->td0frno];
2828         iso->stdu = iso->stdi = iso->sitdps[iso->td0frno];
2829         coherence();
2830
2831         ilock(ctlr);
2832         frno = iso->td0frno;
2833         for(i = 0; i < iso->nframes; i++){
2834                 *iso->tdps[frno] = ctlr->frames[frno];
2835                 frno = TRUNC(frno+ival, Nisoframes);
2836         }
2837
2838         /*
2839          * Iso uses a virtual frame window of Nisoframes, and we must
2840          * fill the actual ctlr frame array by placing ctlr->nframes/Nisoframes
2841          * copies of the window in the frame array.
2842          */
2843         assert(ctlr->nframes >= Nisoframes && Nisoframes >= iso->nframes);
2844         assert(Nisoframes >= Nintrleafs);
2845         n = ctlr->nframes / Nisoframes;
2846         for(w = 0; w < n; w++){
2847                 frno = iso->td0frno;
2848                 woff = w * Nisoframes;
2849                 for(i = 0; i < iso->nframes ; i++){
2850                         assert(woff+frno < ctlr->nframes);
2851                         assert(iso->tdps[frno] != nil);
2852                         if(ep->dev->speed == Highspeed)
2853                                 ctlr->frames[woff+frno] = PADDR(iso->tdps[frno])
2854                                         |Litd;
2855                         else
2856                                 ctlr->frames[woff+frno] = PADDR(iso->tdps[frno])
2857                                         |Lsitd;
2858                         coherence();
2859                         frno = TRUNC(frno+ep->pollival, Nisoframes);
2860                 }
2861         }
2862         coherence();
2863         iso->next = ctlr->iso;
2864         ctlr->iso = iso;
2865         coherence();
2866         iso->state = Qdone;
2867         iunlock(ctlr);
2868         if(ehcidebug > 1 || iso->debug >1)
2869                 isodump(iso, 0);
2870 }
2871
2872 /*
2873  * Allocate the endpoint and set it up for I/O
2874  * in the controller. This must follow what's said
2875  * in Ep regarding configuration, including perhaps
2876  * the saved toggles (saved on a previous close of
2877  * the endpoint data file by epclose).
2878  */
2879 static void
2880 epopen(Ep *ep)
2881 {
2882         Ctlr *ctlr;
2883         Ctlio *cio;
2884         Qio *io;
2885         int usbid;
2886
2887         ctlr = ep->hp->aux;
2888         deprint("ehci: epopen ep%d.%d\n", ep->dev->nb, ep->nb);
2889         if(ep->aux != nil)
2890                 panic("ehci: epopen called with open ep");
2891         if(waserror()){
2892                 free(ep->aux);
2893                 ep->aux = nil;
2894                 nexterror();
2895         }
2896         switch(ep->ttype){
2897         case Tnone:
2898                 error("endpoint not configured");
2899         case Tiso:
2900                 ep->aux = smalloc(sizeof(Isoio));
2901                 isoopen(ctlr, ep);
2902                 break;
2903         case Tctl:
2904                 cio = ep->aux = smalloc(sizeof(Ctlio));
2905                 cio->debug = ep->debug;
2906                 cio->ndata = -1;
2907                 cio->data = nil;
2908                 if(ep->dev->isroot != 0 && ep->nb == 0) /* root hub */
2909                         break;
2910                 cio->qh = qhalloc(ctlr, ep, cio, "epc");
2911                 break;
2912         case Tbulk:
2913                 ep->pollival = 1;       /* assume this; doesn't really matter */
2914                 /* and fall... */
2915         case Tintr:
2916                 io = ep->aux = smalloc(sizeof(Qio)*2);
2917                 io[OREAD].debug = io[OWRITE].debug = ep->debug;
2918                 usbid = (ep->nb&Epmax) << 7 | ep->dev->nb &Devmax;
2919                 assert(ep->pollival != 0);
2920                 if(ep->mode != OREAD){
2921                         if(ep->toggle[OWRITE] != 0)
2922                                 io[OWRITE].toggle = Tddata1;
2923                         else
2924                                 io[OWRITE].toggle = Tddata0;
2925                         io[OWRITE].tok = Tdtokout;
2926                         io[OWRITE].usbid = usbid;
2927                         io[OWRITE].bw = ep->maxpkt*1000/ep->pollival; /* bytes/s */
2928                         io[OWRITE].qh = qhalloc(ctlr, ep, io+OWRITE, "epw");
2929                 }
2930                 if(ep->mode != OWRITE){
2931                         if(ep->toggle[OREAD] != 0)
2932                                 io[OREAD].toggle = Tddata1;
2933                         else
2934                                 io[OREAD].toggle = Tddata0;
2935                         io[OREAD].tok = Tdtokin;
2936                         io[OREAD].usbid = usbid;
2937                         io[OREAD].bw = ep->maxpkt*1000/ep->pollival; /* bytes/s */
2938                         io[OREAD].qh = qhalloc(ctlr, ep, io+OREAD, "epr");
2939                 }
2940                 break;
2941         }
2942         coherence();
2943         if(ehcidebug>1 || ep->debug)
2944                 dump(ep->hp);
2945         deprint("ehci: epopen done\n");
2946         poperror();
2947 }
2948
2949 static void
2950 cancelio(Ctlr *ctlr, Qio *io)
2951 {
2952         Qh *qh;
2953
2954         ilock(ctlr);
2955         qh = io->qh;
2956         if(io == nil || io->qh == nil || io->qh->state == Qclose){
2957                 iunlock(ctlr);
2958                 return;
2959         }
2960         dqprint("ehci: cancelio for qh %#p state %s\n",
2961                 qh, qhsname[qh->state]);
2962         aborttds(qh);
2963         qh->state = Qclose;
2964         iunlock(ctlr);
2965         if(!waserror()){
2966                 tsleep(&up->sleep, return0, 0, Abortdelay);
2967                 poperror();
2968         }
2969         wakeup(io);
2970         qlock(io);
2971         /* wait for epio if running */
2972         qunlock(io);
2973
2974         qhfree(ctlr, qh);
2975         io->qh = nil;
2976 }
2977
2978 static void
2979 cancelisoio(Ctlr *ctlr, Isoio *iso, int pollival, ulong load)
2980 {
2981         int frno, i, n, t, w, woff;
2982         ulong *lp, *tp;
2983         Isoio **il;
2984         Itd *td;
2985         Sitd *std;
2986
2987         ilock(ctlr);
2988         if(iso->state == Qclose){
2989                 iunlock(ctlr);
2990                 return;
2991         }
2992         ctlr->nreqs--;
2993         if(iso->state != Qrun && iso->state != Qdone)
2994                 panic("bad iso state");
2995         iso->state = Qclose;
2996         coherence();
2997         if(ctlr->isoload < load)
2998                 panic("ehci: low isoload");
2999         ctlr->isoload -= load;
3000         ctlr->load -= load;
3001         for(il = &ctlr->iso; *il != nil; il = &(*il)->next)
3002                 if(*il == iso)
3003                         break;
3004         if(*il == nil)
3005                 panic("cancleiso: not found");
3006         *il = iso->next;
3007
3008         frno = iso->td0frno;
3009         for(i = 0; i < iso->nframes; i++){
3010                 tp = iso->tdps[frno];
3011                 if(iso->hs != 0){
3012                         td = iso->itdps[frno];
3013                         for(t = 0; t < nelem(td->csw); t++)
3014                                 td->csw[t] &= ~(Itdioc|Itdactive);
3015                 }else{
3016                         std = iso->sitdps[frno];
3017                         std->csw &= ~(Stdioc|Stdactive);
3018                 }
3019                 coherence();
3020                 for(lp = &ctlr->frames[frno]; !(*lp & Lterm);
3021                     lp = &LPTR(*lp)[0])
3022                         if(LPTR(*lp) == tp)
3023                                 break;
3024                 if(*lp & Lterm)
3025                         panic("cancelisoio: td not found");
3026                 *lp = tp[0];
3027                 /*
3028                  * Iso uses a virtual frame window of Nisoframes, and we must
3029                  * restore pointers in copies of the window kept at ctlr->frames.
3030                  */
3031                 if(lp == &ctlr->frames[frno]){
3032                         n = ctlr->nframes / Nisoframes;
3033                         for(w = 1; w < n; w++){
3034                                 woff = w * Nisoframes;
3035                                 ctlr->frames[woff+frno] = *lp;
3036                         }
3037                 }
3038                 coherence();
3039                 frno = TRUNC(frno+pollival, Nisoframes);
3040         }
3041         iunlock(ctlr);
3042
3043         /*
3044          * wakeup anyone waiting for I/O and
3045          * wait to be sure no I/O is in progress in the controller.
3046          * and then wait to be sure episo* is no longer running.
3047          */
3048         wakeup(iso);
3049         diprint("cancelisoio iso %#p waiting for I/O to cease\n", iso);
3050         tsleep(&up->sleep, return0, 0, 5);
3051         qlock(iso);
3052         qunlock(iso);
3053         diprint("cancelisoio iso %#p releasing iso\n", iso);
3054
3055         frno = iso->td0frno;
3056         for(i = 0; i < iso->nframes; i++){
3057                 if(iso->hs != 0)
3058                         itdfree(iso->itdps[frno]);
3059                 else
3060                         sitdfree(iso->sitdps[frno]);
3061                 iso->tdps[frno] = nil;
3062                 frno = TRUNC(frno+pollival, Nisoframes);
3063         }
3064         free(iso->tdps);
3065         iso->tdps = nil;
3066         free(iso->data);
3067         iso->data = nil;
3068         coherence();
3069 }
3070
3071 static void
3072 epclose(Ep *ep)
3073 {
3074         Qio *io;
3075         Ctlio *cio;
3076         Isoio *iso;
3077         Ctlr *ctlr;
3078
3079         ctlr = ep->hp->aux;
3080         deprint("ehci: epclose ep%d.%d\n", ep->dev->nb, ep->nb);
3081
3082         if(ep->aux == nil)
3083                 panic("ehci: epclose called with closed ep");
3084         switch(ep->ttype){
3085         case Tctl:
3086                 cio = ep->aux;
3087                 cancelio(ctlr, cio);
3088                 free(cio->data);
3089                 cio->data = nil;
3090                 break;
3091         case Tintr:
3092         case Tbulk:
3093                 io = ep->aux;
3094                 ep->toggle[OREAD] = ep->toggle[OWRITE] = 0;
3095                 if(ep->mode != OWRITE){
3096                         cancelio(ctlr, &io[OREAD]);
3097                         if(io[OREAD].toggle == Tddata1)
3098                                 ep->toggle[OREAD] = 1;
3099                 }
3100                 if(ep->mode != OREAD){
3101                         cancelio(ctlr, &io[OWRITE]);
3102                         if(io[OWRITE].toggle == Tddata1)
3103                                 ep->toggle[OWRITE] = 1;
3104                 }
3105                 coherence();
3106                 break;
3107         case Tiso:
3108                 iso = ep->aux;
3109                 cancelisoio(ctlr, iso, ep->pollival, ep->load);
3110                 break;
3111         default:
3112                 panic("epclose: bad ttype");
3113         }
3114         free(ep->aux);
3115         ep->aux = nil;
3116 }
3117
3118 /*
3119  * return smallest power of 2 >= n
3120  */
3121 static int
3122 flog2(int n)
3123 {
3124         int i;
3125
3126         for(i = 0; (1 << i) < n; i++)
3127                 ;
3128         return i;
3129 }
3130
3131 /*
3132  * build the periodic scheduling tree:
3133  * framesize must be a multiple of the tree size
3134  */
3135 static void
3136 mkqhtree(Ctlr *ctlr)
3137 {
3138         int i, n, d, o, leaf0, depth;
3139         ulong leafs[Nintrleafs];
3140         Qh *qh;
3141         Qh **tree;
3142         Qtree *qt;
3143
3144         depth = flog2(Nintrleafs);
3145         n = (1 << (depth+1)) - 1;
3146         qt = mallocz(sizeof(*qt), 1);
3147         if(qt == nil)
3148                 panic("ehci: mkqhtree: no memory");
3149         qt->nel = n;
3150         qt->depth = depth;
3151         qt->bw = mallocz(n * sizeof(qt->bw), 1);
3152         qt->root = tree = mallocz(n * sizeof(Qh *), 1);
3153         if(qt->bw == nil || tree == nil)
3154                 panic("ehci: mkqhtree: no memory");
3155         for(i = 0; i < n; i++){
3156                 tree[i] = qh = edalloc();
3157                 if(qh == nil)
3158                         panic("ehci: mkqhtree: no memory");
3159                 qh->nlink = qh->alink = qh->link = Lterm;
3160                 qh->csw = Tdhalt;
3161                 qh->state = Qidle;
3162                 coherence();
3163                 if(i > 0)
3164                         qhlinkqh(tree[i], tree[(i-1)/2]);
3165         }
3166         ctlr->ntree = i;
3167         dprint("ehci: tree: %d endpoints allocated\n", i);
3168
3169         /* distribute leaves evenly round the frame list */
3170         leaf0 = n / 2;
3171         for(i = 0; i < Nintrleafs; i++){
3172                 o = 0;
3173                 for(d = 0; d < depth; d++){
3174                         o <<= 1;
3175                         if(i & (1 << d))
3176                                 o |= 1;
3177                 }
3178                 if(leaf0 + o >= n){
3179                         print("leaf0=%d o=%d i=%d n=%d\n", leaf0, o, i, n);
3180                         break;
3181                 }
3182                 leafs[i] = PADDR(tree[leaf0 + o]) | Lqh;
3183         }
3184         assert((ctlr->nframes % Nintrleafs) == 0);
3185         for(i = 0; i < ctlr->nframes; i += Nintrleafs){
3186                 memmove(ctlr->frames + i, leafs, sizeof leafs);
3187                 coherence();
3188         }
3189         ctlr->tree = qt;
3190         coherence();
3191 }
3192
3193 void
3194 ehcimeminit(Ctlr *ctlr)
3195 {
3196         int i, frsize;
3197         Eopio *opio;
3198
3199         opio = ctlr->opio;
3200         frsize = ctlr->nframes * sizeof(ulong);
3201         assert((frsize & 0xFFF) == 0);          /* must be 4k aligned */
3202         ctlr->frames = xspanalloc(frsize, frsize, 0);
3203         if(ctlr->frames == nil)
3204                 panic("ehci reset: no memory");
3205
3206         for (i = 0; i < ctlr->nframes; i++)
3207                 ctlr->frames[i] = Lterm;
3208         opio->frbase = PADDR(ctlr->frames);
3209         opio->frno = 0;
3210         coherence();
3211
3212         qhalloc(ctlr, nil, nil, nil);   /* init async list */
3213         mkqhtree(ctlr);                 /* init sync list */
3214         edfree(edalloc());              /* try to get some ones pre-allocated */
3215
3216         dprint("ehci %#p flb %#lux frno %#lux\n",
3217                 ctlr->capio, opio->frbase, opio->frno);
3218 }
3219
3220 static void
3221 init(Hci *hp)
3222 {
3223         Ctlr *ctlr;
3224         Eopio *opio;
3225         static int ctlrno;
3226         int i;
3227
3228         hp->highspeed = 1;
3229         ctlr = hp->aux;
3230         opio = ctlr->opio;
3231         dprint("ehci %#p init\n", ctlr->capio);
3232
3233         ilock(ctlr);
3234         /*
3235          * Unless we activate frroll interrupt
3236          * some machines won't post other interrupts.
3237          */
3238         opio->intr = Iusb|Ierr|Iportchg|Ihcerr|Iasync;
3239         coherence();
3240         opio->cmd |= Cpse;
3241         coherence();
3242         opio->cmd |= Case;
3243         coherence();
3244         ehcirun(ctlr, 1);
3245         /*
3246          * route all ports by default to only one ehci (the first).
3247          * it's not obvious how multiple ehcis could work and on some
3248          * machines, setting Callmine on all ehcis makes the machine seize up.
3249          */
3250         opio->config = (ctlrno == 0 ? Callmine : 0);
3251         coherence();
3252
3253         for (i = 0; i < hp->nports; i++)
3254                 opio->portsc[i] = Pspower;
3255         iunlock(ctlr);
3256         if(ehcidebug > 1)
3257                 dump(hp);
3258         ctlrno++;
3259 }
3260
3261 void
3262 ehcilinkage(Hci *hp)
3263 {
3264         hp->init = init;
3265         hp->dump = dump;
3266         hp->interrupt = interrupt;
3267         hp->epopen = epopen;
3268         hp->epclose = epclose;
3269         hp->epread = epread;
3270         hp->epwrite = epwrite;
3271         hp->seprintep = seprintep;
3272         hp->portenable = portenable;
3273         hp->portreset = portreset;
3274         hp->portstatus = portstatus;
3275 //      hp->shutdown = shutdown;
3276 //      hp->debug = setdebug;
3277         hp->type = "ehci";
3278 }