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