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