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