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