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