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