]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/pc/usbohci.c
usbohci, usbuhci, usbehci: use physical address of registers for matching controllers...
[plan9front.git] / sys / src / 9 / pc / usbohci.c
1 /*
2  * USB Open Host Controller Interface (Ohci) driver
3  *
4  * BUGS:
5  * - Missing isochronous input streams.
6  * - Too many delays and ilocks.
7  * - bandwidth admission control must be done per-frame.
8  * - Buffering could be handled like in uhci, to avoid
9  * needed block allocation and avoid allocs for small Tds.
10  * - must warn of power overruns.
11  */
12
13 #include        "u.h"
14 #include        "../port/lib.h"
15 #include        "mem.h"
16 #include        "dat.h"
17 #include        "fns.h"
18 #include        "io.h"
19 #include        "../port/error.h"
20
21 #include        "../port/usb.h"
22
23 typedef struct Ctlio Ctlio;
24 typedef struct Ctlr Ctlr;
25 typedef struct Ed Ed;
26 typedef struct Edpool Edpool;
27 typedef struct Epx Epx;
28 typedef struct Hcca Hcca;
29 typedef struct Isoio Isoio;
30 typedef struct Ohci Ohci;
31 typedef struct Qio Qio;
32 typedef struct Qtree Qtree;
33 typedef struct Td Td;
34 typedef struct Tdpool Tdpool;
35
36 enum
37 {
38         Incr            = 64,           /* for Td and Ed pools */
39
40         Edalign         = 0x10,
41         Tdalign         = 0x20, 
42
43         Abortdelay      = 1,            /* delay after cancelling Tds (ms) */
44         Tdatomic                = 8,            /* max nb. of Tds per bulk I/O op. */
45         Enabledelay     = 100,          /* waiting for a port to enable */
46
47
48         /* Queue states (software) */
49         Qidle           = 0,
50         Qinstall,
51         Qrun,
52         Qdone,
53         Qclose,
54         Qfree,
55
56         /* Ed control bits */
57         Edmpsmask       = 0x7ff,        /* max packet size */
58         Edmpsshift      = 16,
59         Edlow           = 1 << 13,      /* low speed */
60         Edskip          = 1 << 14,      /* skip this ed */
61         Ediso           = 1 << 15,      /* iso Tds used */
62         Edtddir         = 0,            /* get dir from td */
63         Edin            = 2 << 11,      /* direction in */
64         Edout           = 1 << 11,      /* direction out */
65         Eddirmask       = 3 << 11,      /* direction bits */
66         Edhalt          = 1,            /* halted (in head ptr) */
67         Edtoggle        = 2,            /* toggle (in head ptr) 1 == data1 */
68
69         /* Td control bits */
70         Tdround         = 1<<18,        /* (rounding) short packets ok */
71         Tdtoksetup      = 0<<19,        /* setup packet */
72         Tdtokin         = 2<<19,        /* in packet */
73         Tdtokout        = 1<<19,        /* out packet */
74         Tdtokmask       = 3<<19,        /* in/out/setup bits */
75         Tdnoioc         = 7<<21,        /* intr. cnt. value for no interrupt */
76         Tdusetog        = 1<<25,        /* use toggle from Td (1) or Ed (0) */
77         Tddata1         = 1<<24,        /* data toggle (1 == data1) */
78         Tddata0         = 0<<24,
79         Tdfcmask        = 7,            /* frame count (iso) */
80         Tdfcshift       = 24,
81         Tdsfmask        = 0xFFFF,       /* starting frame (iso) */
82         Tderrmask       = 3,            /* error counter */
83         Tderrshift      = 26,
84         Tdccmask        = 0xf,          /* condition code (status) */
85         Tdccshift       = 28,
86         Tdiccmask       = 0xf,          /* condition code (iso, offsets) */
87         Tdiccshift      = 12,
88
89         Ntdframes       = 0x10000,      /* # of different iso frame numbers */
90
91         /* Td errors (condition code) */
92         Tdok            = 0,
93         Tdcrc           = 1,
94         Tdbitstuff      = 2,
95         Tdbadtog        = 3,
96         Tdstalled       = 4,
97         Tdtmout         = 5,
98         Tdpidchk        = 6,
99         Tdbadpid        = 7,
100         Tddataovr       = 8,
101         Tddataund       = 9,
102         Tdbufovr        = 0xC,
103         Tdbufund        = 0xD,
104         Tdnotacc        = 0xE,
105
106         /* control register */
107         Cple            = 0x04,         /* periodic list enable */
108         Cie             = 0x08,         /* iso. list enable */
109         Ccle            = 0x10,         /* ctl list enable */
110         Cble            = 0x20,         /* bulk list enable */
111         Cir             = 0x100,        /* interrupt routing (smm active) */
112         Cfsmask         = 3 << 6,       /* functional state... */
113         Cfsreset        = 0 << 6,
114         Cfsresume       = 1 << 6,
115         Cfsoper         = 2 << 6,
116         Cfssuspend      = 3 << 6,
117
118         /* command status */
119         Socr =  1 << 3,                 /* ownership change request */
120         Sblf =  1 << 2,                 /* bulk list (load) flag */
121         Sclf =  1 << 1,                 /* control list (load) flag */
122         Shcr =  1 << 0,                 /* host controller reset */
123
124         /* intr enable */
125         Mie =   1 << 31,
126         Oc =    1 << 30,
127         Rhsc =  1 << 6,
128         Fno =   1 << 5,
129         Ue =    1 << 4,
130         Rd =    1 << 3,
131         Sf =    1 << 2,
132         Wdh =   1 << 1,
133         So =    1 << 0,
134
135         Fmaxpktmask = 0x7fff,
136         Fmaxpktshift = 16,
137         HcRhDescA_POTPGT_MASK = 0xff << 24,
138         HcRhDescA_POTPGT_SHIFT =        24,
139
140         /* Rh status */
141         Lps =   1 << 0,
142         Cgp =   1 << 0,
143         Oci =   1 << 1,
144         Psm =   1 << 8,
145         Nps =   1 << 9,
146         Drwe =  1 << 15,
147         Srwe =  1 << 15,
148         Lpsc =  1 << 16,
149         Ccic =  1 << 17,
150         Crwe =  1 << 31,
151
152         /* port status */
153         Ccs =   0x00001,        /* current connect status */
154         Pes =   0x00002,        /* port enable status */
155         Pss =   0x00004,        /* port suspend status */
156         Poci =  0x00008,        /* over current indicator */
157         Prs =   0x00010,        /* port reset status */
158         Pps =   0x00100,        /* port power status */
159         Lsda =  0x00200,        /* low speed device attached */
160         Csc =   0x10000,        /* connect status change */
161         Pesc =  0x20000,        /* enable status change */
162         Pssc =  0x40000,        /* suspend status change */
163         Ocic =  0x80000,        /* over current ind. change */
164         Prsc =  0x100000,       /* reset status change */
165
166         /* port status write bits */
167         Cpe =   0x001,          /* clear port enable */
168         Spe =   0x002,          /* set port enable */
169         Spr =   0x010,          /* set port reset */
170         Spp =   0x100,          /* set port power */
171         Cpp =   0x200,          /* clear port power */
172
173 };
174
175 /*
176  * Endpoint descriptor. (first 4 words used by hardware)
177  */
178 struct Ed {
179         ulong   ctrl;
180         ulong   tail;           /* transfer descriptor */
181         ulong   head;
182         ulong   nexted;
183
184         Ed*     next;           /* sw; in free list or next in list */
185         Td*     tds;            /* in use by current xfer; all for iso */
186         Ep*     ep;             /* debug/align */
187         Ed*     inext;          /* debug/align (dump interrupt eds). */
188 };
189
190 /*
191  * Endpoint I/O state (software), per direction.
192  */
193 struct Qio
194 {
195         QLock;                  /* for the entire I/O process */
196         Rendez;                 /* wait for completion */
197         Ed*     ed;             /* to place Tds on it */
198         int     sched;          /* queue number (intr/iso) */
199         int     toggle;         /* Tddata0/Tddata1 */
200         ulong   usbid;          /* device/endpoint address */
201         int     tok;            /* Tdsetup, Tdtokin, Tdtokout */
202         long    iotime;         /* last I/O time; to hold interrupt polls */
203         int     debug;          /* for the endpoint */
204         char*   err;            /* error status */
205         int     state;          /* Qidle -> Qinstall -> Qrun -> Qdone | Qclose */
206         long    bw;             /* load (intr/iso) */
207 };
208
209 struct Ctlio
210 {
211         Qio;                    /* single Ed for all transfers */
212         uchar*  data;           /* read from last ctl req. */
213         int     ndata;          /* number of bytes read */
214 };
215
216 struct Isoio
217 {
218         Qio;
219         int     nframes;        /* number of frames for a full second */
220         Td*     atds;           /* Tds avail for further I/O */
221         int     navail;         /* number of avail Tds */
222         ulong   frno;           /* next frame number avail for I/O */
223         ulong   left;           /* remainder after rounding Hz to samples/ms */
224         int     nerrs;          /* consecutive errors on iso I/O */
225         int     delay;          /* maximum number of frames to buffer */
226 };
227
228 /*
229  * Transfer descriptor. Size must be multiple of 32
230  * First block is used by hardware (aligned to 32).
231  */
232 struct Td
233 {
234         ulong   ctrl;
235         ulong   cbp;            /* current buffer pointer */
236         ulong   nexttd;
237         ulong   be;
238         ushort  offsets[8];     /* used by Iso Tds only */
239
240         Td*     next;           /* in free or Ed tds list */
241         Td*     anext;          /* in avail td list (iso) */
242         Ep*     ep;             /* using this Td for I/O */
243         Qio*    io;             /* using this Td for I/O */
244         Block*  bp;             /* data for this Td */
245         ulong   nbytes;         /* bytes in this Td */
246         ulong   cbp0;           /* initial value for cbp */
247         ulong   last;           /* true for last Td in Qio */
248 };
249
250 /*
251  * Host controller communication area (hardware)
252  */
253 struct Hcca
254 {
255         ulong   intrtable[32];
256         ushort  framenumber;
257         ushort  pad1;
258         ulong   donehead;
259         uchar   reserved[116];
260 };
261
262 /*
263  * I/O registers
264  */
265 struct Ohci
266 {
267         /* control and status group */
268         ulong   revision;               /*00*/
269         ulong   control;                /*04*/
270         ulong   cmdsts;                 /*08*/
271         ulong   intrsts;                        /*0c*/
272         ulong   intrenable;             /*10*/
273         ulong   intrdisable;            /*14*/
274
275         /* memory pointer group */
276         ulong   hcca;                   /*18*/
277         ulong   periodcurred;           /*1c*/
278         ulong   ctlheaded;              /*20*/
279         ulong   ctlcurred;              /*24*/
280         ulong   bulkheaded;             /*28*/
281         ulong   bulkcurred;             /*2c*/
282         ulong   donehead;               /*30*/
283
284         /* frame counter group */
285         ulong   fminterval;             /*34*/
286         ulong   fmremaining;            /*38*/
287         ulong   fmnumber;               /*3c*/
288         ulong   periodicstart;          /*40*/
289         ulong   lsthreshold;            /*44*/
290
291         /* root hub group */
292         ulong   rhdesca;                /*48*/
293         ulong   rhdescb;                /*4c*/
294         ulong   rhsts;                  /*50*/
295         ulong   rhportsts[15];          /*54*/
296         ulong   pad25[20];              /*90*/
297
298         /* unknown */
299         ulong   hostueaddr;             /*e0*/
300         ulong   hostuests;              /*e4*/
301         ulong   hosttimeoutctrl;                /*e8*/
302         ulong   pad59;                  /*ec*/
303         ulong   pad60;                  /*f0*/
304         ulong   hostrevision;           /*f4*/
305         ulong   pad62[2];
306                                         /*100*/
307 };
308
309 /*
310  * Endpoint tree (software)
311  */
312 struct Qtree
313 {
314         int     nel;
315         int     depth;
316         ulong*  bw;
317         Ed**    root;
318 };
319
320 struct Tdpool
321 {
322         Lock;
323         Td*     free;
324         int     nalloc;
325         int     ninuse;
326         int     nfree;
327 };
328
329 struct Edpool
330 {
331         Lock;
332         Ed*     free;
333         int     nalloc;
334         int     ninuse;
335         int     nfree;
336 };
337
338 struct Ctlr
339 {
340         Lock;                   /* for ilock; lists and basic ctlr I/O */
341         QLock   resetl;         /* lock controller during USB reset */
342         int     active;
343         Ctlr*   next;
344         int     nports;
345
346         Ohci*   ohci;           /* base I/O address */
347         Hcca*   hcca;           /* intr/done Td lists (used by hardware) */
348         int     overrun;        /* sched. overrun */
349         Ed*     intrhd;         /* list of intr. eds in tree */
350         Qtree*  tree;           /* tree for t Ep i/o */
351         int     ntree;          /* number of dummy Eds in tree */
352         Pcidev* pcidev;
353 };
354
355 #define dqprint         if(debug || io && io->debug)print
356 #define ddqprint                if(debug>1 || (io && io->debug>1))print
357 #define diprint         if(debug || iso && iso->debug)print
358 #define ddiprint                if(debug>1 || (iso && iso->debug>1))print
359 #define TRUNC(x, sz)    ((x) & ((sz)-1))
360
361 static int ohciinterrupts[Nttypes];
362 static char* iosname[] = { "idle", "install", "run", "done", "close", "FREE" };
363
364 static int debug;
365 static Edpool edpool;
366 static Tdpool tdpool;
367 static Ctlr* ctlrs[Nhcis];
368
369 static  char    EnotWritten[] = "usb write unfinished";
370 static  char    EnotRead[] = "usb read unfinished";
371 static  char    Eunderrun[] = "usb endpoint underrun";
372
373 static  QLock   usbhstate;      /* protects name space state */
374
375 static int      schedendpt(Ctlr *ub, Ep *ep);
376 static void     unschedendpt(Ctlr *ub, Ep *ep);
377 static long     qtd(Ctlr*, Ep*, int, Block*, uchar*, uchar*, int, ulong);
378
379 static char* errmsgs[] =
380 {
381 [Tdcrc]         "crc error",
382 [Tdbitstuff]    "bit stuffing error",
383 [Tdbadtog]      "bad toggle",
384 [Tdstalled]     Estalled,
385 [Tdtmout]       "timeout error",
386 [Tdpidchk]      "pid check error",
387 [Tdbadpid]      "bad pid",
388 [Tddataovr]     "data overrun",
389 [Tddataund]     "data underrun",
390 [Tdbufovr]      "buffer overrun",
391 [Tdbufund]      "buffer underrun",
392 [Tdnotacc]      "not accessed"
393 };
394
395 static void*
396 pa2ptr(ulong pa)
397 {
398         if(pa == 0)
399                 return nil;
400         else
401                 return KADDR(pa);
402 }
403
404 static ulong
405 ptr2pa(void *p)
406 {
407         if(p == nil)
408                 return 0;
409         else
410                 return PADDR(p);
411 }
412
413 static void
414 waitSOF(Ctlr *ub)
415 {
416         int frame = ub->hcca->framenumber & 0x3f;
417
418         do {
419                 delay(2);
420         } while(frame == (ub->hcca->framenumber & 0x3f));
421 }
422
423 static char*
424 errmsg(int err)
425 {
426
427         if(err < nelem(errmsgs))
428                 return errmsgs[err];
429         return nil;
430 }
431
432 static Ed*
433 ctlhd(Ctlr *ctlr)
434 {
435         return pa2ptr(ctlr->ohci->ctlheaded);
436 }
437
438 static Ed*
439 bulkhd(Ctlr *ctlr)
440 {
441         return pa2ptr(ctlr->ohci->bulkheaded);
442 }
443
444 static void
445 edlinked(Ed *ed, Ed *next)
446 {
447         if(ed == nil)
448                 print("edlinked: nil ed: pc %#p\n", getcallerpc(&ed));
449         ed->nexted = ptr2pa(next);
450         ed->next = next;
451 }
452
453 static void
454 setctlhd(Ctlr *ctlr, Ed *ed)
455 {
456         ctlr->ohci->ctlheaded = ptr2pa(ed);
457         if(ed != nil)
458                 ctlr->ohci->cmdsts |= Sclf;     /* reload it on next pass */
459 }
460
461 static void
462 setbulkhd(Ctlr *ctlr, Ed *ed)
463 {
464         ctlr->ohci->bulkheaded = ptr2pa(ed);
465         if(ed != nil)
466                 ctlr->ohci->cmdsts |= Sblf;     /* reload it on next pass */
467 }
468
469 static void
470 unlinkctl(Ctlr *ctlr, Ed *ed)
471 {
472         Ed *this, *prev, *next;
473
474         ctlr->ohci->control &= ~Ccle;
475         waitSOF(ctlr);
476         this = ctlhd(ctlr);
477         ctlr->ohci->ctlcurred = 0;
478         prev = nil;
479         while(this != nil && this != ed){
480                 prev = this;
481                 this = this->next;
482         }
483         if(this == nil){
484                 print("unlinkctl: not found\n");
485                 return;
486         }
487         next = this->next;
488         if(prev == nil)
489                 setctlhd(ctlr, next);
490         else
491                 edlinked(prev, next);
492         ctlr->ohci->control |= Ccle;
493         edlinked(ed, nil);              /* wipe out next field */
494 }
495
496 static void
497 unlinkbulk(Ctlr *ctlr, Ed *ed)
498 {
499         Ed *this, *prev, *next;
500
501         ctlr->ohci->control &= ~Cble;
502         waitSOF(ctlr);
503         this = bulkhd(ctlr);
504         ctlr->ohci->bulkcurred = 0;
505         prev = nil;
506         while(this != nil && this != ed){
507                 prev = this;
508                 this = this->next;
509         }
510         if(this == nil){
511                 print("unlinkbulk: not found\n");
512                 return;
513         }
514         next = this->next;
515         if(prev == nil)
516                 setbulkhd(ctlr, next);
517         else
518                 edlinked(prev, next);
519         ctlr->ohci->control |= Cble;
520         edlinked(ed, nil);              /* wipe out next field */
521 }
522
523 static void
524 edsetaddr(Ed *ed, ulong addr)
525 {
526         ulong ctrl;
527
528         ctrl = ed->ctrl & ~((Epmax<<7)|Devmax);
529         ctrl |= (addr & ((Epmax<<7)|Devmax));
530         ed->ctrl = ctrl;
531 }
532
533 static void
534 edsettog(Ed *ed, int c)
535 {
536         if(c != 0)
537                 ed->head |= Edtoggle;
538         else
539                 ed->head &= ~Edtoggle;
540 }
541
542 static int
543 edtoggle(Ed *ed)
544 {
545         return ed->head & Edtoggle;
546 }
547
548 static int
549 edhalted(Ed *ed)
550 {
551         return ed->head & Edhalt;
552 }
553
554 static int
555 edmaxpkt(Ed *ed)
556 {
557         return (ed->ctrl >> Edmpsshift) & Edmpsmask;
558 }
559
560 static void
561 edsetmaxpkt(Ed *ed, int m)
562 {
563         ulong c;
564
565         c = ed->ctrl & ~(Edmpsmask << Edmpsshift);
566         ed->ctrl = c | ((m&Edmpsmask) << Edmpsshift);
567 }
568
569 static int
570 tderrs(Td *td)
571 {
572         return (td->ctrl >> Tdccshift) & Tdccmask;
573 }
574
575 static int
576 tdtok(Td *td)
577 {
578         return (td->ctrl & Tdtokmask);
579 }
580
581 static Td*
582 tdalloc(void)
583 {
584         uchar *pool;
585         Td *td;
586         int i;
587
588         lock(&tdpool);
589         if(tdpool.free == nil){
590                 ddprint("ohci: tdalloc %d Tds\n", Incr);
591                 pool = xspanalloc(Incr*ROUND(sizeof(Td), Tdalign), Tdalign, 0);
592                 if(pool == nil)
593                         panic("ohci: tdalloc");
594                 for(i=Incr; --i>=0;){
595                         td = (Td*)(pool + i*ROUND(sizeof(Td), Tdalign));
596                         td->next = tdpool.free;
597                         tdpool.free = td;
598                 }
599                 tdpool.nalloc += Incr;
600                 tdpool.nfree += Incr;
601         }
602         tdpool.ninuse++;
603         tdpool.nfree--;
604         td = tdpool.free;
605         tdpool.free = td->next;
606         unlock(&tdpool);
607         assert(((uintptr)td & 0x1F) == 0);
608         memset(td, 0, sizeof(Td));
609         return td;
610 }
611
612 static void
613 tdfree(Td *td)
614 {
615         if(td == 0)
616                 return;
617         freeb(td->bp);
618         td->bp = nil;
619         lock(&tdpool);
620         if(td->nexttd == 0x77777777)
621                 panic("ohci: tdfree: double free");
622         memset(td, 7, sizeof(Td));      /* poison */
623         td->next = tdpool.free;
624         tdpool.free = td;
625         tdpool.ninuse--;
626         tdpool.nfree++;
627         unlock(&tdpool);
628 }
629
630 static Ed*
631 edalloc(void)
632 {
633         uchar *pool;
634         Ed *ed;
635         int i;
636
637         lock(&edpool);
638         if(edpool.free == nil){
639                 ddprint("ohci: edalloc %d Eds\n", Incr);
640                 pool = xspanalloc(Incr*ROUND(sizeof(Ed), Edalign), Edalign, 0);
641                 if(pool == nil)
642                         panic("ohci: edalloc");
643                 for(i=Incr; --i>=0;){
644                         ed = (Ed*)(pool + i*ROUND(sizeof(Ed), Edalign));
645                         ed->next = edpool.free;
646                         edpool.free = ed;
647                 }
648                 edpool.nalloc += Incr;
649                 edpool.nfree += Incr;
650         }
651         edpool.ninuse++;
652         edpool.nfree--;
653         ed = edpool.free;
654         edpool.free = ed->next;
655         unlock(&edpool);
656         assert(((uintptr)ed & 0xF) == 0);
657         memset(ed, 0, sizeof(Ed));
658         return ed;
659 }
660
661 static void
662 edfree(Ed *ed)
663 {
664         Td *td, *next;
665         int i;
666
667         if(ed == 0)
668                 return;
669         i = 0;
670         for(td = ed->tds; td != nil; td = next){
671                 next = td->next;
672                 tdfree(td);
673                 if(i++ > 2000){
674                         print("ohci: bug: ed with more than 2000 tds\n");
675                         break;
676                 }
677         }
678         lock(&edpool);
679         if(ed->nexted == 0x99999999)
680                 panic("ohci: edfree: double free");
681         memset(ed, 9, sizeof(Ed));      /* poison */
682         ed->next = edpool.free;
683         edpool.free = ed;
684         edpool.ninuse--;
685         edpool.nfree++;
686         unlock(&edpool);
687         ddprint("edfree: ed %#p\n", ed);
688 }
689
690 /*
691  * return smallest power of 2 >= n
692  */
693 static int
694 flog2(int n)
695 {
696         int i;
697
698         for(i = 0; (1 << i) < n; i++)
699                 ;
700         return i;
701 }
702
703 /*
704  * return smallest power of 2 <= n
705  */
706 static int
707 flog2lower(int n)
708 {
709         int i;
710
711         for(i = 0; (1 << (i + 1)) <= n; i++)
712                 ;
713         return i;
714 }
715
716 static int
717 pickschedq(Qtree *qt, int pollival, ulong bw, ulong limit)
718 {
719         int i, j, d, upperb, q;
720         ulong best, worst, total;
721
722         d = flog2lower(pollival);
723         if(d > qt->depth)
724                 d = qt->depth;
725         q = -1;
726         worst = 0;
727         best = ~0;
728         upperb = (1 << (d+1)) - 1;
729         for(i = (1 << d) - 1; i < upperb; i++){
730                 total = qt->bw[0];
731                 for(j = i; j > 0; j = (j - 1) / 2)
732                         total += qt->bw[j];
733                 if(total < best){
734                         best = total;
735                         q = i;
736                 }
737                 if(total > worst)
738                         worst = total;
739         }
740         if(worst + bw >= limit)
741                 return -1;
742         return q;
743 }
744
745 static int
746 schedq(Ctlr *ctlr, Qio *io, int pollival)
747 {
748         int q;
749         Ed *ted;
750
751         q = pickschedq(ctlr->tree, pollival, io->bw, ~0);
752         ddqprint("ohci: sched %#p q %d, ival %d, bw %ld\n", io, q, pollival, io->bw);
753         if(q < 0){
754                 print("ohci: no room for ed\n");
755                 return -1;
756         }
757         ctlr->tree->bw[q] += io->bw;
758         ted = ctlr->tree->root[q];
759         io->sched = q;
760         edlinked(io->ed, ted->next);
761         edlinked(ted, io->ed);
762         io->ed->inext = ctlr->intrhd;
763         ctlr->intrhd = io->ed;
764         return 0;
765 }
766
767 static void
768 unschedq(Ctlr *ctlr, Qio *qio)
769 {
770         int q;
771         Ed *prev, *this, *next;
772         Ed **l;
773
774         q = qio->sched;
775         if(q < 0)
776                 return;
777         ctlr->tree->bw[q] -= qio->bw;
778
779         prev = ctlr->tree->root[q];
780         this = prev->next;
781         while(this != nil && this != qio->ed){
782                 prev = this;
783                 this = this->next;
784         }
785         if(this == nil)
786                 print("ohci: unschedq %d: not found\n", q);
787         else{
788                 next = this->next;
789                 edlinked(prev, next);
790         }
791         waitSOF(ctlr);
792         for(l = &ctlr->intrhd; *l != nil; l = &(*l)->inext)
793                 if(*l == qio->ed){
794                         *l = (*l)->inext;
795                         return;
796                 }
797         print("ohci: unschedq: ed %#p not found\n", qio->ed);
798 }
799
800 static char*
801 seprinttdtok(char *s, char *e, int tok)
802 {
803         switch(tok){
804         case Tdtoksetup:
805                 s = seprint(s, e, " setup");
806                 break;
807         case Tdtokin:
808                 s = seprint(s, e, " in");
809                 break;
810         case Tdtokout:
811                 s = seprint(s, e, " out");
812                 break;
813         }
814         return s;
815 }
816
817
818 static char*
819 seprinttd(char *s, char *e, Td *td, int iso)
820 {
821         int i;
822         Block *bp;
823
824         if(td == nil)
825                 return seprint(s, e, "<nil td>\n");
826         s = seprint(s, e, "%#p ep %#p ctrl %#lux", td, td->ep, td->ctrl);
827         s = seprint(s, e, " cc=%#ulx", (td->ctrl >> Tdccshift) & Tdccmask);
828         if(iso == 0){
829                 if((td->ctrl & Tdround) != 0)
830                         s = seprint(s, e, " rnd");
831                 s = seprinttdtok(s, e, td->ctrl & Tdtokmask);
832                 if((td->ctrl & Tdusetog) != 0)
833                         s = seprint(s, e, " d%d", (td->ctrl & Tddata1) ? 1 : 0);
834                 else
835                         s = seprint(s, e, " d-");
836                 s = seprint(s, e, " ec=%uld", (td->ctrl >> Tderrshift) & Tderrmask);
837         }else{
838                 s = seprint(s, e, " fc=%uld", (td->ctrl >> Tdfcshift) & Tdfcmask);
839                 s = seprint(s, e, " sf=%uld", td->ctrl & Tdsfmask);
840         }
841         s = seprint(s, e, " cbp0 %#lux cbp %#lux next %#lux be %#lux %s",
842                 td->cbp0, td->cbp, td->nexttd, td->be, td->last ? "last" : "");
843         s = seprint(s, e, "\n\t\t%ld bytes", td->nbytes);
844         if((bp = td->bp) != nil){
845                 s = seprint(s, e, " rp %#p wp %#p ", bp->rp, bp->wp);
846                 if(BLEN(bp) > 0)
847                         s = seprintdata(s, e, bp->rp, bp->wp - bp->rp);
848         }
849         if(iso == 0)
850                 return seprint(s, e, "\n");
851         s = seprint(s, e, "\n\t\t");
852         /* we use only offsets[0] */
853         i = 0;
854         s = seprint(s, e, "[%d] %#ux cc=%#ux sz=%ud\n", i, td->offsets[i],
855                 (td->offsets[i] >> Tdiccshift) & Tdiccmask,
856                 td->offsets[i] & 0x7FF);
857         return s;
858 }
859
860 static void
861 dumptd(Td *td, char *p, int iso)
862 {
863         static char buf[512];   /* Too much */
864         char *s;
865
866         s = seprint(buf, buf+sizeof(buf), "%s: ", p);
867         s = seprinttd(s, buf+sizeof(buf), td, iso);
868         if(s > buf && s[-1] != '\n')
869                 s[-1] = '\n';
870         print("\t%s", buf);
871 }
872
873 static void
874 dumptds(Td *td, char *p, int iso)
875 {
876         int i;
877
878         for(i = 0; td != nil; td = td->next){
879                 dumptd(td, p, iso);
880                 if(td->last)
881                         break;
882                 if(tdtok(td) == Tdtokin && ++i > 2){
883                         print("\t\t...\n");
884                         break;
885                 }
886         }
887 }
888
889 static void
890 dumped(Ed *ed)
891 {
892         char *buf, *s, *e;
893
894         if(ed == nil){
895                 print("<null ed>\n");
896                 return;
897         }
898         buf = malloc(512);
899         /* no waserror; may want to use from interrupt context */
900         if(buf == nil)
901                 return;
902         e = buf+512;
903         s = seprint(buf, e, "\ted %#p: ctrl %#lux", ed, ed->ctrl);
904         if((ed->ctrl & Edskip) != 0)
905                 s = seprint(s, e, " skip");
906         if((ed->ctrl & Ediso) != 0)
907                 s = seprint(s, e, " iso");
908         if((ed->ctrl & Edlow) != 0)
909                 s = seprint(s, e, " low");
910         s = seprint(s, e, " d%d", (ed->head & Edtoggle) ? 1 : 0);
911         if((ed->ctrl & Eddirmask) == Edin)
912                 s = seprint(s, e, " in");
913         if((ed->ctrl & Eddirmask) == Edout)
914                 s = seprint(s, e, " out");
915         if(edhalted(ed))
916                 s = seprint(s, e, " hlt");
917         s = seprint(s, e, " ep%uld.%uld", (ed->ctrl>>7)&Epmax, ed->ctrl&0x7f);
918         s = seprint(s, e, " maxpkt %uld", (ed->ctrl>>Edmpsshift)&Edmpsmask);
919         seprint(s, e, " tail %#lux head %#lux next %#lux\n",ed->tail,ed->head,ed->nexted);
920         print("%s", buf);
921         free(buf);
922         if(ed->tds != nil && (ed->ctrl & Ediso) == 0)
923                 dumptds(ed->tds, "td", 0);
924 }
925
926 static char*
927 seprintio(char *s, char *e, Qio *io, char *pref)
928 {
929         s = seprint(s, e, "%s qio %#p ed %#p", pref, io, io->ed);
930         s = seprint(s, e, " tog %d iot %ld err %s id %#ulx",
931                 io->toggle, io->iotime, io->err, io->usbid);
932         s = seprinttdtok(s, e, io->tok);
933         s = seprint(s, e, " %s\n", iosname[io->state]);
934         return s;
935 }
936
937 static char*
938 seprintep(char* s, char* e, Ep *ep)
939 {
940         Isoio *iso;
941         Qio *io;
942         Ctlio *cio;
943
944         if(ep == nil)
945                 return seprint(s, e, "<nil ep>\n");
946         if(ep->aux == nil)
947                 return seprint(s, e, "no mdep\n");
948         switch(ep->ttype){
949         case Tctl:
950                 cio = ep->aux;
951                 s = seprintio(s, e, cio, "c");
952                 s = seprint(s, e, "\trepl %d ndata %d\n", ep->rhrepl, cio->ndata);
953                 break;
954         case Tbulk:
955         case Tintr:
956                 io = ep->aux;
957                 if(ep->mode != OWRITE)
958                         s = seprintio(s, e, &io[OREAD], "r");
959                 if(ep->mode != OREAD)
960                         s = seprintio(s, e, &io[OWRITE], "w");
961                 break;
962         case Tiso:
963                 iso = ep->aux;
964                 s = seprintio(s, e, iso, "w");
965                 s = seprint(s, e, "\tntds %d avail %d frno %uld left %uld next avail %#p\n",
966                         iso->nframes, iso->navail, iso->frno, iso->left, iso->atds);
967                 break;
968         }
969         return s;
970 }
971
972 static char*
973 seprintctl(char *s, char *se, ulong ctl)
974 {
975         s = seprint(s, se, "en=");
976         if((ctl&Cple) != 0)
977                 s = seprint(s, se, "p");
978         if((ctl&Cie) != 0)
979                 s = seprint(s, se, "i");
980         if((ctl&Ccle) != 0)
981                 s = seprint(s, se, "c");
982         if((ctl&Cble) != 0)
983                 s = seprint(s, se, "b");
984         switch(ctl & Cfsmask){
985         case Cfsreset:
986                 return seprint(s, se, " reset");
987         case Cfsresume:
988                 return seprint(s, se, " resume");
989         case Cfsoper:
990                 return seprint(s, se, " run");
991         case Cfssuspend:
992                 return seprint(s, se, " suspend");
993         default:
994                 return seprint(s, se, " ???");
995         }
996 }
997
998 static void
999 dump(Hci *hp)
1000 {
1001         Ctlr *ctlr;
1002         Ed *ed;
1003         char cs[20];
1004
1005         ctlr = hp->aux;
1006         ilock(ctlr);
1007         seprintctl(cs, cs+sizeof(cs), ctlr->ohci->control);
1008         print("ohci ctlr %#p: frno %#ux ctl %#lux %s sts %#lux intr %#lux\n",
1009                 ctlr, ctlr->hcca->framenumber, ctlr->ohci->control, cs,
1010                 ctlr->ohci->cmdsts, ctlr->ohci->intrsts);
1011         print("ctlhd %#ulx cur %#ulx bulkhd %#ulx cur %#ulx done %#ulx\n",
1012                 ctlr->ohci->ctlheaded, ctlr->ohci->ctlcurred,
1013                 ctlr->ohci->bulkheaded, ctlr->ohci->bulkcurred,
1014                 ctlr->ohci->donehead);
1015         if(ctlhd(ctlr) != nil)
1016                 print("[ctl]\n");
1017         for(ed = ctlhd(ctlr); ed != nil; ed = ed->next)
1018                 dumped(ed);
1019         if(bulkhd(ctlr) != nil)
1020                 print("[bulk]\n");
1021         for(ed = bulkhd(ctlr); ed != nil; ed = ed->next)
1022                 dumped(ed);
1023         if(ctlr->intrhd != nil)
1024                 print("[intr]\n");
1025         for(ed = ctlr->intrhd; ed != nil; ed = ed->inext)
1026                 dumped(ed);
1027         if(ctlr->tree->root[0]->next != nil)
1028                 print("[iso]");
1029         for(ed = ctlr->tree->root[0]->next; ed != nil; ed = ed->next)
1030                 dumped(ed);
1031         print("%d eds in tree\n", ctlr->ntree);
1032         iunlock(ctlr);
1033         lock(&tdpool);
1034         print("%d tds allocated = %d in use + %d free\n",
1035                 tdpool.nalloc, tdpool.ninuse, tdpool.nfree);
1036         unlock(&tdpool);
1037         lock(&edpool);
1038         print("%d eds allocated = %d in use + %d free\n",
1039                 edpool.nalloc, edpool.ninuse, edpool.nfree);
1040         unlock(&edpool);
1041 }
1042
1043 /*
1044  * Compute size for the next iso Td and setup its
1045  * descriptor for I/O according to the buffer size.
1046  */
1047 static void
1048 isodtdinit(Ep *ep, Isoio *iso, Td *td)
1049 {
1050         Block *bp;
1051         long size;
1052         int i;
1053
1054         bp = td->bp;
1055         assert(bp != nil && BLEN(bp) == 0);
1056         size = (ep->hz+iso->left) * ep->pollival / 1000;
1057         iso->left = (ep->hz+iso->left) * ep->pollival % 1000;
1058         size *= ep->samplesz;
1059         if(size > ep->maxpkt){
1060                 print("ohci: ep%d.%d: size > maxpkt\n",
1061                         ep->dev->nb, ep->nb);
1062                 print("size = %uld max = %ld\n", size, ep->maxpkt);
1063                 size = ep->maxpkt;
1064         }
1065         td->nbytes = size;
1066         memset(bp->wp, 0, size);        /* in case we don't fill it on time */
1067         td->cbp0 = td->cbp = ptr2pa(bp->rp) & ~0xFFF;
1068         td->ctrl = TRUNC(iso->frno, Ntdframes);
1069         td->offsets[0] = (ptr2pa(bp->rp) & 0xFFF);
1070         td->offsets[0] |= (Tdnotacc << Tdiccshift);
1071         /* in case the controller checks out the offests... */
1072         for(i = 1; i < nelem(td->offsets); i++)
1073                 td->offsets[i] = td->offsets[0];
1074         td->be = ptr2pa(bp->rp + size - 1);
1075         td->ctrl |= (0 << Tdfcshift);   /* frame count is 1 */
1076
1077         iso->frno = TRUNC(iso->frno + ep->pollival, Ntdframes);
1078 }
1079
1080 /*
1081  * start I/O on the dummy td and setup a new dummy to fill up.
1082  */
1083 static void
1084 isoadvance(Ep *ep, Isoio *iso, Td *td)
1085 {
1086         Td *dtd;
1087
1088         dtd = iso->atds;
1089         iso->atds = dtd->anext;
1090         iso->navail--;
1091         dtd->anext = nil;
1092         dtd->bp->wp = dtd->bp->rp;
1093         dtd->nexttd = 0;
1094         td->nexttd = ptr2pa(dtd);
1095         isodtdinit(ep, iso, dtd);
1096         iso->ed->tail = ptr2pa(dtd);
1097 }
1098
1099 static int
1100 isocanwrite(void *a)
1101 {
1102         Isoio *iso;
1103
1104         iso = a;
1105         return iso->state == Qclose || iso->err != nil ||
1106                 iso->navail > iso->nframes / 2;
1107 }
1108
1109 static int
1110 isodelay(void *a)
1111 {
1112         Isoio *iso;
1113
1114         iso = a;
1115         if(iso->state == Qclose || iso->err != nil || iso->delay == 0)
1116                 return 1;
1117         return (iso->nframes - iso->navail) <= iso->delay;
1118 }
1119
1120 /*
1121  * Service a completed/failed Td from the done queue.
1122  * It may be of any transfer type.
1123  * The queue is not in completion order.
1124  * (It's actually in reverse completion order).
1125  *
1126  * When an error, a short packet, or a last Td is found
1127  * we awake the process waiting for the transfer.
1128  * Although later we will process other Tds completed
1129  * before, epio won't be able to touch the current Td
1130  * until interrupt returns and releases the lock on the
1131  * controller.
1132  */
1133 static void
1134 qhinterrupt(Ctlr *, Ep *ep, Qio *io, Td *td, int)
1135 {
1136         Block *bp;
1137         int mode, err;
1138         Ed *ed;
1139
1140         ed = io->ed;
1141         if(io->state != Qrun)
1142                 return;
1143         if(tdtok(td) == Tdtokin)
1144                 mode = OREAD;
1145         else
1146                 mode = OWRITE;
1147         bp = td->bp;
1148         err = tderrs(td);
1149
1150         switch(err){
1151         case Tddataovr:                 /* Overrun is not an error */
1152         case Tdok:
1153                 /* virtualbox doesn't always report underflow on short packets */
1154                 if(td->cbp == 0)
1155                         break;
1156                 /* fall through */
1157         case Tddataund:
1158                 /* short input packets are ok */
1159                 if(mode == OREAD){
1160                         if(td->cbp == 0)
1161                                 panic("ohci: short packet but cbp == 0");
1162                         /*
1163                          * td->cbp and td->cbp0 are the real addresses
1164                          * corresponding to virtual addresses bp->wp and
1165                          * bp->rp respectively.
1166                          */
1167                         bp->wp = bp->rp + (td->cbp - td->cbp0);
1168                         if(bp->wp < bp->rp)
1169                                 panic("ohci: wp < rp");
1170                         /*
1171                          * It's ok. clear error and flag as last in xfer.
1172                          * epio must ignore following Tds.
1173                          */
1174                         td->last = 1;
1175                         td->ctrl &= ~(Tdccmask << Tdccshift);
1176                         break;
1177                 }
1178                 /* else fall; it's an error */
1179         case Tdcrc:
1180         case Tdbitstuff:
1181         case Tdbadtog:
1182         case Tdstalled:
1183         case Tdtmout:
1184         case Tdpidchk:
1185         case Tdbadpid:
1186                 bp->wp = bp->rp;        /* no bytes in xfer. */
1187                 io->err = errmsg(err);
1188                 if(debug || ep->debug){
1189                         print("tdinterrupt: failed err %d (%s)\n", err, io->err);
1190                         dumptd(td, "failed", ed->ctrl & Ediso);
1191                 }
1192                 td->last = 1;
1193                 break;
1194         default:
1195                 panic("ohci: td cc %ud unknown", err);
1196         }
1197
1198         if(td->last != 0){
1199                 /*
1200                  * clear td list and halt flag.
1201                  */
1202                 ed->head = (ed->head & Edtoggle) | ed->tail;
1203                 ed->tds = pa2ptr(ed->tail);
1204                 io->state = Qdone;
1205                 wakeup(io);
1206         }
1207 }
1208
1209 /*
1210  * BUG: Iso input streams are not implemented.
1211  */
1212 static void
1213 isointerrupt(Ctlr *ctlr, Ep *ep, Qio *io, Td *td, int)
1214 {
1215         Isoio *iso;
1216         Block *bp;
1217         Ed *ed;
1218         int err, isoerr;
1219
1220         iso = ep->aux;
1221         ed = io->ed;
1222         if(io->state == Qclose)
1223                 return;
1224         bp = td->bp;
1225         /*
1226          * When we get more than half the frames consecutive errors
1227          * we signal an actual error. Errors in the entire Td are
1228          * more serious and are always singaled.
1229          * Errors like overrun are not really errors. In fact, for
1230          * output, errors cannot be really detected. The driver will
1231          * hopefully notice I/O errors on input endpoints and detach the device.
1232          */
1233         err = tderrs(td);
1234         isoerr = (td->offsets[0] >> Tdiccshift) & Tdiccmask;
1235         if(isoerr == Tdok || isoerr == Tdnotacc)
1236                 iso->nerrs = 0;
1237         else if(iso->nerrs++ > iso->nframes/2)
1238                 err = Tdstalled;
1239         if(err != Tdok && err != Tddataovr){
1240                 bp->wp = bp->rp;
1241                 io->err = errmsg(err);
1242                 if(debug || ep->debug){
1243                         print("ohci: isointerrupt: ep%d.%d: err %d (%s) frnum 0x%lux\n",
1244                                 ep->dev->nb, ep->nb,
1245                                 err, errmsg(err), ctlr->ohci->fmnumber);
1246                         dumptd(td, "failed", ed->ctrl & Ediso);
1247                 }
1248         }
1249         td->bp->wp = td->bp->rp;
1250         td->nbytes = 0;
1251         td->anext = iso->atds;
1252         iso->atds = td;
1253         iso->navail++;
1254         /*
1255          * If almost all Tds are avail the user is not doing I/O at the
1256          * required rate. We put another Td in place to keep the polling rate.
1257          */
1258         if(iso->err == nil && iso->navail > iso->nframes - 10)
1259                 isoadvance(ep, iso, pa2ptr(iso->ed->tail));
1260         /*
1261          * If there's enough buffering futher I/O can be done.
1262          */
1263         if(isocanwrite(iso))
1264                 wakeup(iso);
1265 }
1266
1267 static void
1268 interrupt(Ureg *, void *arg)
1269 {
1270         Td *td, *ntd;
1271         Hci *hp;
1272         Ctlr *ctlr;
1273         ulong status, curred, done;
1274         int i, frno;
1275
1276         hp = arg;
1277         ctlr = hp->aux;
1278         ilock(ctlr);
1279         done = ctlr->hcca->donehead;
1280         status = ctlr->ohci->intrsts;
1281         if(status == ~0){
1282                 iunlock(ctlr);
1283                 return;
1284         }
1285         if(done & ~0xF){
1286                 ctlr->hcca->donehead = 0;
1287                 status |= Wdh;
1288         }
1289         else if(status & Wdh){
1290                 done = ctlr->hcca->donehead;
1291                 ctlr->hcca->donehead = 0;
1292         }
1293         status &= ~Mie;
1294         if(status == 0){
1295                 iunlock(ctlr);
1296                 return;
1297         }
1298         ctlr->ohci->intrsts = status;
1299         status &= ctlr->ohci->intrenable;
1300         status &= Oc|Rhsc|Fno|Ue|Rd|Sf|Wdh|So;
1301         if(status & Wdh){
1302                 frno = TRUNC(ctlr->ohci->fmnumber, Ntdframes);
1303                 td = pa2ptr(done & ~0xF);
1304                 for(i = 0; td != nil && i < 1024; i++){
1305                         if(0)ddprint("ohci tdinterrupt: td %#p\n", td);
1306                         ntd = pa2ptr(td->nexttd & ~0xF);
1307                         td->nexttd = 0;
1308                         if(td->ep == nil || td->io == nil)
1309                                 panic("ohci: interrupt: ep %#p io %#p", td->ep, td->io);
1310                         ohciinterrupts[td->ep->ttype]++;
1311                         if(td->ep->ttype == Tiso)
1312                                 isointerrupt(ctlr, td->ep, td->io, td, frno);
1313                         else
1314                                 qhinterrupt(ctlr, td->ep, td->io, td, frno);
1315                         td = ntd;
1316                 }
1317                 if(i == 1024)
1318                         iprint("ohci: bug: more than 1024 done Tds?\n");
1319                 status &= ~Wdh;
1320         }
1321         status &= ~Sf;
1322         if(status & So){
1323                 iprint("ohci: sched overrun: too much load\n");
1324                 ctlr->overrun++;
1325                 status &= ~So;
1326         }
1327         if(status & Ue){
1328                 curred = ctlr->ohci->periodcurred;
1329                 iprint("ohci: unrecoverable error frame 0x%.8lux ed 0x%.8lux, "
1330                         "ints %d %d %d %d\n",
1331                         ctlr->ohci->fmnumber, curred,
1332                         ohciinterrupts[Tctl], ohciinterrupts[Tintr],
1333                         ohciinterrupts[Tbulk], ohciinterrupts[Tiso]);
1334                 if(curred != 0)
1335                         dumped(pa2ptr(curred));
1336                 status &= ~Ue;
1337         }
1338         if(status != 0){
1339                 iprint("ohci interrupt: unhandled sts 0x%.8lux\n", status);
1340                 ctlr->ohci->intrdisable = status;
1341         }
1342         iunlock(ctlr);
1343 }
1344
1345 /*
1346  * The old dummy Td is used to implement the new Td.
1347  * A new dummy is linked at the end of the old one and
1348  * returned, to link further Tds if needed.
1349  */
1350 static Td*
1351 epgettd(Ep *ep, Qio *io, Td **dtdp, int flags, void *a, int count)
1352 {
1353         Td *td, *dtd;
1354         Block *bp;
1355
1356         if(count <= BY2PG)
1357                 bp = allocb(count);
1358         else{
1359                 if(count > 2*BY2PG)
1360                         panic("ohci: transfer > two pages");
1361                 /* maximum of one physical page crossing allowed */
1362                 bp = allocb(count+BY2PG);
1363                 bp->rp = (uchar*)PGROUND((uintptr)bp->rp);
1364                 bp->wp = bp->rp;
1365         }
1366         dtd = *dtdp;
1367         td = dtd;
1368         td->bp = bp;
1369         if(count > 0){
1370                 td->cbp0 = td->cbp = ptr2pa(bp->wp);
1371                 td->be = ptr2pa(bp->wp + count - 1);
1372                 if(a != nil){
1373                         /* validaddr((uintptr)a, count, 0); DEBUG */
1374                         assert(bp != nil);
1375                         assert(bp->wp != nil);
1376                         memmove(bp->wp, a, count);
1377                 }
1378                 bp->wp += count;
1379         }
1380         td->nbytes = count;
1381         td->ctrl = io->tok|Tdusetog|io->toggle|flags;
1382         if(io->toggle == Tddata0)
1383                 io->toggle = Tddata1;
1384         else
1385                 io->toggle = Tddata0;
1386         assert(td->ep == ep);
1387         td->io = io;
1388         dtd = tdalloc();        /* new dummy */
1389         dtd->ep = ep;
1390         td->nexttd = ptr2pa(dtd);
1391         td->next = dtd;
1392         *dtdp = dtd;
1393         return td;
1394 }
1395
1396 /*
1397  * Try to get them idle
1398  */
1399 static void
1400 aborttds(Qio *io)
1401 {
1402         Ed *ed;
1403         Td *td;
1404
1405         ed = io->ed;
1406         if(ed == nil)
1407                 return;
1408         ed->ctrl |= Edskip;
1409         for(td = ed->tds; td != nil; td = td->next)
1410                 if(td->bp != nil)
1411                         td->bp->wp = td->bp->rp;
1412         ed->head = (ed->head&0xF) | ed->tail;
1413         if((ed->ctrl & Ediso) == 0)
1414                 ed->tds = pa2ptr(ed->tail);
1415 }
1416
1417 static int
1418 epiodone(void *a)
1419 {
1420         Qio *io;
1421
1422         io = a;
1423         return io->state != Qrun;
1424 }
1425
1426 static void
1427 epiowait(Ctlr *ctlr, Qio *io, int tmout, ulong)
1428 {
1429         Ed *ed;
1430         int timedout;
1431
1432         ed = io->ed;
1433         if(0)ddqprint("ohci io %#p sleep on ed %#p state %s\n",
1434                 io, ed, iosname[io->state]);
1435         timedout = 0;
1436         if(waserror()){
1437                 dqprint("ohci io %#p ed %#p timed out\n", io, ed);
1438                 timedout++;
1439         }else{
1440                 if(tmout == 0)
1441                         sleep(io, epiodone, io);
1442                 else
1443                         tsleep(io, epiodone, io, tmout);
1444                 poperror();
1445         }
1446         ilock(ctlr);
1447         if(io->state == Qrun)
1448                 timedout = 1;
1449         else if(io->state != Qdone && io->state != Qclose)
1450                 panic("epio: ed not done and not closed");
1451         if(timedout){
1452                 aborttds(io);
1453                 io->err = "request timed out";
1454                 iunlock(ctlr);
1455                 if(!waserror()){
1456                         tsleep(&up->sleep, return0, 0, Abortdelay);
1457                         poperror();
1458                 }
1459                 ilock(ctlr);
1460         }
1461         if(io->state != Qclose)
1462                 io->state = Qidle;
1463         iunlock(ctlr);
1464 }
1465
1466 /*
1467  * Non iso I/O.
1468  * To make it work for control transfers, the caller may
1469  * lock the Qio for the entire control transfer.
1470  */
1471 static long
1472 epio(Ep *ep, Qio *io, void *a, long count, int mustlock)
1473 {
1474         Ed *ed;
1475         Ctlr *ctlr;
1476         char buf[80];
1477         char *err;
1478         uchar *c;
1479         Td *td, *ltd, *ntd, *td0;
1480         int last, ntds, tmout;
1481         long tot, n;
1482         ulong load;
1483
1484         ed = io->ed;
1485         ctlr = ep->hp->aux;
1486         io->debug = ep->debug;
1487         tmout = ep->tmout;
1488         ddeprint("ohci: %s ep%d.%d io %#p count %ld\n",
1489                 io->tok == Tdtokin ? "in" : "out",
1490                 ep->dev->nb, ep->nb, io, count);
1491         if((debug > 1 || ep->debug > 1) && io->tok != Tdtokin){
1492                 seprintdata(buf, buf+sizeof(buf), a, count);
1493                 print("\t%s\n", buf);
1494         }
1495         if(mustlock){
1496                 eqlock(io);
1497                 if(waserror()){
1498                         qunlock(io);
1499                         nexterror();
1500                 }
1501         }
1502         io->err = nil;
1503         ilock(ctlr);
1504         if(io->state == Qclose){        /* Tds released by cancelio */
1505                 iunlock(ctlr);
1506                 error(io->err ? io->err : Eio);
1507         }
1508         if(io->state != Qidle)
1509                 panic("epio: qio not idle");
1510         io->state = Qinstall;
1511
1512         c = a;
1513         ltd = td0 = ed->tds;
1514         load = tot = 0;
1515         do{
1516                 n = 2*BY2PG;
1517                 if(count-tot < n)
1518                         n = count-tot;
1519                 if(c != nil && io->tok != Tdtokin)
1520                         td = epgettd(ep, io, &ltd, 0, c+tot, n);
1521                 else
1522                         td = epgettd(ep, io, &ltd, 0, nil, n);
1523                 tot += n;
1524                 load += ep->load;
1525         }while(tot < count);
1526         if(td0 == nil || ltd == nil || td0 == ltd)
1527                 panic("epio: no td");
1528         td->last = 1;
1529         if(debug > 2 || ep->debug > 2)
1530                 dumptds(td0, "put td", ep->ttype == Tiso);
1531         iunlock(ctlr);
1532
1533         ilock(ctlr);
1534         if(io->state != Qclose){
1535                 io->iotime = TK2MS(MACHP(0)->ticks);
1536                 io->state = Qrun;
1537                 ed->tail = ptr2pa(ltd);
1538                 if(ep->ttype == Tctl)
1539                         ctlr->ohci->cmdsts |= Sclf;
1540                 else if(ep->ttype == Tbulk)
1541                         ctlr->ohci->cmdsts |= Sblf;
1542         }
1543         iunlock(ctlr);
1544
1545         epiowait(ctlr, io, tmout, load);
1546         ilock(ctlr);
1547         if(debug > 1 || ep->debug > 1)
1548                 dumptds(td0, "got td", 0);
1549         iunlock(ctlr);
1550
1551         tot = 0;
1552         c = a;
1553         ntds = last = 0;
1554         for(td = td0; td != ltd; td = ntd){
1555                 ntds++;
1556                 /*
1557                  * If the Td is flagged as last we must
1558                  * ignore any following Td. The block may
1559                  * seem to have bytes but interrupt has not seen
1560                  * those Tds through the done queue, and they are void.
1561                  */
1562                 if(last == 0 && tderrs(td) == Tdok){
1563                         n = BLEN(td->bp);
1564                         tot += n;
1565                         if(c != nil && tdtok(td) == Tdtokin && n > 0){
1566                                 memmove(c, td->bp->rp, n);
1567                                 c += n;
1568                         }
1569                 }
1570                 last |= td->last;
1571                 ntd = td->next;
1572                 tdfree(td);
1573         }
1574         if(edtoggle(ed) == 0)
1575                 io->toggle = Tddata0;
1576         else
1577                 io->toggle = Tddata1;
1578
1579         err = io->err;
1580         if(mustlock){
1581                 qunlock(io);
1582                 poperror();
1583         }
1584         ddeprint("ohci: io %#p: %d tds: return %ld err '%s'\n\n",
1585                 io, ntds, tot, err);
1586         if(err != nil)
1587                 error(err);
1588         if(tot < 0)
1589                 error(Eio);
1590         return tot;
1591 }
1592
1593 /*
1594  * halt condition was cleared on the endpoint. update our toggles.
1595  */
1596 static void
1597 clrhalt(Ep *ep)
1598 {
1599         Qio *io;
1600
1601         ep->clrhalt = 0;
1602         switch(ep->ttype){
1603         case Tbulk:
1604         case Tintr:
1605                 io = ep->aux;
1606                 if(ep->mode != OREAD){
1607                         qlock(&io[OWRITE]);
1608                         io[OWRITE].toggle = Tddata0;
1609                         deprint("ep clrhalt for io %#p\n", io+OWRITE);
1610                         qunlock(&io[OWRITE]);
1611                 }
1612                 if(ep->mode != OWRITE){
1613                         qlock(&io[OREAD]);
1614                         io[OREAD].toggle = Tddata0;
1615                         deprint("ep clrhalt for io %#p\n", io+OREAD);
1616                         qunlock(&io[OREAD]);
1617                 }
1618                 break;
1619         }
1620 }
1621
1622 static long
1623 epread(Ep *ep, void *a, long count)
1624 {
1625         Ctlio *cio;
1626         Qio *io;
1627         char buf[80];
1628         ulong delta;
1629
1630         if(ep->aux == nil)
1631                 panic("epread: not open");
1632
1633         switch(ep->ttype){
1634         case Tctl:
1635                 cio = ep->aux;
1636                 eqlock(cio);
1637                 if(waserror()){
1638                         qunlock(cio);
1639                         nexterror();
1640                 }
1641                 ddeprint("epread ctl ndata %d\n", cio->ndata);
1642                 if(cio->ndata < 0)
1643                         error("request expected");
1644                 else if(cio->ndata == 0){
1645                         cio->ndata = -1;
1646                         count = 0;
1647                 }else{
1648                         if(count > cio->ndata)
1649                                 count = cio->ndata;
1650                         if(count > 0)
1651                                 memmove(a, cio->data, count);
1652                         /* BUG for big transfers */
1653                         free(cio->data);
1654                         cio->data = nil;
1655                         cio->ndata = 0; /* signal EOF next time */
1656                 }
1657                 qunlock(cio);
1658                 poperror();
1659                 if(debug>1 || ep->debug){
1660                         seprintdata(buf, buf+sizeof(buf), a, count);
1661                         print("epread: %s\n", buf);
1662                 }
1663                 return count;
1664         case Tbulk:
1665                 io = ep->aux;
1666                 if(ep->clrhalt)
1667                         clrhalt(ep);
1668                 return epio(ep, &io[OREAD], a, count, 1);
1669         case Tintr:
1670                 io = ep->aux;
1671                 delta = TK2MS(MACHP(0)->ticks) - io[OREAD].iotime + 1;
1672                 if(delta < ep->pollival / 2)
1673                         tsleep(&up->sleep, return0, 0, ep->pollival/2 - delta);
1674                 if(ep->clrhalt)
1675                         clrhalt(ep);
1676                 return epio(ep, &io[OREAD], a, count, 1);
1677         case Tiso:
1678                 error("iso read not implemented");
1679                 break;
1680         default:
1681                 panic("epread: bad ep ttype %d", ep->ttype);
1682         }
1683         return -1;
1684 }
1685
1686 /*
1687  * Control transfers are one setup write (data0)
1688  * plus zero or more reads/writes (data1, data0, ...)
1689  * plus a final write/read with data1 to ack.
1690  * For both host to device and device to host we perform
1691  * the entire transfer when the user writes the request,
1692  * and keep any data read from the device for a later read.
1693  * We call epio three times instead of placing all Tds at
1694  * the same time because doing so leads to crc/tmout errors
1695  * for some devices.
1696  * Upon errors on the data phase we must still run the status
1697  * phase or the device may cease responding in the future.
1698  */
1699 static long
1700 epctlio(Ep *ep, Ctlio *cio, void *a, long count)
1701 {
1702         uchar *c;
1703         long len;
1704
1705         ddeprint("epctlio: cio %#p ep%d.%d count %ld\n",
1706                 cio, ep->dev->nb, ep->nb, count);
1707         if(count < Rsetuplen)
1708                 error("short usb command");
1709         eqlock(cio);
1710         free(cio->data);
1711         cio->data = nil;
1712         cio->ndata = 0;
1713         if(waserror()){
1714                 qunlock(cio);
1715                 free(cio->data);
1716                 cio->data = nil;
1717                 cio->ndata = 0;
1718                 nexterror();
1719         }
1720
1721         /* set the address if unset and out of configuration state */
1722         if(ep->dev->state != Dconfig && ep->dev->state != Dreset)
1723                 if(cio->usbid == 0){
1724                         cio->usbid = (ep->nb&Epmax)<<7 | (ep->dev->nb&Devmax);
1725                         edsetaddr(cio->ed, cio->usbid);
1726                 }
1727         /* adjust maxpkt if the user has learned a different one */
1728         if(edmaxpkt(cio->ed) != ep->maxpkt)
1729                 edsetmaxpkt(cio->ed, ep->maxpkt);
1730         c = a;
1731         cio->tok = Tdtoksetup;
1732         cio->toggle = Tddata0;
1733         if(epio(ep, cio, a, Rsetuplen, 0) < Rsetuplen)
1734                 error(Eio);
1735
1736         a = c + Rsetuplen;
1737         count -= Rsetuplen;
1738
1739         cio->toggle = Tddata1;
1740         if(c[Rtype] & Rd2h){
1741                 cio->tok = Tdtokin;
1742                 len = GET2(c+Rcount);
1743                 if(len <= 0)
1744                         error("bad length in d2h request");
1745                 if(len > Maxctllen)
1746                         error("d2h data too large to fit in ohci");
1747                 a = cio->data = smalloc(len+1);
1748         }else{
1749                 cio->tok = Tdtokout;
1750                 len = count;
1751         }
1752         if(len > 0)
1753                 if(waserror())
1754                         len = -1;
1755                 else{
1756                         len = epio(ep, cio, a, len, 0);
1757                         poperror();
1758                 }
1759         if(c[Rtype] & Rd2h){
1760                 count = Rsetuplen;
1761                 cio->ndata = len;
1762                 cio->tok = Tdtokout;
1763         }else{
1764                 if(len < 0)
1765                         count = -1;
1766                 else
1767                         count = Rsetuplen + len;
1768                 cio->tok = Tdtokin;
1769         }
1770         cio->toggle = Tddata1;
1771         epio(ep, cio, nil, 0, 0);
1772         qunlock(cio);
1773         poperror();
1774         ddeprint("epctlio cio %#p return %ld\n", cio, count);
1775         return count;
1776 }
1777
1778 /*
1779  * Put new samples in the dummy Td.
1780  */
1781 static long
1782 putsamples(Ctlr *ctlr, Ep *ep, Isoio *iso, uchar *b, long n)
1783 {
1784         Td *td;
1785
1786         td = pa2ptr(iso->ed->tail);
1787         if(n > td->nbytes - BLEN(td->bp))
1788                 n = td->nbytes - BLEN(td->bp);
1789         assert(td->bp->wp + n <= td->bp->lim);
1790         iunlock(ctlr);          /* We could page fault here */
1791         memmove(td->bp->wp, b, n);
1792         ilock(ctlr);
1793         if(td == pa2ptr(iso->ed->tail)){
1794                 td->bp->wp += n;
1795                 if(BLEN(td->bp) == td->nbytes)  /* full Td: activate it */
1796                         isoadvance(ep, iso, td);
1797         }
1798         return n;
1799 }
1800
1801 static long
1802 episowrite(Ep *ep, void *a, long count)
1803 {
1804         long tot, nw;
1805         char *err;
1806         uchar *b;
1807         Ctlr *ctlr;
1808         Isoio *iso;
1809
1810         ctlr = ep->hp->aux;
1811         iso = ep->aux;
1812         iso->delay = (ep->sampledelay*ep->samplesz + ep->maxpkt-1) / ep->maxpkt;
1813         iso->debug = ep->debug;
1814
1815         eqlock(iso);
1816         if(waserror()){
1817                 qunlock(iso);
1818                 nexterror();
1819         }
1820         diprint("ohci: episowrite: %#p ep%d.%d\n", iso, ep->dev->nb, ep->nb);
1821         ilock(ctlr);
1822         if(iso->state == Qclose){
1823                 iunlock(ctlr);
1824                 error(iso->err ? iso->err : Eio);
1825         }
1826         iso->state = Qrun;
1827         b = a;
1828         for(tot = 0; tot < count; tot += nw){
1829                 while(isocanwrite(iso) == 0){
1830                         iunlock(ctlr);
1831                         diprint("ohci: episowrite: %#p sleep\n", iso);
1832                         if(waserror()){
1833                                 if(iso->err == nil)
1834                                         iso->err = "I/O timed out";
1835                                 ilock(ctlr);
1836                                 break;
1837                         }
1838                         tsleep(iso, isocanwrite, iso, ep->tmout);
1839                         poperror();
1840                         ilock(ctlr);
1841                 }
1842                 err = iso->err;
1843                 iso->err = nil;
1844                 if(iso->state == Qclose || err != nil){
1845                         iunlock(ctlr);
1846                         error(err ? err : Eio);
1847                 }
1848                 if(iso->state != Qrun)
1849                         panic("episowrite: iso not running");
1850                 nw = putsamples(ctlr, ep, iso, b+tot, count-tot);
1851         }
1852         while(isodelay(iso) == 0){
1853                 iunlock(ctlr);
1854                 sleep(iso, isodelay, iso);
1855                 ilock(ctlr);
1856         }
1857         if(iso->state != Qclose)
1858                 iso->state = Qdone;
1859         iunlock(ctlr);
1860         err = iso->err;         /* in case it failed early */
1861         iso->err = nil;
1862         qunlock(iso);
1863         poperror();
1864         if(err != nil)
1865                 error(err);
1866         diprint("ohci: episowrite: %#p %ld bytes\n", iso, tot);
1867         return tot;
1868 }
1869
1870 static long
1871 epwrite(Ep *ep, void *a, long count)
1872 {
1873         Qio *io;
1874         Ctlio *cio;
1875         ulong delta;
1876         uchar *b;
1877         long tot, nw;
1878
1879         if(ep->aux == nil)
1880                 panic("ohci: epwrite: not open");
1881         switch(ep->ttype){
1882         case Tctl:
1883                 cio = ep->aux;
1884                 return epctlio(ep, cio, a, count);
1885         case Tbulk:
1886                 io = ep->aux;
1887                 if(ep->clrhalt)
1888                         clrhalt(ep);
1889                 /*
1890                  * Put at most Tdatomic Tds (512 bytes) at a time.
1891                  * Otherwise some devices produce babble errors.
1892                  */
1893                 b = a;
1894                 assert(a != nil);
1895                 for(tot = 0; tot < count ; tot += nw){
1896                         nw = count - tot;
1897                         if(nw > Tdatomic * ep->maxpkt)
1898                                 nw = Tdatomic * ep->maxpkt;
1899                         nw = epio(ep, &io[OWRITE], b+tot, nw, 1);
1900                 }
1901                 return tot;
1902         case Tintr:
1903                 io = ep->aux;
1904                 delta = TK2MS(MACHP(0)->ticks) - io[OWRITE].iotime + 1;
1905                 if(delta < ep->pollival)
1906                         tsleep(&up->sleep, return0, 0, ep->pollival - delta);
1907                 if(ep->clrhalt)
1908                         clrhalt(ep);
1909                 return epio(ep, &io[OWRITE], a, count, 1);
1910         case Tiso:
1911                 return episowrite(ep, a, count);
1912         default:
1913                 panic("ohci: epwrite: bad ep ttype %d", ep->ttype);
1914         }
1915         return -1;
1916 }
1917
1918 static Ed*
1919 newed(Ctlr *ctlr, Ep *ep, Qio *io, char *)
1920 {
1921         Ed *ed;
1922         Td *td;
1923
1924         ed = io->ed = edalloc();        /* no errors raised here, really */
1925         td = tdalloc();
1926         td->ep = ep;
1927         td->io = io;
1928         ed->tail =  ptr2pa(td);
1929         ed->head = ptr2pa(td);
1930         ed->tds = td;
1931         ed->ep = ep;
1932         ed->ctrl = (ep->maxpkt & Edmpsmask) << Edmpsshift;
1933         if(ep->ttype == Tiso)
1934                 ed->ctrl |= Ediso;
1935         if(waserror()){
1936                 edfree(ed);
1937                 io->ed = nil;
1938                 nexterror();
1939         }
1940         /* For setup endpoints we start with the config address */
1941         if(ep->ttype != Tctl)
1942                 edsetaddr(io->ed, io->usbid);
1943         if(ep->dev->speed == Lowspeed)
1944                 ed->ctrl |= Edlow;
1945         switch(io->tok){
1946         case Tdtokin:
1947                 ed->ctrl |= Edin;
1948                 break;
1949         case Tdtokout:
1950                 ed->ctrl |= Edout;
1951                 break;
1952         default:
1953                 ed->ctrl |= Edtddir;    /* Td will say */
1954                 break;
1955         }
1956
1957         switch(ep->ttype){
1958         case Tctl:
1959                 ilock(ctlr);
1960                 edlinked(ed, ctlhd(ctlr));
1961                 setctlhd(ctlr, ed);
1962                 iunlock(ctlr);
1963                 break;
1964         case Tbulk:
1965                 ilock(ctlr);
1966                 edlinked(ed, bulkhd(ctlr));
1967                 setbulkhd(ctlr, ed);
1968                 iunlock(ctlr);
1969                 break;
1970         case Tintr:
1971         case Tiso:
1972                 ilock(ctlr);
1973                 schedq(ctlr, io, ep->pollival);
1974                 iunlock(ctlr);
1975                 break;
1976         default:
1977                 panic("ohci: newed: bad ttype");
1978         }
1979         poperror();
1980         return ed;
1981 }
1982
1983 static void
1984 isoopen(Ctlr *ctlr, Ep *ep)
1985 {
1986         Td *td, *edtds;
1987         Isoio *iso;
1988         int i;
1989
1990         iso = ep->aux;
1991         iso->usbid = (ep->nb&Epmax)<<7 | (ep->dev->nb&Devmax);
1992         iso->bw = ep->hz * ep->samplesz;        /* bytes/sec */
1993         if(ep->mode != OWRITE){
1994                 print("ohci: bug: iso input streams not implemented\n");
1995                 error("ohci iso input streams not implemented");
1996         }else
1997                 iso->tok = Tdtokout;
1998
1999         iso->left = 0;
2000         iso->nerrs = 0;
2001         iso->frno = TRUNC(ctlr->ohci->fmnumber + 10, Ntdframes);
2002         iso->nframes = 1000 / ep->pollival;
2003         if(iso->nframes < 10){
2004                 print("ohci: isoopen: less than 10 frames; using 10.\n");
2005                 iso->nframes = 10;
2006         }
2007         iso->navail = iso->nframes;
2008         iso->atds = edtds = nil;
2009         for(i = 0; i < iso->nframes-1; i++){    /* -1 for dummy */
2010                 td = tdalloc();
2011                 td->ep = ep;
2012                 td->io = iso;
2013                 td->bp = allocb(ep->maxpkt);
2014                 td->anext = iso->atds;          /* link as avail */
2015                 iso->atds = td;
2016                 td->next = edtds;
2017                 edtds = td;
2018         }
2019         newed(ctlr, ep, iso, "iso");            /* allocates a dummy td */
2020         iso->ed->tds->bp = allocb(ep->maxpkt);  /* but not its block */
2021         iso->ed->tds->next = edtds;
2022         isodtdinit(ep, iso, iso->ed->tds);
2023 }
2024
2025 /*
2026  * Allocate the endpoint and set it up for I/O
2027  * in the controller. This must follow what's said
2028  * in Ep regarding configuration, including perhaps
2029  * the saved toggles (saved on a previous close of
2030  * the endpoint data file by epclose).
2031  */
2032 static void
2033 epopen(Ep *ep)
2034 {
2035         Ctlr *ctlr;
2036         Qio *io;
2037         Ctlio *cio;
2038         ulong usbid;
2039
2040         ctlr = ep->hp->aux;
2041         deprint("ohci: epopen ep%d.%d\n", ep->dev->nb, ep->nb);
2042         if(ep->aux != nil)
2043                 panic("ohci: epopen called with open ep");
2044         if(waserror()){
2045                 free(ep->aux);
2046                 ep->aux = nil;
2047                 nexterror();
2048         }
2049         switch(ep->ttype){
2050         case Tnone:
2051                 error("endpoint not configured");
2052         case Tiso:
2053                 ep->aux = smalloc(sizeof(Isoio));
2054                 isoopen(ctlr, ep);
2055                 break;
2056         case Tctl:
2057                 cio = ep->aux = smalloc(sizeof(Ctlio));
2058                 cio->debug = ep->debug;
2059                 cio->ndata = -1;
2060                 cio->data = nil;
2061                 cio->tok = -1;  /* invalid; Tds will say */
2062                 if(ep->dev->isroot != 0 && ep->nb == 0) /* root hub */
2063                         break;
2064                 newed(ctlr, ep, cio, "epc");
2065                 break;
2066         case Tbulk:
2067                 ep->pollival = 1;       /* assume this; doesn't really matter */
2068                 /* and fall... */
2069         case Tintr:
2070                 io = ep->aux = smalloc(sizeof(Qio)*2);
2071                 io[OREAD].debug = io[OWRITE].debug = ep->debug;
2072                 usbid = (ep->nb&Epmax)<<7 | (ep->dev->nb&Devmax);
2073                 if(ep->mode != OREAD){
2074                         if(ep->toggle[OWRITE] != 0)
2075                                 io[OWRITE].toggle = Tddata1;
2076                         else
2077                                 io[OWRITE].toggle = Tddata0;
2078                         io[OWRITE].tok = Tdtokout;
2079                         io[OWRITE].usbid = usbid;
2080                         io[OWRITE].bw = ep->maxpkt*1000/ep->pollival; /* bytes/s */
2081                         newed(ctlr, ep, io+OWRITE, "epw");
2082                 }
2083                 if(ep->mode != OWRITE){
2084                         if(ep->toggle[OREAD] != 0)
2085                                 io[OREAD].toggle = Tddata1;
2086                         else
2087                                 io[OREAD].toggle = Tddata0;
2088                         io[OREAD].tok = Tdtokin;
2089                         io[OREAD].usbid = usbid;
2090                         io[OREAD].bw = ep->maxpkt*1000/ep->pollival; /* bytes/s */
2091                         newed(ctlr, ep, io+OREAD, "epr");
2092                 }
2093                 break;
2094         }
2095         deprint("ohci: epopen done:\n");
2096         if(debug || ep->debug)
2097                 dump(ep->hp);
2098         poperror();
2099 }
2100
2101 static void
2102 cancelio(Ep *ep, Qio *io)
2103 {
2104         Ed *ed;
2105         Ctlr *ctlr;
2106
2107         ctlr = ep->hp->aux;
2108
2109         ilock(ctlr);
2110         if(io == nil || io->state == Qclose){
2111                 assert(io == nil || io->ed == nil);
2112                 iunlock(ctlr);
2113                 return;
2114         }
2115         ed = io->ed;
2116         io->state = Qclose;
2117         io->err = Eio;
2118         aborttds(io);
2119         iunlock(ctlr);
2120         if(!waserror()){
2121                 tsleep(&up->sleep, return0, 0, Abortdelay);
2122                 poperror();
2123         }
2124
2125         wakeup(io);
2126         qlock(io);
2127         /* wait for epio if running */
2128         qunlock(io);
2129
2130         ilock(ctlr);
2131         switch(ep->ttype){
2132         case Tctl:
2133                 unlinkctl(ctlr, ed);
2134                 break;
2135         case Tbulk:
2136                 unlinkbulk(ctlr, ed);
2137                 break;
2138         case Tintr:
2139         case Tiso:
2140                 unschedq(ctlr, io);
2141                 break;
2142         default:
2143                 panic("ohci cancelio: bad ttype");
2144         }
2145         iunlock(ctlr);
2146         edfree(io->ed);
2147         io->ed = nil;
2148 }
2149
2150 static void
2151 epclose(Ep *ep)
2152 {
2153         Ctlio *cio;
2154         Isoio *iso;
2155         Qio *io;
2156
2157         deprint("ohci: epclose ep%d.%d\n", ep->dev->nb, ep->nb);
2158         if(ep->aux == nil)
2159                 panic("ohci: epclose called with closed ep");
2160         switch(ep->ttype){
2161         case Tctl:
2162                 cio = ep->aux;
2163                 cancelio(ep, cio);
2164                 free(cio->data);
2165                 cio->data = nil;
2166                 break;
2167         case Tbulk:
2168         case Tintr:
2169                 io = ep->aux;
2170                 if(ep->mode != OWRITE){
2171                         cancelio(ep, &io[OREAD]);
2172                         if(io[OREAD].toggle == Tddata1)
2173                                 ep->toggle[OREAD] = 1;
2174                 }
2175                 if(ep->mode != OREAD){
2176                         cancelio(ep, &io[OWRITE]);
2177                         if(io[OWRITE].toggle == Tddata1)
2178                                 ep->toggle[OWRITE] = 1;
2179                 }
2180                 break;
2181         case Tiso:
2182                 iso = ep->aux;
2183                 cancelio(ep, iso);
2184                 break;
2185         default:
2186                 panic("epclose: bad ttype %d", ep->ttype);
2187         }
2188
2189         deprint("ohci: epclose ep%d.%d: done\n", ep->dev->nb, ep->nb);
2190         free(ep->aux);
2191         ep->aux = nil;
2192 }
2193
2194 static int
2195 portreset(Hci *hp, int port, int on)
2196 {
2197         Ctlr *ctlr;
2198         Ohci *ohci;
2199
2200         if(on == 0)
2201                 return 0;
2202
2203         ctlr = hp->aux;
2204         eqlock(&ctlr->resetl);
2205         if(waserror()){
2206                 qunlock(&ctlr->resetl);
2207                 nexterror();
2208         }
2209         ilock(ctlr);
2210         ohci = ctlr->ohci;
2211         ohci->rhportsts[port - 1] = Spp;
2212         if((ohci->rhportsts[port - 1] & Ccs) == 0){
2213                 iunlock(ctlr);
2214                 error("port not connected");
2215         }
2216         ohci->rhportsts[port - 1] = Spr;
2217         while((ohci->rhportsts[port - 1] & Prsc) == 0){
2218                 iunlock(ctlr);
2219                 dprint("ohci: portreset, wait for reset complete\n");
2220                 ilock(ctlr);
2221         }
2222         ohci->rhportsts[port - 1] = Prsc;
2223         iunlock(ctlr);
2224         poperror();
2225         qunlock(&ctlr->resetl);
2226         return 0;
2227 }
2228
2229 static int
2230 portenable(Hci *hp, int port, int on)
2231 {
2232         Ctlr *ctlr;
2233
2234         ctlr = hp->aux;
2235         dprint("ohci: %#p port %d enable=%d\n", ctlr->ohci, port, on);
2236         eqlock(&ctlr->resetl);
2237         if(waserror()){
2238                 qunlock(&ctlr->resetl);
2239                 nexterror();
2240         }
2241         ilock(ctlr);
2242         if(on)
2243                 ctlr->ohci->rhportsts[port - 1] = Spe | Spp;
2244         else
2245                 ctlr->ohci->rhportsts[port - 1] = Cpe;
2246         iunlock(ctlr);
2247         tsleep(&up->sleep, return0, 0, Enabledelay);
2248         poperror();
2249         qunlock(&ctlr->resetl);
2250         return 0;
2251 }
2252
2253 static int
2254 portstatus(Hci *hp, int port)
2255 {
2256         int v;
2257         Ctlr *ub;
2258         ulong ohcistatus;
2259
2260         /*
2261          * We must return status bits as a
2262          * get port status hub request would do.
2263          */
2264         ub = hp->aux;
2265         ohcistatus = ub->ohci->rhportsts[port - 1];
2266         v = 0;
2267         if(ohcistatus & Ccs)
2268                 v |= HPpresent;
2269         if(ohcistatus & Pes)
2270                 v |= HPenable;
2271         if(ohcistatus & Pss)
2272                 v |= HPsuspend;
2273         if(ohcistatus & Prs)
2274                 v |= HPreset;
2275         else {
2276                 /* port is not in reset; these potential writes are ok */
2277                 if(ohcistatus & Csc){
2278                         v |= HPstatuschg;
2279                         ub->ohci->rhportsts[port - 1] = Csc;
2280                 }
2281                 if(ohcistatus & Pesc){
2282                         v |= HPchange;
2283                         ub->ohci->rhportsts[port - 1] = Pesc;
2284                 }
2285         }
2286         if(ohcistatus & Lsda)
2287                 v |= HPslow;
2288         if(v & (HPstatuschg|HPchange))
2289                 ddprint("ohci port %d sts %#ulx hub sts %#x\n", port, ohcistatus, v);
2290         return v;
2291 }
2292
2293 static void
2294 dumpohci(Ctlr *ctlr)
2295 {
2296         int i;
2297         ulong *ohci;
2298
2299         ohci = &ctlr->ohci->revision;
2300         print("ohci registers: \n");
2301         for(i = 0; i < sizeof(Ohci)/sizeof(ulong); i++)
2302                 if(i < 3 || ohci[i] != 0)
2303                         print("\t[%#2.2x]\t%#8.8ulx\n", i * 4, ohci[i]);
2304         print("\n");
2305 }
2306
2307 static void
2308 init(Hci *hp)
2309 {
2310         Ctlr *ctlr;
2311         Ohci *ohci;
2312         int i;
2313         ulong ival, ctrl, fmi;
2314
2315         ctlr = hp->aux;
2316         dprint("ohci %#p init\n", ctlr->ohci);
2317         ohci = ctlr->ohci;
2318
2319         fmi = ohci->fminterval;
2320         ohci->cmdsts = Shcr;    /* reset the block */
2321         for(i = 0; i<100; i++){
2322                 if((ohci->cmdsts & Shcr) == 0)
2323                         break;
2324                 delay(1);       /* wait till reset complete, Ohci says 10us max. */
2325         }
2326         if(i == 100)
2327                 print("ohci: reset timed out\n");
2328         ohci->fminterval = fmi;
2329
2330         /*
2331          * now that soft reset is done we are in suspend state.
2332          * Setup registers which take in suspend state
2333          * (will only be here for 2ms).
2334          */
2335
2336         ctlr->ohci->hcca = ptr2pa(ctlr->hcca);
2337         setctlhd(ctlr, nil);
2338         ctlr->ohci->ctlcurred = 0;
2339         setbulkhd(ctlr, nil);
2340         ctlr->ohci->bulkcurred = 0;
2341
2342         ohci->intrenable = Mie | Wdh | Ue;
2343         ohci->control |= Ccle | Cble | Cple | Cie | Cfsoper;
2344
2345         /* set frame after operational */
2346         ohci->rhdesca = Nps;    /* no power switching */
2347         if(ohci->rhdesca & Nps){
2348                 dprint("ohci: ports are not power switched\n");
2349         }else{
2350                 dprint("ohci: ports are power switched\n");
2351                 ohci->rhdesca &= ~Psm;
2352                 ohci->rhsts &= ~Lpsc;
2353         }
2354         for(i = 0; i < ctlr->nports; i++)       /* paranoia */
2355                 ohci->rhportsts[i] = 0;         /* this has no effect */
2356         delay(50);
2357
2358         for(i = 0; i < ctlr->nports; i++){
2359                 ohci->rhportsts[i] =  Spp;
2360                 if((ohci->rhportsts[i] & Ccs) != 0)
2361                         ohci->rhportsts[i] |= Spr;
2362         }
2363         delay(100);
2364
2365         ctrl = ohci->control;
2366         if((ctrl & Cfsmask) != Cfsoper){
2367                 ctrl = (ctrl & ~Cfsmask) | Cfsoper;
2368                 ohci->control = ctrl;
2369                 ohci->rhsts = Lpsc;
2370         }
2371         ival = ohci->fminterval & ~(Fmaxpktmask << Fmaxpktshift);
2372         ohci->fminterval = ival | (5120 << Fmaxpktshift);
2373
2374         if(debug > 1)
2375                 dumpohci(ctlr);
2376 }
2377
2378 static void
2379 scanpci(void)
2380 {
2381         ulong mem;
2382         Ctlr *ctlr;
2383         Pcidev *p;
2384         int i;
2385         static int already = 0;
2386
2387         if(already)
2388                 return;
2389         already = 1;
2390         p = nil;
2391         while(p = pcimatch(p, 0, 0)) {
2392                 /*
2393                  * Find Ohci controllers (Programming Interface = 0x10).
2394                  */
2395                 if(p->ccrb != Pcibcserial || p->ccru != Pciscusb ||
2396                     p->ccrp != 0x10)
2397                         continue;
2398                 mem = p->mem[0].bar & ~0x0F;
2399                 dprint("ohci: %x/%x port 0x%lux size 0x%x irq %d\n",
2400                         p->vid, p->did, mem, p->mem[0].size, p->intl);
2401                 if(mem == 0){
2402                         print("ohci: failed to map registers\n");
2403                         continue;
2404                 }
2405
2406                 ctlr = malloc(sizeof(Ctlr));
2407                 if(ctlr == nil){
2408                         print("ohci: no memory\n");
2409                         continue;
2410                 }
2411                 ctlr->pcidev = p;
2412                 ctlr->ohci = vmap(mem, p->mem[0].size);
2413                 dprint("scanpci: ctlr %#p, ohci %#p\n", ctlr, ctlr->ohci);
2414                 pcisetbme(p);
2415                 pcisetpms(p, 0);
2416                 for(i = 0; i < Nhcis; i++)
2417                         if(ctlrs[i] == nil){
2418                                 ctlrs[i] = ctlr;
2419                                 break;
2420                         }
2421                 if(i == Nhcis)
2422                         print("ohci: bug: no more controllers\n");
2423         }
2424 }
2425
2426 static void
2427 usbdebug(Hci*, int d)
2428 {
2429         debug = d;
2430 }
2431
2432 /*
2433  * build the periodic scheduling tree:
2434  * framesize must be a multiple of the tree size
2435  */
2436 static void
2437 mkqhtree(Ctlr *ctlr)
2438 {
2439         int i, n, d, o, leaf0, depth;
2440         Ed **tree;
2441         Qtree *qt;
2442
2443         depth = flog2(32);
2444         n = (1 << (depth+1)) - 1;
2445         qt = mallocz(sizeof(*qt), 1);
2446         if(qt == nil)
2447                 panic("ohci: can't allocate scheduling tree");
2448         qt->nel = n;
2449         qt->depth = depth;
2450         qt->bw = mallocz(n * sizeof(qt->bw), 1);
2451         qt->root = tree = mallocz(n * sizeof(Ed *), 1);
2452         if(qt->bw == nil || qt->root == nil)
2453                 panic("ohci: can't allocate scheduling tree");
2454         for(i = 0; i < n; i++){
2455                 if((tree[i] = edalloc()) == nil)
2456                         panic("ohci: mkqhtree");
2457                 tree[i]->ctrl = (8 << Edmpsshift);      /* not needed */
2458                 tree[i]->ctrl |= Edskip;
2459
2460                 if(i > 0)
2461                         edlinked(tree[i], tree[(i-1)/2]);
2462                 else
2463                         edlinked(tree[i], nil);
2464         }
2465         ctlr->ntree = i;
2466         dprint("ohci: tree: %d endpoints allocated\n", i);
2467
2468         /* distribute leaves evenly round the frame list */
2469         leaf0 = n / 2;
2470         for(i = 0; i < 32; i++){
2471                 o = 0;
2472                 for(d = 0; d < depth; d++){
2473                         o <<= 1;
2474                         if(i & (1 << d))
2475                                 o |= 1;
2476                 }
2477                 if(leaf0 + o >= n){
2478                         print("leaf0=%d o=%d i=%d n=%d\n", leaf0, o, i, n);
2479                         break;
2480                 }
2481                 ctlr->hcca->intrtable[i] = ptr2pa(tree[leaf0 + o]);
2482         }
2483         ctlr->tree = qt;
2484 }
2485
2486 static void
2487 ohcimeminit(Ctlr *ctlr)
2488 {
2489         Hcca *hcca;
2490
2491         edfree(edalloc());      /* allocate pools now */
2492         tdfree(tdalloc());
2493
2494         hcca = xspanalloc(sizeof(Hcca), 256, 0);
2495         if(hcca == nil)
2496                 panic("ohci: no memory for Hcca");
2497         memset(hcca, 0, sizeof(*hcca));
2498         ctlr->hcca = hcca;
2499
2500         mkqhtree(ctlr);
2501 }
2502
2503 static void
2504 ohcireset(Ctlr *ctlr)
2505 {
2506         int i;
2507
2508         ilock(ctlr);
2509         dprint("ohci %#p reset\n", ctlr->ohci);
2510
2511         if(ctlr->ohci->control & Cir){
2512                 dprint("ohci: smm active, taking over\n");
2513                 ctlr->ohci->cmdsts |= Socr;         /* take ownership */
2514                 for(i = 0; i<100; i++){
2515                         if((ctlr->ohci->control & Cir) == 0)
2516                                 break;
2517                         delay(1);
2518                 }
2519                 if(i == 100)
2520                         print("ohci: smm takeover timed out\n");
2521         }
2522
2523         /*
2524          * usually enter here in reset, wait till its through,
2525          * then do our own so we are on known timing conditions.
2526          * Is this needed?
2527          */
2528         delay(100);
2529         ctlr->ohci->control = 0;
2530         delay(100);
2531
2532         /* legacy support register: turn off lunacy mode */
2533         pcicfgw16(ctlr->pcidev, 0xc0, 0x2000);
2534
2535         iunlock(ctlr);
2536 }
2537
2538 static void
2539 shutdown(Hci *hp)
2540 {
2541         Ctlr *ctlr;
2542
2543         ctlr = hp->aux;
2544
2545         ilock(ctlr);
2546         ctlr->ohci->intrdisable = Mie;
2547         ctlr->ohci->intrenable = 0;
2548         ctlr->ohci->control = 0;
2549         delay(100);
2550         iunlock(ctlr);
2551 }
2552
2553 static int
2554 reset(Hci *hp)
2555 {
2556         int i;
2557         Ctlr *ctlr;
2558         Pcidev *p;
2559         static Lock resetlck;
2560
2561         if(getconf("*nousbohci"))
2562                 return -1;
2563         ilock(&resetlck);
2564         scanpci();
2565
2566         /*
2567          * Any adapter matches if no hp->port is supplied,
2568          * otherwise the ports must match.
2569          */
2570         ctlr = nil;
2571         for(i = 0; i < Nhcis && ctlrs[i] != nil; i++){
2572                 ctlr = ctlrs[i];
2573                 if(ctlr->active == 0)
2574                 if(hp->port == 0 || hp->port == PADDR(ctlr->ohci)){
2575                         ctlr->active = 1;
2576                         break;
2577                 }
2578         }
2579         iunlock(&resetlck);
2580         if(ctlrs[i] == nil || i == Nhcis)
2581                 return -1;
2582         if(ctlr->ohci->control == ~0)
2583                 return -1;
2584
2585
2586         p = ctlr->pcidev;
2587         hp->aux = ctlr;
2588         hp->port = PADDR(ctlr->ohci);
2589         hp->irq = p->intl;
2590         hp->tbdf = p->tbdf;
2591         ctlr->nports = hp->nports = ctlr->ohci->rhdesca & 0xff;
2592
2593         ohcireset(ctlr);
2594         ohcimeminit(ctlr);
2595
2596         /*
2597          * Linkage to the generic HCI driver.
2598          */
2599         hp->init = init;
2600         hp->dump = dump;
2601         hp->interrupt = interrupt;
2602         hp->epopen = epopen;
2603         hp->epclose = epclose;
2604         hp->epread = epread;
2605         hp->epwrite = epwrite;
2606         hp->seprintep = seprintep;
2607         hp->portenable = portenable;
2608         hp->portreset = portreset;
2609         hp->portstatus = portstatus;
2610         hp->shutdown = shutdown;
2611         hp->debug = usbdebug;
2612         hp->type = "ohci";
2613
2614         /*
2615          * IRQ2 doesn't really exist, it's used to gang the interrupt
2616          * controllers together. A device set to IRQ2 will appear on
2617          * the second interrupt controller as IRQ9.
2618          */
2619         if(hp->irq == 2)
2620                 hp->irq = 9;
2621         intrenable(hp->irq, hp->interrupt, hp, hp->tbdf, hp->type);
2622
2623         return 0;
2624 }
2625
2626 void
2627 usbohcilink(void)
2628 {
2629         addhcitype("ohci", reset);
2630 }