]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/pc/usbuhci.c
usb: fix isowrite putsamples race
[plan9front.git] / sys / src / 9 / pc / usbuhci.c
1 /*
2  * USB Universal Host Controller Interface (sic) driver.
3  *
4  * BUGS:
5  * - Too many delays and ilocks.
6  * - bandwidth admission control must be done per-frame.
7  * - interrupt endpoints should go on a tree like [oe]hci.
8  * - must warn of power overruns.
9  */
10
11 #include        "u.h"
12 #include        "../port/lib.h"
13 #include        "mem.h"
14 #include        "dat.h"
15 #include        "fns.h"
16 #include        "io.h"
17 #include        "../port/error.h"
18 #include        "../port/usb.h"
19
20 typedef struct Ctlio Ctlio;
21 typedef struct Ctlr Ctlr;
22 typedef struct Isoio Isoio;
23 typedef struct Qh Qh;
24 typedef struct Qhpool Qhpool;
25 typedef struct Qio Qio;
26 typedef struct Td Td;
27 typedef struct Tdpool Tdpool;
28
29 enum
30 {
31         Resetdelay      = 100,          /* delay after a controller reset (ms) */
32         Enabledelay     = 100,          /* waiting for a port to enable */
33         Abortdelay      = 5,            /* delay after cancelling Tds (ms) */
34         Incr            = 64,           /* for Td and Qh pools */
35
36         Tdatomic        = 8,            /* max nb. of Tds per bulk I/O op. */
37
38         /* Queue states (software) */
39         Qidle           = 0,
40         Qinstall,
41         Qrun,
42         Qdone,
43         Qclose,
44         Qfree,
45
46         /*
47          * HW constants
48          */
49
50         Nframes         = 1024,         /* 2ⁿ for xspanalloc; max 1024 */
51         Align           = 16,           /* for data structures */
52
53         /* Size of small buffer kept within Tds. (software) */
54         /* Keep as a multiple of Align to maintain alignment of Tds in pool */
55         Tdndata         = 1*Align,
56
57         /* i/o space
58          * Some ports are short, some are long, some are byte.
59          * We use ins[bsl] and not vmap.
60          */
61         Cmd             = 0,
62                 Crun            = 0x01,
63                 Chcreset        = 0x02, /* host controller reset */
64                 Cgreset         = 0x04, /* global reset */
65                 Cegsm           = 0x08, /* enter global suspend */
66                 Cfgr            = 0x10, /* forge global resume */
67                 Cdbg            = 0x20, /* single step, debug */
68                 Cmaxp           = 0x80, /* max packet */
69
70         Status          = 2,
71                 Susbintr                = 0x01, /* interrupt */
72                 Seintr          = 0x02, /* error interrupt */
73                 Sresume         = 0x04, /* resume detect */
74                 Shserr          = 0x08, /* host system error */
75                 Shcerr          = 0x10, /* host controller error */
76                 Shalted         = 0x20, /* controller halted */
77                 Sall            = 0x3F,
78
79         Usbintr                 = 4,
80                 Itmout          = 0x01, /* timeout or crc */
81                 Iresume         = 0x02, /* resume interrupt enable */
82                 Ioc             = 0x04, /* interrupt on complete */
83                 Ishort          = 0x08, /* short packet interrupt */
84                 Iall            = 0x0F,
85         Frnum           = 6,
86         Flbaseadd       = 8,
87         SOFmod          = 0xC,          /* start of frame modifier register */
88
89         Portsc0         = 0x10,
90                 PSpresent       = 0x0001,       /* device present */
91                 PSstatuschg     = 0x0002,       /* PSpresent changed */
92                 PSenable        = 0x0004,       /* device enabled */
93                 PSchange        = 0x0008,       /* PSenable changed */
94                 PSresume        = 0x0040,       /* resume detected */
95                 PSreserved1     = 0x0080,       /* always read as 1; reserved */
96                 PSslow          = 0x0100,       /* device has low speed */
97                 PSreset         = 0x0200,       /* port reset */
98                 PSsuspend       = 0x1000,       /* port suspended */
99
100         /* Transfer descriptor link */
101         Tdterm          = 0x1,          /* nil (terminate) */
102         Tdlinkqh        = 0x2,                  /* link refers to a QH */
103         Tdvf            = 0x4,          /* run linked Tds first (depth-first)*/
104
105         /* Transfer status bits */
106         Tdbitstuff      = 0x00020000,   /* bit stuffing error */
107         Tdcrcto         = 0x00040000,   /* crc or timeout error */
108         Tdnak           = 0x00080000,   /* nak packet received */
109         Tdbabble        = 0x00100000,   /* babble detected */
110         Tddberr         = 0x00200000,   /* data buf. error */
111         Tdstalled       = 0x00400000,   /* serious error to ep. */
112         Tdactive                = 0x00800000,   /* enabled/in use by hw */
113         /* Transfer control bits */
114         Tdioc           = 0x01000000,   /* interrupt on complete */
115         Tdiso           = 0x02000000,   /* isochronous select */
116         Tdlow           = 0x04000000,   /* low speed device */
117         Tderr1          = 0x08000000,   /* bit 0 of error counter */
118         Tderr2          = 0x10000000,   /* bit 1 of error counter */
119         Tdspd           = 0x20000000,   /* short packet detect */
120
121         Tdlen           = 0x000003FF,   /* actual length field */
122
123         Tdfatalerr      = Tdnak|Tdbabble|Tdstalled, /* hw retries others */
124         Tderrors        = Tdfatalerr|Tdbitstuff|Tdcrcto|Tddberr,
125
126         /* Transfer descriptor token bits */
127         Tddata0         = 0,
128         Tddata1         = 0x80000,      /* data toggle (1==DATA1) */
129         Tdtokin         = 0x69,
130         Tdtokout        = 0xE1,
131         Tdtoksetup      = 0x2D,
132
133         Tdmaxpkt        = 0x800,        /* max packet size */
134
135         /* Queue head bits */
136         QHterm          = 1<<0,         /* nil (terminate) */
137         QHlinkqh                = 1<<1,         /* link refers to a QH */
138         QHvf            = 1<<2,         /* vertical first (depth first) */
139 };
140
141 struct Ctlr
142 {
143         Lock;                   /* for ilock. qh lists and basic ctlr I/O */
144         QLock   portlck;        /* for port resets/enable... */
145         Pcidev* pcidev;
146         int     active;
147         int     port;           /* I/O address */
148         Qh*     qhs;            /* list of Qhs for this controller */
149         Qh*     qh[Tmax];       /* Dummy Qhs to insert Qhs after */
150         Isoio*  iso;            /* list of active iso I/O */
151         ulong*  frames;         /* frame list (used by hw) */
152         ulong   load;           /* max load for a single frame */
153         ulong   isoload;                /* max iso load for a single frame */
154         int     nintr;          /* number of interrupts attended */
155         int     ntdintr;                /* number of intrs. with something to do */
156         int     nqhintr;                /* number of intrs. for Qhs */
157         int     nisointr;       /* number of intrs. for iso transfers */
158 };
159
160 struct Qio
161 {
162         QLock;                  /* for the entire I/O process */
163         Rendez;                 /* wait for completion */
164         Qh*     qh;             /* Td list (field const after init) */
165         int     usbid;          /* usb address for endpoint/device */
166         int     toggle;         /* Tddata0/Tddata1 */
167         int     tok;            /* Tdtoksetup, Tdtokin, Tdtokout */
168         ulong   iotime;         /* time of last I/O */
169         int     debug;          /* debug flag from the endpoint */
170         char*   err;            /* error string */
171 };
172
173 struct Ctlio
174 {
175         Qio;                    /* a single Qio for each RPC */
176         uchar*  data;           /* read from last ctl req. */
177         int     ndata;          /* number of bytes read */
178 };
179
180 struct Isoio
181 {
182         QLock;
183         Rendez;                 /* wait for space/completion/errors */
184         int     usbid;          /* address used for device/endpoint */
185         int     tok;            /* Tdtokin or Tdtokout */
186         int     state;          /* Qrun -> Qdone -> Qrun... -> Qclose */
187         int     nframes;        /* Nframes/ep->pollival */
188         uchar*  data;           /* iso data buffers if not embedded */
189         int     td0frno;        /* frame number for first Td */
190         Td*     tdu;            /* next td for user I/O in tdps */
191         Td*     tdi;            /* next td processed by interrupt */
192         char*   err;            /* error string */
193         int     nerrs;          /* nb of consecutive I/O errors */
194         long    nleft;          /* number of bytes left from last write */
195         int     debug;          /* debug flag from the endpoint */
196         Isoio*  next;           /* in list of active Isoios */
197         Td*     tdps[Nframes];  /* pointer to Td used for i-th frame or nil */
198         int     delay;          /* maximum number of bytes to buffer */
199 };
200
201 struct Tdpool
202 {
203         Lock;
204         Td*     free;
205         int     nalloc;
206         int     ninuse;
207         int     nfree;
208 };
209
210 struct Qhpool
211 {
212         Lock;
213         Qh*     free;
214         int     nalloc;
215         int     ninuse;
216         int     nfree;
217 };
218
219 /*
220  * HW data structures
221  */
222
223 /*
224  * Queue header (known by hw).
225  * 16-byte aligned. first two words used by hw.
226  * They are taken from the pool upon endpoint opening and
227  * queued after the dummy queue header for the endpoint type
228  * in the controller. Actual I/O happens as Tds are linked into it.
229  * The driver does I/O in lock-step.
230  * The user builds a list of Tds and links it into the Qh,
231  * then the Qh goes from Qidle to Qrun and nobody touches it until
232  * it becomes Qdone at interrupt time.
233  * At that point the user collects the Tds and it goes Qidle.
234  * A premature cancel may set the state to Qclose and abort I/O.
235  * The Ctlr lock protects change of state for Qhs in use.
236  */
237 struct Qh
238 {
239         ulong   link;           /* link to next horiz. item (eg. Qh) */
240         ulong   elink;          /* link to element (eg. Td; updated by hw) */
241
242         ulong   state;          /* Qidle -> Qinstall -> Qrun -> Qdone | Qclose */
243         Qio*    io;             /* for this queue */
244
245         Qh*     next;           /* in active or free list */
246         Td*     tds;            /* Td list in this Qh (initially, elink) */
247         char*   tag;            /* debug and align, mostly */
248         ulong   align;
249 };
250
251 /*
252  * Transfer descriptor.
253  * 16-byte aligned. first two words used by hw. Next 4 by sw.
254  * We keep an embedded buffer for small I/O transfers.
255  * They are taken from the pool when buffers are needed for I/O
256  * and linked at the Qh/Isoio for the endpoint and direction requiring it.
257  * The block keeps actual data. They are protected from races by
258  * the queue or the pool keeping it. The owner of the link to the Td
259  * is free to use it and can be the only one using it.
260  */
261 struct Td
262 {
263         ulong   link;           /* Link to next Td or Qh */
264         ulong   csw;            /* control and status word (updated by hw) */
265         ulong   token;          /* endpt, device, pid */
266         ulong   buffer;         /* buffer pointer */
267
268         Td*     next;           /* in qh or Isoio or free list */
269         ulong   ndata;          /* bytes available/used at data */
270         uchar*  data;           /* pointer to actual data */
271         void*   buff;           /* allocated data, for large transfers */
272
273         uchar   sbuff[Tdndata]; /* embedded buffer, for small transfers */
274 };
275
276 #define INB(x)          inb(ctlr->port+(x))
277 #define INS(x)          ins(ctlr->port+(x))
278 #define INL(x)          inl(ctlr->port+(x))
279 #define OUTB(x, v)      outb(ctlr->port+(x), (v))
280 #define OUTS(x, v)      outs(ctlr->port+(x), (v))
281 #define OUTL(x, v)      outl(ctlr->port+(x), (v))
282 #define TRUNC(x, sz)    ((x) & ((sz)-1))
283 #define PTR(q)          ((void*)KADDR((ulong)(q) & ~ (0xF|PCIWINDOW)))
284 #define QPTR(q)         ((Qh*)PTR(q))
285 #define TPTR(q)         ((Td*)PTR(q))
286 #define PORT(p)         (Portsc0 + 2*(p))
287 #define diprint         if(debug || iso->debug)print
288 #define ddiprint                if(debug>1 || iso->debug>1)print
289 #define dqprint         if(debug || (qh->io && qh->io->debug))print
290 #define ddqprint                if(debug>1 || (qh->io && qh->io->debug>1))print
291
292 static Ctlr* ctlrs[Nhcis];
293
294 static Tdpool tdpool;
295 static Qhpool qhpool;
296 static int debug;
297
298 static char* qhsname[] = { "idle", "install", "run", "done", "close", "FREE" };
299
300 static void
301 uhcicmd(Ctlr *ctlr, int c)
302 {
303         OUTS(Cmd, c);
304 }
305
306 static void
307 uhcirun(Ctlr *ctlr, int on)
308 {
309         int i;
310
311         ddprint("uhci %#ux setting run to %d\n", ctlr->port, on);
312
313         if(on)
314                 uhcicmd(ctlr, INS(Cmd)|Crun);
315         else
316                 uhcicmd(ctlr, INS(Cmd) & ~Crun);
317         for(i = 0; i < 100; i++)
318                 if(on == 0 && (INS(Status) & Shalted) != 0)
319                         break;
320                 else if(on != 0 && (INS(Status) & Shalted) == 0)
321                         break;
322                 else
323                         delay(1);
324         if(i == 100)
325                 dprint("uhci %#x run cmd timed out\n", ctlr->port);
326         ddprint("uhci %#ux cmd %#ux sts %#ux\n",
327                 ctlr->port, INS(Cmd), INS(Status));
328 }
329
330 static int
331 tdlen(Td *td)
332 {
333         return (td->csw+1) & Tdlen;
334 }
335
336 static int
337 maxtdlen(Td *td)
338 {
339         return ((td->token>>21)+1) & (Tdmaxpkt-1);
340 }
341
342 static int
343 tdtok(Td *td)
344 {
345         return td->token & 0xFF;
346 }
347
348 static char*
349 seprinttd(char *s, char *se, Td *td)
350 {
351         s = seprint(s, se, "%#p link %#ulx", td, td->link);
352         if((td->link & Tdvf) != 0)
353                 s = seprint(s, se, "V");
354         if((td->link & Tdterm) != 0)
355                 s = seprint(s, se, "T");
356         if((td->link & Tdlinkqh) != 0)
357                 s = seprint(s, se, "Q");
358         s = seprint(s, se, " csw %#ulx ", td->csw);
359         if(td->csw & Tdactive)
360                 s = seprint(s, se, "a");
361         if(td->csw & Tdiso)
362                 s = seprint(s, se, "I");
363         if(td->csw & Tdioc)
364                 s = seprint(s, se, "i");
365         if(td->csw & Tdlow)
366                 s = seprint(s, se, "l");
367         if((td->csw & (Tderr1|Tderr2)) == 0)
368                 s = seprint(s, se, "z");
369         if(td->csw & Tderrors)
370                 s = seprint(s, se, " err %#ulx", td->csw & Tderrors);
371         if(td->csw & Tdstalled)
372                 s = seprint(s, se, "s");
373         if(td->csw & Tddberr)
374                 s = seprint(s, se, "d");
375         if(td->csw & Tdbabble)
376                 s = seprint(s, se, "b");
377         if(td->csw & Tdnak)
378                 s = seprint(s, se, "n");
379         if(td->csw & Tdcrcto)
380                 s = seprint(s, se, "c");
381         if(td->csw & Tdbitstuff)
382                 s = seprint(s, se, "B");
383         s = seprint(s, se, " stslen %d", tdlen(td));
384
385         s = seprint(s, se, " token %#ulx", td->token);
386         if(td->token == 0)              /* the BWS loopback Td, ignore rest */
387                 return s;
388         s = seprint(s, se, " maxlen %d", maxtdlen(td));
389         if(td->token & Tddata1)
390                 s = seprint(s, se, " d1");
391         else
392                 s = seprint(s, se, " d0");
393         s = seprint(s, se, " id %#ulx:", (td->token>>15) & Epmax);
394         s = seprint(s, se, "%#ulx", (td->token>>8) & Devmax);
395         switch(tdtok(td)){
396         case Tdtokin:
397                 s = seprint(s, se, " in");
398                 break;
399         case Tdtokout:
400                 s = seprint(s, se, " out");
401                 break;
402         case Tdtoksetup:
403                 s = seprint(s, se, " setup");
404                 break;
405         default:
406                 s = seprint(s, se, " BADPID");
407         }
408         s = seprint(s, se, "\n\t  buffer %#ulx data %#p", td->buffer, td->data);
409         s = seprint(s, se, " ndata %uld sbuff %#p buff %#p",
410                 td->ndata, td->sbuff, td->buff);
411         if(td->ndata > 0)
412                 s = seprintdata(s, se, td->data, td->ndata);
413         return s;
414 }
415
416 static void
417 isodump(Isoio *iso, int all)
418 {
419         char buf[256];
420         Td *td;
421         int i;
422
423         print("iso %#p %s state %d nframes %d"
424                 " td0 %#p tdu %#p tdi %#p data %#p\n",
425                 iso, iso->tok == Tdtokin ? "in" : "out",
426                 iso->state, iso->nframes, iso->tdps[iso->td0frno],
427                 iso->tdu, iso->tdi, iso->data);
428         if(iso->err != nil)
429                 print("\terr='%s'\n", iso->err);
430         if(all == 0){
431                 seprinttd(buf, buf+sizeof(buf), iso->tdu);
432                 print("\ttdu %s\n", buf);
433                 seprinttd(buf, buf+sizeof(buf), iso->tdi);
434                 print("\ttdi %s\n", buf);
435         }else{
436                 td = iso->tdps[iso->td0frno];
437                 for(i = 0; i < iso->nframes; i++){
438                         seprinttd(buf, buf+sizeof(buf), td);
439                         if(td == iso->tdi)
440                                 print("i->");
441                         if(td == iso->tdu)
442                                 print("u->");
443                         print("\t%s\n", buf);
444                         td = td->next;
445                 }
446         }
447 }
448
449 static int
450 sameptr(void *p, ulong l)
451 {
452         if(l & QHterm)
453                 return p == nil;
454         return PTR(l) == p;
455 }
456
457 static void
458 dumptd(Td *td, char *pref)
459 {
460         char buf[256];
461         char *s;
462         char *se;
463         int i;
464
465         i = 0;
466         se = buf+sizeof(buf);
467         for(; td != nil; td = td->next){
468                 s = seprinttd(buf, se, td);
469                 if(!sameptr(td->next, td->link))
470                         seprint(s, se, " next %#p != link %#ulx %#p",
471                                 td->next, td->link, TPTR(td->link));
472                 print("%std %s\n", pref, buf);
473                 if(i++ > 20){
474                         print("...more tds...\n");
475                         break;
476                 }
477         }
478 }
479
480 static void
481 qhdump(Qh *qh, char *pref)
482 {
483         char buf[256];
484         char *s;
485         char *se;
486         ulong td;
487         int i;
488
489         s = buf;
490         se = buf+sizeof(buf);
491         s = seprint(s, se, "%sqh %s %#p state %s link %#ulx", pref,
492                 qh->tag, qh, qhsname[qh->state], qh->link);
493         if(!sameptr(qh->tds, qh->elink))
494                 s = seprint(s, se, " [tds %#p != elink %#ulx %#p]",
495                         qh->tds, qh->elink, TPTR(qh->elink));
496         if(!sameptr(qh->next, qh->link))
497                 s = seprint(s, se, " [next %#p != link %#ulx %#p]",
498                         qh->next, qh->link, QPTR(qh->link));
499         if((qh->link & Tdterm) != 0)
500                 s = seprint(s, se, "T");
501         if((qh->link & Tdlinkqh) != 0)
502                 s = seprint(s, se, "Q");
503         s = seprint(s, se, " elink %#ulx", qh->elink);
504         if((qh->elink & Tdterm) != 0)
505                 s = seprint(s, se, "T");
506         if((qh->elink & Tdlinkqh) != 0)
507                 s = seprint(s, se, "Q");
508         s = seprint(s, se, " io %#p", qh->io);
509         if(qh->io != nil && qh->io->err != nil)
510                 seprint(s, se, " err='%s'", qh->io->err);
511         print("%s\n", buf);
512         dumptd(qh->tds, "\t");
513         if((qh->elink & QHterm) == 0){
514                 print("\thw tds:");
515                 i = 0;
516                 for(td = qh->elink; (td & Tdterm) == 0; td = TPTR(td)->link){
517                         print(" %#ulx", td);
518                         if(td == TPTR(td)->link)        /* BWS Td */
519                                 break;
520                         if(i++ > 40){
521                                 print("...");
522                                 break;
523                         }
524                 }
525                 print("\n");
526         }
527 }
528
529 static void
530 xdump(Ctlr *ctlr, int doilock)
531 {
532         Isoio *iso;
533         Qh *qh;
534         int i;
535
536         if(doilock){
537                 if(ctlr == ctlrs[0]){
538                         lock(&tdpool);
539                         print("tds: alloc %d = inuse %d + free %d\n",
540                                 tdpool.nalloc, tdpool.ninuse, tdpool.nfree);
541                         unlock(&tdpool);
542                         lock(&qhpool);
543                         print("qhs: alloc %d = inuse %d + free %d\n",
544                                 qhpool.nalloc, qhpool.ninuse, qhpool.nfree);
545                         unlock(&qhpool);
546                 }
547                 ilock(ctlr);
548         }
549         print("uhci port %#x frames %#p nintr %d ntdintr %d",
550                 ctlr->port, ctlr->frames, ctlr->nintr, ctlr->ntdintr);
551         print(" nqhintr %d nisointr %d\n", ctlr->nqhintr, ctlr->nisointr);
552         print("cmd %#ux sts %#ux fl %#ulx ps1 %#ux ps2 %#ux frames[0] %#ulx\n",
553                 INS(Cmd), INS(Status),
554                 INL(Flbaseadd), INS(PORT(0)), INS(PORT(1)),
555                 ctlr->frames[0]);
556         for(iso = ctlr->iso; iso != nil; iso = iso->next)
557                 isodump(iso, 1);
558         i = 0;
559         for(qh = ctlr->qhs; qh != nil; qh = qh->next){
560                 qhdump(qh, "");
561                 if(i++ > 20){
562                         print("qhloop\n");
563                         break;
564                 }
565         }
566         print("\n");
567         if(doilock)
568                 iunlock(ctlr);
569 }
570
571 static void
572 dump(Hci *hp)
573 {
574         xdump(hp->aux, 1);
575 }
576
577 static Td*
578 tdalloc(void)
579 {
580         int i;
581         Td *td;
582         Td *pool;
583
584         lock(&tdpool);
585         if(tdpool.free == nil){
586                 ddprint("uhci: tdalloc %d Tds\n", Incr);
587                 pool = xspanalloc(Incr*sizeof(Td), Align, 0);
588                 if(pool == nil)
589                         panic("tdalloc");
590                 for(i=Incr; --i>=0;){
591                         pool[i].next = tdpool.free;
592                         tdpool.free = &pool[i];
593                 }
594                 tdpool.nalloc += Incr;
595                 tdpool.nfree += Incr;
596         }
597         td = tdpool.free;
598         tdpool.free = td->next;
599         tdpool.ninuse++;
600         tdpool.nfree--;
601         unlock(&tdpool);
602
603         memset(td, 0, sizeof(Td));
604         td->link = Tdterm;
605         assert(((ulong)td & 0xF) == 0);
606         return td;
607 }
608
609 static void
610 tdfree(Td *td)
611 {
612         if(td == nil)
613                 return;
614         free(td->buff);
615         td->buff = nil;
616         lock(&tdpool);
617         td->next = tdpool.free;
618         tdpool.free = td;
619         tdpool.ninuse--;
620         tdpool.nfree++;
621         unlock(&tdpool);
622 }
623
624 static void
625 qhlinkqh(Qh* qh, Qh* next)
626 {
627         if(next == nil)
628                 qh->link = QHterm;
629         else{
630                 next->link = qh->link;
631                 next->next = qh->next;
632                 qh->link = PCIWADDR(next)|QHlinkqh;
633         }
634         qh->next = next;
635 }
636
637 static void
638 qhlinktd(Qh *qh, Td *td)
639 {
640         qh->tds = td;
641         if(td == nil)
642                 qh->elink = QHvf|QHterm;
643         else
644                 qh->elink = PCIWADDR(td);
645 }
646
647 static void
648 tdlinktd(Td *td, Td *next)
649 {
650         td->next = next;
651         if(next == nil)
652                 td->link = Tdterm;
653         else
654                 td->link = PCIWADDR(next)|Tdvf;
655 }
656
657 static Qh*
658 qhalloc(Ctlr *ctlr, Qh *prev, Qio *io, char *tag)
659 {
660         int i;
661         Qh *qh;
662         Qh *pool;
663
664         lock(&qhpool);
665         if(qhpool.free == nil){
666                 ddprint("uhci: qhalloc %d Qhs\n", Incr);
667                 pool = xspanalloc(Incr*sizeof(Qh), Align, 0);
668                 if(pool == nil)
669                         panic("qhalloc");
670                 for(i=Incr; --i>=0;){
671                         pool[i].next = qhpool.free;
672                         qhpool.free = &pool[i];
673                 }
674                 qhpool.nalloc += Incr;
675                 qhpool.nfree += Incr;
676         }
677         qh = qhpool.free;
678         qhpool.free = qh->next;
679         qh->next = nil;
680         qh->link = QHterm;
681         qhpool.ninuse++;
682         qhpool.nfree--;
683         unlock(&qhpool);
684
685         qh->tds = nil;
686         qh->elink = QHterm;
687         qh->state = Qidle;
688         qh->io = io;
689         qh->tag = nil;
690         kstrdup(&qh->tag, tag);
691
692         if(prev != nil){
693                 coherence();
694                 ilock(ctlr);
695                 qhlinkqh(prev, qh);
696                 iunlock(ctlr);
697         }
698
699         assert(((ulong)qh & 0xF) == 0);
700         return qh;
701 }
702
703 static void
704 qhfree(Ctlr *ctlr, Qh *qh)
705 {
706         Td *td;
707         Td *ltd;
708         Qh *q;
709
710         if(qh == nil)
711                 return;
712
713         ilock(ctlr);
714         for(q = ctlr->qhs; q != nil; q = q->next)
715                 if(q->next == qh)
716                         break;
717         if(q == nil)
718                 panic("qhfree: nil q");
719         q->next = qh->next;
720         q->link = qh->link;
721         iunlock(ctlr);
722
723         for(td = qh->tds; td != nil; td = ltd){
724                 ltd = td->next;
725                 tdfree(td);
726         }
727         lock(&qhpool);
728         qh->state = Qfree;      /* paranoia */
729         qh->next = qhpool.free;
730         qh->tag = nil;
731         qh->io = nil;
732         qhpool.free = qh;
733         qhpool.ninuse--;
734         qhpool.nfree++;
735         unlock(&qhpool);
736         ddprint("qhfree: qh %#p\n", qh);
737 }
738
739 static char*
740 errmsg(int err)
741 {
742         if(err == 0)
743                 return "ok";
744         if(err & Tdcrcto)
745                 return "crc/timeout error";
746         if(err & Tdbabble)
747                 return "babble detected";
748         if(err & Tddberr)
749                 return "db error";
750         if(err & Tdbitstuff)
751                 return "bit stuffing error";
752         if(err & Tdstalled)
753                 return Estalled;
754         return Eio;
755 }
756
757 static int
758 isocanread(void *a)
759 {
760         Isoio *iso;
761
762         iso = a;
763         return iso->state == Qclose ||
764                 (iso->state == Qrun &&
765                 iso->tok == Tdtokin && iso->tdi != iso->tdu);
766 }
767
768 static int
769 isocanwrite(void *a)
770 {
771         Isoio *iso;
772
773         iso = a;
774         return iso->state == Qclose ||
775                 (iso->state == Qrun &&
776                 iso->tok == Tdtokout && iso->tdu->next != iso->tdi);
777 }
778
779 static int
780 isodelay(void *a)
781 {
782         Isoio *iso;
783         int delay;
784         Td *tdi;
785
786         iso = a;
787         if(iso->state == Qclose || iso->err || iso->delay == 0)
788                 return 1;
789
790         delay = 0;
791         for(tdi = iso->tdi; tdi->next != iso->tdu; tdi = tdi->next){
792                 if((tdi->csw & Tdactive) == 0)
793                         continue;
794                 delay += maxtdlen(tdi);
795                 if(delay > iso->delay)
796                         break;
797         }
798
799         return delay <= iso->delay;
800 }
801
802 static void
803 tdisoinit(Isoio *iso, Td *td, long count)
804 {
805         td->ndata = count;
806         td->token = ((count-1)<<21)| ((iso->usbid & 0x7FF)<<8) | iso->tok;
807         td->csw = Tderr1|Tdiso|Tdactive|Tdioc;
808 }
809
810 /*
811  * Process Iso i/o on interrupt. For writes update just error status.
812  * For reads update tds to reflect data and also error status.
813  * When tdi aproaches tdu, advance tdu; data may be lost.
814  * (If nframes is << Nframes tdu might be far away but this avoids
815  * races regarding frno.)
816  * If we suffer errors for more than half the frames we stall.
817  */
818 static void
819 isointerrupt(Ctlr *ctlr, Isoio* iso)
820 {
821         Td *tdi;
822         int err;
823         int i;
824         int nframes;
825
826         tdi = iso->tdi;
827         if((tdi->csw & Tdactive) != 0)          /* nothing new done */
828                 return;
829         ctlr->nisointr++;
830         ddiprint("isointr: iso %#p: tdi %#p tdu %#p\n", iso, tdi, iso->tdu);
831         if(iso->state != Qrun && iso->state != Qdone)
832                 panic("isointr: iso state");
833         if(debug > 1 || iso->debug > 1)
834                 isodump(iso, 0);
835
836         nframes = iso->nframes / 2;             /* limit how many we look */
837         if(nframes > 64)
838                 nframes = 64;
839         for(i = 0; i < nframes && (tdi->csw & Tdactive) == 0; i++){
840                 tdi->csw &= ~Tdioc;
841                 err = tdi->csw & Tderrors;
842                 if(err == 0)
843                         iso->nerrs = 0;
844                 else if(iso->nerrs++ > iso->nframes/2)
845                         tdi->csw |= Tdstalled;
846                 if((tdi->csw & Tdstalled) != 0){
847                         if(iso->err == nil){
848                                 iso->err = errmsg(err);
849                                 diprint("isointerrupt: tdi %#p error %#ux %s\n",
850                                         tdi, err, iso->err);
851                                 diprint("ctlr load %uld\n", ctlr->load);
852                         }
853                         tdi->ndata = 0;
854                 }else
855                         tdi->ndata = tdlen(tdi);
856
857                 if(tdi->next == iso->tdu || tdi->next->next == iso->tdu){
858                         memset(iso->tdu->data, 0, maxtdlen(iso->tdu));
859                         tdisoinit(iso, iso->tdu, maxtdlen(iso->tdu));
860                         iso->tdu = iso->tdu->next;
861                         iso->nleft = 0;
862                 }
863                 tdi = tdi->next;
864         }
865         ddiprint("isointr: %d frames processed\n", i);
866         if(i == nframes)
867                 tdi->csw |= Tdioc;
868         iso->tdi = tdi;
869         if(isocanwrite(iso) || isocanread(iso)){
870                 diprint("wakeup iso %#p tdi %#p tdu %#p\n", iso,
871                         iso->tdi, iso->tdu);
872                 wakeup(iso);
873         }
874 }
875
876 /*
877  * Process a Qh upon interrupt. There's one per ongoing user I/O.
878  * User process releases resources later, that is not done here.
879  * We may find in this order one or more Tds:
880  * - none/many non active and completed Tds
881  * - none/one (usually(!) not active) and failed Td
882  * - none/many active Tds.
883  * Upon errors the entire transfer is aborted and error reported.
884  * Otherwise, the transfer is complete only when all Tds are done or
885  * when a read with less than maxpkt is found.
886  * Use the software list and not qh->elink to avoid races.
887  * We could use qh->elink to see if there's something new or not.
888  */
889 static void
890 qhinterrupt(Ctlr *ctlr, Qh *qh)
891 {
892         Td *td;
893         int err;
894
895         ctlr->nqhintr++;
896         if(qh->state != Qrun)
897                 panic("qhinterrupt: qh state");
898         if(qh->tds == nil)
899                 panic("qhinterrupt: no tds");
900         if((qh->tds->csw & Tdactive) == 0)
901                 ddqprint("qhinterrupt port %#ux qh %#p p0 %#x p1 %#x\n",
902                         ctlr->port, qh, INS(PORT(0)), INS(PORT(1)));
903         for(td = qh->tds; td != nil; td = td->next){
904                 if(td->csw & Tdactive)
905                         return;
906                 td->csw &= ~Tdioc;
907                 if((td->csw & Tdstalled) != 0){
908                         err = td->csw & Tderrors;
909                         /* just stalled is end of xfer but not an error */
910                         if(err != Tdstalled && qh->io->err == nil){
911                                 qh->io->err = errmsg(td->csw & Tderrors);
912                                 dqprint("qhinterrupt: td %#p error %#ux %s\n",
913                                         td, err, qh->io->err);
914                                 dqprint("ctlr load %uld\n", ctlr->load);
915                         }
916                         break;
917                 }
918                 if((td->csw & Tdnak) != 0){     /* retransmit; not serious */
919                         td->csw &= ~Tdnak;
920                         if(td->next == nil)
921                                 td->csw |= Tdioc;
922                 }
923                 td->ndata = tdlen(td);
924                 if(td->ndata < maxtdlen(td)){   /* EOT */
925                         td = td->next;
926                         break;
927                 }
928         }
929
930         /*
931          * Done. Make void the Tds not used (errors or EOT) and wakeup epio.
932          */
933         qh->elink = QHterm;
934         for(; td != nil; td = td->next)
935                 td->ndata = 0;
936         qh->state = Qdone;
937         wakeup(qh->io);
938 }
939
940 static void
941 interrupt(Ureg*, void *a)
942 {
943         Hci *hp;
944         Ctlr *ctlr;
945         int frptr;
946         int frno;
947         Qh *qh;
948         Isoio *iso;
949         int sts;
950         int cmd;
951
952         hp = a;
953         ctlr = hp->aux;
954         ilock(ctlr);
955         ctlr->nintr++;
956         sts = INS(Status);
957         if((sts & Sall) == 0){          /* not for us; sharing irq */
958                 iunlock(ctlr);
959                 return;
960         }
961         OUTS(Status, sts & Sall);
962         cmd = INS(Cmd);
963         if(cmd & Crun == 0){
964                 print("uhci %#ux: not running: uhci bug?\n", ctlr->port);
965                 /* BUG: should abort everything in this case */
966         }
967         if(debug > 1){
968                 frptr = INL(Flbaseadd);
969                 frno = INL(Frnum);
970                 frno = TRUNC(frno, Nframes);
971                 print("cmd %#ux sts %#ux frptr %#ux frno %d\n",
972                         cmd, sts, frptr, frno);
973         }
974         ctlr->ntdintr++;
975         /*
976          * Will we know in USB 3.0 who the interrupt was for?.
977          * Do they still teach indexing in CS?
978          * This is Intel's doing.
979          */
980         for(iso = ctlr->iso; iso != nil; iso = iso->next)
981                 if(iso->state == Qrun || iso->state == Qdone)
982                         isointerrupt(ctlr, iso);
983         for(qh = ctlr->qhs; qh != nil; qh = qh->next)
984                 if(qh->state == Qrun)
985                         qhinterrupt(ctlr, qh);
986                 else if(qh->state == Qclose)
987                         qhlinktd(qh, nil);
988         iunlock(ctlr);
989 }
990
991 /*
992  * iso->tdu is the next place to put data. When it gets full
993  * it is activated and tdu advanced.
994  */
995 static long
996 putsamples(Ctlr *ctlr, Isoio *iso, uchar *b, long count)
997 {
998         long n, tot, left;
999         Td *tdu;
1000
1001         for(tot = 0; isocanwrite(iso) && tot < count; tot += n){
1002                 n = count-tot;
1003                 tdu = iso->tdu;
1004                 left = iso->nleft;
1005                 if(n > maxtdlen(tdu) - left)
1006                         n = maxtdlen(tdu) - left;
1007                 iunlock(ctlr);  /* can pagefault here */
1008                 memmove(tdu->data+left, b+tot, n);
1009                 ilock(ctlr);
1010                 if(tdu != iso->tdu)
1011                         continue;
1012                 iso->nleft += n;
1013                 if(iso->nleft == maxtdlen(tdu)){
1014                         tdisoinit(iso, tdu, iso->nleft);
1015                         iso->tdu = tdu->next;
1016                         iso->nleft = 0;
1017                 }
1018         }
1019         return tot;
1020 }
1021
1022 /*
1023  * Queue data for writing and return error status from
1024  * last writes done, to maintain buffered data.
1025  */
1026 static long
1027 episowrite(Ep *ep, Isoio *iso, void *a, long count)
1028 {
1029         Ctlr *ctlr;
1030         uchar *b;
1031         int tot;
1032         int nw;
1033         char *err;
1034
1035         iso->debug = ep->debug;
1036         iso->delay = ep->sampledelay * ep->samplesz;
1037         diprint("uhci: episowrite: %#p ep%d.%d\n", iso, ep->dev->nb, ep->nb);
1038
1039         ctlr = ep->hp->aux;
1040         eqlock(iso);
1041         if(waserror()){
1042                 qunlock(iso);
1043                 nexterror();
1044         }
1045         ilock(ctlr);
1046         if(iso->state == Qclose){
1047                 iunlock(ctlr);
1048                 error(iso->err ? iso->err : Eio);
1049         }
1050         iso->state = Qrun;
1051         b = a;
1052         for(tot = 0; tot < count; tot += nw){
1053                 while(isocanwrite(iso) == 0){
1054                         iunlock(ctlr);
1055                         diprint("uhci: episowrite: %#p sleep\n", iso);
1056                         if(waserror()){
1057                                 if(iso->err == nil)
1058                                         iso->err = "I/O timed out";
1059                                 ilock(ctlr);
1060                                 break;
1061                         }
1062                         tsleep(iso, isocanwrite, iso, ep->tmout);
1063                         poperror();
1064                         ilock(ctlr);
1065                 }
1066                 err = iso->err;
1067                 iso->err = nil;
1068                 if(iso->state == Qclose || err != nil){
1069                         iunlock(ctlr);
1070                         error(err ? err : Eio);
1071                 }
1072                 if(iso->state != Qrun)
1073                         panic("episowrite: iso not running");
1074                 nw = putsamples(ctlr, iso, b+tot, count-tot);
1075         }
1076         while(isodelay(iso) == 0){
1077                 iunlock(ctlr);
1078                 sleep(iso, isodelay, iso);
1079                 ilock(ctlr);
1080         }
1081         if(iso->state != Qclose)
1082                 iso->state = Qdone;
1083         iunlock(ctlr);
1084         err = iso->err;         /* in case it failed early */
1085         iso->err = nil;
1086         qunlock(iso);
1087         poperror();
1088         if(err != nil)
1089                 error(err);
1090         diprint("uhci: episowrite: %#p %d bytes\n", iso, tot);
1091         return tot;
1092 }
1093
1094 /*
1095  * Available data is kept at tdu and following tds, up to tdi (excluded).
1096  */
1097 static long
1098 episoread(Ep *ep, Isoio *iso, void *a, int count)
1099 {
1100         Ctlr *ctlr;
1101         uchar *b;
1102         int nr;
1103         int tot;
1104         Td *tdu;
1105
1106         iso->debug = ep->debug;
1107         diprint("uhci: episoread: %#p ep%d.%d\n", iso, ep->dev->nb, ep->nb);
1108
1109         b = a;
1110         ctlr = ep->hp->aux;
1111         eqlock(iso);
1112         if(waserror()){
1113                 qunlock(iso);
1114                 nexterror();
1115         }
1116         iso->err = nil;
1117         iso->nerrs = 0;
1118         ilock(ctlr);
1119         if(iso->state == Qclose){
1120                 iunlock(ctlr);
1121                 error(iso->err ? iso->err : Eio);
1122         }
1123         iso->state = Qrun;
1124         while(isocanread(iso) == 0){
1125                 iunlock(ctlr);
1126                 diprint("uhci: episoread: %#p sleep\n", iso);
1127                 if(waserror()){
1128                         if(iso->err == nil)
1129                                 iso->err = "I/O timed out";
1130                         ilock(ctlr);
1131                         break;
1132                 }
1133                 tsleep(iso, isocanread, iso, ep->tmout);
1134                 poperror();
1135                 ilock(ctlr);
1136         }
1137         if(iso->state == Qclose){
1138                 iunlock(ctlr);
1139                 error(iso->err ? iso->err : Eio);
1140         }
1141         iso->state = Qdone;
1142
1143         for(tot = 0; iso->tdi != iso->tdu && tot < count; tot += nr){
1144                 tdu = iso->tdu;
1145                 if(tdu->csw & Tdactive){
1146                         diprint("uhci: episoread: %#p tdu active\n", iso);
1147                         break;
1148                 }
1149                 nr = tdu->ndata;
1150                 if(tot + nr > count)
1151                         nr = count - tot;
1152                 if(nr == 0)
1153                         print("uhci: ep%d.%d: too many polls\n",
1154                                 ep->dev->nb, ep->nb);
1155                 else{
1156                         iunlock(ctlr);          /* We could page fault here */
1157                         memmove(b+tot, tdu->data, nr);
1158                         ilock(ctlr);
1159                         if(nr < tdu->ndata)
1160                                 memmove(tdu->data, tdu->data+nr, tdu->ndata - nr);
1161                         tdu->ndata -= nr;
1162                 }
1163                 if(tdu->ndata == 0){
1164                         tdisoinit(iso, tdu, ep->maxpkt);
1165                         iso->tdu = tdu->next;
1166                 }
1167         }
1168         iunlock(ctlr);
1169         qunlock(iso);
1170         poperror();
1171         diprint("uhci: episoread: %#p %d bytes err '%s'\n", iso, tot, iso->err);
1172         if(iso->err != nil)
1173                 error(iso->err);
1174         return tot;
1175 }
1176
1177 static int
1178 nexttoggle(int tog)
1179 {
1180         if(tog == Tddata0)
1181                 return Tddata1;
1182         else
1183                 return Tddata0;
1184 }
1185
1186 static Td*
1187 epgettd(Ep *ep, Qio *io, int flags, void *a, int count)
1188 {
1189         Td *td;
1190         int tok;
1191
1192         if(ep->maxpkt < count)
1193                 error("maxpkt too short");
1194         td = tdalloc();
1195         if(count <= Tdndata)
1196                 td->data = td->sbuff;
1197         else
1198                 td->data = td->buff = smalloc(ep->maxpkt);
1199         td->buffer = PCIWADDR(td->data);
1200         td->ndata = count;
1201         if(a != nil && count > 0)
1202                 memmove(td->data, a, count);
1203         td->csw = Tderr2|Tderr1|flags;
1204         if(ep->dev->speed == Lowspeed)
1205                 td->csw |= Tdlow;
1206         tok = io->tok | io->toggle;
1207         io->toggle = nexttoggle(io->toggle);
1208         td->token = ((count-1)<<21) | ((io->usbid&0x7FF)<<8) | tok;
1209
1210         return td;
1211 }
1212
1213 /*
1214  * Try to get them idle
1215  */
1216 static void
1217 aborttds(Qh *qh)
1218 {
1219         Td *td;
1220
1221         qh->state = Qdone;
1222         qh->elink = QHterm;
1223         for(td = qh->tds; td != nil; td = td->next){
1224                 if(td->csw & Tdactive)
1225                         td->ndata = 0;
1226                 td->csw &= ~(Tdactive|Tdioc);
1227         }
1228 }
1229
1230 static int
1231 epiodone(void *a)
1232 {
1233         Qh *qh;
1234
1235         qh = a;
1236         return qh->state != Qrun;
1237 }
1238
1239 static void
1240 epiowait(Ctlr *ctlr, Qio *io, int tmout, ulong load)
1241 {
1242         Qh *qh;
1243         int timedout;
1244
1245         qh = io->qh;
1246         ddqprint("uhci io %#p sleep on qh %#p state %uld\n", io, qh, qh->state);
1247         timedout = 0;
1248         if(waserror()){
1249                 dqprint("uhci io %#p qh %#p timed out\n", io, qh);
1250                 timedout++;
1251         }else{
1252                 if(tmout == 0)
1253                         sleep(io, epiodone, qh);
1254                 else
1255                         tsleep(io, epiodone, qh, tmout);
1256                 poperror();
1257         }
1258         ilock(ctlr);
1259         if(qh->state == Qrun)
1260                 timedout = 1;
1261         else if(qh->state != Qdone && qh->state != Qclose)
1262                 panic("epio: queue not done and not closed");
1263         if(timedout){
1264                 aborttds(io->qh);
1265                 io->err = "request timed out";
1266                 iunlock(ctlr);
1267                 if(!waserror()){
1268                         tsleep(&up->sleep, return0, 0, Abortdelay);
1269                         poperror();
1270                 }
1271                 ilock(ctlr);
1272         }
1273         if(qh->state != Qclose)
1274                 qh->state = Qidle;
1275         qhlinktd(qh, nil);
1276         ctlr->load -= load;
1277         iunlock(ctlr);
1278 }
1279
1280 /*
1281  * Non iso I/O.
1282  * To make it work for control transfers, the caller may
1283  * lock the Qio for the entire control transfer.
1284  */
1285 static long
1286 epio(Ep *ep, Qio *io, void *a, long count, int mustlock)
1287 {
1288         Td *td, *ltd, *td0, *ntd;
1289         Ctlr *ctlr;
1290         Qh* qh;
1291         long n, tot;
1292         char buf[128];
1293         uchar *c;
1294         int saved, ntds, tmout;
1295         ulong load;
1296         char *err;
1297
1298         qh = io->qh;
1299         ctlr = ep->hp->aux;
1300         io->debug = ep->debug;
1301         tmout = ep->tmout;
1302         ddeprint("epio: %s ep%d.%d io %#p count %ld load %uld\n",
1303                 io->tok == Tdtokin ? "in" : "out",
1304                 ep->dev->nb, ep->nb, io, count, ctlr->load);
1305         if((debug > 1 || ep->debug > 1) && io->tok != Tdtokin){
1306                 seprintdata(buf, buf+sizeof(buf), a, count);
1307                 print("uchi epio: user data: %s\n", buf);
1308         }
1309         if(mustlock){
1310                 eqlock(io);
1311                 if(waserror()){
1312                         qunlock(io);
1313                         nexterror();
1314                 }
1315         }
1316         io->err = nil;
1317         ilock(ctlr);
1318         if(qh->state == Qclose){        /* Tds released by cancelio */
1319                 iunlock(ctlr);
1320                 error(io->err ? io->err : Eio);
1321         }
1322         if(qh->state != Qidle)
1323                 panic("epio: qh not idle");
1324         qh->state = Qinstall;
1325         iunlock(ctlr);
1326
1327         c = a;
1328         td0 = ltd = nil;
1329         load = tot = 0;
1330         do{
1331                 n = ep->maxpkt;
1332                 if(count-tot < n)
1333                         n = count-tot;
1334                 if(c != nil && io->tok != Tdtokin)
1335                         td = epgettd(ep, io, Tdactive, c+tot, n);
1336                 else
1337                         td = epgettd(ep, io, Tdactive|Tdspd, nil, n);
1338                 if(td0 == nil)
1339                         td0 = td;
1340                 else
1341                         tdlinktd(ltd, td);
1342                 ltd = td;
1343                 tot += n;
1344                 load += ep->load;
1345         }while(tot < count);
1346         if(td0 == nil || ltd == nil)
1347                 panic("epio: no td");
1348
1349         ltd->csw |= Tdioc;      /* the last one interrupts */
1350         ddeprint("uhci: load %uld ctlr load %uld\n", load, ctlr->load);
1351         ilock(ctlr);
1352         if(qh->state != Qclose){
1353                 io->iotime = TK2MS(MACHP(0)->ticks);
1354                 qh->state = Qrun;
1355                 coherence();
1356                 qhlinktd(qh, td0);
1357                 ctlr->load += load;
1358         }
1359         iunlock(ctlr);
1360
1361         epiowait(ctlr, io, tmout, load);
1362
1363         if(debug > 1 || ep->debug > 1)
1364                 dumptd(td0, "epio: got tds: ");
1365
1366         tot = 0;
1367         c = a;
1368         saved = 0;
1369         ntds = 0;
1370         for(td = td0; td != nil; td = ntd){
1371                 ntds++;
1372                 /*
1373                  * Use td tok, not io tok, because of setup packets.
1374                  * Also, if the Td was stalled or active (previous Td
1375                  * was a short packet), we must save the toggle as it is.
1376                  */
1377                 if(td->csw & (Tdstalled|Tdactive)){
1378                         if(saved++ == 0)
1379                                 io->toggle = td->token & Tddata1;
1380                 }else{
1381                         tot += td->ndata;
1382                         if(c != nil && tdtok(td) == Tdtokin && td->ndata > 0){
1383                                 memmove(c, td->data, td->ndata);
1384                                 c += td->ndata;
1385                         }
1386                 }
1387                 ntd = td->next;
1388                 tdfree(td);
1389         }
1390         err = io->err;
1391         if(mustlock){
1392                 qunlock(io);
1393                 poperror();
1394         }
1395         ddeprint("epio: io %#p: %d tds: return %ld err '%s'\n",
1396                 io, ntds, tot, err);
1397         if(err != nil)
1398                 error(err);
1399         if(tot < 0)
1400                 error(Eio);
1401         return tot;
1402 }
1403
1404 /*
1405  * halt condition was cleared on the endpoint. update our toggles.
1406  */
1407 static void
1408 clrhalt(Ep *ep)
1409 {
1410         Qio *io;
1411
1412         ep->clrhalt = 0;
1413         switch(ep->ttype){
1414         case Tbulk:
1415         case Tintr:
1416                 io = ep->aux;
1417                 if(ep->mode != OREAD){
1418                         qlock(&io[OWRITE]);
1419                         io[OWRITE].toggle = Tddata0;
1420                         deprint("ep clrhalt for io %#p\n", io+OWRITE);
1421                         qunlock(&io[OWRITE]);
1422                 }
1423                 if(ep->mode != OWRITE){
1424                         qlock(&io[OREAD]);
1425                         io[OREAD].toggle = Tddata0;
1426                         deprint("ep clrhalt for io %#p\n", io+OREAD);
1427                         qunlock(&io[OREAD]);
1428                 }
1429                 break;
1430         }
1431 }
1432
1433 static long
1434 epread(Ep *ep, void *a, long count)
1435 {
1436         Ctlio *cio;
1437         Qio *io;
1438         Isoio *iso;
1439         char buf[160];
1440         ulong delta;
1441
1442         ddeprint("uhci: epread\n");
1443         if(ep->aux == nil)
1444                 panic("epread: not open");
1445
1446         switch(ep->ttype){
1447         case Tctl:
1448                 cio = ep->aux;
1449                 eqlock(cio);
1450                 if(waserror()){
1451                         qunlock(cio);
1452                         nexterror();
1453                 }
1454                 ddeprint("epread ctl ndata %d\n", cio->ndata);
1455                 if(cio->ndata < 0)
1456                         error("request expected");
1457                 else if(cio->ndata == 0){
1458                         cio->ndata = -1;
1459                         count = 0;
1460                 }else{
1461                         if(count > cio->ndata)
1462                                 count = cio->ndata;
1463                         if(count > 0)
1464                                 memmove(a, cio->data, count);
1465                         /* BUG for big transfers */
1466                         free(cio->data);
1467                         cio->data = nil;
1468                         cio->ndata = 0; /* signal EOF next time */
1469                 }
1470                 qunlock(cio);
1471                 poperror();
1472                 if(debug>1 || ep->debug){
1473                         seprintdata(buf, buf+sizeof(buf), a, count);
1474                         print("epread: %s\n", buf);
1475                 }
1476                 return count;
1477         case Tbulk:
1478                 io = ep->aux;
1479                 if(ep->clrhalt)
1480                         clrhalt(ep);
1481                 return epio(ep, &io[OREAD], a, count, 1);
1482         case Tintr:
1483                 io = ep->aux;
1484                 delta = TK2MS(MACHP(0)->ticks) - io[OREAD].iotime + 1;
1485                 if(delta < ep->pollival / 2)
1486                         tsleep(&up->sleep, return0, 0, ep->pollival/2 - delta);
1487                 if(ep->clrhalt)
1488                         clrhalt(ep);
1489                 return epio(ep, &io[OREAD], a, count, 1);
1490         case Tiso:
1491                 iso = ep->aux;
1492                 return episoread(ep, iso, a, count);
1493         default:
1494                 panic("epread: bad ep ttype %d", ep->ttype);
1495         }
1496         return -1;
1497 }
1498
1499 /*
1500  * Control transfers are one setup write (data0)
1501  * plus zero or more reads/writes (data1, data0, ...)
1502  * plus a final write/read with data1 to ack.
1503  * For both host to device and device to host we perform
1504  * the entire transfer when the user writes the request,
1505  * and keep any data read from the device for a later read.
1506  * We call epio three times instead of placing all Tds at
1507  * the same time because doing so leads to crc/tmout errors
1508  * for some devices.
1509  * Upon errors on the data phase we must still run the status
1510  * phase or the device may cease responding in the future.
1511  */
1512 static long
1513 epctlio(Ep *ep, Ctlio *cio, void *a, long count)
1514 {
1515         uchar *c;
1516         long len;
1517
1518         ddeprint("epctlio: cio %#p ep%d.%d count %ld\n",
1519                 cio, ep->dev->nb, ep->nb, count);
1520         if(count < Rsetuplen)
1521                 error("short usb comand");
1522         eqlock(cio);
1523         free(cio->data);
1524         cio->data = nil;
1525         cio->ndata = 0;
1526         if(waserror()){
1527                 qunlock(cio);
1528                 free(cio->data);
1529                 cio->data = nil;
1530                 cio->ndata = 0;
1531                 nexterror();
1532         }
1533
1534         /* set the address if unset and out of configuration state */
1535         if(ep->dev->state != Dconfig && ep->dev->state != Dreset)
1536                 if(cio->usbid == 0)
1537                         cio->usbid = ((ep->nb&Epmax)<<7)|(ep->dev->nb&Devmax);
1538         c = a;
1539         cio->tok = Tdtoksetup;
1540         cio->toggle = Tddata0;
1541         if(epio(ep, cio, a, Rsetuplen, 0) < Rsetuplen)
1542                 error(Eio);
1543         a = c + Rsetuplen;
1544         count -= Rsetuplen;
1545
1546         cio->toggle = Tddata1;
1547         if(c[Rtype] & Rd2h){
1548                 cio->tok = Tdtokin;
1549                 len = GET2(c+Rcount);
1550                 if(len <= 0)
1551                         error("bad length in d2h request");
1552                 if(len > Maxctllen)
1553                         error("d2h data too large to fit in uhci");
1554                 a = cio->data = smalloc(len+1);
1555         }else{
1556                 cio->tok = Tdtokout;
1557                 len = count;
1558         }
1559         if(len > 0)
1560                 if(waserror())
1561                         len = -1;
1562                 else{
1563                         len = epio(ep, cio, a, len, 0);
1564                         poperror();
1565                 }
1566         if(c[Rtype] & Rd2h){
1567                 count = Rsetuplen;
1568                 cio->ndata = len;
1569                 cio->tok = Tdtokout;
1570         }else{
1571                 if(len < 0)
1572                         count = -1;
1573                 else
1574                         count = Rsetuplen + len;
1575                 cio->tok = Tdtokin;
1576         }
1577         cio->toggle = Tddata1;
1578         epio(ep, cio, nil, 0, 0);
1579         qunlock(cio);
1580         poperror();
1581         ddeprint("epctlio cio %#p return %ld\n", cio, count);
1582         return count;
1583 }
1584
1585 static long
1586 epwrite(Ep *ep, void *a, long count)
1587 {
1588         Ctlio *cio;
1589         Isoio *iso;
1590         Qio *io;
1591         ulong delta;
1592         char *b;
1593         int tot;
1594         int nw;
1595
1596         ddeprint("uhci: epwrite ep%d.%d\n", ep->dev->nb, ep->nb);
1597         if(ep->aux == nil)
1598                 panic("uhci: epwrite: not open");
1599         switch(ep->ttype){
1600         case Tctl:
1601                 cio = ep->aux;
1602                 return epctlio(ep, cio, a, count);
1603         case Tbulk:
1604                 io = ep->aux;
1605                 if(ep->clrhalt)
1606                         clrhalt(ep);
1607                 /*
1608                  * Put at most Tdatomic Tds (512 bytes) at a time.
1609                  * Otherwise some devices produce babble errors.
1610                  */
1611                 b = a;
1612                 for(tot = 0; tot < count ; tot += nw){
1613                         nw = count - tot;
1614                         if(nw > Tdatomic * ep->maxpkt)
1615                                 nw = Tdatomic * ep->maxpkt;
1616                         nw = epio(ep, &io[OWRITE], b+tot, nw, 1);
1617                 }
1618                 return tot;
1619         case Tintr:
1620                 io = ep->aux;
1621                 delta = TK2MS(MACHP(0)->ticks) - io[OWRITE].iotime + 1;
1622                 if(delta < ep->pollival)
1623                         tsleep(&up->sleep, return0, 0, ep->pollival - delta);
1624                 if(ep->clrhalt)
1625                         clrhalt(ep);
1626                 return epio(ep, &io[OWRITE], a, count, 1);
1627         case Tiso:
1628                 iso = ep->aux;
1629                 return episowrite(ep, iso, a, count);
1630         default:
1631                 panic("uhci: epwrite: bad ep ttype %d", ep->ttype);
1632         }
1633         return -1;
1634 }
1635
1636 static void
1637 isoopen(Ep *ep)
1638 {
1639         Ctlr *ctlr;
1640         Isoio *iso;
1641         int frno;
1642         int i;
1643         Td* td;
1644         Td* ltd;
1645         int size;
1646         int left;
1647
1648         if(ep->mode == ORDWR)
1649                 error("iso i/o is half-duplex");
1650         ctlr = ep->hp->aux;
1651         iso = ep->aux;
1652         iso->debug = ep->debug;
1653         iso->next = nil;                        /* paranoia */
1654         if(ep->mode == OREAD)
1655                 iso->tok = Tdtokin;
1656         else
1657                 iso->tok = Tdtokout;
1658         iso->usbid = ((ep->nb & Epmax)<<7)|(ep->dev->nb & Devmax);
1659         iso->state = Qidle;
1660         iso->nframes = Nframes/ep->pollival;
1661         if(iso->nframes < 3)
1662                 error("uhci isoopen bug");      /* we need at least 3 tds */
1663
1664         ilock(ctlr);
1665         if(ctlr->load + ep->load > 800)
1666                 print("usb: uhci: bandwidth may be exceeded\n");
1667         ctlr->load += ep->load;
1668         ctlr->isoload += ep->load;
1669         dprint("uhci: load %uld isoload %uld\n", ctlr->load, ctlr->isoload);
1670         iunlock(ctlr);
1671
1672         /*
1673          * From here on this cannot raise errors
1674          * unless we catch them and release here all memory allocated.
1675          */
1676         if(ep->maxpkt > Tdndata)
1677                 iso->data = smalloc(iso->nframes*ep->maxpkt);
1678         ilock(ctlr);
1679         frno = INS(Frnum) + 10;                 /* start 10ms ahead */
1680         frno = TRUNC(frno, Nframes);
1681         iunlock(ctlr);
1682         iso->td0frno = frno;
1683         ltd = nil;
1684         left = 0;
1685         for(i = 0; i < iso->nframes; i++){
1686                 td = iso->tdps[frno] = tdalloc();
1687                 if(ep->mode == OREAD)
1688                         size = ep->maxpkt;
1689                 else{
1690                         size = (ep->hz+left) * ep->pollival / 1000;
1691                         size *= ep->samplesz;
1692                         left = (ep->hz+left) * ep->pollival % 1000;
1693                         if(size > ep->maxpkt){
1694                                 print("uhci: ep%d.%d: size > maxpkt\n",
1695                                         ep->dev->nb, ep->nb);
1696                                 print("size = %d max = %ld\n", size, ep->maxpkt);
1697                                 size = ep->maxpkt;
1698                         }
1699                 }
1700                 if(size > Tdndata)
1701                         td->data = iso->data + i * ep->maxpkt;
1702                 else
1703                         td->data = td->sbuff;
1704                 td->buffer = PCIWADDR(td->data);
1705                 tdisoinit(iso, td, size);
1706                 if(ltd != nil)
1707                         ltd->next = td;
1708                 ltd = td;
1709                 frno = TRUNC(frno+ep->pollival, Nframes);
1710         }
1711         ltd->next = iso->tdps[iso->td0frno];
1712         iso->tdi = iso->tdps[iso->td0frno];
1713         iso->tdu = iso->tdi;
1714         ilock(ctlr);
1715         frno = iso->td0frno;
1716         for(i = 0; i < iso->nframes; i++){
1717                 iso->tdps[frno]->link = ctlr->frames[frno];
1718                 frno = TRUNC(frno+ep->pollival, Nframes);
1719         }
1720         coherence();
1721         frno = iso->td0frno;
1722         for(i = 0; i < iso->nframes; i++){
1723                 ctlr->frames[frno] = PCIWADDR(iso->tdps[frno]);
1724                 frno = TRUNC(frno+ep->pollival, Nframes);
1725         }
1726         iso->next = ctlr->iso;
1727         ctlr->iso = iso;
1728         iso->state = Qdone;
1729         iunlock(ctlr);
1730         if(debug > 1 || iso->debug >1)
1731                 isodump(iso, 0);
1732 }
1733
1734 /*
1735  * Allocate the endpoint and set it up for I/O
1736  * in the controller. This must follow what's said
1737  * in Ep regarding configuration, including perhaps
1738  * the saved toggles (saved on a previous close of
1739  * the endpoint data file by epclose).
1740  */
1741 static void
1742 epopen(Ep *ep)
1743 {
1744         Ctlr *ctlr;
1745         Qh *cqh;
1746         Qio *io;
1747         Ctlio *cio;
1748         int usbid;
1749
1750         ctlr = ep->hp->aux;
1751         deprint("uhci: epopen ep%d.%d\n", ep->dev->nb, ep->nb);
1752         if(ep->aux != nil)
1753                 panic("uhci: epopen called with open ep");
1754         if(waserror()){
1755                 free(ep->aux);
1756                 ep->aux = nil;
1757                 nexterror();
1758         }
1759         if(ep->maxpkt > Tdmaxpkt){
1760                 print("uhci: maxkpkt too large: using %d\n", Tdmaxpkt);
1761                 ep->maxpkt = Tdmaxpkt;
1762         }
1763         cqh = ctlr->qh[ep->ttype];
1764         switch(ep->ttype){
1765         case Tnone:
1766                 error("endpoint not configured");
1767         case Tiso:
1768                 ep->aux = smalloc(sizeof(Isoio));
1769                 isoopen(ep);
1770                 break;
1771         case Tctl:
1772                 cio = ep->aux = smalloc(sizeof(Ctlio));
1773                 cio->debug = ep->debug;
1774                 cio->ndata = -1;
1775                 cio->data = nil;
1776                 if(ep->dev->isroot != 0 && ep->nb == 0) /* root hub */
1777                         break;
1778                 cio->qh = qhalloc(ctlr, cqh, cio, "epc");
1779                 break;
1780         case Tbulk:
1781         case Tintr:
1782                 io = ep->aux = smalloc(sizeof(Qio)*2);
1783                 io[OREAD].debug = io[OWRITE].debug = ep->debug;
1784                 usbid = ((ep->nb&Epmax)<<7)|(ep->dev->nb &Devmax);
1785                 if(ep->mode != OREAD){
1786                         if(ep->toggle[OWRITE] != 0)
1787                                 io[OWRITE].toggle = Tddata1;
1788                         else
1789                                 io[OWRITE].toggle = Tddata0;
1790                         io[OWRITE].tok = Tdtokout;
1791                         io[OWRITE].qh = qhalloc(ctlr, cqh, io+OWRITE, "epw");
1792                         io[OWRITE].usbid = usbid;
1793                 }
1794                 if(ep->mode != OWRITE){
1795                         if(ep->toggle[OREAD] != 0)
1796                                 io[OREAD].toggle = Tddata1;
1797                         else
1798                                 io[OREAD].toggle = Tddata0;
1799                         io[OREAD].tok = Tdtokin;
1800                         io[OREAD].qh = qhalloc(ctlr, cqh, io+OREAD, "epr");
1801                         io[OREAD].usbid = usbid;
1802                 }
1803                 break;
1804         }
1805         if(debug>1 || ep->debug)
1806                 dump(ep->hp);
1807         deprint("uhci: epopen done\n");
1808         poperror();
1809 }
1810
1811 static void
1812 cancelio(Ctlr *ctlr, Qio *io)
1813 {
1814         Qh *qh;
1815
1816         ilock(ctlr);
1817         qh = io->qh;
1818         if(io == nil || io->qh == nil || io->qh->state == Qclose){
1819                 iunlock(ctlr);
1820                 return;
1821         }
1822         dqprint("uhci: cancelio for qh %#p state %s\n",
1823                 qh, qhsname[qh->state]);
1824         aborttds(qh);
1825         qh->state = Qclose;
1826         iunlock(ctlr);
1827         if(!waserror()){
1828                 tsleep(&up->sleep, return0, 0, Abortdelay);
1829                 poperror();
1830         }
1831
1832         wakeup(io);
1833         qlock(io);
1834         /* wait for epio if running */
1835         qunlock(io);
1836
1837         qhfree(ctlr, qh);
1838         io->qh = nil;
1839 }
1840
1841 static void
1842 cancelisoio(Ctlr *ctlr, Isoio *iso, int pollival, ulong load)
1843 {
1844         Isoio **il;
1845         ulong *lp;
1846         int i;
1847         int frno;
1848         Td *td;
1849
1850         ilock(ctlr);
1851         if(iso->state == Qclose){
1852                 iunlock(ctlr);
1853                 return;
1854         }
1855         if(iso->state != Qrun && iso->state != Qdone)
1856                 panic("bad iso state");
1857         iso->state = Qclose;
1858         if(ctlr->isoload < load)
1859                 panic("uhci: low isoload");
1860         ctlr->isoload -= load;
1861         ctlr->load -= load;
1862         for(il = &ctlr->iso; *il != nil; il = &(*il)->next)
1863                 if(*il == iso)
1864                         break;
1865         if(*il == nil)
1866                 panic("isocancel: not found");
1867         *il = iso->next;
1868         frno = iso->td0frno;
1869         for(i = 0; i < iso->nframes; i++){
1870                 td = iso->tdps[frno];
1871                 td->csw &= ~(Tdioc|Tdactive);
1872                 for(lp=&ctlr->frames[frno]; !(*lp & Tdterm);
1873                                         lp = &TPTR(*lp)->link)
1874                         if(TPTR(*lp) == td)
1875                                 break;
1876                 if(*lp & Tdterm)
1877                         panic("cancelisoio: td not found");
1878                 *lp = td->link;
1879                 frno = TRUNC(frno+pollival, Nframes);
1880         }
1881         iunlock(ctlr);
1882
1883         /*
1884          * wakeup anyone waiting for I/O and
1885          * wait to be sure no I/O is in progress in the controller.
1886          * and then wait to be sure episo-io is no longer running.
1887          */
1888         wakeup(iso);
1889         diprint("cancelisoio iso %#p waiting for I/O to cease\n", iso);
1890         tsleep(&up->sleep, return0, 0, 5);
1891         qlock(iso);
1892         qunlock(iso);
1893         diprint("cancelisoio iso %#p releasing iso\n", iso);
1894
1895         frno = iso->td0frno;
1896         for(i = 0; i < iso->nframes; i++){
1897                 tdfree(iso->tdps[frno]);
1898                 iso->tdps[frno] = nil;
1899                 frno = TRUNC(frno+pollival, Nframes);
1900         }
1901         free(iso->data);
1902         iso->data = nil;
1903 }
1904
1905 static void
1906 epclose(Ep *ep)
1907 {
1908         Ctlr *ctlr;
1909         Ctlio *cio;
1910         Isoio *iso;
1911         Qio *io;
1912
1913         ctlr = ep->hp->aux;
1914         deprint("uhci: epclose ep%d.%d\n", ep->dev->nb, ep->nb);
1915
1916         if(ep->aux == nil)
1917                 panic("uhci: epclose called with closed ep");
1918         switch(ep->ttype){
1919         case Tctl:
1920                 cio = ep->aux;
1921                 cancelio(ctlr, cio);
1922                 free(cio->data);
1923                 cio->data = nil;
1924                 break;
1925         case Tbulk:
1926         case Tintr:
1927                 io = ep->aux;
1928                 ep->toggle[OREAD] = ep->toggle[OWRITE] = 0;
1929                 if(ep->mode != OWRITE){
1930                         cancelio(ctlr, &io[OREAD]);
1931                         if(io[OREAD].toggle == Tddata1)
1932                                 ep->toggle[OREAD] = 1;
1933                 }
1934                 if(ep->mode != OREAD){
1935                         cancelio(ctlr, &io[OWRITE]);
1936                         if(io[OWRITE].toggle == Tddata1)
1937                                 ep->toggle[OWRITE] = 1;
1938                 }
1939                 break;
1940         case Tiso:
1941                 iso = ep->aux;
1942                 cancelisoio(ctlr, iso, ep->pollival, ep->load);
1943                 break;
1944         default:
1945                 panic("epclose: bad ttype %d", ep->ttype);
1946         }
1947
1948         free(ep->aux);
1949         ep->aux = nil;
1950
1951 }
1952
1953 static char*
1954 seprintep(char *s, char *e, Ep *ep)
1955 {
1956         Ctlio *cio;
1957         Qio *io;
1958         Isoio *iso;
1959         Ctlr *ctlr;
1960
1961         ctlr = ep->hp->aux;
1962         ilock(ctlr);
1963         if(ep->aux == nil){
1964                 *s = 0;
1965                 iunlock(ctlr);
1966                 return s;
1967         }
1968         switch(ep->ttype){
1969         case Tctl:
1970                 cio = ep->aux;
1971                 s = seprint(s,e,"cio %#p qh %#p"
1972                         " id %#x tog %#x tok %#x err %s\n",
1973                         cio, cio->qh, cio->usbid, cio->toggle,
1974                         cio->tok, cio->err);
1975                 break;
1976         case Tbulk:
1977         case Tintr:
1978                 io = ep->aux;
1979                 if(ep->mode != OWRITE)
1980                         s = seprint(s,e,"r: qh %#p id %#x tog %#x tok %#x err %s\n",
1981                                 io[OREAD].qh, io[OREAD].usbid, io[OREAD].toggle,
1982                                 io[OREAD].tok, io[OREAD].err);
1983                 if(ep->mode != OREAD)
1984                         s = seprint(s,e,"w: qh %#p id %#x tog %#x tok %#x err %s\n",
1985                                 io[OWRITE].qh, io[OWRITE].usbid, io[OWRITE].toggle,
1986                                 io[OWRITE].tok, io[OWRITE].err);
1987                 break;
1988         case Tiso:
1989                 iso = ep->aux;
1990                 s = seprint(s,e,"iso %#p id %#x tok %#x tdu %#p tdi %#p err %s\n",
1991                         iso, iso->usbid, iso->tok, iso->tdu, iso->tdi, iso->err);
1992                 break;
1993         }
1994         iunlock(ctlr);
1995         return s;
1996 }
1997
1998 static int
1999 portenable(Hci *hp, int port, int on)
2000 {
2001         int s;
2002         int ioport;
2003         Ctlr *ctlr;
2004
2005         ctlr = hp->aux;
2006         dprint("uhci: %#x port %d enable=%d\n", ctlr->port, port, on);
2007         ioport = PORT(port-1);
2008         eqlock(&ctlr->portlck);
2009         if(waserror()){
2010                 qunlock(&ctlr->portlck);
2011                 nexterror();
2012         }
2013         ilock(ctlr);
2014         s = INS(ioport);
2015         if(on)
2016                 OUTS(ioport, s | PSenable);
2017         else
2018                 OUTS(ioport, s & ~PSenable);
2019         microdelay(64);
2020         iunlock(ctlr);
2021         tsleep(&up->sleep, return0, 0, Enabledelay);
2022         dprint("uhci %#ux port %d enable=%d: sts %#x\n",
2023                 ctlr->port, port, on, INS(ioport));
2024         qunlock(&ctlr->portlck);
2025         poperror();
2026         return 0;
2027 }
2028
2029 static int
2030 portreset(Hci *hp, int port, int on)
2031 {
2032         int i, p;
2033         Ctlr *ctlr;
2034
2035         if(on == 0)
2036                 return 0;
2037         ctlr = hp->aux;
2038         dprint("uhci: %#ux port %d reset\n", ctlr->port, port);
2039         p = PORT(port-1);
2040         ilock(ctlr);
2041         OUTS(p, PSreset);
2042         delay(50);
2043         OUTS(p, INS(p) & ~PSreset);
2044         OUTS(p, INS(p) | PSenable);
2045         microdelay(64);
2046         for(i=0; i<1000 && (INS(p) & PSenable) == 0; i++)
2047                 ;
2048         OUTS(p, (INS(p) & ~PSreset)|PSenable);
2049         iunlock(ctlr);
2050         dprint("uhci %#ux after port %d reset: sts %#x\n",
2051                 ctlr->port, port, INS(p));
2052         return 0;
2053 }
2054
2055 static int
2056 portstatus(Hci *hp, int port)
2057 {
2058         int s;
2059         int r;
2060         int ioport;
2061         Ctlr *ctlr;
2062
2063         ctlr = hp->aux;
2064         ioport = PORT(port-1);
2065         eqlock(&ctlr->portlck);
2066         if(waserror()){
2067                 iunlock(ctlr);
2068                 qunlock(&ctlr->portlck);
2069                 nexterror();
2070         }
2071         ilock(ctlr);
2072         s = INS(ioport);
2073         if(s & (PSstatuschg | PSchange)){
2074                 OUTS(ioport, s);
2075                 ddprint("uhci %#ux port %d status %#x\n", ctlr->port, port, s);
2076         }
2077         iunlock(ctlr);
2078         qunlock(&ctlr->portlck);
2079         poperror();
2080
2081         /*
2082          * We must return status bits as a
2083          * get port status hub request would do.
2084          */
2085         r = 0;
2086         if(s & PSpresent)
2087                 r |= HPpresent;
2088         if(s & PSenable)
2089                 r |= HPenable;
2090         if(s & PSsuspend)
2091                 r |= HPsuspend;
2092         if(s & PSreset)
2093                 r |= HPreset;
2094         if(s & PSslow)
2095                 r |= HPslow;
2096         if(s & PSstatuschg)
2097                 r |= HPstatuschg;
2098         if(s & PSchange)
2099                 r |= HPchange;
2100         return r;
2101 }
2102
2103 static void
2104 scanpci(void)
2105 {
2106         static int already = 0;
2107         int io;
2108         int i;
2109         Ctlr *ctlr;
2110         Pcidev *p;
2111
2112         if(already)
2113                 return;
2114         already = 1;
2115         p = nil;
2116         while(p = pcimatch(p, 0, 0)){
2117                 /*
2118                  * Find UHCI controllers (Programming Interface = 0).
2119                  */
2120                 if(p->ccrb != Pcibcserial || p->ccru != Pciscusb)
2121                         continue;
2122                 switch(p->ccrp){
2123                 case 0:
2124                         io = p->mem[4].bar & ~0x0F;
2125                         break;
2126                 default:
2127                         continue;
2128                 }
2129                 if(io == 0){
2130                         print("usbuhci: %#x %#x: failed to map registers\n",
2131                                 p->vid, p->did);
2132                         continue;
2133                 }
2134                 if(ioalloc(io, p->mem[4].size, 0, "usbuhci") < 0){
2135                         print("usbuhci: port %#ux in use\n", io);
2136                         continue;
2137                 }
2138                 if(p->intl == 0xFF || p->intl == 0){
2139                         print("usbuhci: no irq assigned for port %#ux\n", io);
2140                         continue;
2141                 }
2142
2143                 dprint("uhci: %#x %#x: port %#ux size %#x irq %d\n",
2144                         p->vid, p->did, io, p->mem[4].size, p->intl);
2145
2146                 ctlr = malloc(sizeof(Ctlr));
2147                 if(ctlr == nil){
2148                         iofree(io);
2149                         print("usbuhci: no memory\n");
2150                         continue;
2151                 }
2152                 ctlr->pcidev = p;
2153                 ctlr->port = io;
2154                 for(i = 0; i < Nhcis; i++)
2155                         if(ctlrs[i] == nil){
2156                                 ctlrs[i] = ctlr;
2157                                 break;
2158                         }
2159                 if(i == Nhcis)
2160                         print("usbuhci: bug: no more controllers\n");
2161         }
2162 }
2163
2164 static void
2165 uhcimeminit(Ctlr *ctlr)
2166 {
2167         Td* td;
2168         Qh *qh;
2169         int frsize;
2170         int i;
2171
2172         ctlr->qhs = ctlr->qh[Tctl] = qhalloc(ctlr, nil, nil, "CTL");
2173         ctlr->qh[Tintr] = qhalloc(ctlr, ctlr->qh[Tctl], nil, "INT");
2174         ctlr->qh[Tbulk] = qhalloc(ctlr, ctlr->qh[Tintr], nil, "BLK");
2175
2176         /* idle Td from dummy Qh at the end. looped back to itself */
2177         /* This is a workaround for PIIX4 errata 29773804.pdf */
2178         qh = qhalloc(ctlr, ctlr->qh[Tbulk], nil, "BWS");
2179         td = tdalloc();
2180         td->link = PCIWADDR(td);
2181         qhlinktd(qh, td);
2182
2183         /* loop (hw only) from the last qh back to control xfers.
2184          * this may be done only for some of them. Disable until ehci comes.
2185          */
2186         if(0)
2187         qh->link = PCIWADDR(ctlr->qhs);
2188
2189         frsize = Nframes*sizeof(ulong);
2190         ctlr->frames = xspanalloc(frsize, frsize, 0);
2191         if(ctlr->frames == nil)
2192                 panic("uhci reset: no memory");
2193
2194         ctlr->iso = nil;
2195         for(i = 0; i < Nframes; i++)
2196                 ctlr->frames[i] = PCIWADDR(ctlr->qhs)|QHlinkqh;
2197         OUTL(Flbaseadd, PCIWADDR(ctlr->frames));
2198         OUTS(Frnum, 0);
2199         dprint("uhci %#ux flb %#ulx frno %#ux\n", ctlr->port,
2200                 INL(Flbaseadd), INS(Frnum));
2201 }
2202
2203 static void
2204 init(Hci *hp)
2205 {
2206         Ctlr *ctlr;
2207         int sts;
2208         int i;
2209
2210         ctlr = hp->aux;
2211         dprint("uhci %#ux init\n", ctlr->port);
2212         coherence();
2213         ilock(ctlr);
2214         OUTS(Usbintr, Itmout|Iresume|Ioc|Ishort);
2215         uhcirun(ctlr, 1);
2216         dprint("uhci: init: cmd %#ux sts %#ux sof %#ux",
2217                 INS(Cmd), INS(Status), INS(SOFmod));
2218         dprint(" flb %#ulx frno %#ux psc0 %#ux psc1 %#ux",
2219                 INL(Flbaseadd), INS(Frnum), INS(PORT(0)), INS(PORT(1)));
2220         /* guess other ports */
2221         for(i = 2; i < 6; i++){
2222                 sts = INS(PORT(i));
2223                 if(sts != 0xFFFF && (sts & PSreserved1) == 1){
2224                         dprint(" psc%d %#ux", i, sts);
2225                         hp->nports++;
2226                 }else
2227                         break;
2228         }
2229         for(i = 0; i < hp->nports; i++)
2230                 OUTS(PORT(i), 0);
2231         iunlock(ctlr);
2232 }
2233
2234 static void
2235 uhcireset(Ctlr *ctlr)
2236 {
2237         int i;
2238         int sof;
2239
2240         ilock(ctlr);
2241         dprint("uhci %#ux reset\n", ctlr->port);
2242
2243         /*
2244          * Turn off legacy mode. Some controllers won't
2245          * interrupt us as expected otherwise.
2246          */
2247         uhcirun(ctlr, 0);
2248         pcicfgw16(ctlr->pcidev, 0xc0, 0x2000);
2249
2250         OUTS(Usbintr, 0);
2251         sof = INB(SOFmod);
2252         uhcicmd(ctlr, Cgreset);                 /* global reset */
2253         delay(Resetdelay);
2254         uhcicmd(ctlr, 0);                       /* all halt */
2255         uhcicmd(ctlr, Chcreset);                        /* controller reset */
2256         for(i = 0; i < 100; i++){
2257                 if((INS(Cmd) & Chcreset) == 0)
2258                         break;
2259                 delay(1);
2260         }
2261         if(i == 100)
2262                 print("uhci %#x controller reset timed out\n", ctlr->port);
2263         OUTB(SOFmod, sof);
2264         iunlock(ctlr);
2265 }
2266
2267 static void
2268 setdebug(Hci*, int d)
2269 {
2270         debug = d;
2271 }
2272
2273 static void
2274 shutdown(Hci *hp)
2275 {
2276         Ctlr *ctlr;
2277
2278         ctlr = hp->aux;
2279
2280         ilock(ctlr);
2281         uhcirun(ctlr, 0);
2282         delay(100);
2283         iunlock(ctlr);
2284 }
2285
2286 static int
2287 reset(Hci *hp)
2288 {
2289         static Lock resetlck;
2290         int i;
2291         Ctlr *ctlr;
2292         Pcidev *p;
2293
2294         if(getconf("*nousbuhci"))
2295                 return -1;
2296
2297         ilock(&resetlck);
2298         scanpci();
2299
2300         /*
2301          * Any adapter matches if no hp->port is supplied,
2302          * otherwise the ports must match.
2303          */
2304         ctlr = nil;
2305         for(i = 0; i < Nhcis && ctlrs[i] != nil; i++){
2306                 ctlr = ctlrs[i];
2307                 if(ctlr->active == 0)
2308                 if(hp->port == 0 || hp->port == ctlr->port){
2309                         ctlr->active = 1;
2310                         break;
2311                 }
2312         }
2313         iunlock(&resetlck);
2314         if(ctlrs[i] == nil || i == Nhcis)
2315                 return -1;
2316
2317         p = ctlr->pcidev;
2318         hp->aux = ctlr;
2319         hp->port = ctlr->port;
2320         hp->irq = p->intl;
2321         hp->tbdf = p->tbdf;
2322         hp->nports = 2;                 /* default */
2323
2324         uhcireset(ctlr);
2325         uhcimeminit(ctlr);
2326
2327         /*
2328          * Linkage to the generic HCI driver.
2329          */
2330         hp->init = init;
2331         hp->dump = dump;
2332         hp->interrupt = interrupt;
2333         hp->epopen = epopen;
2334         hp->epclose = epclose;
2335         hp->epread = epread;
2336         hp->epwrite = epwrite;
2337         hp->seprintep = seprintep;
2338         hp->portenable = portenable;
2339         hp->portreset = portreset;
2340         hp->portstatus = portstatus;
2341         hp->shutdown = shutdown;
2342         hp->debug = setdebug;
2343         hp->type = "uhci";
2344         return 0;
2345 }
2346
2347 void
2348 usbuhcilink(void)
2349 {
2350         addhcitype("uhci", reset);
2351 }