]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/pc/usbohci.c
merge
[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         Align           = 0x20,         /* OHCI only requires 0x10 */
41                                         /* use always a power of 2 */
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         Td *td;
585         Td *pool;
586         int i;
587
588         lock(&tdpool);
589         if(tdpool.free == nil){
590                 ddprint("ohci: tdalloc %d Tds\n", Incr);
591                 pool = xspanalloc(Incr*sizeof(Td), Align, 0);
592                 if(pool == nil)
593                         panic("ohci: tdalloc");
594                 for(i=Incr; --i>=0;){
595                         pool[i].next = tdpool.free;
596                         tdpool.free = &pool[i];
597                 }
598                 tdpool.nalloc += Incr;
599                 tdpool.nfree += Incr;
600         }
601         tdpool.ninuse++;
602         tdpool.nfree--;
603         td = tdpool.free;
604         tdpool.free = td->next;
605         memset(td, 0, sizeof(Td));
606         unlock(&tdpool);
607
608         assert(((uintptr)td & 0xF) == 0);
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         Ed *ed, *pool;
634         int i;
635
636         lock(&edpool);
637         if(edpool.free == nil){
638                 ddprint("ohci: edalloc %d Eds\n", Incr);
639                 pool = xspanalloc(Incr*sizeof(Ed), Align, 0);
640                 if(pool == nil)
641                         panic("ohci: edalloc");
642                 for(i=Incr; --i>=0;){
643                         pool[i].next = edpool.free;
644                         edpool.free = &pool[i];
645                 }
646                 edpool.nalloc += Incr;
647                 edpool.nfree += Incr;
648         }
649         edpool.ninuse++;
650         edpool.nfree--;
651         ed = edpool.free;
652         edpool.free = ed->next;
653         memset(ed, 0, sizeof(Ed));
654         unlock(&edpool);
655
656         return ed;
657 }
658
659 static void
660 edfree(Ed *ed)
661 {
662         Td *td, *next;
663         int i;
664
665         if(ed == 0)
666                 return;
667         i = 0;
668         for(td = ed->tds; td != nil; td = next){
669                 next = td->next;
670                 tdfree(td);
671                 if(i++ > 2000){
672                         print("ohci: bug: ed with more than 2000 tds\n");
673                         break;
674                 }
675         }
676         lock(&edpool);
677         if(ed->nexted == 0x99999999)
678                 panic("ohci: edfree: double free");
679         memset(ed, 9, sizeof(Ed));      /* poison */
680         ed->next = edpool.free;
681         edpool.free = ed;
682         edpool.ninuse--;
683         edpool.nfree++;
684         unlock(&edpool);
685         ddprint("edfree: ed %#p\n", ed);
686 }
687
688 /*
689  * return smallest power of 2 >= n
690  */
691 static int
692 flog2(int n)
693 {
694         int i;
695
696         for(i = 0; (1 << i) < n; i++)
697                 ;
698         return i;
699 }
700
701 /*
702  * return smallest power of 2 <= n
703  */
704 static int
705 flog2lower(int n)
706 {
707         int i;
708
709         for(i = 0; (1 << (i + 1)) <= n; i++)
710                 ;
711         return i;
712 }
713
714 static int
715 pickschedq(Qtree *qt, int pollival, ulong bw, ulong limit)
716 {
717         int i, j, d, upperb, q;
718         ulong best, worst, total;
719
720         d = flog2lower(pollival);
721         if(d > qt->depth)
722                 d = qt->depth;
723         q = -1;
724         worst = 0;
725         best = ~0;
726         upperb = (1 << (d+1)) - 1;
727         for(i = (1 << d) - 1; i < upperb; i++){
728                 total = qt->bw[0];
729                 for(j = i; j > 0; j = (j - 1) / 2)
730                         total += qt->bw[j];
731                 if(total < best){
732                         best = total;
733                         q = i;
734                 }
735                 if(total > worst)
736                         worst = total;
737         }
738         if(worst + bw >= limit)
739                 return -1;
740         return q;
741 }
742
743 static int
744 schedq(Ctlr *ctlr, Qio *io, int pollival)
745 {
746         int q;
747         Ed *ted;
748
749         q = pickschedq(ctlr->tree, pollival, io->bw, ~0);
750         ddqprint("ohci: sched %#p q %d, ival %d, bw %ld\n", io, q, pollival, io->bw);
751         if(q < 0){
752                 print("ohci: no room for ed\n");
753                 return -1;
754         }
755         ctlr->tree->bw[q] += io->bw;
756         ted = ctlr->tree->root[q];
757         io->sched = q;
758         edlinked(io->ed, ted->next);
759         edlinked(ted, io->ed);
760         io->ed->inext = ctlr->intrhd;
761         ctlr->intrhd = io->ed;
762         return 0;
763 }
764
765 static void
766 unschedq(Ctlr *ctlr, Qio *qio)
767 {
768         int q;
769         Ed *prev, *this, *next;
770         Ed **l;
771
772         q = qio->sched;
773         if(q < 0)
774                 return;
775         ctlr->tree->bw[q] -= qio->bw;
776
777         prev = ctlr->tree->root[q];
778         this = prev->next;
779         while(this != nil && this != qio->ed){
780                 prev = this;
781                 this = this->next;
782         }
783         if(this == nil)
784                 print("ohci: unschedq %d: not found\n", q);
785         else{
786                 next = this->next;
787                 edlinked(prev, next);
788         }
789         waitSOF(ctlr);
790         for(l = &ctlr->intrhd; *l != nil; l = &(*l)->inext)
791                 if(*l == qio->ed){
792                         *l = (*l)->inext;
793                         return;
794                 }
795         print("ohci: unschedq: ed %#p not found\n", qio->ed);
796 }
797
798 static char*
799 seprinttdtok(char *s, char *e, int tok)
800 {
801         switch(tok){
802         case Tdtoksetup:
803                 s = seprint(s, e, " setup");
804                 break;
805         case Tdtokin:
806                 s = seprint(s, e, " in");
807                 break;
808         case Tdtokout:
809                 s = seprint(s, e, " out");
810                 break;
811         }
812         return s;
813 }
814
815
816 static char*
817 seprinttd(char *s, char *e, Td *td, int iso)
818 {
819         int i;
820         Block *bp;
821
822         if(td == nil)
823                 return seprint(s, e, "<nil td>\n");
824         s = seprint(s, e, "%#p ep %#p ctrl %#p", td, td->ep, td->ctrl);
825         s = seprint(s, e, " cc=%#ulx", (td->ctrl >> Tdccshift) & Tdccmask);
826         if(iso == 0){
827                 if((td->ctrl & Tdround) != 0)
828                         s = seprint(s, e, " rnd");
829                 s = seprinttdtok(s, e, td->ctrl & Tdtokmask);
830                 if((td->ctrl & Tdusetog) != 0)
831                         s = seprint(s, e, " d%d", (td->ctrl & Tddata1) ? 1 : 0);
832                 else
833                         s = seprint(s, e, " d-");
834                 s = seprint(s, e, " ec=%uld", (td->ctrl >> Tderrshift) & Tderrmask);
835         }else{
836                 s = seprint(s, e, " fc=%uld", (td->ctrl >> Tdfcshift) & Tdfcmask);
837                 s = seprint(s, e, " sf=%uld", td->ctrl & Tdsfmask);
838         }
839         s = seprint(s, e, " cbp0 %#p cbp %#p next %#p be %#p %s",
840                 td->cbp0, td->cbp, td->nexttd, td->be, td->last ? "last" : "");
841         s = seprint(s, e, "\n\t\t%ld bytes", td->nbytes);
842         if((bp = td->bp) != nil){
843                 s = seprint(s, e, " rp %#p wp %#p ", bp->rp, bp->wp);
844                 if(BLEN(bp) > 0)
845                         s = seprintdata(s, e, bp->rp, bp->wp - bp->rp);
846         }
847         if(iso == 0)
848                 return seprint(s, e, "\n");
849         s = seprint(s, e, "\n\t\t");
850         /* we use only offsets[0] */
851         i = 0;
852         s = seprint(s, e, "[%d] %#ux cc=%#ux sz=%ud\n", i, td->offsets[i],
853                 (td->offsets[i] >> Tdiccshift) & Tdiccmask,
854                 td->offsets[i] & 0x7FF);
855         return s;
856 }
857
858 static void
859 dumptd(Td *td, char *p, int iso)
860 {
861         static char buf[512];   /* Too much */
862         char *s;
863
864         s = seprint(buf, buf+sizeof(buf), "%s: ", p);
865         s = seprinttd(s, buf+sizeof(buf), td, iso);
866         if(s > buf && s[-1] != '\n')
867                 s[-1] = '\n';
868         print("\t%s", buf);
869 }
870
871 static void
872 dumptds(Td *td, char *p, int iso)
873 {
874         int i;
875
876         for(i = 0; td != nil; td = td->next){
877                 dumptd(td, p, iso);
878                 if(td->last)
879                         break;
880                 if(tdtok(td) == Tdtokin && ++i > 2){
881                         print("\t\t...\n");
882                         break;
883                 }
884         }
885 }
886
887 static void
888 dumped(Ed *ed)
889 {
890         char *buf, *s, *e;
891
892         if(ed == nil){
893                 print("<null ed>\n");
894                 return;
895         }
896         buf = malloc(512);
897         /* no waserror; may want to use from interrupt context */
898         if(buf == nil)
899                 return;
900         e = buf+512;
901         s = seprint(buf, e, "\ted %#p: ctrl %#p", ed, ed->ctrl);
902         if((ed->ctrl & Edskip) != 0)
903                 s = seprint(s, e, " skip");
904         if((ed->ctrl & Ediso) != 0)
905                 s = seprint(s, e, " iso");
906         if((ed->ctrl & Edlow) != 0)
907                 s = seprint(s, e, " low");
908         s = seprint(s, e, " d%d", (ed->head & Edtoggle) ? 1 : 0);
909         if((ed->ctrl & Eddirmask) == Edin)
910                 s = seprint(s, e, " in");
911         if((ed->ctrl & Eddirmask) == Edout)
912                 s = seprint(s, e, " out");
913         if(edhalted(ed))
914                 s = seprint(s, e, " hlt");
915         s = seprint(s, e, " ep%uld.%uld", (ed->ctrl>>7)&Epmax, ed->ctrl&0x7f);
916         s = seprint(s, e, " maxpkt %uld", (ed->ctrl>>Edmpsshift)&Edmpsmask);
917         seprint(s, e, " tail %#p head %#p next %#p\n",ed->tail,ed->head,ed->nexted);
918         print("%s", buf);
919         free(buf);
920         if(ed->tds != nil && (ed->ctrl & Ediso) == 0)
921                 dumptds(ed->tds, "td", 0);
922 }
923
924 static char*
925 seprintio(char *s, char *e, Qio *io, char *pref)
926 {
927         s = seprint(s, e, "%s qio %#p ed %#p", pref, io, io->ed);
928         s = seprint(s, e, " tog %d iot %ld err %s id %#ulx",
929                 io->toggle, io->iotime, io->err, io->usbid);
930         s = seprinttdtok(s, e, io->tok);
931         s = seprint(s, e, " %s\n", iosname[io->state]);
932         return s;
933 }
934
935 static char*
936 seprintep(char* s, char* e, Ep *ep)
937 {
938         Isoio *iso;
939         Qio *io;
940         Ctlio *cio;
941
942         if(ep == nil)
943                 return seprint(s, e, "<nil ep>\n");
944         if(ep->aux == nil)
945                 return seprint(s, e, "no mdep\n");
946         switch(ep->ttype){
947         case Tctl:
948                 cio = ep->aux;
949                 s = seprintio(s, e, cio, "c");
950                 s = seprint(s, e, "\trepl %d ndata %d\n", ep->rhrepl, cio->ndata);
951                 break;
952         case Tbulk:
953         case Tintr:
954                 io = ep->aux;
955                 if(ep->mode != OWRITE)
956                         s = seprintio(s, e, &io[OREAD], "r");
957                 if(ep->mode != OREAD)
958                         s = seprintio(s, e, &io[OWRITE], "w");
959                 break;
960         case Tiso:
961                 iso = ep->aux;
962                 s = seprintio(s, e, iso, "w");
963                 s = seprint(s, e, "\tntds %d avail %d frno %uld left %uld next avail %#p\n",
964                         iso->nframes, iso->navail, iso->frno, iso->left, iso->atds);
965                 break;
966         }
967         return s;
968 }
969
970 static char*
971 seprintctl(char *s, char *se, ulong ctl)
972 {
973         s = seprint(s, se, "en=");
974         if((ctl&Cple) != 0)
975                 s = seprint(s, se, "p");
976         if((ctl&Cie) != 0)
977                 s = seprint(s, se, "i");
978         if((ctl&Ccle) != 0)
979                 s = seprint(s, se, "c");
980         if((ctl&Cble) != 0)
981                 s = seprint(s, se, "b");
982         switch(ctl & Cfsmask){
983         case Cfsreset:
984                 return seprint(s, se, " reset");
985         case Cfsresume:
986                 return seprint(s, se, " resume");
987         case Cfsoper:
988                 return seprint(s, se, " run");
989         case Cfssuspend:
990                 return seprint(s, se, " suspend");
991         default:
992                 return seprint(s, se, " ???");
993         }
994 }
995
996 static void
997 dump(Hci *hp)
998 {
999         Ctlr *ctlr;
1000         Ed *ed;
1001         char cs[20];
1002
1003         ctlr = hp->aux;
1004         ilock(ctlr);
1005         seprintctl(cs, cs+sizeof(cs), ctlr->ohci->control);
1006         print("ohci ctlr %#p: frno %#ux ctl %#lux %s sts %#lux intr %#lux\n",
1007                 ctlr, ctlr->hcca->framenumber, ctlr->ohci->control, cs,
1008                 ctlr->ohci->cmdsts, ctlr->ohci->intrsts);
1009         print("ctlhd %#ulx cur %#ulx bulkhd %#ulx cur %#ulx done %#ulx\n",
1010                 ctlr->ohci->ctlheaded, ctlr->ohci->ctlcurred,
1011                 ctlr->ohci->bulkheaded, ctlr->ohci->bulkcurred,
1012                 ctlr->ohci->donehead);
1013         if(ctlhd(ctlr) != nil)
1014                 print("[ctl]\n");
1015         for(ed = ctlhd(ctlr); ed != nil; ed = ed->next)
1016                 dumped(ed);
1017         if(bulkhd(ctlr) != nil)
1018                 print("[bulk]\n");
1019         for(ed = bulkhd(ctlr); ed != nil; ed = ed->next)
1020                 dumped(ed);
1021         if(ctlr->intrhd != nil)
1022                 print("[intr]\n");
1023         for(ed = ctlr->intrhd; ed != nil; ed = ed->inext)
1024                 dumped(ed);
1025         if(ctlr->tree->root[0]->next != nil)
1026                 print("[iso]");
1027         for(ed = ctlr->tree->root[0]->next; ed != nil; ed = ed->next)
1028                 dumped(ed);
1029         print("%d eds in tree\n", ctlr->ntree);
1030         iunlock(ctlr);
1031         lock(&tdpool);
1032         print("%d tds allocated = %d in use + %d free\n",
1033                 tdpool.nalloc, tdpool.ninuse, tdpool.nfree);
1034         unlock(&tdpool);
1035         lock(&edpool);
1036         print("%d eds allocated = %d in use + %d free\n",
1037                 edpool.nalloc, edpool.ninuse, edpool.nfree);
1038         unlock(&edpool);
1039 }
1040
1041 /*
1042  * Compute size for the next iso Td and setup its
1043  * descriptor for I/O according to the buffer size.
1044  */
1045 static void
1046 isodtdinit(Ep *ep, Isoio *iso, Td *td)
1047 {
1048         Block *bp;
1049         long size;
1050         int i;
1051
1052         bp = td->bp;
1053         assert(bp != nil && BLEN(bp) == 0);
1054         size = (ep->hz+iso->left) * ep->pollival / 1000;
1055         iso->left = (ep->hz+iso->left) * ep->pollival % 1000;
1056         size *= ep->samplesz;
1057         if(size > ep->maxpkt){
1058                 print("ohci: ep%d.%d: size > maxpkt\n",
1059                         ep->dev->nb, ep->nb);
1060                 print("size = %uld max = %ld\n", size, ep->maxpkt);
1061                 size = ep->maxpkt;
1062         }
1063         td->nbytes = size;
1064         memset(bp->wp, 0, size);        /* in case we don't fill it on time */
1065         td->cbp0 = td->cbp = ptr2pa(bp->rp) & ~0xFFF;
1066         td->ctrl = TRUNC(iso->frno, Ntdframes);
1067         td->offsets[0] = (ptr2pa(bp->rp) & 0xFFF);
1068         td->offsets[0] |= (Tdnotacc << Tdiccshift);
1069         /* in case the controller checks out the offests... */
1070         for(i = 1; i < nelem(td->offsets); i++)
1071                 td->offsets[i] = td->offsets[0];
1072         td->be = ptr2pa(bp->rp + size - 1);
1073         td->ctrl |= (0 << Tdfcshift);   /* frame count is 1 */
1074
1075         iso->frno = TRUNC(iso->frno + ep->pollival, Ntdframes);
1076 }
1077
1078 /*
1079  * start I/O on the dummy td and setup a new dummy to fill up.
1080  */
1081 static void
1082 isoadvance(Ep *ep, Isoio *iso, Td *td)
1083 {
1084         Td *dtd;
1085
1086         dtd = iso->atds;
1087         iso->atds = dtd->anext;
1088         iso->navail--;
1089         dtd->anext = nil;
1090         dtd->bp->wp = dtd->bp->rp;
1091         dtd->nexttd = 0;
1092         td->nexttd = ptr2pa(dtd);
1093         isodtdinit(ep, iso, dtd);
1094         iso->ed->tail = ptr2pa(dtd);
1095 }
1096
1097 static int
1098 isocanwrite(void *a)
1099 {
1100         Isoio *iso;
1101
1102         iso = a;
1103         return iso->state == Qclose || iso->err != nil ||
1104                 iso->navail > iso->nframes / 2;
1105 }
1106
1107 static int
1108 isodelay(void *a)
1109 {
1110         Isoio *iso;
1111
1112         iso = a;
1113         if(iso->state == Qclose || iso->err != nil || iso->delay == 0)
1114                 return 1;
1115         return (iso->nframes - iso->navail) <= iso->delay;
1116 }
1117
1118 /*
1119  * Service a completed/failed Td from the done queue.
1120  * It may be of any transfer type.
1121  * The queue is not in completion order.
1122  * (It's actually in reverse completion order).
1123  *
1124  * When an error, a short packet, or a last Td is found
1125  * we awake the process waiting for the transfer.
1126  * Although later we will process other Tds completed
1127  * before, epio won't be able to touch the current Td
1128  * until interrupt returns and releases the lock on the
1129  * controller.
1130  */
1131 static void
1132 qhinterrupt(Ctlr *, Ep *ep, Qio *io, Td *td, int)
1133 {
1134         Block *bp;
1135         int mode, err;
1136         Ed *ed;
1137
1138         ed = io->ed;
1139         if(io->state != Qrun)
1140                 return;
1141         if(tdtok(td) == Tdtokin)
1142                 mode = OREAD;
1143         else
1144                 mode = OWRITE;
1145         bp = td->bp;
1146         err = tderrs(td);
1147
1148         switch(err){
1149         case Tddataovr:                 /* Overrun is not an error */
1150         case Tdok:
1151                 /* virtualbox doesn't always report underflow on short packets */
1152                 if(td->cbp == 0)
1153                         break;
1154                 /* fall through */
1155         case Tddataund:
1156                 /* short input packets are ok */
1157                 if(mode == OREAD){
1158                         if(td->cbp == 0)
1159                                 panic("ohci: short packet but cbp == 0");
1160                         /*
1161                          * td->cbp and td->cbp0 are the real addresses
1162                          * corresponding to virtual addresses bp->wp and
1163                          * bp->rp respectively.
1164                          */
1165                         bp->wp = bp->rp + (td->cbp - td->cbp0);
1166                         if(bp->wp < bp->rp)
1167                                 panic("ohci: wp < rp");
1168                         /*
1169                          * It's ok. clear error and flag as last in xfer.
1170                          * epio must ignore following Tds.
1171                          */
1172                         td->last = 1;
1173                         td->ctrl &= ~(Tdccmask << Tdccshift);
1174                         break;
1175                 }
1176                 /* else fall; it's an error */
1177         case Tdcrc:
1178         case Tdbitstuff:
1179         case Tdbadtog:
1180         case Tdstalled:
1181         case Tdtmout:
1182         case Tdpidchk:
1183         case Tdbadpid:
1184                 bp->wp = bp->rp;        /* no bytes in xfer. */
1185                 io->err = errmsg(err);
1186                 if(debug || ep->debug){
1187                         print("tdinterrupt: failed err %d (%s)\n", err, io->err);
1188                         dumptd(td, "failed", ed->ctrl & Ediso);
1189                 }
1190                 td->last = 1;
1191                 break;
1192         default:
1193                 panic("ohci: td cc %ud unknown", err);
1194         }
1195
1196         if(td->last != 0){
1197                 /*
1198                  * clear td list and halt flag.
1199                  */
1200                 ed->head = (ed->head & Edtoggle) | ed->tail;
1201                 ed->tds = pa2ptr(ed->tail);
1202                 io->state = Qdone;
1203                 wakeup(io);
1204         }
1205 }
1206
1207 /*
1208  * BUG: Iso input streams are not implemented.
1209  */
1210 static void
1211 isointerrupt(Ctlr *ctlr, Ep *ep, Qio *io, Td *td, int)
1212 {
1213         Isoio *iso;
1214         Block *bp;
1215         Ed *ed;
1216         int err, isoerr;
1217
1218         iso = ep->aux;
1219         ed = io->ed;
1220         if(io->state == Qclose)
1221                 return;
1222         bp = td->bp;
1223         /*
1224          * When we get more than half the frames consecutive errors
1225          * we signal an actual error. Errors in the entire Td are
1226          * more serious and are always singaled.
1227          * Errors like overrun are not really errors. In fact, for
1228          * output, errors cannot be really detected. The driver will
1229          * hopefully notice I/O errors on input endpoints and detach the device.
1230          */
1231         err = tderrs(td);
1232         isoerr = (td->offsets[0] >> Tdiccshift) & Tdiccmask;
1233         if(isoerr == Tdok || isoerr == Tdnotacc)
1234                 iso->nerrs = 0;
1235         else if(iso->nerrs++ > iso->nframes/2)
1236                 err = Tdstalled;
1237         if(err != Tdok && err != Tddataovr){
1238                 bp->wp = bp->rp;
1239                 io->err = errmsg(err);
1240                 if(debug || ep->debug){
1241                         print("ohci: isointerrupt: ep%d.%d: err %d (%s) frnum 0x%lux\n",
1242                                 ep->dev->nb, ep->nb,
1243                                 err, errmsg(err), ctlr->ohci->fmnumber);
1244                         dumptd(td, "failed", ed->ctrl & Ediso);
1245                 }
1246         }
1247         td->bp->wp = td->bp->rp;
1248         td->nbytes = 0;
1249         td->anext = iso->atds;
1250         iso->atds = td;
1251         iso->navail++;
1252         /*
1253          * If almost all Tds are avail the user is not doing I/O at the
1254          * required rate. We put another Td in place to keep the polling rate.
1255          */
1256         if(iso->err == nil && iso->navail > iso->nframes - 10)
1257                 isoadvance(ep, iso, pa2ptr(iso->ed->tail));
1258         /*
1259          * If there's enough buffering futher I/O can be done.
1260          */
1261         if(isocanwrite(iso))
1262                 wakeup(iso);
1263 }
1264
1265 static void
1266 interrupt(Ureg *, void *arg)
1267 {
1268         Td *td, *ntd;
1269         Hci *hp;
1270         Ctlr *ctlr;
1271         ulong status, curred, done;
1272         int i, frno;
1273
1274         hp = arg;
1275         ctlr = hp->aux;
1276         ilock(ctlr);
1277         done = ctlr->hcca->donehead;
1278         status = ctlr->ohci->intrsts;
1279         if(status == ~0){
1280                 iunlock(ctlr);
1281                 return;
1282         }
1283         if(done & ~0xF){
1284                 ctlr->hcca->donehead = 0;
1285                 status |= Wdh;
1286         }
1287         else if(status & Wdh){
1288                 done = ctlr->hcca->donehead;
1289                 ctlr->hcca->donehead = 0;
1290         }
1291         status &= ~Mie;
1292         if(status == 0){
1293                 iunlock(ctlr);
1294                 return;
1295         }
1296         ctlr->ohci->intrsts = status;
1297         status &= ctlr->ohci->intrenable;
1298         status &= Oc|Rhsc|Fno|Ue|Rd|Sf|Wdh|So;
1299         if(status & Wdh){
1300                 frno = TRUNC(ctlr->ohci->fmnumber, Ntdframes);
1301                 td = pa2ptr(done & ~0xF);
1302                 for(i = 0; td != nil && i < 1024; i++){
1303                         if(0)ddprint("ohci tdinterrupt: td %#p\n", td);
1304                         ntd = pa2ptr(td->nexttd & ~0xF);
1305                         td->nexttd = 0;
1306                         if(td->ep == nil || td->io == nil)
1307                                 panic("ohci: interrupt: ep %#p io %#p", td->ep, td->io);
1308                         ohciinterrupts[td->ep->ttype]++;
1309                         if(td->ep->ttype == Tiso)
1310                                 isointerrupt(ctlr, td->ep, td->io, td, frno);
1311                         else
1312                                 qhinterrupt(ctlr, td->ep, td->io, td, frno);
1313                         td = ntd;
1314                 }
1315                 if(i == 1024)
1316                         iprint("ohci: bug: more than 1024 done Tds?\n");
1317                 status &= ~Wdh;
1318         }
1319         status &= ~Sf;
1320         if(status & So){
1321                 iprint("ohci: sched overrun: too much load\n");
1322                 ctlr->overrun++;
1323                 status &= ~So;
1324         }
1325         if(status & Ue){
1326                 curred = ctlr->ohci->periodcurred;
1327                 iprint("ohci: unrecoverable error frame 0x%.8lux ed 0x%.8lux, "
1328                         "ints %d %d %d %d\n",
1329                         ctlr->ohci->fmnumber, curred,
1330                         ohciinterrupts[Tctl], ohciinterrupts[Tintr],
1331                         ohciinterrupts[Tbulk], ohciinterrupts[Tiso]);
1332                 if(curred != 0)
1333                         dumped(pa2ptr(curred));
1334                 status &= ~Ue;
1335         }
1336         if(status != 0){
1337                 iprint("ohci interrupt: unhandled sts 0x%.8lux\n", status);
1338                 ctlr->ohci->intrdisable = status;
1339         }
1340         iunlock(ctlr);
1341 }
1342
1343 /*
1344  * The old dummy Td is used to implement the new Td.
1345  * A new dummy is linked at the end of the old one and
1346  * returned, to link further Tds if needed.
1347  */
1348 static Td*
1349 epgettd(Ep *ep, Qio *io, Td **dtdp, int flags, void *a, int count)
1350 {
1351         Td *td, *dtd;
1352         Block *bp;
1353
1354         if(count <= BY2PG)
1355                 bp = allocb(count);
1356         else{
1357                 if(count > 2*BY2PG)
1358                         panic("ohci: transfer > two pages");
1359                 /* maximum of one physical page crossing allowed */
1360                 bp = allocb(count+BY2PG);
1361                 bp->rp = (uchar*)PGROUND((uintptr)bp->rp);
1362                 bp->wp = bp->rp;
1363         }
1364         dtd = *dtdp;
1365         td = dtd;
1366         td->bp = bp;
1367         if(count > 0){
1368                 td->cbp0 = td->cbp = ptr2pa(bp->wp);
1369                 td->be = ptr2pa(bp->wp + count - 1);
1370                 if(a != nil){
1371                         /* validaddr((uintptr)a, count, 0); DEBUG */
1372                         assert(bp != nil);
1373                         assert(bp->wp != nil);
1374                         memmove(bp->wp, a, count);
1375                 }
1376                 bp->wp += count;
1377         }
1378         td->nbytes = count;
1379         td->ctrl = io->tok|Tdusetog|io->toggle|flags;
1380         if(io->toggle == Tddata0)
1381                 io->toggle = Tddata1;
1382         else
1383                 io->toggle = Tddata0;
1384         assert(td->ep == ep);
1385         td->io = io;
1386         dtd = tdalloc();        /* new dummy */
1387         dtd->ep = ep;
1388         td->nexttd = ptr2pa(dtd);
1389         td->next = dtd;
1390         *dtdp = dtd;
1391         return td;
1392 }
1393
1394 /*
1395  * Try to get them idle
1396  */
1397 static void
1398 aborttds(Qio *io)
1399 {
1400         Ed *ed;
1401         Td *td;
1402
1403         ed = io->ed;
1404         if(ed == nil)
1405                 return;
1406         ed->ctrl |= Edskip;
1407         for(td = ed->tds; td != nil; td = td->next)
1408                 if(td->bp != nil)
1409                         td->bp->wp = td->bp->rp;
1410         ed->head = (ed->head&0xF) | ed->tail;
1411         if((ed->ctrl & Ediso) == 0)
1412                 ed->tds = pa2ptr(ed->tail);
1413 }
1414
1415 static int
1416 epiodone(void *a)
1417 {
1418         Qio *io;
1419
1420         io = a;
1421         return io->state != Qrun;
1422 }
1423
1424 static void
1425 epiowait(Ctlr *ctlr, Qio *io, int tmout, ulong)
1426 {
1427         Ed *ed;
1428         int timedout;
1429
1430         ed = io->ed;
1431         if(0)ddqprint("ohci io %#p sleep on ed %#p state %s\n",
1432                 io, ed, iosname[io->state]);
1433         timedout = 0;
1434         if(waserror()){
1435                 dqprint("ohci io %#p ed %#p timed out\n", io, ed);
1436                 timedout++;
1437         }else{
1438                 if(tmout == 0)
1439                         sleep(io, epiodone, io);
1440                 else
1441                         tsleep(io, epiodone, io, tmout);
1442                 poperror();
1443         }
1444         ilock(ctlr);
1445         if(io->state == Qrun)
1446                 timedout = 1;
1447         else if(io->state != Qdone && io->state != Qclose)
1448                 panic("epio: ed not done and not closed");
1449         if(timedout){
1450                 aborttds(io);
1451                 io->err = "request timed out";
1452                 iunlock(ctlr);
1453                 if(!waserror()){
1454                         tsleep(&up->sleep, return0, 0, Abortdelay);
1455                         poperror();
1456                 }
1457                 ilock(ctlr);
1458         }
1459         if(io->state != Qclose)
1460                 io->state = Qidle;
1461         iunlock(ctlr);
1462 }
1463
1464 /*
1465  * Non iso I/O.
1466  * To make it work for control transfers, the caller may
1467  * lock the Qio for the entire control transfer.
1468  */
1469 static long
1470 epio(Ep *ep, Qio *io, void *a, long count, int mustlock)
1471 {
1472         Ed *ed;
1473         Ctlr *ctlr;
1474         char buf[80];
1475         char *err;
1476         uchar *c;
1477         Td *td, *ltd, *ntd, *td0;
1478         int last, ntds, tmout;
1479         long tot, n;
1480         ulong load;
1481
1482         ed = io->ed;
1483         ctlr = ep->hp->aux;
1484         io->debug = ep->debug;
1485         tmout = ep->tmout;
1486         ddeprint("ohci: %s ep%d.%d io %#p count %ld\n",
1487                 io->tok == Tdtokin ? "in" : "out",
1488                 ep->dev->nb, ep->nb, io, count);
1489         if((debug > 1 || ep->debug > 1) && io->tok != Tdtokin){
1490                 seprintdata(buf, buf+sizeof(buf), a, count);
1491                 print("\t%s\n", buf);
1492         }
1493         if(mustlock){
1494                 eqlock(io);
1495                 if(waserror()){
1496                         qunlock(io);
1497                         nexterror();
1498                 }
1499         }
1500         io->err = nil;
1501         ilock(ctlr);
1502         if(io->state == Qclose){        /* Tds released by cancelio */
1503                 iunlock(ctlr);
1504                 error(io->err ? io->err : Eio);
1505         }
1506         if(io->state != Qidle)
1507                 panic("epio: qio not idle");
1508         io->state = Qinstall;
1509
1510         c = a;
1511         ltd = td0 = ed->tds;
1512         load = tot = 0;
1513         do{
1514                 n = 2*BY2PG;
1515                 if(count-tot < n)
1516                         n = count-tot;
1517                 if(c != nil && io->tok != Tdtokin)
1518                         td = epgettd(ep, io, &ltd, 0, c+tot, n);
1519                 else
1520                         td = epgettd(ep, io, &ltd, 0, nil, n);
1521                 tot += n;
1522                 load += ep->load;
1523         }while(tot < count);
1524         if(td0 == nil || ltd == nil || td0 == ltd)
1525                 panic("epio: no td");
1526         td->last = 1;
1527         if(debug > 2 || ep->debug > 2)
1528                 dumptds(td0, "put td", ep->ttype == Tiso);
1529         iunlock(ctlr);
1530
1531         ilock(ctlr);
1532         if(io->state != Qclose){
1533                 io->iotime = TK2MS(MACHP(0)->ticks);
1534                 io->state = Qrun;
1535                 ed->tail = ptr2pa(ltd);
1536                 if(ep->ttype == Tctl)
1537                         ctlr->ohci->cmdsts |= Sclf;
1538                 else if(ep->ttype == Tbulk)
1539                         ctlr->ohci->cmdsts |= Sblf;
1540         }
1541         iunlock(ctlr);
1542
1543         epiowait(ctlr, io, tmout, load);
1544         ilock(ctlr);
1545         if(debug > 1 || ep->debug > 1)
1546                 dumptds(td0, "got td", 0);
1547         iunlock(ctlr);
1548
1549         tot = 0;
1550         c = a;
1551         ntds = last = 0;
1552         for(td = td0; td != ltd; td = ntd){
1553                 ntds++;
1554                 /*
1555                  * If the Td is flagged as last we must
1556                  * ignore any following Td. The block may
1557                  * seem to have bytes but interrupt has not seen
1558                  * those Tds through the done queue, and they are void.
1559                  */
1560                 if(last == 0 && tderrs(td) == Tdok){
1561                         n = BLEN(td->bp);
1562                         tot += n;
1563                         if(c != nil && tdtok(td) == Tdtokin && n > 0){
1564                                 memmove(c, td->bp->rp, n);
1565                                 c += n;
1566                         }
1567                 }
1568                 last |= td->last;
1569                 ntd = td->next;
1570                 tdfree(td);
1571         }
1572         if(edtoggle(ed) == 0)
1573                 io->toggle = Tddata0;
1574         else
1575                 io->toggle = Tddata1;
1576
1577         err = io->err;
1578         if(mustlock){
1579                 qunlock(io);
1580                 poperror();
1581         }
1582         ddeprint("ohci: io %#p: %d tds: return %ld err '%s'\n\n",
1583                 io, ntds, tot, err);
1584         if(err != nil)
1585                 error(err);
1586         if(tot < 0)
1587                 error(Eio);
1588         return tot;
1589 }
1590
1591 /*
1592  * halt condition was cleared on the endpoint. update our toggles.
1593  */
1594 static void
1595 clrhalt(Ep *ep)
1596 {
1597         Qio *io;
1598
1599         ep->clrhalt = 0;
1600         switch(ep->ttype){
1601         case Tbulk:
1602         case Tintr:
1603                 io = ep->aux;
1604                 if(ep->mode != OREAD){
1605                         qlock(&io[OWRITE]);
1606                         io[OWRITE].toggle = Tddata0;
1607                         deprint("ep clrhalt for io %#p\n", io+OWRITE);
1608                         qunlock(&io[OWRITE]);
1609                 }
1610                 if(ep->mode != OWRITE){
1611                         qlock(&io[OREAD]);
1612                         io[OREAD].toggle = Tddata0;
1613                         deprint("ep clrhalt for io %#p\n", io+OREAD);
1614                         qunlock(&io[OREAD]);
1615                 }
1616                 break;
1617         }
1618 }
1619
1620 static long
1621 epread(Ep *ep, void *a, long count)
1622 {
1623         Ctlio *cio;
1624         Qio *io;
1625         char buf[80];
1626         ulong delta;
1627
1628         if(ep->aux == nil)
1629                 panic("epread: not open");
1630
1631         switch(ep->ttype){
1632         case Tctl:
1633                 cio = ep->aux;
1634                 eqlock(cio);
1635                 if(waserror()){
1636                         qunlock(cio);
1637                         nexterror();
1638                 }
1639                 ddeprint("epread ctl ndata %d\n", cio->ndata);
1640                 if(cio->ndata < 0)
1641                         error("request expected");
1642                 else if(cio->ndata == 0){
1643                         cio->ndata = -1;
1644                         count = 0;
1645                 }else{
1646                         if(count > cio->ndata)
1647                                 count = cio->ndata;
1648                         if(count > 0)
1649                                 memmove(a, cio->data, count);
1650                         /* BUG for big transfers */
1651                         free(cio->data);
1652                         cio->data = nil;
1653                         cio->ndata = 0; /* signal EOF next time */
1654                 }
1655                 qunlock(cio);
1656                 poperror();
1657                 if(debug>1 || ep->debug){
1658                         seprintdata(buf, buf+sizeof(buf), a, count);
1659                         print("epread: %s\n", buf);
1660                 }
1661                 return count;
1662         case Tbulk:
1663                 io = ep->aux;
1664                 if(ep->clrhalt)
1665                         clrhalt(ep);
1666                 return epio(ep, &io[OREAD], a, count, 1);
1667         case Tintr:
1668                 io = ep->aux;
1669                 delta = TK2MS(MACHP(0)->ticks) - io[OREAD].iotime + 1;
1670                 if(delta < ep->pollival / 2)
1671                         tsleep(&up->sleep, return0, 0, ep->pollival/2 - delta);
1672                 if(ep->clrhalt)
1673                         clrhalt(ep);
1674                 return epio(ep, &io[OREAD], a, count, 1);
1675         case Tiso:
1676                 error("iso read not implemented");
1677                 break;
1678         default:
1679                 panic("epread: bad ep ttype %d", ep->ttype);
1680         }
1681         return -1;
1682 }
1683
1684 /*
1685  * Control transfers are one setup write (data0)
1686  * plus zero or more reads/writes (data1, data0, ...)
1687  * plus a final write/read with data1 to ack.
1688  * For both host to device and device to host we perform
1689  * the entire transfer when the user writes the request,
1690  * and keep any data read from the device for a later read.
1691  * We call epio three times instead of placing all Tds at
1692  * the same time because doing so leads to crc/tmout errors
1693  * for some devices.
1694  * Upon errors on the data phase we must still run the status
1695  * phase or the device may cease responding in the future.
1696  */
1697 static long
1698 epctlio(Ep *ep, Ctlio *cio, void *a, long count)
1699 {
1700         uchar *c;
1701         long len;
1702
1703         ddeprint("epctlio: cio %#p ep%d.%d count %ld\n",
1704                 cio, ep->dev->nb, ep->nb, count);
1705         if(count < Rsetuplen)
1706                 error("short usb command");
1707         eqlock(cio);
1708         free(cio->data);
1709         cio->data = nil;
1710         cio->ndata = 0;
1711         if(waserror()){
1712                 qunlock(cio);
1713                 free(cio->data);
1714                 cio->data = nil;
1715                 cio->ndata = 0;
1716                 nexterror();
1717         }
1718
1719         /* set the address if unset and out of configuration state */
1720         if(ep->dev->state != Dconfig && ep->dev->state != Dreset)
1721                 if(cio->usbid == 0){
1722                         cio->usbid = (ep->nb<<7)|(ep->dev->nb & Devmax);
1723                         edsetaddr(cio->ed, cio->usbid);
1724                 }
1725         /* adjust maxpkt if the user has learned a different one */
1726         if(edmaxpkt(cio->ed) != ep->maxpkt)
1727                 edsetmaxpkt(cio->ed, ep->maxpkt);
1728         c = a;
1729         cio->tok = Tdtoksetup;
1730         cio->toggle = Tddata0;
1731         if(epio(ep, cio, a, Rsetuplen, 0) < Rsetuplen)
1732                 error(Eio);
1733
1734         a = c + Rsetuplen;
1735         count -= Rsetuplen;
1736
1737         cio->toggle = Tddata1;
1738         if(c[Rtype] & Rd2h){
1739                 cio->tok = Tdtokin;
1740                 len = GET2(c+Rcount);
1741                 if(len <= 0)
1742                         error("bad length in d2h request");
1743                 if(len > Maxctllen)
1744                         error("d2h data too large to fit in ohci");
1745                 a = cio->data = smalloc(len+1);
1746         }else{
1747                 cio->tok = Tdtokout;
1748                 len = count;
1749         }
1750         if(len > 0)
1751                 if(waserror())
1752                         len = -1;
1753                 else{
1754                         len = epio(ep, cio, a, len, 0);
1755                         poperror();
1756                 }
1757         if(c[Rtype] & Rd2h){
1758                 count = Rsetuplen;
1759                 cio->ndata = len;
1760                 cio->tok = Tdtokout;
1761         }else{
1762                 if(len < 0)
1763                         count = -1;
1764                 else
1765                         count = Rsetuplen + len;
1766                 cio->tok = Tdtokin;
1767         }
1768         cio->toggle = Tddata1;
1769         epio(ep, cio, nil, 0, 0);
1770         qunlock(cio);
1771         poperror();
1772         ddeprint("epctlio cio %#p return %ld\n", cio, count);
1773         return count;
1774 }
1775
1776 /*
1777  * Put new samples in the dummy Td.
1778  */
1779 static long
1780 putsamples(Ctlr *ctlr, Ep *ep, Isoio *iso, uchar *b, long n)
1781 {
1782         Td *td;
1783
1784         td = pa2ptr(iso->ed->tail);
1785         if(n > td->nbytes - BLEN(td->bp))
1786                 n = td->nbytes - BLEN(td->bp);
1787         assert(td->bp->wp + n <= td->bp->lim);
1788         iunlock(ctlr);          /* We could page fault here */
1789         memmove(td->bp->wp, b, n);
1790         ilock(ctlr);
1791         if(td == pa2ptr(iso->ed->tail)){
1792                 td->bp->wp += n;
1793                 if(BLEN(td->bp) == td->nbytes)  /* full Td: activate it */
1794                         isoadvance(ep, iso, td);
1795         }
1796         return n;
1797 }
1798
1799 static long
1800 episowrite(Ep *ep, void *a, long count)
1801 {
1802         long tot, nw;
1803         char *err;
1804         uchar *b;
1805         Ctlr *ctlr;
1806         Isoio *iso;
1807
1808         ctlr = ep->hp->aux;
1809         iso = ep->aux;
1810         iso->delay = (ep->sampledelay*ep->samplesz + ep->maxpkt-1) / ep->maxpkt;
1811         iso->debug = ep->debug;
1812
1813         eqlock(iso);
1814         if(waserror()){
1815                 qunlock(iso);
1816                 nexterror();
1817         }
1818         diprint("ohci: episowrite: %#p ep%d.%d\n", iso, ep->dev->nb, ep->nb);
1819         ilock(ctlr);
1820         if(iso->state == Qclose){
1821                 iunlock(ctlr);
1822                 error(iso->err ? iso->err : Eio);
1823         }
1824         iso->state = Qrun;
1825         b = a;
1826         for(tot = 0; tot < count; tot += nw){
1827                 while(isocanwrite(iso) == 0){
1828                         iunlock(ctlr);
1829                         diprint("ohci: episowrite: %#p sleep\n", iso);
1830                         if(waserror()){
1831                                 if(iso->err == nil)
1832                                         iso->err = "I/O timed out";
1833                                 ilock(ctlr);
1834                                 break;
1835                         }
1836                         tsleep(iso, isocanwrite, iso, ep->tmout);
1837                         poperror();
1838                         ilock(ctlr);
1839                 }
1840                 err = iso->err;
1841                 iso->err = nil;
1842                 if(iso->state == Qclose || err != nil){
1843                         iunlock(ctlr);
1844                         error(err ? err : Eio);
1845                 }
1846                 if(iso->state != Qrun)
1847                         panic("episowrite: iso not running");
1848                 nw = putsamples(ctlr, ep, iso, b+tot, count-tot);
1849         }
1850         while(isodelay(iso) == 0){
1851                 iunlock(ctlr);
1852                 sleep(iso, isodelay, iso);
1853                 ilock(ctlr);
1854         }
1855         if(iso->state != Qclose)
1856                 iso->state = Qdone;
1857         iunlock(ctlr);
1858         err = iso->err;         /* in case it failed early */
1859         iso->err = nil;
1860         qunlock(iso);
1861         poperror();
1862         if(err != nil)
1863                 error(err);
1864         diprint("ohci: episowrite: %#p %ld bytes\n", iso, tot);
1865         return tot;
1866 }
1867
1868 static long
1869 epwrite(Ep *ep, void *a, long count)
1870 {
1871         Qio *io;
1872         Ctlio *cio;
1873         ulong delta;
1874         uchar *b;
1875         long tot, nw;
1876
1877         if(ep->aux == nil)
1878                 panic("ohci: epwrite: not open");
1879         switch(ep->ttype){
1880         case Tctl:
1881                 cio = ep->aux;
1882                 return epctlio(ep, cio, a, count);
1883         case Tbulk:
1884                 io = ep->aux;
1885                 if(ep->clrhalt)
1886                         clrhalt(ep);
1887                 /*
1888                  * Put at most Tdatomic Tds (512 bytes) at a time.
1889                  * Otherwise some devices produce babble errors.
1890                  */
1891                 b = a;
1892                 assert(a != nil);
1893                 for(tot = 0; tot < count ; tot += nw){
1894                         nw = count - tot;
1895                         if(nw > Tdatomic * ep->maxpkt)
1896                                 nw = Tdatomic * ep->maxpkt;
1897                         nw = epio(ep, &io[OWRITE], b+tot, nw, 1);
1898                 }
1899                 return tot;
1900         case Tintr:
1901                 io = ep->aux;
1902                 delta = TK2MS(MACHP(0)->ticks) - io[OWRITE].iotime + 1;
1903                 if(delta < ep->pollival)
1904                         tsleep(&up->sleep, return0, 0, ep->pollival - delta);
1905                 if(ep->clrhalt)
1906                         clrhalt(ep);
1907                 return epio(ep, &io[OWRITE], a, count, 1);
1908         case Tiso:
1909                 return episowrite(ep, a, count);
1910         default:
1911                 panic("ohci: epwrite: bad ep ttype %d", ep->ttype);
1912         }
1913         return -1;
1914 }
1915
1916 static Ed*
1917 newed(Ctlr *ctlr, Ep *ep, Qio *io, char *)
1918 {
1919         Ed *ed;
1920         Td *td;
1921
1922         ed = io->ed = edalloc();        /* no errors raised here, really */
1923         td = tdalloc();
1924         td->ep = ep;
1925         td->io = io;
1926         ed->tail =  ptr2pa(td);
1927         ed->head = ptr2pa(td);
1928         ed->tds = td;
1929         ed->ep = ep;
1930         ed->ctrl = (ep->maxpkt & Edmpsmask) << Edmpsshift;
1931         if(ep->ttype == Tiso)
1932                 ed->ctrl |= Ediso;
1933         if(waserror()){
1934                 edfree(ed);
1935                 io->ed = nil;
1936                 nexterror();
1937         }
1938         /* For setup endpoints we start with the config address */
1939         if(ep->ttype != Tctl)
1940                 edsetaddr(io->ed, io->usbid);
1941         if(ep->dev->speed == Lowspeed)
1942                 ed->ctrl |= Edlow;
1943         switch(io->tok){
1944         case Tdtokin:
1945                 ed->ctrl |= Edin;
1946                 break;
1947         case Tdtokout:
1948                 ed->ctrl |= Edout;
1949                 break;
1950         default:
1951                 ed->ctrl |= Edtddir;    /* Td will say */
1952                 break;
1953         }
1954
1955         switch(ep->ttype){
1956         case Tctl:
1957                 ilock(ctlr);
1958                 edlinked(ed, ctlhd(ctlr));
1959                 setctlhd(ctlr, ed);
1960                 iunlock(ctlr);
1961                 break;
1962         case Tbulk:
1963                 ilock(ctlr);
1964                 edlinked(ed, bulkhd(ctlr));
1965                 setbulkhd(ctlr, ed);
1966                 iunlock(ctlr);
1967                 break;
1968         case Tintr:
1969         case Tiso:
1970                 ilock(ctlr);
1971                 schedq(ctlr, io, ep->pollival);
1972                 iunlock(ctlr);
1973                 break;
1974         default:
1975                 panic("ohci: newed: bad ttype");
1976         }
1977         poperror();
1978         return ed;
1979 }
1980
1981 static void
1982 isoopen(Ctlr *ctlr, Ep *ep)
1983 {
1984         Td *td, *edtds;
1985         Isoio *iso;
1986         int i;
1987
1988         iso = ep->aux;
1989         iso->usbid = (ep->nb<<7)|(ep->dev->nb & Devmax);
1990         iso->bw = ep->hz * ep->samplesz;        /* bytes/sec */
1991         if(ep->mode != OWRITE){
1992                 print("ohci: bug: iso input streams not implemented\n");
1993                 error("ohci iso input streams not implemented");
1994         }else
1995                 iso->tok = Tdtokout;
1996
1997         iso->left = 0;
1998         iso->nerrs = 0;
1999         iso->frno = TRUNC(ctlr->ohci->fmnumber + 10, Ntdframes);
2000         iso->nframes = 1000 / ep->pollival;
2001         if(iso->nframes < 10){
2002                 print("ohci: isoopen: less than 10 frames; using 10.\n");
2003                 iso->nframes = 10;
2004         }
2005         iso->navail = iso->nframes;
2006         iso->atds = edtds = nil;
2007         for(i = 0; i < iso->nframes-1; i++){    /* -1 for dummy */
2008                 td = tdalloc();
2009                 td->ep = ep;
2010                 td->io = iso;
2011                 td->bp = allocb(ep->maxpkt);
2012                 td->anext = iso->atds;          /* link as avail */
2013                 iso->atds = td;
2014                 td->next = edtds;
2015                 edtds = td;
2016         }
2017         newed(ctlr, ep, iso, "iso");            /* allocates a dummy td */
2018         iso->ed->tds->bp = allocb(ep->maxpkt);  /* but not its block */
2019         iso->ed->tds->next = edtds;
2020         isodtdinit(ep, iso, iso->ed->tds);
2021 }
2022
2023 /*
2024  * Allocate the endpoint and set it up for I/O
2025  * in the controller. This must follow what's said
2026  * in Ep regarding configuration, including perhaps
2027  * the saved toggles (saved on a previous close of
2028  * the endpoint data file by epclose).
2029  */
2030 static void
2031 epopen(Ep *ep)
2032 {
2033         Ctlr *ctlr;
2034         Qio *io;
2035         Ctlio *cio;
2036         ulong usbid;
2037
2038         ctlr = ep->hp->aux;
2039         deprint("ohci: epopen ep%d.%d\n", ep->dev->nb, ep->nb);
2040         if(ep->aux != nil)
2041                 panic("ohci: epopen called with open ep");
2042         if(waserror()){
2043                 free(ep->aux);
2044                 ep->aux = nil;
2045                 nexterror();
2046         }
2047         switch(ep->ttype){
2048         case Tnone:
2049                 error("endpoint not configured");
2050         case Tiso:
2051                 ep->aux = smalloc(sizeof(Isoio));
2052                 isoopen(ctlr, ep);
2053                 break;
2054         case Tctl:
2055                 cio = ep->aux = smalloc(sizeof(Ctlio));
2056                 cio->debug = ep->debug;
2057                 cio->ndata = -1;
2058                 cio->data = nil;
2059                 cio->tok = -1;  /* invalid; Tds will say */
2060                 if(ep->dev->isroot != 0 && ep->nb == 0) /* root hub */
2061                         break;
2062                 newed(ctlr, ep, cio, "epc");
2063                 break;
2064         case Tbulk:
2065                 ep->pollival = 1;       /* assume this; doesn't really matter */
2066                 /* and fall... */
2067         case Tintr:
2068                 io = ep->aux = smalloc(sizeof(Qio)*2);
2069                 io[OREAD].debug = io[OWRITE].debug = ep->debug;
2070                 usbid = (ep->nb<<7)|(ep->dev->nb & Devmax);
2071                 if(ep->mode != OREAD){
2072                         if(ep->toggle[OWRITE] != 0)
2073                                 io[OWRITE].toggle = Tddata1;
2074                         else
2075                                 io[OWRITE].toggle = Tddata0;
2076                         io[OWRITE].tok = Tdtokout;
2077                         io[OWRITE].usbid = usbid;
2078                         io[OWRITE].bw = ep->maxpkt*1000/ep->pollival; /* bytes/s */
2079                         newed(ctlr, ep, io+OWRITE, "epw");
2080                 }
2081                 if(ep->mode != OWRITE){
2082                         if(ep->toggle[OREAD] != 0)
2083                                 io[OREAD].toggle = Tddata1;
2084                         else
2085                                 io[OREAD].toggle = Tddata0;
2086                         io[OREAD].tok = Tdtokin;
2087                         io[OREAD].usbid = usbid;
2088                         io[OREAD].bw = ep->maxpkt*1000/ep->pollival; /* bytes/s */
2089                         newed(ctlr, ep, io+OREAD, "epr");
2090                 }
2091                 break;
2092         }
2093         deprint("ohci: epopen done:\n");
2094         if(debug || ep->debug)
2095                 dump(ep->hp);
2096         poperror();
2097 }
2098
2099 static void
2100 cancelio(Ep *ep, Qio *io)
2101 {
2102         Ed *ed;
2103         Ctlr *ctlr;
2104
2105         ctlr = ep->hp->aux;
2106
2107         ilock(ctlr);
2108         if(io == nil || io->state == Qclose){
2109                 assert(io == nil || io->ed == nil);
2110                 iunlock(ctlr);
2111                 return;
2112         }
2113         ed = io->ed;
2114         io->state = Qclose;
2115         io->err = Eio;
2116         aborttds(io);
2117         iunlock(ctlr);
2118         if(!waserror()){
2119                 tsleep(&up->sleep, return0, 0, Abortdelay);
2120                 poperror();
2121         }
2122
2123         wakeup(io);
2124         qlock(io);
2125         /* wait for epio if running */
2126         qunlock(io);
2127
2128         ilock(ctlr);
2129         switch(ep->ttype){
2130         case Tctl:
2131                 unlinkctl(ctlr, ed);
2132                 break;
2133         case Tbulk:
2134                 unlinkbulk(ctlr, ed);
2135                 break;
2136         case Tintr:
2137         case Tiso:
2138                 unschedq(ctlr, io);
2139                 break;
2140         default:
2141                 panic("ohci cancelio: bad ttype");
2142         }
2143         iunlock(ctlr);
2144         edfree(io->ed);
2145         io->ed = nil;
2146 }
2147
2148 static void
2149 epclose(Ep *ep)
2150 {
2151         Ctlio *cio;
2152         Isoio *iso;
2153         Qio *io;
2154
2155         deprint("ohci: epclose ep%d.%d\n", ep->dev->nb, ep->nb);
2156         if(ep->aux == nil)
2157                 panic("ohci: epclose called with closed ep");
2158         switch(ep->ttype){
2159         case Tctl:
2160                 cio = ep->aux;
2161                 cancelio(ep, cio);
2162                 free(cio->data);
2163                 cio->data = nil;
2164                 break;
2165         case Tbulk:
2166         case Tintr:
2167                 io = ep->aux;
2168                 if(ep->mode != OWRITE){
2169                         cancelio(ep, &io[OREAD]);
2170                         if(io[OREAD].toggle == Tddata1)
2171                                 ep->toggle[OREAD] = 1;
2172                 }
2173                 if(ep->mode != OREAD){
2174                         cancelio(ep, &io[OWRITE]);
2175                         if(io[OWRITE].toggle == Tddata1)
2176                                 ep->toggle[OWRITE] = 1;
2177                 }
2178                 break;
2179         case Tiso:
2180                 iso = ep->aux;
2181                 cancelio(ep, iso);
2182                 break;
2183         default:
2184                 panic("epclose: bad ttype %d", ep->ttype);
2185         }
2186
2187         deprint("ohci: epclose ep%d.%d: done\n", ep->dev->nb, ep->nb);
2188         free(ep->aux);
2189         ep->aux = nil;
2190 }
2191
2192 static int
2193 portreset(Hci *hp, int port, int on)
2194 {
2195         Ctlr *ctlr;
2196         Ohci *ohci;
2197
2198         if(on == 0)
2199                 return 0;
2200
2201         ctlr = hp->aux;
2202         eqlock(&ctlr->resetl);
2203         if(waserror()){
2204                 qunlock(&ctlr->resetl);
2205                 nexterror();
2206         }
2207         ilock(ctlr);
2208         ohci = ctlr->ohci;
2209         ohci->rhportsts[port - 1] = Spp;
2210         if((ohci->rhportsts[port - 1] & Ccs) == 0){
2211                 iunlock(ctlr);
2212                 error("port not connected");
2213         }
2214         ohci->rhportsts[port - 1] = Spr;
2215         while((ohci->rhportsts[port - 1] & Prsc) == 0){
2216                 iunlock(ctlr);
2217                 dprint("ohci: portreset, wait for reset complete\n");
2218                 ilock(ctlr);
2219         }
2220         ohci->rhportsts[port - 1] = Prsc;
2221         iunlock(ctlr);
2222         poperror();
2223         qunlock(&ctlr->resetl);
2224         return 0;
2225 }
2226
2227 static int
2228 portenable(Hci *hp, int port, int on)
2229 {
2230         Ctlr *ctlr;
2231
2232         ctlr = hp->aux;
2233         dprint("ohci: %#p port %d enable=%d\n", ctlr->ohci, port, on);
2234         eqlock(&ctlr->resetl);
2235         if(waserror()){
2236                 qunlock(&ctlr->resetl);
2237                 nexterror();
2238         }
2239         ilock(ctlr);
2240         if(on)
2241                 ctlr->ohci->rhportsts[port - 1] = Spe | Spp;
2242         else
2243                 ctlr->ohci->rhportsts[port - 1] = Cpe;
2244         iunlock(ctlr);
2245         tsleep(&up->sleep, return0, 0, Enabledelay);
2246         poperror();
2247         qunlock(&ctlr->resetl);
2248         return 0;
2249 }
2250
2251 static int
2252 portstatus(Hci *hp, int port)
2253 {
2254         int v;
2255         Ctlr *ub;
2256         ulong ohcistatus;
2257
2258         /*
2259          * We must return status bits as a
2260          * get port status hub request would do.
2261          */
2262         ub = hp->aux;
2263         ohcistatus = ub->ohci->rhportsts[port - 1];
2264         v = 0;
2265         if(ohcistatus & Ccs)
2266                 v |= HPpresent;
2267         if(ohcistatus & Pes)
2268                 v |= HPenable;
2269         if(ohcistatus & Pss)
2270                 v |= HPsuspend;
2271         if(ohcistatus & Prs)
2272                 v |= HPreset;
2273         else {
2274                 /* port is not in reset; these potential writes are ok */
2275                 if(ohcistatus & Csc){
2276                         v |= HPstatuschg;
2277                         ub->ohci->rhportsts[port - 1] = Csc;
2278                 }
2279                 if(ohcistatus & Pesc){
2280                         v |= HPchange;
2281                         ub->ohci->rhportsts[port - 1] = Pesc;
2282                 }
2283         }
2284         if(ohcistatus & Lsda)
2285                 v |= HPslow;
2286         if(v & (HPstatuschg|HPchange))
2287                 ddprint("ohci port %d sts %#ulx hub sts %#x\n", port, ohcistatus, v);
2288         return v;
2289 }
2290
2291 static void
2292 dumpohci(Ctlr *ctlr)
2293 {
2294         int i;
2295         ulong *ohci;
2296
2297         ohci = &ctlr->ohci->revision;
2298         print("ohci registers: \n");
2299         for(i = 0; i < sizeof(Ohci)/sizeof(ulong); i++)
2300                 if(i < 3 || ohci[i] != 0)
2301                         print("\t[%#2.2x]\t%#8.8ulx\n", i * 4, ohci[i]);
2302         print("\n");
2303 }
2304
2305 static void
2306 init(Hci *hp)
2307 {
2308         Ctlr *ctlr;
2309         Ohci *ohci;
2310         int i;
2311         ulong ival, ctrl, fmi;
2312
2313         ctlr = hp->aux;
2314         dprint("ohci %#p init\n", ctlr->ohci);
2315         ohci = ctlr->ohci;
2316
2317         fmi = ohci->fminterval;
2318         ohci->cmdsts = Shcr;    /* reset the block */
2319         for(i = 0; i<100; i++){
2320                 if((ohci->cmdsts & Shcr) == 0)
2321                         break;
2322                 delay(1);       /* wait till reset complete, Ohci says 10us max. */
2323         }
2324         if(i == 100)
2325                 print("ohci: reset timed out\n");
2326         ohci->fminterval = fmi;
2327
2328         /*
2329          * now that soft reset is done we are in suspend state.
2330          * Setup registers which take in suspend state
2331          * (will only be here for 2ms).
2332          */
2333
2334         ctlr->ohci->hcca = ptr2pa(ctlr->hcca);
2335         setctlhd(ctlr, nil);
2336         ctlr->ohci->ctlcurred = 0;
2337         setbulkhd(ctlr, nil);
2338         ctlr->ohci->bulkcurred = 0;
2339
2340         ohci->intrenable = Mie | Wdh | Ue;
2341         ohci->control |= Ccle | Cble | Cple | Cie | Cfsoper;
2342
2343         /* set frame after operational */
2344         ohci->rhdesca = Nps;    /* no power switching */
2345         if(ohci->rhdesca & Nps){
2346                 dprint("ohci: ports are not power switched\n");
2347         }else{
2348                 dprint("ohci: ports are power switched\n");
2349                 ohci->rhdesca &= ~Psm;
2350                 ohci->rhsts &= ~Lpsc;
2351         }
2352         for(i = 0; i < ctlr->nports; i++)       /* paranoia */
2353                 ohci->rhportsts[i] = 0;         /* this has no effect */
2354         delay(50);
2355
2356         for(i = 0; i < ctlr->nports; i++){
2357                 ohci->rhportsts[i] =  Spp;
2358                 if((ohci->rhportsts[i] & Ccs) != 0)
2359                         ohci->rhportsts[i] |= Spr;
2360         }
2361         delay(100);
2362
2363         ctrl = ohci->control;
2364         if((ctrl & Cfsmask) != Cfsoper){
2365                 ctrl = (ctrl & ~Cfsmask) | Cfsoper;
2366                 ohci->control = ctrl;
2367                 ohci->rhsts = Lpsc;
2368         }
2369         ival = ohci->fminterval & ~(Fmaxpktmask << Fmaxpktshift);
2370         ohci->fminterval = ival | (5120 << Fmaxpktshift);
2371
2372         if(debug > 1)
2373                 dumpohci(ctlr);
2374 }
2375
2376 static void
2377 scanpci(void)
2378 {
2379         ulong mem;
2380         Ctlr *ctlr;
2381         Pcidev *p;
2382         int i;
2383         static int already = 0;
2384
2385         if(already)
2386                 return;
2387         already = 1;
2388         p = nil;
2389         while(p = pcimatch(p, 0, 0)) {
2390                 /*
2391                  * Find Ohci controllers (Programming Interface = 0x10).
2392                  */
2393                 if(p->ccrb != Pcibcserial || p->ccru != Pciscusb ||
2394                     p->ccrp != 0x10)
2395                         continue;
2396                 mem = p->mem[0].bar & ~0x0F;
2397                 dprint("ohci: %x/%x port 0x%lux size 0x%x irq %d\n",
2398                         p->vid, p->did, mem, p->mem[0].size, p->intl);
2399                 if(mem == 0){
2400                         print("ohci: failed to map registers\n");
2401                         continue;
2402                 }
2403
2404                 ctlr = malloc(sizeof(Ctlr));
2405                 if(ctlr == nil){
2406                         print("ohci: no memory\n");
2407                         continue;
2408                 }
2409                 ctlr->pcidev = p;
2410                 ctlr->ohci = vmap(mem, p->mem[0].size);
2411                 dprint("scanpci: ctlr %#p, ohci %#p\n", ctlr, ctlr->ohci);
2412                 pcisetbme(p);
2413                 pcisetpms(p, 0);
2414                 for(i = 0; i < Nhcis; i++)
2415                         if(ctlrs[i] == nil){
2416                                 ctlrs[i] = ctlr;
2417                                 break;
2418                         }
2419                 if(i == Nhcis)
2420                         print("ohci: bug: no more controllers\n");
2421         }
2422 }
2423
2424 static void
2425 usbdebug(Hci*, int d)
2426 {
2427         debug = d;
2428 }
2429
2430 /*
2431  * build the periodic scheduling tree:
2432  * framesize must be a multiple of the tree size
2433  */
2434 static void
2435 mkqhtree(Ctlr *ctlr)
2436 {
2437         int i, n, d, o, leaf0, depth;
2438         Ed **tree;
2439         Qtree *qt;
2440
2441         depth = flog2(32);
2442         n = (1 << (depth+1)) - 1;
2443         qt = mallocz(sizeof(*qt), 1);
2444         if(qt == nil)
2445                 panic("ohci: can't allocate scheduling tree");
2446         qt->nel = n;
2447         qt->depth = depth;
2448         qt->bw = mallocz(n * sizeof(qt->bw), 1);
2449         qt->root = tree = mallocz(n * sizeof(Ed *), 1);
2450         if(qt->bw == nil || qt->root == nil)
2451                 panic("ohci: can't allocate scheduling tree");
2452         for(i = 0; i < n; i++){
2453                 if((tree[i] = edalloc()) == nil)
2454                         panic("ohci: mkqhtree");
2455                 tree[i]->ctrl = (8 << Edmpsshift);      /* not needed */
2456                 tree[i]->ctrl |= Edskip;
2457
2458                 if(i > 0)
2459                         edlinked(tree[i], tree[(i-1)/2]);
2460                 else
2461                         edlinked(tree[i], nil);
2462         }
2463         ctlr->ntree = i;
2464         dprint("ohci: tree: %d endpoints allocated\n", i);
2465
2466         /* distribute leaves evenly round the frame list */
2467         leaf0 = n / 2;
2468         for(i = 0; i < 32; i++){
2469                 o = 0;
2470                 for(d = 0; d < depth; d++){
2471                         o <<= 1;
2472                         if(i & (1 << d))
2473                                 o |= 1;
2474                 }
2475                 if(leaf0 + o >= n){
2476                         print("leaf0=%d o=%d i=%d n=%d\n", leaf0, o, i, n);
2477                         break;
2478                 }
2479                 ctlr->hcca->intrtable[i] = ptr2pa(tree[leaf0 + o]);
2480         }
2481         ctlr->tree = qt;
2482 }
2483
2484 static void
2485 ohcimeminit(Ctlr *ctlr)
2486 {
2487         Hcca *hcca;
2488
2489         edfree(edalloc());      /* allocate pools now */
2490         tdfree(tdalloc());
2491
2492         hcca = xspanalloc(sizeof(Hcca), 256, 0);
2493         if(hcca == nil)
2494                 panic("ohci: no memory for Hcca");
2495         memset(hcca, 0, sizeof(*hcca));
2496         ctlr->hcca = hcca;
2497
2498         mkqhtree(ctlr);
2499 }
2500
2501 static void
2502 ohcireset(Ctlr *ctlr)
2503 {
2504         int i;
2505
2506         ilock(ctlr);
2507         dprint("ohci %#p reset\n", ctlr->ohci);
2508
2509         if(ctlr->ohci->control & Cir){
2510                 dprint("ohci: smm active, taking over\n");
2511                 ctlr->ohci->cmdsts |= Socr;         /* take ownership */
2512                 for(i = 0; i<100; i++){
2513                         if((ctlr->ohci->control & Cir) == 0)
2514                                 break;
2515                         delay(1);
2516                 }
2517                 if(i == 100)
2518                         print("ohci: smm takeover timed out\n");
2519         }
2520
2521         /*
2522          * usually enter here in reset, wait till its through,
2523          * then do our own so we are on known timing conditions.
2524          * Is this needed?
2525          */
2526         delay(100);
2527         ctlr->ohci->control = 0;
2528         delay(100);
2529
2530         /* legacy support register: turn off lunacy mode */
2531         pcicfgw16(ctlr->pcidev, 0xc0, 0x2000);
2532
2533         iunlock(ctlr);
2534 }
2535
2536 static void
2537 shutdown(Hci *hp)
2538 {
2539         Ctlr *ctlr;
2540
2541         ctlr = hp->aux;
2542
2543         ilock(ctlr);
2544         ctlr->ohci->intrdisable = Mie;
2545         ctlr->ohci->intrenable = 0;
2546         ctlr->ohci->control = 0;
2547         delay(100);
2548         iunlock(ctlr);
2549 }
2550
2551 static int
2552 reset(Hci *hp)
2553 {
2554         int i;
2555         Ctlr *ctlr;
2556         Pcidev *p;
2557         static Lock resetlck;
2558
2559         if(getconf("*nousbohci"))
2560                 return -1;
2561         ilock(&resetlck);
2562         scanpci();
2563
2564         /*
2565          * Any adapter matches if no hp->port is supplied,
2566          * otherwise the ports must match.
2567          */
2568         ctlr = nil;
2569         for(i = 0; i < Nhcis && ctlrs[i] != nil; i++){
2570                 ctlr = ctlrs[i];
2571                 if(ctlr->active == 0)
2572                 if(hp->port == 0 || hp->port == (uintptr)ctlr->ohci){
2573                         ctlr->active = 1;
2574                         break;
2575                 }
2576         }
2577         iunlock(&resetlck);
2578         if(ctlrs[i] == nil || i == Nhcis)
2579                 return -1;
2580         if(ctlr->ohci->control == ~0)
2581                 return -1;
2582
2583
2584         p = ctlr->pcidev;
2585         hp->aux = ctlr;
2586         hp->port = (uintptr)ctlr->ohci;
2587         hp->irq = p->intl;
2588         hp->tbdf = p->tbdf;
2589         ctlr->nports = hp->nports = ctlr->ohci->rhdesca & 0xff;
2590
2591         ohcireset(ctlr);
2592         ohcimeminit(ctlr);
2593
2594         /*
2595          * Linkage to the generic HCI driver.
2596          */
2597         hp->init = init;
2598         hp->dump = dump;
2599         hp->interrupt = interrupt;
2600         hp->epopen = epopen;
2601         hp->epclose = epclose;
2602         hp->epread = epread;
2603         hp->epwrite = epwrite;
2604         hp->seprintep = seprintep;
2605         hp->portenable = portenable;
2606         hp->portreset = portreset;
2607         hp->portstatus = portstatus;
2608         hp->shutdown = shutdown;
2609         hp->debug = usbdebug;
2610         hp->type = "ohci";
2611
2612         /*
2613          * IRQ2 doesn't really exist, it's used to gang the interrupt
2614          * controllers together. A device set to IRQ2 will appear on
2615          * the second interrupt controller as IRQ9.
2616          */
2617         if(hp->irq == 2)
2618                 hp->irq = 9;
2619         intrenable(hp->irq, hp->interrupt, hp, hp->tbdf, hp->type);
2620
2621         return 0;
2622 }
2623
2624 void
2625 usbohcilink(void)
2626 {
2627         addhcitype("ohci", reset);
2628 }