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