]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/pc/usbuhci.c
usb: fix potential uninterruptable calls
[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(Isoio *iso, uchar *b, long count)
997 {
998         long tot;
999         long n;
1000
1001         for(tot = 0; isocanwrite(iso) && tot < count; tot += n){
1002                 n = count-tot;
1003                 if(n > maxtdlen(iso->tdu) - iso->nleft)
1004                         n = maxtdlen(iso->tdu) - iso->nleft;
1005                 memmove(iso->tdu->data+iso->nleft, b+tot, n);
1006                 iso->nleft += n;
1007                 if(iso->nleft == maxtdlen(iso->tdu)){
1008                         tdisoinit(iso, iso->tdu, iso->nleft);
1009                         iso->nleft = 0;
1010                         iso->tdu = iso->tdu->next;
1011                 }
1012         }
1013         return tot;
1014 }
1015
1016 /*
1017  * Queue data for writing and return error status from
1018  * last writes done, to maintain buffered data.
1019  */
1020 static long
1021 episowrite(Ep *ep, Isoio *iso, void *a, long count)
1022 {
1023         Ctlr *ctlr;
1024         uchar *b;
1025         int tot;
1026         int nw;
1027         char *err;
1028
1029         iso->debug = ep->debug;
1030         iso->delay = ep->sampledelay * ep->samplesz;
1031         diprint("uhci: episowrite: %#p ep%d.%d\n", iso, ep->dev->nb, ep->nb);
1032
1033         ctlr = ep->hp->aux;
1034         eqlock(iso);
1035         if(waserror()){
1036                 qunlock(iso);
1037                 nexterror();
1038         }
1039         ilock(ctlr);
1040         if(iso->state == Qclose){
1041                 iunlock(ctlr);
1042                 error(iso->err ? iso->err : Eio);
1043         }
1044         iso->state = Qrun;
1045         b = a;
1046         for(tot = 0; tot < count; tot += nw){
1047                 while(isocanwrite(iso) == 0){
1048                         iunlock(ctlr);
1049                         diprint("uhci: episowrite: %#p sleep\n", iso);
1050                         if(waserror()){
1051                                 if(iso->err == nil)
1052                                         iso->err = "I/O timed out";
1053                                 ilock(ctlr);
1054                                 break;
1055                         }
1056                         tsleep(iso, isocanwrite, iso, ep->tmout);
1057                         poperror();
1058                         ilock(ctlr);
1059                 }
1060                 err = iso->err;
1061                 iso->err = nil;
1062                 if(iso->state == Qclose || err != nil){
1063                         iunlock(ctlr);
1064                         error(err ? err : Eio);
1065                 }
1066                 if(iso->state != Qrun)
1067                         panic("episowrite: iso not running");
1068                 iunlock(ctlr);          /* We could page fault here */
1069                 nw = putsamples(iso, b+tot, count-tot);
1070                 ilock(ctlr);
1071         }
1072         while(isodelay(iso) == 0){
1073                 iunlock(ctlr);
1074                 sleep(iso, isodelay, iso);
1075                 ilock(ctlr);
1076         }
1077         if(iso->state != Qclose)
1078                 iso->state = Qdone;
1079         iunlock(ctlr);
1080         err = iso->err;         /* in case it failed early */
1081         iso->err = nil;
1082         qunlock(iso);
1083         poperror();
1084         if(err != nil)
1085                 error(err);
1086         diprint("uhci: episowrite: %#p %d bytes\n", iso, tot);
1087         return tot;
1088 }
1089
1090 /*
1091  * Available data is kept at tdu and following tds, up to tdi (excluded).
1092  */
1093 static long
1094 episoread(Ep *ep, Isoio *iso, void *a, int count)
1095 {
1096         Ctlr *ctlr;
1097         uchar *b;
1098         int nr;
1099         int tot;
1100         Td *tdu;
1101
1102         iso->debug = ep->debug;
1103         diprint("uhci: episoread: %#p ep%d.%d\n", iso, ep->dev->nb, ep->nb);
1104
1105         b = a;
1106         ctlr = ep->hp->aux;
1107         eqlock(iso);
1108         if(waserror()){
1109                 qunlock(iso);
1110                 nexterror();
1111         }
1112         iso->err = nil;
1113         iso->nerrs = 0;
1114         ilock(ctlr);
1115         if(iso->state == Qclose){
1116                 iunlock(ctlr);
1117                 error(iso->err ? iso->err : Eio);
1118         }
1119         iso->state = Qrun;
1120         while(isocanread(iso) == 0){
1121                 iunlock(ctlr);
1122                 diprint("uhci: episoread: %#p sleep\n", iso);
1123                 if(waserror()){
1124                         if(iso->err == nil)
1125                                 iso->err = "I/O timed out";
1126                         ilock(ctlr);
1127                         break;
1128                 }
1129                 tsleep(iso, isocanread, iso, ep->tmout);
1130                 poperror();
1131                 ilock(ctlr);
1132         }
1133         if(iso->state == Qclose){
1134                 iunlock(ctlr);
1135                 error(iso->err ? iso->err : Eio);
1136         }
1137         iso->state = Qdone;
1138
1139         for(tot = 0; iso->tdi != iso->tdu && tot < count; tot += nr){
1140                 tdu = iso->tdu;
1141                 if(tdu->csw & Tdactive){
1142                         diprint("uhci: episoread: %#p tdu active\n", iso);
1143                         break;
1144                 }
1145                 nr = tdu->ndata;
1146                 if(tot + nr > count)
1147                         nr = count - tot;
1148                 if(nr == 0)
1149                         print("uhci: ep%d.%d: too many polls\n",
1150                                 ep->dev->nb, ep->nb);
1151                 else{
1152                         iunlock(ctlr);          /* We could page fault here */
1153                         memmove(b+tot, tdu->data, nr);
1154                         ilock(ctlr);
1155                         if(nr < tdu->ndata)
1156                                 memmove(tdu->data, tdu->data+nr, tdu->ndata - nr);
1157                         tdu->ndata -= nr;
1158                 }
1159                 if(tdu->ndata == 0){
1160                         tdisoinit(iso, tdu, ep->maxpkt);
1161                         iso->tdu = tdu->next;
1162                 }
1163         }
1164         iunlock(ctlr);
1165         qunlock(iso);
1166         poperror();
1167         diprint("uhci: episoread: %#p %d bytes err '%s'\n", iso, tot, iso->err);
1168         if(iso->err != nil)
1169                 error(iso->err);
1170         return tot;
1171 }
1172
1173 static int
1174 nexttoggle(int tog)
1175 {
1176         if(tog == Tddata0)
1177                 return Tddata1;
1178         else
1179                 return Tddata0;
1180 }
1181
1182 static Td*
1183 epgettd(Ep *ep, Qio *io, int flags, void *a, int count)
1184 {
1185         Td *td;
1186         int tok;
1187
1188         if(ep->maxpkt < count)
1189                 error("maxpkt too short");
1190         td = tdalloc();
1191         if(count <= Tdndata)
1192                 td->data = td->sbuff;
1193         else
1194                 td->data = td->buff = smalloc(ep->maxpkt);
1195         td->buffer = PCIWADDR(td->data);
1196         td->ndata = count;
1197         if(a != nil && count > 0)
1198                 memmove(td->data, a, count);
1199         td->csw = Tderr2|Tderr1|flags;
1200         if(ep->dev->speed == Lowspeed)
1201                 td->csw |= Tdlow;
1202         tok = io->tok | io->toggle;
1203         io->toggle = nexttoggle(io->toggle);
1204         td->token = ((count-1)<<21) | ((io->usbid&0x7FF)<<8) | tok;
1205
1206         return td;
1207 }
1208
1209 /*
1210  * Try to get them idle
1211  */
1212 static void
1213 aborttds(Qh *qh)
1214 {
1215         Td *td;
1216
1217         qh->state = Qdone;
1218         qh->elink = QHterm;
1219         for(td = qh->tds; td != nil; td = td->next){
1220                 if(td->csw & Tdactive)
1221                         td->ndata = 0;
1222                 td->csw &= ~(Tdactive|Tdioc);
1223         }
1224 }
1225
1226 static int
1227 epiodone(void *a)
1228 {
1229         Qh *qh;
1230
1231         qh = a;
1232         return qh->state != Qrun;
1233 }
1234
1235 static void
1236 epiowait(Ctlr *ctlr, Qio *io, int tmout, ulong load)
1237 {
1238         Qh *qh;
1239         int timedout;
1240
1241         qh = io->qh;
1242         ddqprint("uhci io %#p sleep on qh %#p state %uld\n", io, qh, qh->state);
1243         timedout = 0;
1244         if(waserror()){
1245                 dqprint("uhci io %#p qh %#p timed out\n", io, qh);
1246                 timedout++;
1247         }else{
1248                 if(tmout == 0)
1249                         sleep(io, epiodone, qh);
1250                 else
1251                         tsleep(io, epiodone, qh, tmout);
1252                 poperror();
1253         }
1254         ilock(ctlr);
1255         if(qh->state == Qrun)
1256                 timedout = 1;
1257         else if(qh->state != Qdone && qh->state != Qclose)
1258                 panic("epio: queue not done and not closed");
1259         if(timedout){
1260                 aborttds(io->qh);
1261                 io->err = "request timed out";
1262                 iunlock(ctlr);
1263                 if(!waserror()){
1264                         tsleep(&up->sleep, return0, 0, Abortdelay);
1265                         poperror();
1266                 }
1267                 ilock(ctlr);
1268         }
1269         if(qh->state != Qclose)
1270                 qh->state = Qidle;
1271         qhlinktd(qh, nil);
1272         ctlr->load -= load;
1273         iunlock(ctlr);
1274 }
1275
1276 /*
1277  * Non iso I/O.
1278  * To make it work for control transfers, the caller may
1279  * lock the Qio for the entire control transfer.
1280  */
1281 static long
1282 epio(Ep *ep, Qio *io, void *a, long count, int mustlock)
1283 {
1284         Td *td, *ltd, *td0, *ntd;
1285         Ctlr *ctlr;
1286         Qh* qh;
1287         long n, tot;
1288         char buf[128];
1289         uchar *c;
1290         int saved, ntds, tmout;
1291         ulong load;
1292         char *err;
1293
1294         qh = io->qh;
1295         ctlr = ep->hp->aux;
1296         io->debug = ep->debug;
1297         tmout = ep->tmout;
1298         ddeprint("epio: %s ep%d.%d io %#p count %ld load %uld\n",
1299                 io->tok == Tdtokin ? "in" : "out",
1300                 ep->dev->nb, ep->nb, io, count, ctlr->load);
1301         if((debug > 1 || ep->debug > 1) && io->tok != Tdtokin){
1302                 seprintdata(buf, buf+sizeof(buf), a, count);
1303                 print("uchi epio: user data: %s\n", buf);
1304         }
1305         if(mustlock){
1306                 eqlock(io);
1307                 if(waserror()){
1308                         qunlock(io);
1309                         nexterror();
1310                 }
1311         }
1312         io->err = nil;
1313         ilock(ctlr);
1314         if(qh->state == Qclose){        /* Tds released by cancelio */
1315                 iunlock(ctlr);
1316                 error(io->err ? io->err : Eio);
1317         }
1318         if(qh->state != Qidle)
1319                 panic("epio: qh not idle");
1320         qh->state = Qinstall;
1321         iunlock(ctlr);
1322
1323         c = a;
1324         td0 = ltd = nil;
1325         load = tot = 0;
1326         do{
1327                 n = ep->maxpkt;
1328                 if(count-tot < n)
1329                         n = count-tot;
1330                 if(c != nil && io->tok != Tdtokin)
1331                         td = epgettd(ep, io, Tdactive, c+tot, n);
1332                 else
1333                         td = epgettd(ep, io, Tdactive|Tdspd, nil, n);
1334                 if(td0 == nil)
1335                         td0 = td;
1336                 else
1337                         tdlinktd(ltd, td);
1338                 ltd = td;
1339                 tot += n;
1340                 load += ep->load;
1341         }while(tot < count);
1342         if(td0 == nil || ltd == nil)
1343                 panic("epio: no td");
1344
1345         ltd->csw |= Tdioc;      /* the last one interrupts */
1346         ddeprint("uhci: load %uld ctlr load %uld\n", load, ctlr->load);
1347         ilock(ctlr);
1348         if(qh->state != Qclose){
1349                 io->iotime = TK2MS(MACHP(0)->ticks);
1350                 qh->state = Qrun;
1351                 coherence();
1352                 qhlinktd(qh, td0);
1353                 ctlr->load += load;
1354         }
1355         iunlock(ctlr);
1356
1357         epiowait(ctlr, io, tmout, load);
1358
1359         if(debug > 1 || ep->debug > 1)
1360                 dumptd(td0, "epio: got tds: ");
1361
1362         tot = 0;
1363         c = a;
1364         saved = 0;
1365         ntds = 0;
1366         for(td = td0; td != nil; td = ntd){
1367                 ntds++;
1368                 /*
1369                  * Use td tok, not io tok, because of setup packets.
1370                  * Also, if the Td was stalled or active (previous Td
1371                  * was a short packet), we must save the toggle as it is.
1372                  */
1373                 if(td->csw & (Tdstalled|Tdactive)){
1374                         if(saved++ == 0)
1375                                 io->toggle = td->token & Tddata1;
1376                 }else{
1377                         tot += td->ndata;
1378                         if(c != nil && tdtok(td) == Tdtokin && td->ndata > 0){
1379                                 memmove(c, td->data, td->ndata);
1380                                 c += td->ndata;
1381                         }
1382                 }
1383                 ntd = td->next;
1384                 tdfree(td);
1385         }
1386         err = io->err;
1387         if(mustlock){
1388                 qunlock(io);
1389                 poperror();
1390         }
1391         ddeprint("epio: io %#p: %d tds: return %ld err '%s'\n",
1392                 io, ntds, tot, err);
1393         if(err != nil)
1394                 error(err);
1395         if(tot < 0)
1396                 error(Eio);
1397         return tot;
1398 }
1399
1400 /*
1401  * halt condition was cleared on the endpoint. update our toggles.
1402  */
1403 static void
1404 clrhalt(Ep *ep)
1405 {
1406         Qio *io;
1407
1408         ep->clrhalt = 0;
1409         switch(ep->ttype){
1410         case Tbulk:
1411         case Tintr:
1412                 io = ep->aux;
1413                 if(ep->mode != OREAD){
1414                         qlock(&io[OWRITE]);
1415                         io[OWRITE].toggle = Tddata0;
1416                         deprint("ep clrhalt for io %#p\n", io+OWRITE);
1417                         qunlock(&io[OWRITE]);
1418                 }
1419                 if(ep->mode != OWRITE){
1420                         qlock(&io[OREAD]);
1421                         io[OREAD].toggle = Tddata0;
1422                         deprint("ep clrhalt for io %#p\n", io+OREAD);
1423                         qunlock(&io[OREAD]);
1424                 }
1425                 break;
1426         }
1427 }
1428
1429 static long
1430 epread(Ep *ep, void *a, long count)
1431 {
1432         Ctlio *cio;
1433         Qio *io;
1434         Isoio *iso;
1435         char buf[160];
1436         ulong delta;
1437
1438         ddeprint("uhci: epread\n");
1439         if(ep->aux == nil)
1440                 panic("epread: not open");
1441
1442         switch(ep->ttype){
1443         case Tctl:
1444                 cio = ep->aux;
1445                 eqlock(cio);
1446                 if(waserror()){
1447                         qunlock(cio);
1448                         nexterror();
1449                 }
1450                 ddeprint("epread ctl ndata %d\n", cio->ndata);
1451                 if(cio->ndata < 0)
1452                         error("request expected");
1453                 else if(cio->ndata == 0){
1454                         cio->ndata = -1;
1455                         count = 0;
1456                 }else{
1457                         if(count > cio->ndata)
1458                                 count = cio->ndata;
1459                         if(count > 0)
1460                                 memmove(a, cio->data, count);
1461                         /* BUG for big transfers */
1462                         free(cio->data);
1463                         cio->data = nil;
1464                         cio->ndata = 0; /* signal EOF next time */
1465                 }
1466                 qunlock(cio);
1467                 poperror();
1468                 if(debug>1 || ep->debug){
1469                         seprintdata(buf, buf+sizeof(buf), a, count);
1470                         print("epread: %s\n", buf);
1471                 }
1472                 return count;
1473         case Tbulk:
1474                 io = ep->aux;
1475                 if(ep->clrhalt)
1476                         clrhalt(ep);
1477                 return epio(ep, &io[OREAD], a, count, 1);
1478         case Tintr:
1479                 io = ep->aux;
1480                 delta = TK2MS(MACHP(0)->ticks) - io[OREAD].iotime + 1;
1481                 if(delta < ep->pollival / 2)
1482                         tsleep(&up->sleep, return0, 0, ep->pollival/2 - delta);
1483                 if(ep->clrhalt)
1484                         clrhalt(ep);
1485                 return epio(ep, &io[OREAD], a, count, 1);
1486         case Tiso:
1487                 iso = ep->aux;
1488                 return episoread(ep, iso, a, count);
1489         default:
1490                 panic("epread: bad ep ttype %d", ep->ttype);
1491         }
1492         return -1;
1493 }
1494
1495 /*
1496  * Control transfers are one setup write (data0)
1497  * plus zero or more reads/writes (data1, data0, ...)
1498  * plus a final write/read with data1 to ack.
1499  * For both host to device and device to host we perform
1500  * the entire transfer when the user writes the request,
1501  * and keep any data read from the device for a later read.
1502  * We call epio three times instead of placing all Tds at
1503  * the same time because doing so leads to crc/tmout errors
1504  * for some devices.
1505  * Upon errors on the data phase we must still run the status
1506  * phase or the device may cease responding in the future.
1507  */
1508 static long
1509 epctlio(Ep *ep, Ctlio *cio, void *a, long count)
1510 {
1511         uchar *c;
1512         long len;
1513
1514         ddeprint("epctlio: cio %#p ep%d.%d count %ld\n",
1515                 cio, ep->dev->nb, ep->nb, count);
1516         if(count < Rsetuplen)
1517                 error("short usb comand");
1518         eqlock(cio);
1519         free(cio->data);
1520         cio->data = nil;
1521         cio->ndata = 0;
1522         if(waserror()){
1523                 qunlock(cio);
1524                 free(cio->data);
1525                 cio->data = nil;
1526                 cio->ndata = 0;
1527                 nexterror();
1528         }
1529
1530         /* set the address if unset and out of configuration state */
1531         if(ep->dev->state != Dconfig && ep->dev->state != Dreset)
1532                 if(cio->usbid == 0)
1533                         cio->usbid = ((ep->nb&Epmax)<<7)|(ep->dev->nb&Devmax);
1534         c = a;
1535         cio->tok = Tdtoksetup;
1536         cio->toggle = Tddata0;
1537         if(epio(ep, cio, a, Rsetuplen, 0) < Rsetuplen)
1538                 error(Eio);
1539         a = c + Rsetuplen;
1540         count -= Rsetuplen;
1541
1542         cio->toggle = Tddata1;
1543         if(c[Rtype] & Rd2h){
1544                 cio->tok = Tdtokin;
1545                 len = GET2(c+Rcount);
1546                 if(len <= 0)
1547                         error("bad length in d2h request");
1548                 if(len > Maxctllen)
1549                         error("d2h data too large to fit in uhci");
1550                 a = cio->data = smalloc(len+1);
1551         }else{
1552                 cio->tok = Tdtokout;
1553                 len = count;
1554         }
1555         if(len > 0)
1556                 if(waserror())
1557                         len = -1;
1558                 else{
1559                         len = epio(ep, cio, a, len, 0);
1560                         poperror();
1561                 }
1562         if(c[Rtype] & Rd2h){
1563                 count = Rsetuplen;
1564                 cio->ndata = len;
1565                 cio->tok = Tdtokout;
1566         }else{
1567                 if(len < 0)
1568                         count = -1;
1569                 else
1570                         count = Rsetuplen + len;
1571                 cio->tok = Tdtokin;
1572         }
1573         cio->toggle = Tddata1;
1574         epio(ep, cio, nil, 0, 0);
1575         qunlock(cio);
1576         poperror();
1577         ddeprint("epctlio cio %#p return %ld\n", cio, count);
1578         return count;
1579 }
1580
1581 static long
1582 epwrite(Ep *ep, void *a, long count)
1583 {
1584         Ctlio *cio;
1585         Isoio *iso;
1586         Qio *io;
1587         ulong delta;
1588         char *b;
1589         int tot;
1590         int nw;
1591
1592         ddeprint("uhci: epwrite ep%d.%d\n", ep->dev->nb, ep->nb);
1593         if(ep->aux == nil)
1594                 panic("uhci: epwrite: not open");
1595         switch(ep->ttype){
1596         case Tctl:
1597                 cio = ep->aux;
1598                 return epctlio(ep, cio, a, count);
1599         case Tbulk:
1600                 io = ep->aux;
1601                 if(ep->clrhalt)
1602                         clrhalt(ep);
1603                 /*
1604                  * Put at most Tdatomic Tds (512 bytes) at a time.
1605                  * Otherwise some devices produce babble errors.
1606                  */
1607                 b = a;
1608                 for(tot = 0; tot < count ; tot += nw){
1609                         nw = count - tot;
1610                         if(nw > Tdatomic * ep->maxpkt)
1611                                 nw = Tdatomic * ep->maxpkt;
1612                         nw = epio(ep, &io[OWRITE], b+tot, nw, 1);
1613                 }
1614                 return tot;
1615         case Tintr:
1616                 io = ep->aux;
1617                 delta = TK2MS(MACHP(0)->ticks) - io[OWRITE].iotime + 1;
1618                 if(delta < ep->pollival)
1619                         tsleep(&up->sleep, return0, 0, ep->pollival - delta);
1620                 if(ep->clrhalt)
1621                         clrhalt(ep);
1622                 return epio(ep, &io[OWRITE], a, count, 1);
1623         case Tiso:
1624                 iso = ep->aux;
1625                 return episowrite(ep, iso, a, count);
1626         default:
1627                 panic("uhci: epwrite: bad ep ttype %d", ep->ttype);
1628         }
1629         return -1;
1630 }
1631
1632 static void
1633 isoopen(Ep *ep)
1634 {
1635         Ctlr *ctlr;
1636         Isoio *iso;
1637         int frno;
1638         int i;
1639         Td* td;
1640         Td* ltd;
1641         int size;
1642         int left;
1643
1644         if(ep->mode == ORDWR)
1645                 error("iso i/o is half-duplex");
1646         ctlr = ep->hp->aux;
1647         iso = ep->aux;
1648         iso->debug = ep->debug;
1649         iso->next = nil;                        /* paranoia */
1650         if(ep->mode == OREAD)
1651                 iso->tok = Tdtokin;
1652         else
1653                 iso->tok = Tdtokout;
1654         iso->usbid = ((ep->nb & Epmax)<<7)|(ep->dev->nb & Devmax);
1655         iso->state = Qidle;
1656         iso->nframes = Nframes/ep->pollival;
1657         if(iso->nframes < 3)
1658                 error("uhci isoopen bug");      /* we need at least 3 tds */
1659
1660         ilock(ctlr);
1661         if(ctlr->load + ep->load > 800)
1662                 print("usb: uhci: bandwidth may be exceeded\n");
1663         ctlr->load += ep->load;
1664         ctlr->isoload += ep->load;
1665         dprint("uhci: load %uld isoload %uld\n", ctlr->load, ctlr->isoload);
1666         iunlock(ctlr);
1667
1668         /*
1669          * From here on this cannot raise errors
1670          * unless we catch them and release here all memory allocated.
1671          */
1672         if(ep->maxpkt > Tdndata)
1673                 iso->data = smalloc(iso->nframes*ep->maxpkt);
1674         ilock(ctlr);
1675         frno = INS(Frnum) + 10;                 /* start 10ms ahead */
1676         frno = TRUNC(frno, Nframes);
1677         iunlock(ctlr);
1678         iso->td0frno = frno;
1679         ltd = nil;
1680         left = 0;
1681         for(i = 0; i < iso->nframes; i++){
1682                 td = iso->tdps[frno] = tdalloc();
1683                 if(ep->mode == OREAD)
1684                         size = ep->maxpkt;
1685                 else{
1686                         size = (ep->hz+left) * ep->pollival / 1000;
1687                         size *= ep->samplesz;
1688                         left = (ep->hz+left) * ep->pollival % 1000;
1689                         if(size > ep->maxpkt){
1690                                 print("uhci: ep%d.%d: size > maxpkt\n",
1691                                         ep->dev->nb, ep->nb);
1692                                 print("size = %d max = %ld\n", size, ep->maxpkt);
1693                                 size = ep->maxpkt;
1694                         }
1695                 }
1696                 if(size > Tdndata)
1697                         td->data = iso->data + i * ep->maxpkt;
1698                 else
1699                         td->data = td->sbuff;
1700                 td->buffer = PCIWADDR(td->data);
1701                 tdisoinit(iso, td, size);
1702                 if(ltd != nil)
1703                         ltd->next = td;
1704                 ltd = td;
1705                 frno = TRUNC(frno+ep->pollival, Nframes);
1706         }
1707         ltd->next = iso->tdps[iso->td0frno];
1708         iso->tdi = iso->tdps[iso->td0frno];
1709         iso->tdu = iso->tdi;
1710         ilock(ctlr);
1711         frno = iso->td0frno;
1712         for(i = 0; i < iso->nframes; i++){
1713                 iso->tdps[frno]->link = ctlr->frames[frno];
1714                 frno = TRUNC(frno+ep->pollival, Nframes);
1715         }
1716         coherence();
1717         frno = iso->td0frno;
1718         for(i = 0; i < iso->nframes; i++){
1719                 ctlr->frames[frno] = PCIWADDR(iso->tdps[frno]);
1720                 frno = TRUNC(frno+ep->pollival, Nframes);
1721         }
1722         iso->next = ctlr->iso;
1723         ctlr->iso = iso;
1724         iso->state = Qdone;
1725         iunlock(ctlr);
1726         if(debug > 1 || iso->debug >1)
1727                 isodump(iso, 0);
1728 }
1729
1730 /*
1731  * Allocate the endpoint and set it up for I/O
1732  * in the controller. This must follow what's said
1733  * in Ep regarding configuration, including perhaps
1734  * the saved toggles (saved on a previous close of
1735  * the endpoint data file by epclose).
1736  */
1737 static void
1738 epopen(Ep *ep)
1739 {
1740         Ctlr *ctlr;
1741         Qh *cqh;
1742         Qio *io;
1743         Ctlio *cio;
1744         int usbid;
1745
1746         ctlr = ep->hp->aux;
1747         deprint("uhci: epopen ep%d.%d\n", ep->dev->nb, ep->nb);
1748         if(ep->aux != nil)
1749                 panic("uhci: epopen called with open ep");
1750         if(waserror()){
1751                 free(ep->aux);
1752                 ep->aux = nil;
1753                 nexterror();
1754         }
1755         if(ep->maxpkt > Tdmaxpkt){
1756                 print("uhci: maxkpkt too large: using %d\n", Tdmaxpkt);
1757                 ep->maxpkt = Tdmaxpkt;
1758         }
1759         cqh = ctlr->qh[ep->ttype];
1760         switch(ep->ttype){
1761         case Tnone:
1762                 error("endpoint not configured");
1763         case Tiso:
1764                 ep->aux = smalloc(sizeof(Isoio));
1765                 isoopen(ep);
1766                 break;
1767         case Tctl:
1768                 cio = ep->aux = smalloc(sizeof(Ctlio));
1769                 cio->debug = ep->debug;
1770                 cio->ndata = -1;
1771                 cio->data = nil;
1772                 if(ep->dev->isroot != 0 && ep->nb == 0) /* root hub */
1773                         break;
1774                 cio->qh = qhalloc(ctlr, cqh, cio, "epc");
1775                 break;
1776         case Tbulk:
1777         case Tintr:
1778                 io = ep->aux = smalloc(sizeof(Qio)*2);
1779                 io[OREAD].debug = io[OWRITE].debug = ep->debug;
1780                 usbid = ((ep->nb&Epmax)<<7)|(ep->dev->nb &Devmax);
1781                 if(ep->mode != OREAD){
1782                         if(ep->toggle[OWRITE] != 0)
1783                                 io[OWRITE].toggle = Tddata1;
1784                         else
1785                                 io[OWRITE].toggle = Tddata0;
1786                         io[OWRITE].tok = Tdtokout;
1787                         io[OWRITE].qh = qhalloc(ctlr, cqh, io+OWRITE, "epw");
1788                         io[OWRITE].usbid = usbid;
1789                 }
1790                 if(ep->mode != OWRITE){
1791                         if(ep->toggle[OREAD] != 0)
1792                                 io[OREAD].toggle = Tddata1;
1793                         else
1794                                 io[OREAD].toggle = Tddata0;
1795                         io[OREAD].tok = Tdtokin;
1796                         io[OREAD].qh = qhalloc(ctlr, cqh, io+OREAD, "epr");
1797                         io[OREAD].usbid = usbid;
1798                 }
1799                 break;
1800         }
1801         if(debug>1 || ep->debug)
1802                 dump(ep->hp);
1803         deprint("uhci: epopen done\n");
1804         poperror();
1805 }
1806
1807 static void
1808 cancelio(Ctlr *ctlr, Qio *io)
1809 {
1810         Qh *qh;
1811
1812         ilock(ctlr);
1813         qh = io->qh;
1814         if(io == nil || io->qh == nil || io->qh->state == Qclose){
1815                 iunlock(ctlr);
1816                 return;
1817         }
1818         dqprint("uhci: cancelio for qh %#p state %s\n",
1819                 qh, qhsname[qh->state]);
1820         aborttds(qh);
1821         qh->state = Qclose;
1822         iunlock(ctlr);
1823         if(!waserror()){
1824                 tsleep(&up->sleep, return0, 0, Abortdelay);
1825                 poperror();
1826         }
1827
1828         wakeup(io);
1829         qlock(io);
1830         /* wait for epio if running */
1831         qunlock(io);
1832
1833         qhfree(ctlr, qh);
1834         io->qh = nil;
1835 }
1836
1837 static void
1838 cancelisoio(Ctlr *ctlr, Isoio *iso, int pollival, ulong load)
1839 {
1840         Isoio **il;
1841         ulong *lp;
1842         int i;
1843         int frno;
1844         Td *td;
1845
1846         ilock(ctlr);
1847         if(iso->state == Qclose){
1848                 iunlock(ctlr);
1849                 return;
1850         }
1851         if(iso->state != Qrun && iso->state != Qdone)
1852                 panic("bad iso state");
1853         iso->state = Qclose;
1854         if(ctlr->isoload < load)
1855                 panic("uhci: low isoload");
1856         ctlr->isoload -= load;
1857         ctlr->load -= load;
1858         for(il = &ctlr->iso; *il != nil; il = &(*il)->next)
1859                 if(*il == iso)
1860                         break;
1861         if(*il == nil)
1862                 panic("isocancel: not found");
1863         *il = iso->next;
1864         frno = iso->td0frno;
1865         for(i = 0; i < iso->nframes; i++){
1866                 td = iso->tdps[frno];
1867                 td->csw &= ~(Tdioc|Tdactive);
1868                 for(lp=&ctlr->frames[frno]; !(*lp & Tdterm);
1869                                         lp = &TPTR(*lp)->link)
1870                         if(TPTR(*lp) == td)
1871                                 break;
1872                 if(*lp & Tdterm)
1873                         panic("cancelisoio: td not found");
1874                 *lp = td->link;
1875                 frno = TRUNC(frno+pollival, Nframes);
1876         }
1877         iunlock(ctlr);
1878
1879         /*
1880          * wakeup anyone waiting for I/O and
1881          * wait to be sure no I/O is in progress in the controller.
1882          * and then wait to be sure episo-io is no longer running.
1883          */
1884         wakeup(iso);
1885         diprint("cancelisoio iso %#p waiting for I/O to cease\n", iso);
1886         tsleep(&up->sleep, return0, 0, 5);
1887         qlock(iso);
1888         qunlock(iso);
1889         diprint("cancelisoio iso %#p releasing iso\n", iso);
1890
1891         frno = iso->td0frno;
1892         for(i = 0; i < iso->nframes; i++){
1893                 tdfree(iso->tdps[frno]);
1894                 iso->tdps[frno] = nil;
1895                 frno = TRUNC(frno+pollival, Nframes);
1896         }
1897         free(iso->data);
1898         iso->data = nil;
1899 }
1900
1901 static void
1902 epclose(Ep *ep)
1903 {
1904         Ctlr *ctlr;
1905         Ctlio *cio;
1906         Isoio *iso;
1907         Qio *io;
1908
1909         ctlr = ep->hp->aux;
1910         deprint("uhci: epclose ep%d.%d\n", ep->dev->nb, ep->nb);
1911
1912         if(ep->aux == nil)
1913                 panic("uhci: epclose called with closed ep");
1914         switch(ep->ttype){
1915         case Tctl:
1916                 cio = ep->aux;
1917                 cancelio(ctlr, cio);
1918                 free(cio->data);
1919                 cio->data = nil;
1920                 break;
1921         case Tbulk:
1922         case Tintr:
1923                 io = ep->aux;
1924                 ep->toggle[OREAD] = ep->toggle[OWRITE] = 0;
1925                 if(ep->mode != OWRITE){
1926                         cancelio(ctlr, &io[OREAD]);
1927                         if(io[OREAD].toggle == Tddata1)
1928                                 ep->toggle[OREAD] = 1;
1929                 }
1930                 if(ep->mode != OREAD){
1931                         cancelio(ctlr, &io[OWRITE]);
1932                         if(io[OWRITE].toggle == Tddata1)
1933                                 ep->toggle[OWRITE] = 1;
1934                 }
1935                 break;
1936         case Tiso:
1937                 iso = ep->aux;
1938                 cancelisoio(ctlr, iso, ep->pollival, ep->load);
1939                 break;
1940         default:
1941                 panic("epclose: bad ttype %d", ep->ttype);
1942         }
1943
1944         free(ep->aux);
1945         ep->aux = nil;
1946
1947 }
1948
1949 static char*
1950 seprintep(char *s, char *e, Ep *ep)
1951 {
1952         Ctlio *cio;
1953         Qio *io;
1954         Isoio *iso;
1955         Ctlr *ctlr;
1956
1957         ctlr = ep->hp->aux;
1958         ilock(ctlr);
1959         if(ep->aux == nil){
1960                 *s = 0;
1961                 iunlock(ctlr);
1962                 return s;
1963         }
1964         switch(ep->ttype){
1965         case Tctl:
1966                 cio = ep->aux;
1967                 s = seprint(s,e,"cio %#p qh %#p"
1968                         " id %#x tog %#x tok %#x err %s\n",
1969                         cio, cio->qh, cio->usbid, cio->toggle,
1970                         cio->tok, cio->err);
1971                 break;
1972         case Tbulk:
1973         case Tintr:
1974                 io = ep->aux;
1975                 if(ep->mode != OWRITE)
1976                         s = seprint(s,e,"r: qh %#p id %#x tog %#x tok %#x err %s\n",
1977                                 io[OREAD].qh, io[OREAD].usbid, io[OREAD].toggle,
1978                                 io[OREAD].tok, io[OREAD].err);
1979                 if(ep->mode != OREAD)
1980                         s = seprint(s,e,"w: qh %#p id %#x tog %#x tok %#x err %s\n",
1981                                 io[OWRITE].qh, io[OWRITE].usbid, io[OWRITE].toggle,
1982                                 io[OWRITE].tok, io[OWRITE].err);
1983                 break;
1984         case Tiso:
1985                 iso = ep->aux;
1986                 s = seprint(s,e,"iso %#p id %#x tok %#x tdu %#p tdi %#p err %s\n",
1987                         iso, iso->usbid, iso->tok, iso->tdu, iso->tdi, iso->err);
1988                 break;
1989         }
1990         iunlock(ctlr);
1991         return s;
1992 }
1993
1994 static int
1995 portenable(Hci *hp, int port, int on)
1996 {
1997         int s;
1998         int ioport;
1999         Ctlr *ctlr;
2000
2001         ctlr = hp->aux;
2002         dprint("uhci: %#x port %d enable=%d\n", ctlr->port, port, on);
2003         ioport = PORT(port-1);
2004         eqlock(&ctlr->portlck);
2005         if(waserror()){
2006                 qunlock(&ctlr->portlck);
2007                 nexterror();
2008         }
2009         ilock(ctlr);
2010         s = INS(ioport);
2011         if(on)
2012                 OUTS(ioport, s | PSenable);
2013         else
2014                 OUTS(ioport, s & ~PSenable);
2015         microdelay(64);
2016         iunlock(ctlr);
2017         tsleep(&up->sleep, return0, 0, Enabledelay);
2018         dprint("uhci %#ux port %d enable=%d: sts %#x\n",
2019                 ctlr->port, port, on, INS(ioport));
2020         qunlock(&ctlr->portlck);
2021         poperror();
2022         return 0;
2023 }
2024
2025 static int
2026 portreset(Hci *hp, int port, int on)
2027 {
2028         int i, p;
2029         Ctlr *ctlr;
2030
2031         if(on == 0)
2032                 return 0;
2033         ctlr = hp->aux;
2034         dprint("uhci: %#ux port %d reset\n", ctlr->port, port);
2035         p = PORT(port-1);
2036         ilock(ctlr);
2037         OUTS(p, PSreset);
2038         delay(50);
2039         OUTS(p, INS(p) & ~PSreset);
2040         OUTS(p, INS(p) | PSenable);
2041         microdelay(64);
2042         for(i=0; i<1000 && (INS(p) & PSenable) == 0; i++)
2043                 ;
2044         OUTS(p, (INS(p) & ~PSreset)|PSenable);
2045         iunlock(ctlr);
2046         dprint("uhci %#ux after port %d reset: sts %#x\n",
2047                 ctlr->port, port, INS(p));
2048         return 0;
2049 }
2050
2051 static int
2052 portstatus(Hci *hp, int port)
2053 {
2054         int s;
2055         int r;
2056         int ioport;
2057         Ctlr *ctlr;
2058
2059         ctlr = hp->aux;
2060         ioport = PORT(port-1);
2061         eqlock(&ctlr->portlck);
2062         if(waserror()){
2063                 iunlock(ctlr);
2064                 qunlock(&ctlr->portlck);
2065                 nexterror();
2066         }
2067         ilock(ctlr);
2068         s = INS(ioport);
2069         if(s & (PSstatuschg | PSchange)){
2070                 OUTS(ioport, s);
2071                 ddprint("uhci %#ux port %d status %#x\n", ctlr->port, port, s);
2072         }
2073         iunlock(ctlr);
2074         qunlock(&ctlr->portlck);
2075         poperror();
2076
2077         /*
2078          * We must return status bits as a
2079          * get port status hub request would do.
2080          */
2081         r = 0;
2082         if(s & PSpresent)
2083                 r |= HPpresent;
2084         if(s & PSenable)
2085                 r |= HPenable;
2086         if(s & PSsuspend)
2087                 r |= HPsuspend;
2088         if(s & PSreset)
2089                 r |= HPreset;
2090         if(s & PSslow)
2091                 r |= HPslow;
2092         if(s & PSstatuschg)
2093                 r |= HPstatuschg;
2094         if(s & PSchange)
2095                 r |= HPchange;
2096         return r;
2097 }
2098
2099 static void
2100 scanpci(void)
2101 {
2102         static int already = 0;
2103         int io;
2104         int i;
2105         Ctlr *ctlr;
2106         Pcidev *p;
2107
2108         if(already)
2109                 return;
2110         already = 1;
2111         p = nil;
2112         while(p = pcimatch(p, 0, 0)){
2113                 /*
2114                  * Find UHCI controllers (Programming Interface = 0).
2115                  */
2116                 if(p->ccrb != Pcibcserial || p->ccru != Pciscusb)
2117                         continue;
2118                 switch(p->ccrp){
2119                 case 0:
2120                         io = p->mem[4].bar & ~0x0F;
2121                         break;
2122                 default:
2123                         continue;
2124                 }
2125                 if(io == 0){
2126                         print("usbuhci: %#x %#x: failed to map registers\n",
2127                                 p->vid, p->did);
2128                         continue;
2129                 }
2130                 if(ioalloc(io, p->mem[4].size, 0, "usbuhci") < 0){
2131                         print("usbuhci: port %#ux in use\n", io);
2132                         continue;
2133                 }
2134                 if(p->intl == 0xFF || p->intl == 0){
2135                         print("usbuhci: no irq assigned for port %#ux\n", io);
2136                         continue;
2137                 }
2138
2139                 dprint("uhci: %#x %#x: port %#ux size %#x irq %d\n",
2140                         p->vid, p->did, io, p->mem[4].size, p->intl);
2141
2142                 ctlr = smalloc(sizeof(Ctlr));
2143                 ctlr->pcidev = p;
2144                 ctlr->port = io;
2145                 for(i = 0; i < Nhcis; i++)
2146                         if(ctlrs[i] == nil){
2147                                 ctlrs[i] = ctlr;
2148                                 break;
2149                         }
2150                 if(i == Nhcis)
2151                         print("uhci: bug: no more controllers\n");
2152         }
2153 }
2154
2155 static void
2156 uhcimeminit(Ctlr *ctlr)
2157 {
2158         Td* td;
2159         Qh *qh;
2160         int frsize;
2161         int i;
2162
2163         ctlr->qhs = ctlr->qh[Tctl] = qhalloc(ctlr, nil, nil, "CTL");
2164         ctlr->qh[Tintr] = qhalloc(ctlr, ctlr->qh[Tctl], nil, "INT");
2165         ctlr->qh[Tbulk] = qhalloc(ctlr, ctlr->qh[Tintr], nil, "BLK");
2166
2167         /* idle Td from dummy Qh at the end. looped back to itself */
2168         /* This is a workaround for PIIX4 errata 29773804.pdf */
2169         qh = qhalloc(ctlr, ctlr->qh[Tbulk], nil, "BWS");
2170         td = tdalloc();
2171         td->link = PCIWADDR(td);
2172         qhlinktd(qh, td);
2173
2174         /* loop (hw only) from the last qh back to control xfers.
2175          * this may be done only for some of them. Disable until ehci comes.
2176          */
2177         if(0)
2178         qh->link = PCIWADDR(ctlr->qhs);
2179
2180         frsize = Nframes*sizeof(ulong);
2181         ctlr->frames = xspanalloc(frsize, frsize, 0);
2182         if(ctlr->frames == nil)
2183                 panic("uhci reset: no memory");
2184
2185         ctlr->iso = nil;
2186         for(i = 0; i < Nframes; i++)
2187                 ctlr->frames[i] = PCIWADDR(ctlr->qhs)|QHlinkqh;
2188         OUTL(Flbaseadd, PCIWADDR(ctlr->frames));
2189         OUTS(Frnum, 0);
2190         dprint("uhci %#ux flb %#ulx frno %#ux\n", ctlr->port,
2191                 INL(Flbaseadd), INS(Frnum));
2192 }
2193
2194 static void
2195 init(Hci *hp)
2196 {
2197         Ctlr *ctlr;
2198         int sts;
2199         int i;
2200
2201         ctlr = hp->aux;
2202         dprint("uhci %#ux init\n", ctlr->port);
2203         coherence();
2204         ilock(ctlr);
2205         OUTS(Usbintr, Itmout|Iresume|Ioc|Ishort);
2206         uhcirun(ctlr, 1);
2207         dprint("uhci: init: cmd %#ux sts %#ux sof %#ux",
2208                 INS(Cmd), INS(Status), INS(SOFmod));
2209         dprint(" flb %#ulx frno %#ux psc0 %#ux psc1 %#ux",
2210                 INL(Flbaseadd), INS(Frnum), INS(PORT(0)), INS(PORT(1)));
2211         /* guess other ports */
2212         for(i = 2; i < 6; i++){
2213                 sts = INS(PORT(i));
2214                 if(sts != 0xFFFF && (sts & PSreserved1) == 1){
2215                         dprint(" psc%d %#ux", i, sts);
2216                         hp->nports++;
2217                 }else
2218                         break;
2219         }
2220         for(i = 0; i < hp->nports; i++)
2221                 OUTS(PORT(i), 0);
2222         iunlock(ctlr);
2223 }
2224
2225 static void
2226 uhcireset(Ctlr *ctlr)
2227 {
2228         int i;
2229         int sof;
2230
2231         ilock(ctlr);
2232         dprint("uhci %#ux reset\n", ctlr->port);
2233
2234         /*
2235          * Turn off legacy mode. Some controllers won't
2236          * interrupt us as expected otherwise.
2237          */
2238         uhcirun(ctlr, 0);
2239         pcicfgw16(ctlr->pcidev, 0xc0, 0x2000);
2240
2241         OUTS(Usbintr, 0);
2242         sof = INB(SOFmod);
2243         uhcicmd(ctlr, Cgreset);                 /* global reset */
2244         delay(Resetdelay);
2245         uhcicmd(ctlr, 0);                       /* all halt */
2246         uhcicmd(ctlr, Chcreset);                        /* controller reset */
2247         for(i = 0; i < 100; i++){
2248                 if((INS(Cmd) & Chcreset) == 0)
2249                         break;
2250                 delay(1);
2251         }
2252         if(i == 100)
2253                 print("uhci %#x controller reset timed out\n", ctlr->port);
2254         OUTB(SOFmod, sof);
2255         iunlock(ctlr);
2256 }
2257
2258 static void
2259 setdebug(Hci*, int d)
2260 {
2261         debug = d;
2262 }
2263
2264 static void
2265 shutdown(Hci *hp)
2266 {
2267         Ctlr *ctlr;
2268
2269         ctlr = hp->aux;
2270
2271         ilock(ctlr);
2272         uhcirun(ctlr, 0);
2273         delay(100);
2274         iunlock(ctlr);
2275 }
2276
2277 static int
2278 reset(Hci *hp)
2279 {
2280         static Lock resetlck;
2281         int i;
2282         Ctlr *ctlr;
2283         Pcidev *p;
2284
2285         if(getconf("*nousbuhci"))
2286                 return -1;
2287
2288         ilock(&resetlck);
2289         scanpci();
2290
2291         /*
2292          * Any adapter matches if no hp->port is supplied,
2293          * otherwise the ports must match.
2294          */
2295         ctlr = nil;
2296         for(i = 0; i < Nhcis && ctlrs[i] != nil; i++){
2297                 ctlr = ctlrs[i];
2298                 if(ctlr->active == 0)
2299                 if(hp->port == 0 || hp->port == ctlr->port){
2300                         ctlr->active = 1;
2301                         break;
2302                 }
2303         }
2304         iunlock(&resetlck);
2305         if(ctlrs[i] == nil || i == Nhcis)
2306                 return -1;
2307
2308         p = ctlr->pcidev;
2309         hp->aux = ctlr;
2310         hp->port = ctlr->port;
2311         hp->irq = p->intl;
2312         hp->tbdf = p->tbdf;
2313         hp->nports = 2;                 /* default */
2314
2315         uhcireset(ctlr);
2316         uhcimeminit(ctlr);
2317
2318         /*
2319          * Linkage to the generic HCI driver.
2320          */
2321         hp->init = init;
2322         hp->dump = dump;
2323         hp->interrupt = interrupt;
2324         hp->epopen = epopen;
2325         hp->epclose = epclose;
2326         hp->epread = epread;
2327         hp->epwrite = epwrite;
2328         hp->seprintep = seprintep;
2329         hp->portenable = portenable;
2330         hp->portreset = portreset;
2331         hp->portstatus = portstatus;
2332         hp->shutdown = shutdown;
2333         hp->debug = setdebug;
2334         hp->type = "uhci";
2335         return 0;
2336 }
2337
2338 void
2339 usbuhcilink(void)
2340 {
2341         addhcitype("uhci", reset);
2342 }