USB: convert usb_hcd bitfields into atomic flags
[platform/kernel/linux-rpi.git] / drivers / usb / host / ehci-sched.c
1 /*
2  * Copyright (c) 2001-2004 by David Brownell
3  * Copyright (c) 2003 Michal Sojka, for high-speed iso transfers
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; either version 2 of the License, or (at your
8  * option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13  * for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 /* this file is part of ehci-hcd.c */
21
22 /*-------------------------------------------------------------------------*/
23
24 /*
25  * EHCI scheduled transaction support:  interrupt, iso, split iso
26  * These are called "periodic" transactions in the EHCI spec.
27  *
28  * Note that for interrupt transfers, the QH/QTD manipulation is shared
29  * with the "asynchronous" transaction support (control/bulk transfers).
30  * The only real difference is in how interrupt transfers are scheduled.
31  *
32  * For ISO, we make an "iso_stream" head to serve the same role as a QH.
33  * It keeps track of every ITD (or SITD) that's linked, and holds enough
34  * pre-calculated schedule data to make appending to the queue be quick.
35  */
36
37 static int ehci_get_frame (struct usb_hcd *hcd);
38
39 /*-------------------------------------------------------------------------*/
40
41 /*
42  * periodic_next_shadow - return "next" pointer on shadow list
43  * @periodic: host pointer to qh/itd/sitd
44  * @tag: hardware tag for type of this record
45  */
46 static union ehci_shadow *
47 periodic_next_shadow(struct ehci_hcd *ehci, union ehci_shadow *periodic,
48                 __hc32 tag)
49 {
50         switch (hc32_to_cpu(ehci, tag)) {
51         case Q_TYPE_QH:
52                 return &periodic->qh->qh_next;
53         case Q_TYPE_FSTN:
54                 return &periodic->fstn->fstn_next;
55         case Q_TYPE_ITD:
56                 return &periodic->itd->itd_next;
57         // case Q_TYPE_SITD:
58         default:
59                 return &periodic->sitd->sitd_next;
60         }
61 }
62
63 static __hc32 *
64 shadow_next_periodic(struct ehci_hcd *ehci, union ehci_shadow *periodic,
65                 __hc32 tag)
66 {
67         switch (hc32_to_cpu(ehci, tag)) {
68         /* our ehci_shadow.qh is actually software part */
69         case Q_TYPE_QH:
70                 return &periodic->qh->hw->hw_next;
71         /* others are hw parts */
72         default:
73                 return periodic->hw_next;
74         }
75 }
76
77 /* caller must hold ehci->lock */
78 static void periodic_unlink (struct ehci_hcd *ehci, unsigned frame, void *ptr)
79 {
80         union ehci_shadow       *prev_p = &ehci->pshadow[frame];
81         __hc32                  *hw_p = &ehci->periodic[frame];
82         union ehci_shadow       here = *prev_p;
83
84         /* find predecessor of "ptr"; hw and shadow lists are in sync */
85         while (here.ptr && here.ptr != ptr) {
86                 prev_p = periodic_next_shadow(ehci, prev_p,
87                                 Q_NEXT_TYPE(ehci, *hw_p));
88                 hw_p = shadow_next_periodic(ehci, &here,
89                                 Q_NEXT_TYPE(ehci, *hw_p));
90                 here = *prev_p;
91         }
92         /* an interrupt entry (at list end) could have been shared */
93         if (!here.ptr)
94                 return;
95
96         /* update shadow and hardware lists ... the old "next" pointers
97          * from ptr may still be in use, the caller updates them.
98          */
99         *prev_p = *periodic_next_shadow(ehci, &here,
100                         Q_NEXT_TYPE(ehci, *hw_p));
101         *hw_p = *shadow_next_periodic(ehci, &here, Q_NEXT_TYPE(ehci, *hw_p));
102 }
103
104 /* how many of the uframe's 125 usecs are allocated? */
105 static unsigned short
106 periodic_usecs (struct ehci_hcd *ehci, unsigned frame, unsigned uframe)
107 {
108         __hc32                  *hw_p = &ehci->periodic [frame];
109         union ehci_shadow       *q = &ehci->pshadow [frame];
110         unsigned                usecs = 0;
111         struct ehci_qh_hw       *hw;
112
113         while (q->ptr) {
114                 switch (hc32_to_cpu(ehci, Q_NEXT_TYPE(ehci, *hw_p))) {
115                 case Q_TYPE_QH:
116                         hw = q->qh->hw;
117                         /* is it in the S-mask? */
118                         if (hw->hw_info2 & cpu_to_hc32(ehci, 1 << uframe))
119                                 usecs += q->qh->usecs;
120                         /* ... or C-mask? */
121                         if (hw->hw_info2 & cpu_to_hc32(ehci,
122                                         1 << (8 + uframe)))
123                                 usecs += q->qh->c_usecs;
124                         hw_p = &hw->hw_next;
125                         q = &q->qh->qh_next;
126                         break;
127                 // case Q_TYPE_FSTN:
128                 default:
129                         /* for "save place" FSTNs, count the relevant INTR
130                          * bandwidth from the previous frame
131                          */
132                         if (q->fstn->hw_prev != EHCI_LIST_END(ehci)) {
133                                 ehci_dbg (ehci, "ignoring FSTN cost ...\n");
134                         }
135                         hw_p = &q->fstn->hw_next;
136                         q = &q->fstn->fstn_next;
137                         break;
138                 case Q_TYPE_ITD:
139                         if (q->itd->hw_transaction[uframe])
140                                 usecs += q->itd->stream->usecs;
141                         hw_p = &q->itd->hw_next;
142                         q = &q->itd->itd_next;
143                         break;
144                 case Q_TYPE_SITD:
145                         /* is it in the S-mask?  (count SPLIT, DATA) */
146                         if (q->sitd->hw_uframe & cpu_to_hc32(ehci,
147                                         1 << uframe)) {
148                                 if (q->sitd->hw_fullspeed_ep &
149                                                 cpu_to_hc32(ehci, 1<<31))
150                                         usecs += q->sitd->stream->usecs;
151                                 else    /* worst case for OUT start-split */
152                                         usecs += HS_USECS_ISO (188);
153                         }
154
155                         /* ... C-mask?  (count CSPLIT, DATA) */
156                         if (q->sitd->hw_uframe &
157                                         cpu_to_hc32(ehci, 1 << (8 + uframe))) {
158                                 /* worst case for IN complete-split */
159                                 usecs += q->sitd->stream->c_usecs;
160                         }
161
162                         hw_p = &q->sitd->hw_next;
163                         q = &q->sitd->sitd_next;
164                         break;
165                 }
166         }
167 #ifdef  DEBUG
168         if (usecs > 100)
169                 ehci_err (ehci, "uframe %d sched overrun: %d usecs\n",
170                         frame * 8 + uframe, usecs);
171 #endif
172         return usecs;
173 }
174
175 /*-------------------------------------------------------------------------*/
176
177 static int same_tt (struct usb_device *dev1, struct usb_device *dev2)
178 {
179         if (!dev1->tt || !dev2->tt)
180                 return 0;
181         if (dev1->tt != dev2->tt)
182                 return 0;
183         if (dev1->tt->multi)
184                 return dev1->ttport == dev2->ttport;
185         else
186                 return 1;
187 }
188
189 #ifdef CONFIG_USB_EHCI_TT_NEWSCHED
190
191 /* Which uframe does the low/fullspeed transfer start in?
192  *
193  * The parameter is the mask of ssplits in "H-frame" terms
194  * and this returns the transfer start uframe in "B-frame" terms,
195  * which allows both to match, e.g. a ssplit in "H-frame" uframe 0
196  * will cause a transfer in "B-frame" uframe 0.  "B-frames" lag
197  * "H-frames" by 1 uframe.  See the EHCI spec sec 4.5 and figure 4.7.
198  */
199 static inline unsigned char tt_start_uframe(struct ehci_hcd *ehci, __hc32 mask)
200 {
201         unsigned char smask = QH_SMASK & hc32_to_cpu(ehci, mask);
202         if (!smask) {
203                 ehci_err(ehci, "invalid empty smask!\n");
204                 /* uframe 7 can't have bw so this will indicate failure */
205                 return 7;
206         }
207         return ffs(smask) - 1;
208 }
209
210 static const unsigned char
211 max_tt_usecs[] = { 125, 125, 125, 125, 125, 125, 30, 0 };
212
213 /* carryover low/fullspeed bandwidth that crosses uframe boundries */
214 static inline void carryover_tt_bandwidth(unsigned short tt_usecs[8])
215 {
216         int i;
217         for (i=0; i<7; i++) {
218                 if (max_tt_usecs[i] < tt_usecs[i]) {
219                         tt_usecs[i+1] += tt_usecs[i] - max_tt_usecs[i];
220                         tt_usecs[i] = max_tt_usecs[i];
221                 }
222         }
223 }
224
225 /* How many of the tt's periodic downstream 1000 usecs are allocated?
226  *
227  * While this measures the bandwidth in terms of usecs/uframe,
228  * the low/fullspeed bus has no notion of uframes, so any particular
229  * low/fullspeed transfer can "carry over" from one uframe to the next,
230  * since the TT just performs downstream transfers in sequence.
231  *
232  * For example two separate 100 usec transfers can start in the same uframe,
233  * and the second one would "carry over" 75 usecs into the next uframe.
234  */
235 static void
236 periodic_tt_usecs (
237         struct ehci_hcd *ehci,
238         struct usb_device *dev,
239         unsigned frame,
240         unsigned short tt_usecs[8]
241 )
242 {
243         __hc32                  *hw_p = &ehci->periodic [frame];
244         union ehci_shadow       *q = &ehci->pshadow [frame];
245         unsigned char           uf;
246
247         memset(tt_usecs, 0, 16);
248
249         while (q->ptr) {
250                 switch (hc32_to_cpu(ehci, Q_NEXT_TYPE(ehci, *hw_p))) {
251                 case Q_TYPE_ITD:
252                         hw_p = &q->itd->hw_next;
253                         q = &q->itd->itd_next;
254                         continue;
255                 case Q_TYPE_QH:
256                         if (same_tt(dev, q->qh->dev)) {
257                                 uf = tt_start_uframe(ehci, q->qh->hw->hw_info2);
258                                 tt_usecs[uf] += q->qh->tt_usecs;
259                         }
260                         hw_p = &q->qh->hw->hw_next;
261                         q = &q->qh->qh_next;
262                         continue;
263                 case Q_TYPE_SITD:
264                         if (same_tt(dev, q->sitd->urb->dev)) {
265                                 uf = tt_start_uframe(ehci, q->sitd->hw_uframe);
266                                 tt_usecs[uf] += q->sitd->stream->tt_usecs;
267                         }
268                         hw_p = &q->sitd->hw_next;
269                         q = &q->sitd->sitd_next;
270                         continue;
271                 // case Q_TYPE_FSTN:
272                 default:
273                         ehci_dbg(ehci, "ignoring periodic frame %d FSTN\n",
274                                         frame);
275                         hw_p = &q->fstn->hw_next;
276                         q = &q->fstn->fstn_next;
277                 }
278         }
279
280         carryover_tt_bandwidth(tt_usecs);
281
282         if (max_tt_usecs[7] < tt_usecs[7])
283                 ehci_err(ehci, "frame %d tt sched overrun: %d usecs\n",
284                         frame, tt_usecs[7] - max_tt_usecs[7]);
285 }
286
287 /*
288  * Return true if the device's tt's downstream bus is available for a
289  * periodic transfer of the specified length (usecs), starting at the
290  * specified frame/uframe.  Note that (as summarized in section 11.19
291  * of the usb 2.0 spec) TTs can buffer multiple transactions for each
292  * uframe.
293  *
294  * The uframe parameter is when the fullspeed/lowspeed transfer
295  * should be executed in "B-frame" terms, which is the same as the
296  * highspeed ssplit's uframe (which is in "H-frame" terms).  For example
297  * a ssplit in "H-frame" 0 causes a transfer in "B-frame" 0.
298  * See the EHCI spec sec 4.5 and fig 4.7.
299  *
300  * This checks if the full/lowspeed bus, at the specified starting uframe,
301  * has the specified bandwidth available, according to rules listed
302  * in USB 2.0 spec section 11.18.1 fig 11-60.
303  *
304  * This does not check if the transfer would exceed the max ssplit
305  * limit of 16, specified in USB 2.0 spec section 11.18.4 requirement #4,
306  * since proper scheduling limits ssplits to less than 16 per uframe.
307  */
308 static int tt_available (
309         struct ehci_hcd         *ehci,
310         unsigned                period,
311         struct usb_device       *dev,
312         unsigned                frame,
313         unsigned                uframe,
314         u16                     usecs
315 )
316 {
317         if ((period == 0) || (uframe >= 7))     /* error */
318                 return 0;
319
320         for (; frame < ehci->periodic_size; frame += period) {
321                 unsigned short tt_usecs[8];
322
323                 periodic_tt_usecs (ehci, dev, frame, tt_usecs);
324
325                 ehci_vdbg(ehci, "tt frame %d check %d usecs start uframe %d in"
326                         " schedule %d/%d/%d/%d/%d/%d/%d/%d\n",
327                         frame, usecs, uframe,
328                         tt_usecs[0], tt_usecs[1], tt_usecs[2], tt_usecs[3],
329                         tt_usecs[4], tt_usecs[5], tt_usecs[6], tt_usecs[7]);
330
331                 if (max_tt_usecs[uframe] <= tt_usecs[uframe]) {
332                         ehci_vdbg(ehci, "frame %d uframe %d fully scheduled\n",
333                                 frame, uframe);
334                         return 0;
335                 }
336
337                 /* special case for isoc transfers larger than 125us:
338                  * the first and each subsequent fully used uframe
339                  * must be empty, so as to not illegally delay
340                  * already scheduled transactions
341                  */
342                 if (125 < usecs) {
343                         int ufs = (usecs / 125);
344                         int i;
345                         for (i = uframe; i < (uframe + ufs) && i < 8; i++)
346                                 if (0 < tt_usecs[i]) {
347                                         ehci_vdbg(ehci,
348                                                 "multi-uframe xfer can't fit "
349                                                 "in frame %d uframe %d\n",
350                                                 frame, i);
351                                         return 0;
352                                 }
353                 }
354
355                 tt_usecs[uframe] += usecs;
356
357                 carryover_tt_bandwidth(tt_usecs);
358
359                 /* fail if the carryover pushed bw past the last uframe's limit */
360                 if (max_tt_usecs[7] < tt_usecs[7]) {
361                         ehci_vdbg(ehci,
362                                 "tt unavailable usecs %d frame %d uframe %d\n",
363                                 usecs, frame, uframe);
364                         return 0;
365                 }
366         }
367
368         return 1;
369 }
370
371 #else
372
373 /* return true iff the device's transaction translator is available
374  * for a periodic transfer starting at the specified frame, using
375  * all the uframes in the mask.
376  */
377 static int tt_no_collision (
378         struct ehci_hcd         *ehci,
379         unsigned                period,
380         struct usb_device       *dev,
381         unsigned                frame,
382         u32                     uf_mask
383 )
384 {
385         if (period == 0)        /* error */
386                 return 0;
387
388         /* note bandwidth wastage:  split never follows csplit
389          * (different dev or endpoint) until the next uframe.
390          * calling convention doesn't make that distinction.
391          */
392         for (; frame < ehci->periodic_size; frame += period) {
393                 union ehci_shadow       here;
394                 __hc32                  type;
395                 struct ehci_qh_hw       *hw;
396
397                 here = ehci->pshadow [frame];
398                 type = Q_NEXT_TYPE(ehci, ehci->periodic [frame]);
399                 while (here.ptr) {
400                         switch (hc32_to_cpu(ehci, type)) {
401                         case Q_TYPE_ITD:
402                                 type = Q_NEXT_TYPE(ehci, here.itd->hw_next);
403                                 here = here.itd->itd_next;
404                                 continue;
405                         case Q_TYPE_QH:
406                                 hw = here.qh->hw;
407                                 if (same_tt (dev, here.qh->dev)) {
408                                         u32             mask;
409
410                                         mask = hc32_to_cpu(ehci,
411                                                         hw->hw_info2);
412                                         /* "knows" no gap is needed */
413                                         mask |= mask >> 8;
414                                         if (mask & uf_mask)
415                                                 break;
416                                 }
417                                 type = Q_NEXT_TYPE(ehci, hw->hw_next);
418                                 here = here.qh->qh_next;
419                                 continue;
420                         case Q_TYPE_SITD:
421                                 if (same_tt (dev, here.sitd->urb->dev)) {
422                                         u16             mask;
423
424                                         mask = hc32_to_cpu(ehci, here.sitd
425                                                                 ->hw_uframe);
426                                         /* FIXME assumes no gap for IN! */
427                                         mask |= mask >> 8;
428                                         if (mask & uf_mask)
429                                                 break;
430                                 }
431                                 type = Q_NEXT_TYPE(ehci, here.sitd->hw_next);
432                                 here = here.sitd->sitd_next;
433                                 continue;
434                         // case Q_TYPE_FSTN:
435                         default:
436                                 ehci_dbg (ehci,
437                                         "periodic frame %d bogus type %d\n",
438                                         frame, type);
439                         }
440
441                         /* collision or error */
442                         return 0;
443                 }
444         }
445
446         /* no collision */
447         return 1;
448 }
449
450 #endif /* CONFIG_USB_EHCI_TT_NEWSCHED */
451
452 /*-------------------------------------------------------------------------*/
453
454 static int enable_periodic (struct ehci_hcd *ehci)
455 {
456         u32     cmd;
457         int     status;
458
459         if (ehci->periodic_sched++)
460                 return 0;
461
462         /* did clearing PSE did take effect yet?
463          * takes effect only at frame boundaries...
464          */
465         status = handshake_on_error_set_halt(ehci, &ehci->regs->status,
466                                              STS_PSS, 0, 9 * 125);
467         if (status)
468                 return status;
469
470         cmd = ehci_readl(ehci, &ehci->regs->command) | CMD_PSE;
471         ehci_writel(ehci, cmd, &ehci->regs->command);
472         /* posted write ... PSS happens later */
473         ehci_to_hcd(ehci)->state = HC_STATE_RUNNING;
474
475         /* make sure ehci_work scans these */
476         ehci->next_uframe = ehci_readl(ehci, &ehci->regs->frame_index)
477                 % (ehci->periodic_size << 3);
478         if (unlikely(ehci->broken_periodic))
479                 ehci->last_periodic_enable = ktime_get_real();
480         return 0;
481 }
482
483 static int disable_periodic (struct ehci_hcd *ehci)
484 {
485         u32     cmd;
486         int     status;
487
488         if (--ehci->periodic_sched)
489                 return 0;
490
491         if (unlikely(ehci->broken_periodic)) {
492                 /* delay experimentally determined */
493                 ktime_t safe = ktime_add_us(ehci->last_periodic_enable, 1000);
494                 ktime_t now = ktime_get_real();
495                 s64 delay = ktime_us_delta(safe, now);
496
497                 if (unlikely(delay > 0))
498                         udelay(delay);
499         }
500
501         /* did setting PSE not take effect yet?
502          * takes effect only at frame boundaries...
503          */
504         status = handshake_on_error_set_halt(ehci, &ehci->regs->status,
505                                              STS_PSS, STS_PSS, 9 * 125);
506         if (status)
507                 return status;
508
509         cmd = ehci_readl(ehci, &ehci->regs->command) & ~CMD_PSE;
510         ehci_writel(ehci, cmd, &ehci->regs->command);
511         /* posted write ... */
512
513         free_cached_lists(ehci);
514
515         ehci->next_uframe = -1;
516         return 0;
517 }
518
519 /*-------------------------------------------------------------------------*/
520
521 /* periodic schedule slots have iso tds (normal or split) first, then a
522  * sparse tree for active interrupt transfers.
523  *
524  * this just links in a qh; caller guarantees uframe masks are set right.
525  * no FSTN support (yet; ehci 0.96+)
526  */
527 static int qh_link_periodic (struct ehci_hcd *ehci, struct ehci_qh *qh)
528 {
529         unsigned        i;
530         unsigned        period = qh->period;
531
532         dev_dbg (&qh->dev->dev,
533                 "link qh%d-%04x/%p start %d [%d/%d us]\n",
534                 period, hc32_to_cpup(ehci, &qh->hw->hw_info2)
535                         & (QH_CMASK | QH_SMASK),
536                 qh, qh->start, qh->usecs, qh->c_usecs);
537
538         /* high bandwidth, or otherwise every microframe */
539         if (period == 0)
540                 period = 1;
541
542         for (i = qh->start; i < ehci->periodic_size; i += period) {
543                 union ehci_shadow       *prev = &ehci->pshadow[i];
544                 __hc32                  *hw_p = &ehci->periodic[i];
545                 union ehci_shadow       here = *prev;
546                 __hc32                  type = 0;
547
548                 /* skip the iso nodes at list head */
549                 while (here.ptr) {
550                         type = Q_NEXT_TYPE(ehci, *hw_p);
551                         if (type == cpu_to_hc32(ehci, Q_TYPE_QH))
552                                 break;
553                         prev = periodic_next_shadow(ehci, prev, type);
554                         hw_p = shadow_next_periodic(ehci, &here, type);
555                         here = *prev;
556                 }
557
558                 /* sorting each branch by period (slow-->fast)
559                  * enables sharing interior tree nodes
560                  */
561                 while (here.ptr && qh != here.qh) {
562                         if (qh->period > here.qh->period)
563                                 break;
564                         prev = &here.qh->qh_next;
565                         hw_p = &here.qh->hw->hw_next;
566                         here = *prev;
567                 }
568                 /* link in this qh, unless some earlier pass did that */
569                 if (qh != here.qh) {
570                         qh->qh_next = here;
571                         if (here.qh)
572                                 qh->hw->hw_next = *hw_p;
573                         wmb ();
574                         prev->qh = qh;
575                         *hw_p = QH_NEXT (ehci, qh->qh_dma);
576                 }
577         }
578         qh->qh_state = QH_STATE_LINKED;
579         qh->xacterrs = 0;
580         qh_get (qh);
581
582         /* update per-qh bandwidth for usbfs */
583         ehci_to_hcd(ehci)->self.bandwidth_allocated += qh->period
584                 ? ((qh->usecs + qh->c_usecs) / qh->period)
585                 : (qh->usecs * 8);
586
587         /* maybe enable periodic schedule processing */
588         return enable_periodic(ehci);
589 }
590
591 static int qh_unlink_periodic(struct ehci_hcd *ehci, struct ehci_qh *qh)
592 {
593         unsigned        i;
594         unsigned        period;
595
596         // FIXME:
597         // IF this isn't high speed
598         //   and this qh is active in the current uframe
599         //   (and overlay token SplitXstate is false?)
600         // THEN
601         //   qh->hw_info1 |= cpu_to_hc32(1 << 7 /* "ignore" */);
602
603         /* high bandwidth, or otherwise part of every microframe */
604         if ((period = qh->period) == 0)
605                 period = 1;
606
607         for (i = qh->start; i < ehci->periodic_size; i += period)
608                 periodic_unlink (ehci, i, qh);
609
610         /* update per-qh bandwidth for usbfs */
611         ehci_to_hcd(ehci)->self.bandwidth_allocated -= qh->period
612                 ? ((qh->usecs + qh->c_usecs) / qh->period)
613                 : (qh->usecs * 8);
614
615         dev_dbg (&qh->dev->dev,
616                 "unlink qh%d-%04x/%p start %d [%d/%d us]\n",
617                 qh->period,
618                 hc32_to_cpup(ehci, &qh->hw->hw_info2) & (QH_CMASK | QH_SMASK),
619                 qh, qh->start, qh->usecs, qh->c_usecs);
620
621         /* qh->qh_next still "live" to HC */
622         qh->qh_state = QH_STATE_UNLINK;
623         qh->qh_next.ptr = NULL;
624         qh_put (qh);
625
626         /* maybe turn off periodic schedule */
627         return disable_periodic(ehci);
628 }
629
630 static void intr_deschedule (struct ehci_hcd *ehci, struct ehci_qh *qh)
631 {
632         unsigned                wait;
633         struct ehci_qh_hw       *hw = qh->hw;
634         int                     rc;
635
636         /* If the QH isn't linked then there's nothing we can do
637          * unless we were called during a giveback, in which case
638          * qh_completions() has to deal with it.
639          */
640         if (qh->qh_state != QH_STATE_LINKED) {
641                 if (qh->qh_state == QH_STATE_COMPLETING)
642                         qh->needs_rescan = 1;
643                 return;
644         }
645
646         qh_unlink_periodic (ehci, qh);
647
648         /* simple/paranoid:  always delay, expecting the HC needs to read
649          * qh->hw_next or finish a writeback after SPLIT/CSPLIT ... and
650          * expect khubd to clean up after any CSPLITs we won't issue.
651          * active high speed queues may need bigger delays...
652          */
653         if (list_empty (&qh->qtd_list)
654                         || (cpu_to_hc32(ehci, QH_CMASK)
655                                         & hw->hw_info2) != 0)
656                 wait = 2;
657         else
658                 wait = 55;      /* worst case: 3 * 1024 */
659
660         udelay (wait);
661         qh->qh_state = QH_STATE_IDLE;
662         hw->hw_next = EHCI_LIST_END(ehci);
663         wmb ();
664
665         qh_completions(ehci, qh);
666
667         /* reschedule QH iff another request is queued */
668         if (!list_empty(&qh->qtd_list) &&
669                         HC_IS_RUNNING(ehci_to_hcd(ehci)->state)) {
670                 rc = qh_schedule(ehci, qh);
671
672                 /* An error here likely indicates handshake failure
673                  * or no space left in the schedule.  Neither fault
674                  * should happen often ...
675                  *
676                  * FIXME kill the now-dysfunctional queued urbs
677                  */
678                 if (rc != 0)
679                         ehci_err(ehci, "can't reschedule qh %p, err %d\n",
680                                         qh, rc);
681         }
682 }
683
684 /*-------------------------------------------------------------------------*/
685
686 static int check_period (
687         struct ehci_hcd *ehci,
688         unsigned        frame,
689         unsigned        uframe,
690         unsigned        period,
691         unsigned        usecs
692 ) {
693         int             claimed;
694
695         /* complete split running into next frame?
696          * given FSTN support, we could sometimes check...
697          */
698         if (uframe >= 8)
699                 return 0;
700
701         /*
702          * 80% periodic == 100 usec/uframe available
703          * convert "usecs we need" to "max already claimed"
704          */
705         usecs = 100 - usecs;
706
707         /* we "know" 2 and 4 uframe intervals were rejected; so
708          * for period 0, check _every_ microframe in the schedule.
709          */
710         if (unlikely (period == 0)) {
711                 do {
712                         for (uframe = 0; uframe < 7; uframe++) {
713                                 claimed = periodic_usecs (ehci, frame, uframe);
714                                 if (claimed > usecs)
715                                         return 0;
716                         }
717                 } while ((frame += 1) < ehci->periodic_size);
718
719         /* just check the specified uframe, at that period */
720         } else {
721                 do {
722                         claimed = periodic_usecs (ehci, frame, uframe);
723                         if (claimed > usecs)
724                                 return 0;
725                 } while ((frame += period) < ehci->periodic_size);
726         }
727
728         // success!
729         return 1;
730 }
731
732 static int check_intr_schedule (
733         struct ehci_hcd         *ehci,
734         unsigned                frame,
735         unsigned                uframe,
736         const struct ehci_qh    *qh,
737         __hc32                  *c_maskp
738 )
739 {
740         int             retval = -ENOSPC;
741         u8              mask = 0;
742
743         if (qh->c_usecs && uframe >= 6)         /* FSTN territory? */
744                 goto done;
745
746         if (!check_period (ehci, frame, uframe, qh->period, qh->usecs))
747                 goto done;
748         if (!qh->c_usecs) {
749                 retval = 0;
750                 *c_maskp = 0;
751                 goto done;
752         }
753
754 #ifdef CONFIG_USB_EHCI_TT_NEWSCHED
755         if (tt_available (ehci, qh->period, qh->dev, frame, uframe,
756                                 qh->tt_usecs)) {
757                 unsigned i;
758
759                 /* TODO : this may need FSTN for SSPLIT in uframe 5. */
760                 for (i=uframe+1; i<8 && i<uframe+4; i++)
761                         if (!check_period (ehci, frame, i,
762                                                 qh->period, qh->c_usecs))
763                                 goto done;
764                         else
765                                 mask |= 1 << i;
766
767                 retval = 0;
768
769                 *c_maskp = cpu_to_hc32(ehci, mask << 8);
770         }
771 #else
772         /* Make sure this tt's buffer is also available for CSPLITs.
773          * We pessimize a bit; probably the typical full speed case
774          * doesn't need the second CSPLIT.
775          *
776          * NOTE:  both SPLIT and CSPLIT could be checked in just
777          * one smart pass...
778          */
779         mask = 0x03 << (uframe + qh->gap_uf);
780         *c_maskp = cpu_to_hc32(ehci, mask << 8);
781
782         mask |= 1 << uframe;
783         if (tt_no_collision (ehci, qh->period, qh->dev, frame, mask)) {
784                 if (!check_period (ehci, frame, uframe + qh->gap_uf + 1,
785                                         qh->period, qh->c_usecs))
786                         goto done;
787                 if (!check_period (ehci, frame, uframe + qh->gap_uf,
788                                         qh->period, qh->c_usecs))
789                         goto done;
790                 retval = 0;
791         }
792 #endif
793 done:
794         return retval;
795 }
796
797 /* "first fit" scheduling policy used the first time through,
798  * or when the previous schedule slot can't be re-used.
799  */
800 static int qh_schedule(struct ehci_hcd *ehci, struct ehci_qh *qh)
801 {
802         int             status;
803         unsigned        uframe;
804         __hc32          c_mask;
805         unsigned        frame;          /* 0..(qh->period - 1), or NO_FRAME */
806         struct ehci_qh_hw       *hw = qh->hw;
807
808         qh_refresh(ehci, qh);
809         hw->hw_next = EHCI_LIST_END(ehci);
810         frame = qh->start;
811
812         /* reuse the previous schedule slots, if we can */
813         if (frame < qh->period) {
814                 uframe = ffs(hc32_to_cpup(ehci, &hw->hw_info2) & QH_SMASK);
815                 status = check_intr_schedule (ehci, frame, --uframe,
816                                 qh, &c_mask);
817         } else {
818                 uframe = 0;
819                 c_mask = 0;
820                 status = -ENOSPC;
821         }
822
823         /* else scan the schedule to find a group of slots such that all
824          * uframes have enough periodic bandwidth available.
825          */
826         if (status) {
827                 /* "normal" case, uframing flexible except with splits */
828                 if (qh->period) {
829                         int             i;
830
831                         for (i = qh->period; status && i > 0; --i) {
832                                 frame = ++ehci->random_frame % qh->period;
833                                 for (uframe = 0; uframe < 8; uframe++) {
834                                         status = check_intr_schedule (ehci,
835                                                         frame, uframe, qh,
836                                                         &c_mask);
837                                         if (status == 0)
838                                                 break;
839                                 }
840                         }
841
842                 /* qh->period == 0 means every uframe */
843                 } else {
844                         frame = 0;
845                         status = check_intr_schedule (ehci, 0, 0, qh, &c_mask);
846                 }
847                 if (status)
848                         goto done;
849                 qh->start = frame;
850
851                 /* reset S-frame and (maybe) C-frame masks */
852                 hw->hw_info2 &= cpu_to_hc32(ehci, ~(QH_CMASK | QH_SMASK));
853                 hw->hw_info2 |= qh->period
854                         ? cpu_to_hc32(ehci, 1 << uframe)
855                         : cpu_to_hc32(ehci, QH_SMASK);
856                 hw->hw_info2 |= c_mask;
857         } else
858                 ehci_dbg (ehci, "reused qh %p schedule\n", qh);
859
860         /* stuff into the periodic schedule */
861         status = qh_link_periodic (ehci, qh);
862 done:
863         return status;
864 }
865
866 static int intr_submit (
867         struct ehci_hcd         *ehci,
868         struct urb              *urb,
869         struct list_head        *qtd_list,
870         gfp_t                   mem_flags
871 ) {
872         unsigned                epnum;
873         unsigned long           flags;
874         struct ehci_qh          *qh;
875         int                     status;
876         struct list_head        empty;
877
878         /* get endpoint and transfer/schedule data */
879         epnum = urb->ep->desc.bEndpointAddress;
880
881         spin_lock_irqsave (&ehci->lock, flags);
882
883         if (unlikely(!HCD_HW_ACCESSIBLE(ehci_to_hcd(ehci)))) {
884                 status = -ESHUTDOWN;
885                 goto done_not_linked;
886         }
887         status = usb_hcd_link_urb_to_ep(ehci_to_hcd(ehci), urb);
888         if (unlikely(status))
889                 goto done_not_linked;
890
891         /* get qh and force any scheduling errors */
892         INIT_LIST_HEAD (&empty);
893         qh = qh_append_tds(ehci, urb, &empty, epnum, &urb->ep->hcpriv);
894         if (qh == NULL) {
895                 status = -ENOMEM;
896                 goto done;
897         }
898         if (qh->qh_state == QH_STATE_IDLE) {
899                 if ((status = qh_schedule (ehci, qh)) != 0)
900                         goto done;
901         }
902
903         /* then queue the urb's tds to the qh */
904         qh = qh_append_tds(ehci, urb, qtd_list, epnum, &urb->ep->hcpriv);
905         BUG_ON (qh == NULL);
906
907         /* ... update usbfs periodic stats */
908         ehci_to_hcd(ehci)->self.bandwidth_int_reqs++;
909
910 done:
911         if (unlikely(status))
912                 usb_hcd_unlink_urb_from_ep(ehci_to_hcd(ehci), urb);
913 done_not_linked:
914         spin_unlock_irqrestore (&ehci->lock, flags);
915         if (status)
916                 qtd_list_free (ehci, urb, qtd_list);
917
918         return status;
919 }
920
921 /*-------------------------------------------------------------------------*/
922
923 /* ehci_iso_stream ops work with both ITD and SITD */
924
925 static struct ehci_iso_stream *
926 iso_stream_alloc (gfp_t mem_flags)
927 {
928         struct ehci_iso_stream *stream;
929
930         stream = kzalloc(sizeof *stream, mem_flags);
931         if (likely (stream != NULL)) {
932                 INIT_LIST_HEAD(&stream->td_list);
933                 INIT_LIST_HEAD(&stream->free_list);
934                 stream->next_uframe = -1;
935                 stream->refcount = 1;
936         }
937         return stream;
938 }
939
940 static void
941 iso_stream_init (
942         struct ehci_hcd         *ehci,
943         struct ehci_iso_stream  *stream,
944         struct usb_device       *dev,
945         int                     pipe,
946         unsigned                interval
947 )
948 {
949         static const u8 smask_out [] = { 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f };
950
951         u32                     buf1;
952         unsigned                epnum, maxp;
953         int                     is_input;
954         long                    bandwidth;
955
956         /*
957          * this might be a "high bandwidth" highspeed endpoint,
958          * as encoded in the ep descriptor's wMaxPacket field
959          */
960         epnum = usb_pipeendpoint (pipe);
961         is_input = usb_pipein (pipe) ? USB_DIR_IN : 0;
962         maxp = usb_maxpacket(dev, pipe, !is_input);
963         if (is_input) {
964                 buf1 = (1 << 11);
965         } else {
966                 buf1 = 0;
967         }
968
969         /* knows about ITD vs SITD */
970         if (dev->speed == USB_SPEED_HIGH) {
971                 unsigned multi = hb_mult(maxp);
972
973                 stream->highspeed = 1;
974
975                 maxp = max_packet(maxp);
976                 buf1 |= maxp;
977                 maxp *= multi;
978
979                 stream->buf0 = cpu_to_hc32(ehci, (epnum << 8) | dev->devnum);
980                 stream->buf1 = cpu_to_hc32(ehci, buf1);
981                 stream->buf2 = cpu_to_hc32(ehci, multi);
982
983                 /* usbfs wants to report the average usecs per frame tied up
984                  * when transfers on this endpoint are scheduled ...
985                  */
986                 stream->usecs = HS_USECS_ISO (maxp);
987                 bandwidth = stream->usecs * 8;
988                 bandwidth /= interval;
989
990         } else {
991                 u32             addr;
992                 int             think_time;
993                 int             hs_transfers;
994
995                 addr = dev->ttport << 24;
996                 if (!ehci_is_TDI(ehci)
997                                 || (dev->tt->hub !=
998                                         ehci_to_hcd(ehci)->self.root_hub))
999                         addr |= dev->tt->hub->devnum << 16;
1000                 addr |= epnum << 8;
1001                 addr |= dev->devnum;
1002                 stream->usecs = HS_USECS_ISO (maxp);
1003                 think_time = dev->tt ? dev->tt->think_time : 0;
1004                 stream->tt_usecs = NS_TO_US (think_time + usb_calc_bus_time (
1005                                 dev->speed, is_input, 1, maxp));
1006                 hs_transfers = max (1u, (maxp + 187) / 188);
1007                 if (is_input) {
1008                         u32     tmp;
1009
1010                         addr |= 1 << 31;
1011                         stream->c_usecs = stream->usecs;
1012                         stream->usecs = HS_USECS_ISO (1);
1013                         stream->raw_mask = 1;
1014
1015                         /* c-mask as specified in USB 2.0 11.18.4 3.c */
1016                         tmp = (1 << (hs_transfers + 2)) - 1;
1017                         stream->raw_mask |= tmp << (8 + 2);
1018                 } else
1019                         stream->raw_mask = smask_out [hs_transfers - 1];
1020                 bandwidth = stream->usecs + stream->c_usecs;
1021                 bandwidth /= interval << 3;
1022
1023                 /* stream->splits gets created from raw_mask later */
1024                 stream->address = cpu_to_hc32(ehci, addr);
1025         }
1026         stream->bandwidth = bandwidth;
1027
1028         stream->udev = dev;
1029
1030         stream->bEndpointAddress = is_input | epnum;
1031         stream->interval = interval;
1032         stream->maxp = maxp;
1033 }
1034
1035 static void
1036 iso_stream_put(struct ehci_hcd *ehci, struct ehci_iso_stream *stream)
1037 {
1038         stream->refcount--;
1039
1040         /* free whenever just a dev->ep reference remains.
1041          * not like a QH -- no persistent state (toggle, halt)
1042          */
1043         if (stream->refcount == 1) {
1044                 int             is_in;
1045
1046                 // BUG_ON (!list_empty(&stream->td_list));
1047
1048                 while (!list_empty (&stream->free_list)) {
1049                         struct list_head        *entry;
1050
1051                         entry = stream->free_list.next;
1052                         list_del (entry);
1053
1054                         /* knows about ITD vs SITD */
1055                         if (stream->highspeed) {
1056                                 struct ehci_itd         *itd;
1057
1058                                 itd = list_entry (entry, struct ehci_itd,
1059                                                 itd_list);
1060                                 dma_pool_free (ehci->itd_pool, itd,
1061                                                 itd->itd_dma);
1062                         } else {
1063                                 struct ehci_sitd        *sitd;
1064
1065                                 sitd = list_entry (entry, struct ehci_sitd,
1066                                                 sitd_list);
1067                                 dma_pool_free (ehci->sitd_pool, sitd,
1068                                                 sitd->sitd_dma);
1069                         }
1070                 }
1071
1072                 is_in = (stream->bEndpointAddress & USB_DIR_IN) ? 0x10 : 0;
1073                 stream->bEndpointAddress &= 0x0f;
1074                 if (stream->ep)
1075                         stream->ep->hcpriv = NULL;
1076
1077                 if (stream->rescheduled) {
1078                         ehci_info (ehci, "ep%d%s-iso rescheduled "
1079                                 "%lu times in %lu seconds\n",
1080                                 stream->bEndpointAddress, is_in ? "in" : "out",
1081                                 stream->rescheduled,
1082                                 ((jiffies - stream->start)/HZ)
1083                                 );
1084                 }
1085
1086                 kfree(stream);
1087         }
1088 }
1089
1090 static inline struct ehci_iso_stream *
1091 iso_stream_get (struct ehci_iso_stream *stream)
1092 {
1093         if (likely (stream != NULL))
1094                 stream->refcount++;
1095         return stream;
1096 }
1097
1098 static struct ehci_iso_stream *
1099 iso_stream_find (struct ehci_hcd *ehci, struct urb *urb)
1100 {
1101         unsigned                epnum;
1102         struct ehci_iso_stream  *stream;
1103         struct usb_host_endpoint *ep;
1104         unsigned long           flags;
1105
1106         epnum = usb_pipeendpoint (urb->pipe);
1107         if (usb_pipein(urb->pipe))
1108                 ep = urb->dev->ep_in[epnum];
1109         else
1110                 ep = urb->dev->ep_out[epnum];
1111
1112         spin_lock_irqsave (&ehci->lock, flags);
1113         stream = ep->hcpriv;
1114
1115         if (unlikely (stream == NULL)) {
1116                 stream = iso_stream_alloc(GFP_ATOMIC);
1117                 if (likely (stream != NULL)) {
1118                         /* dev->ep owns the initial refcount */
1119                         ep->hcpriv = stream;
1120                         stream->ep = ep;
1121                         iso_stream_init(ehci, stream, urb->dev, urb->pipe,
1122                                         urb->interval);
1123                 }
1124
1125         /* if dev->ep [epnum] is a QH, hw is set */
1126         } else if (unlikely (stream->hw != NULL)) {
1127                 ehci_dbg (ehci, "dev %s ep%d%s, not iso??\n",
1128                         urb->dev->devpath, epnum,
1129                         usb_pipein(urb->pipe) ? "in" : "out");
1130                 stream = NULL;
1131         }
1132
1133         /* caller guarantees an eventual matching iso_stream_put */
1134         stream = iso_stream_get (stream);
1135
1136         spin_unlock_irqrestore (&ehci->lock, flags);
1137         return stream;
1138 }
1139
1140 /*-------------------------------------------------------------------------*/
1141
1142 /* ehci_iso_sched ops can be ITD-only or SITD-only */
1143
1144 static struct ehci_iso_sched *
1145 iso_sched_alloc (unsigned packets, gfp_t mem_flags)
1146 {
1147         struct ehci_iso_sched   *iso_sched;
1148         int                     size = sizeof *iso_sched;
1149
1150         size += packets * sizeof (struct ehci_iso_packet);
1151         iso_sched = kzalloc(size, mem_flags);
1152         if (likely (iso_sched != NULL)) {
1153                 INIT_LIST_HEAD (&iso_sched->td_list);
1154         }
1155         return iso_sched;
1156 }
1157
1158 static inline void
1159 itd_sched_init(
1160         struct ehci_hcd         *ehci,
1161         struct ehci_iso_sched   *iso_sched,
1162         struct ehci_iso_stream  *stream,
1163         struct urb              *urb
1164 )
1165 {
1166         unsigned        i;
1167         dma_addr_t      dma = urb->transfer_dma;
1168
1169         /* how many uframes are needed for these transfers */
1170         iso_sched->span = urb->number_of_packets * stream->interval;
1171
1172         /* figure out per-uframe itd fields that we'll need later
1173          * when we fit new itds into the schedule.
1174          */
1175         for (i = 0; i < urb->number_of_packets; i++) {
1176                 struct ehci_iso_packet  *uframe = &iso_sched->packet [i];
1177                 unsigned                length;
1178                 dma_addr_t              buf;
1179                 u32                     trans;
1180
1181                 length = urb->iso_frame_desc [i].length;
1182                 buf = dma + urb->iso_frame_desc [i].offset;
1183
1184                 trans = EHCI_ISOC_ACTIVE;
1185                 trans |= buf & 0x0fff;
1186                 if (unlikely (((i + 1) == urb->number_of_packets))
1187                                 && !(urb->transfer_flags & URB_NO_INTERRUPT))
1188                         trans |= EHCI_ITD_IOC;
1189                 trans |= length << 16;
1190                 uframe->transaction = cpu_to_hc32(ehci, trans);
1191
1192                 /* might need to cross a buffer page within a uframe */
1193                 uframe->bufp = (buf & ~(u64)0x0fff);
1194                 buf += length;
1195                 if (unlikely ((uframe->bufp != (buf & ~(u64)0x0fff))))
1196                         uframe->cross = 1;
1197         }
1198 }
1199
1200 static void
1201 iso_sched_free (
1202         struct ehci_iso_stream  *stream,
1203         struct ehci_iso_sched   *iso_sched
1204 )
1205 {
1206         if (!iso_sched)
1207                 return;
1208         // caller must hold ehci->lock!
1209         list_splice (&iso_sched->td_list, &stream->free_list);
1210         kfree (iso_sched);
1211 }
1212
1213 static int
1214 itd_urb_transaction (
1215         struct ehci_iso_stream  *stream,
1216         struct ehci_hcd         *ehci,
1217         struct urb              *urb,
1218         gfp_t                   mem_flags
1219 )
1220 {
1221         struct ehci_itd         *itd;
1222         dma_addr_t              itd_dma;
1223         int                     i;
1224         unsigned                num_itds;
1225         struct ehci_iso_sched   *sched;
1226         unsigned long           flags;
1227
1228         sched = iso_sched_alloc (urb->number_of_packets, mem_flags);
1229         if (unlikely (sched == NULL))
1230                 return -ENOMEM;
1231
1232         itd_sched_init(ehci, sched, stream, urb);
1233
1234         if (urb->interval < 8)
1235                 num_itds = 1 + (sched->span + 7) / 8;
1236         else
1237                 num_itds = urb->number_of_packets;
1238
1239         /* allocate/init ITDs */
1240         spin_lock_irqsave (&ehci->lock, flags);
1241         for (i = 0; i < num_itds; i++) {
1242
1243                 /* free_list.next might be cache-hot ... but maybe
1244                  * the HC caches it too. avoid that issue for now.
1245                  */
1246
1247                 /* prefer previously-allocated itds */
1248                 if (likely (!list_empty(&stream->free_list))) {
1249                         itd = list_entry (stream->free_list.prev,
1250                                         struct ehci_itd, itd_list);
1251                         list_del (&itd->itd_list);
1252                         itd_dma = itd->itd_dma;
1253                 } else {
1254                         spin_unlock_irqrestore (&ehci->lock, flags);
1255                         itd = dma_pool_alloc (ehci->itd_pool, mem_flags,
1256                                         &itd_dma);
1257                         spin_lock_irqsave (&ehci->lock, flags);
1258                         if (!itd) {
1259                                 iso_sched_free(stream, sched);
1260                                 spin_unlock_irqrestore(&ehci->lock, flags);
1261                                 return -ENOMEM;
1262                         }
1263                 }
1264
1265                 memset (itd, 0, sizeof *itd);
1266                 itd->itd_dma = itd_dma;
1267                 list_add (&itd->itd_list, &sched->td_list);
1268         }
1269         spin_unlock_irqrestore (&ehci->lock, flags);
1270
1271         /* temporarily store schedule info in hcpriv */
1272         urb->hcpriv = sched;
1273         urb->error_count = 0;
1274         return 0;
1275 }
1276
1277 /*-------------------------------------------------------------------------*/
1278
1279 static inline int
1280 itd_slot_ok (
1281         struct ehci_hcd         *ehci,
1282         u32                     mod,
1283         u32                     uframe,
1284         u8                      usecs,
1285         u32                     period
1286 )
1287 {
1288         uframe %= period;
1289         do {
1290                 /* can't commit more than 80% periodic == 100 usec */
1291                 if (periodic_usecs (ehci, uframe >> 3, uframe & 0x7)
1292                                 > (100 - usecs))
1293                         return 0;
1294
1295                 /* we know urb->interval is 2^N uframes */
1296                 uframe += period;
1297         } while (uframe < mod);
1298         return 1;
1299 }
1300
1301 static inline int
1302 sitd_slot_ok (
1303         struct ehci_hcd         *ehci,
1304         u32                     mod,
1305         struct ehci_iso_stream  *stream,
1306         u32                     uframe,
1307         struct ehci_iso_sched   *sched,
1308         u32                     period_uframes
1309 )
1310 {
1311         u32                     mask, tmp;
1312         u32                     frame, uf;
1313
1314         mask = stream->raw_mask << (uframe & 7);
1315
1316         /* for IN, don't wrap CSPLIT into the next frame */
1317         if (mask & ~0xffff)
1318                 return 0;
1319
1320         /* this multi-pass logic is simple, but performance may
1321          * suffer when the schedule data isn't cached.
1322          */
1323
1324         /* check bandwidth */
1325         uframe %= period_uframes;
1326         do {
1327                 u32             max_used;
1328
1329                 frame = uframe >> 3;
1330                 uf = uframe & 7;
1331
1332 #ifdef CONFIG_USB_EHCI_TT_NEWSCHED
1333                 /* The tt's fullspeed bus bandwidth must be available.
1334                  * tt_available scheduling guarantees 10+% for control/bulk.
1335                  */
1336                 if (!tt_available (ehci, period_uframes << 3,
1337                                 stream->udev, frame, uf, stream->tt_usecs))
1338                         return 0;
1339 #else
1340                 /* tt must be idle for start(s), any gap, and csplit.
1341                  * assume scheduling slop leaves 10+% for control/bulk.
1342                  */
1343                 if (!tt_no_collision (ehci, period_uframes << 3,
1344                                 stream->udev, frame, mask))
1345                         return 0;
1346 #endif
1347
1348                 /* check starts (OUT uses more than one) */
1349                 max_used = 100 - stream->usecs;
1350                 for (tmp = stream->raw_mask & 0xff; tmp; tmp >>= 1, uf++) {
1351                         if (periodic_usecs (ehci, frame, uf) > max_used)
1352                                 return 0;
1353                 }
1354
1355                 /* for IN, check CSPLIT */
1356                 if (stream->c_usecs) {
1357                         uf = uframe & 7;
1358                         max_used = 100 - stream->c_usecs;
1359                         do {
1360                                 tmp = 1 << uf;
1361                                 tmp <<= 8;
1362                                 if ((stream->raw_mask & tmp) == 0)
1363                                         continue;
1364                                 if (periodic_usecs (ehci, frame, uf)
1365                                                 > max_used)
1366                                         return 0;
1367                         } while (++uf < 8);
1368                 }
1369
1370                 /* we know urb->interval is 2^N uframes */
1371                 uframe += period_uframes;
1372         } while (uframe < mod);
1373
1374         stream->splits = cpu_to_hc32(ehci, stream->raw_mask << (uframe & 7));
1375         return 1;
1376 }
1377
1378 /*
1379  * This scheduler plans almost as far into the future as it has actual
1380  * periodic schedule slots.  (Affected by TUNE_FLS, which defaults to
1381  * "as small as possible" to be cache-friendlier.)  That limits the size
1382  * transfers you can stream reliably; avoid more than 64 msec per urb.
1383  * Also avoid queue depths of less than ehci's worst irq latency (affected
1384  * by the per-urb URB_NO_INTERRUPT hint, the log2_irq_thresh module parameter,
1385  * and other factors); or more than about 230 msec total (for portability,
1386  * given EHCI_TUNE_FLS and the slop).  Or, write a smarter scheduler!
1387  */
1388
1389 #define SCHEDULE_SLOP   80      /* microframes */
1390
1391 static int
1392 iso_stream_schedule (
1393         struct ehci_hcd         *ehci,
1394         struct urb              *urb,
1395         struct ehci_iso_stream  *stream
1396 )
1397 {
1398         u32                     now, next, start, period;
1399         int                     status;
1400         unsigned                mod = ehci->periodic_size << 3;
1401         struct ehci_iso_sched   *sched = urb->hcpriv;
1402         struct pci_dev          *pdev;
1403
1404         if (sched->span > (mod - SCHEDULE_SLOP)) {
1405                 ehci_dbg (ehci, "iso request %p too long\n", urb);
1406                 status = -EFBIG;
1407                 goto fail;
1408         }
1409
1410         if ((stream->depth + sched->span) > mod) {
1411                 ehci_dbg (ehci, "request %p would overflow (%d+%d>%d)\n",
1412                         urb, stream->depth, sched->span, mod);
1413                 status = -EFBIG;
1414                 goto fail;
1415         }
1416
1417         period = urb->interval;
1418         if (!stream->highspeed)
1419                 period <<= 3;
1420
1421         now = ehci_readl(ehci, &ehci->regs->frame_index) % mod;
1422
1423         /* Typical case: reuse current schedule, stream is still active.
1424          * Hopefully there are no gaps from the host falling behind
1425          * (irq delays etc), but if there are we'll take the next
1426          * slot in the schedule, implicitly assuming URB_ISO_ASAP.
1427          */
1428         if (likely (!list_empty (&stream->td_list))) {
1429                 pdev = to_pci_dev(ehci_to_hcd(ehci)->self.controller);
1430                 start = stream->next_uframe;
1431
1432                 /* For high speed devices, allow scheduling within the
1433                  * isochronous scheduling threshold.  For full speed devices,
1434                  * don't. (Work around for Intel ICH9 bug.)
1435                  */
1436                 if (!stream->highspeed &&
1437                                 pdev->vendor == PCI_VENDOR_ID_INTEL)
1438                         next = now + ehci->i_thresh;
1439                 else
1440                         next = now;
1441
1442                 /* Fell behind (by up to twice the slop amount)? */
1443                 if (((start - next) & (mod - 1)) >=
1444                                 mod - 2 * SCHEDULE_SLOP)
1445                         start += period * DIV_ROUND_UP(
1446                                         (next - start) & (mod - 1),
1447                                         period);
1448
1449                 /* Tried to schedule too far into the future? */
1450                 if (unlikely(((start - now) & (mod - 1)) + sched->span
1451                                         >= mod - 2 * SCHEDULE_SLOP)) {
1452                         status = -EFBIG;
1453                         goto fail;
1454                 }
1455                 stream->next_uframe = start;
1456                 goto ready;
1457         }
1458
1459         /* need to schedule; when's the next (u)frame we could start?
1460          * this is bigger than ehci->i_thresh allows; scheduling itself
1461          * isn't free, the slop should handle reasonably slow cpus.  it
1462          * can also help high bandwidth if the dma and irq loads don't
1463          * jump until after the queue is primed.
1464          */
1465         start = SCHEDULE_SLOP + (now & ~0x07);
1466         start %= mod;
1467         stream->next_uframe = start;
1468
1469         /* NOTE:  assumes URB_ISO_ASAP, to limit complexity/bugs */
1470
1471         /* find a uframe slot with enough bandwidth */
1472         for (; start < (stream->next_uframe + period); start++) {
1473                 int             enough_space;
1474
1475                 /* check schedule: enough space? */
1476                 if (stream->highspeed)
1477                         enough_space = itd_slot_ok (ehci, mod, start,
1478                                         stream->usecs, period);
1479                 else {
1480                         if ((start % 8) >= 6)
1481                                 continue;
1482                         enough_space = sitd_slot_ok (ehci, mod, stream,
1483                                         start, sched, period);
1484                 }
1485
1486                 /* schedule it here if there's enough bandwidth */
1487                 if (enough_space) {
1488                         stream->next_uframe = start % mod;
1489                         goto ready;
1490                 }
1491         }
1492
1493         /* no room in the schedule */
1494         ehci_dbg (ehci, "iso %ssched full %p (now %d max %d)\n",
1495                 list_empty (&stream->td_list) ? "" : "re",
1496                 urb, now, now + mod);
1497         status = -ENOSPC;
1498
1499 fail:
1500         iso_sched_free (stream, sched);
1501         urb->hcpriv = NULL;
1502         return status;
1503
1504 ready:
1505         /* report high speed start in uframes; full speed, in frames */
1506         urb->start_frame = stream->next_uframe;
1507         if (!stream->highspeed)
1508                 urb->start_frame >>= 3;
1509         return 0;
1510 }
1511
1512 /*-------------------------------------------------------------------------*/
1513
1514 static inline void
1515 itd_init(struct ehci_hcd *ehci, struct ehci_iso_stream *stream,
1516                 struct ehci_itd *itd)
1517 {
1518         int i;
1519
1520         /* it's been recently zeroed */
1521         itd->hw_next = EHCI_LIST_END(ehci);
1522         itd->hw_bufp [0] = stream->buf0;
1523         itd->hw_bufp [1] = stream->buf1;
1524         itd->hw_bufp [2] = stream->buf2;
1525
1526         for (i = 0; i < 8; i++)
1527                 itd->index[i] = -1;
1528
1529         /* All other fields are filled when scheduling */
1530 }
1531
1532 static inline void
1533 itd_patch(
1534         struct ehci_hcd         *ehci,
1535         struct ehci_itd         *itd,
1536         struct ehci_iso_sched   *iso_sched,
1537         unsigned                index,
1538         u16                     uframe
1539 )
1540 {
1541         struct ehci_iso_packet  *uf = &iso_sched->packet [index];
1542         unsigned                pg = itd->pg;
1543
1544         // BUG_ON (pg == 6 && uf->cross);
1545
1546         uframe &= 0x07;
1547         itd->index [uframe] = index;
1548
1549         itd->hw_transaction[uframe] = uf->transaction;
1550         itd->hw_transaction[uframe] |= cpu_to_hc32(ehci, pg << 12);
1551         itd->hw_bufp[pg] |= cpu_to_hc32(ehci, uf->bufp & ~(u32)0);
1552         itd->hw_bufp_hi[pg] |= cpu_to_hc32(ehci, (u32)(uf->bufp >> 32));
1553
1554         /* iso_frame_desc[].offset must be strictly increasing */
1555         if (unlikely (uf->cross)) {
1556                 u64     bufp = uf->bufp + 4096;
1557
1558                 itd->pg = ++pg;
1559                 itd->hw_bufp[pg] |= cpu_to_hc32(ehci, bufp & ~(u32)0);
1560                 itd->hw_bufp_hi[pg] |= cpu_to_hc32(ehci, (u32)(bufp >> 32));
1561         }
1562 }
1563
1564 static inline void
1565 itd_link (struct ehci_hcd *ehci, unsigned frame, struct ehci_itd *itd)
1566 {
1567         union ehci_shadow       *prev = &ehci->pshadow[frame];
1568         __hc32                  *hw_p = &ehci->periodic[frame];
1569         union ehci_shadow       here = *prev;
1570         __hc32                  type = 0;
1571
1572         /* skip any iso nodes which might belong to previous microframes */
1573         while (here.ptr) {
1574                 type = Q_NEXT_TYPE(ehci, *hw_p);
1575                 if (type == cpu_to_hc32(ehci, Q_TYPE_QH))
1576                         break;
1577                 prev = periodic_next_shadow(ehci, prev, type);
1578                 hw_p = shadow_next_periodic(ehci, &here, type);
1579                 here = *prev;
1580         }
1581
1582         itd->itd_next = here;
1583         itd->hw_next = *hw_p;
1584         prev->itd = itd;
1585         itd->frame = frame;
1586         wmb ();
1587         *hw_p = cpu_to_hc32(ehci, itd->itd_dma | Q_TYPE_ITD);
1588 }
1589
1590 /* fit urb's itds into the selected schedule slot; activate as needed */
1591 static int
1592 itd_link_urb (
1593         struct ehci_hcd         *ehci,
1594         struct urb              *urb,
1595         unsigned                mod,
1596         struct ehci_iso_stream  *stream
1597 )
1598 {
1599         int                     packet;
1600         unsigned                next_uframe, uframe, frame;
1601         struct ehci_iso_sched   *iso_sched = urb->hcpriv;
1602         struct ehci_itd         *itd;
1603
1604         next_uframe = stream->next_uframe % mod;
1605
1606         if (unlikely (list_empty(&stream->td_list))) {
1607                 ehci_to_hcd(ehci)->self.bandwidth_allocated
1608                                 += stream->bandwidth;
1609                 ehci_vdbg (ehci,
1610                         "schedule devp %s ep%d%s-iso period %d start %d.%d\n",
1611                         urb->dev->devpath, stream->bEndpointAddress & 0x0f,
1612                         (stream->bEndpointAddress & USB_DIR_IN) ? "in" : "out",
1613                         urb->interval,
1614                         next_uframe >> 3, next_uframe & 0x7);
1615                 stream->start = jiffies;
1616         }
1617         ehci_to_hcd(ehci)->self.bandwidth_isoc_reqs++;
1618
1619         /* fill iTDs uframe by uframe */
1620         for (packet = 0, itd = NULL; packet < urb->number_of_packets; ) {
1621                 if (itd == NULL) {
1622                         /* ASSERT:  we have all necessary itds */
1623                         // BUG_ON (list_empty (&iso_sched->td_list));
1624
1625                         /* ASSERT:  no itds for this endpoint in this uframe */
1626
1627                         itd = list_entry (iso_sched->td_list.next,
1628                                         struct ehci_itd, itd_list);
1629                         list_move_tail (&itd->itd_list, &stream->td_list);
1630                         itd->stream = iso_stream_get (stream);
1631                         itd->urb = urb;
1632                         itd_init (ehci, stream, itd);
1633                 }
1634
1635                 uframe = next_uframe & 0x07;
1636                 frame = next_uframe >> 3;
1637
1638                 itd_patch(ehci, itd, iso_sched, packet, uframe);
1639
1640                 next_uframe += stream->interval;
1641                 stream->depth += stream->interval;
1642                 next_uframe %= mod;
1643                 packet++;
1644
1645                 /* link completed itds into the schedule */
1646                 if (((next_uframe >> 3) != frame)
1647                                 || packet == urb->number_of_packets) {
1648                         itd_link (ehci, frame % ehci->periodic_size, itd);
1649                         itd = NULL;
1650                 }
1651         }
1652         stream->next_uframe = next_uframe;
1653
1654         /* don't need that schedule data any more */
1655         iso_sched_free (stream, iso_sched);
1656         urb->hcpriv = NULL;
1657
1658         timer_action (ehci, TIMER_IO_WATCHDOG);
1659         return enable_periodic(ehci);
1660 }
1661
1662 #define ISO_ERRS (EHCI_ISOC_BUF_ERR | EHCI_ISOC_BABBLE | EHCI_ISOC_XACTERR)
1663
1664 /* Process and recycle a completed ITD.  Return true iff its urb completed,
1665  * and hence its completion callback probably added things to the hardware
1666  * schedule.
1667  *
1668  * Note that we carefully avoid recycling this descriptor until after any
1669  * completion callback runs, so that it won't be reused quickly.  That is,
1670  * assuming (a) no more than two urbs per frame on this endpoint, and also
1671  * (b) only this endpoint's completions submit URBs.  It seems some silicon
1672  * corrupts things if you reuse completed descriptors very quickly...
1673  */
1674 static unsigned
1675 itd_complete (
1676         struct ehci_hcd *ehci,
1677         struct ehci_itd *itd
1678 ) {
1679         struct urb                              *urb = itd->urb;
1680         struct usb_iso_packet_descriptor        *desc;
1681         u32                                     t;
1682         unsigned                                uframe;
1683         int                                     urb_index = -1;
1684         struct ehci_iso_stream                  *stream = itd->stream;
1685         struct usb_device                       *dev;
1686         unsigned                                retval = false;
1687
1688         /* for each uframe with a packet */
1689         for (uframe = 0; uframe < 8; uframe++) {
1690                 if (likely (itd->index[uframe] == -1))
1691                         continue;
1692                 urb_index = itd->index[uframe];
1693                 desc = &urb->iso_frame_desc [urb_index];
1694
1695                 t = hc32_to_cpup(ehci, &itd->hw_transaction [uframe]);
1696                 itd->hw_transaction [uframe] = 0;
1697                 stream->depth -= stream->interval;
1698
1699                 /* report transfer status */
1700                 if (unlikely (t & ISO_ERRS)) {
1701                         urb->error_count++;
1702                         if (t & EHCI_ISOC_BUF_ERR)
1703                                 desc->status = usb_pipein (urb->pipe)
1704                                         ? -ENOSR  /* hc couldn't read */
1705                                         : -ECOMM; /* hc couldn't write */
1706                         else if (t & EHCI_ISOC_BABBLE)
1707                                 desc->status = -EOVERFLOW;
1708                         else /* (t & EHCI_ISOC_XACTERR) */
1709                                 desc->status = -EPROTO;
1710
1711                         /* HC need not update length with this error */
1712                         if (!(t & EHCI_ISOC_BABBLE)) {
1713                                 desc->actual_length = EHCI_ITD_LENGTH(t);
1714                                 urb->actual_length += desc->actual_length;
1715                         }
1716                 } else if (likely ((t & EHCI_ISOC_ACTIVE) == 0)) {
1717                         desc->status = 0;
1718                         desc->actual_length = EHCI_ITD_LENGTH(t);
1719                         urb->actual_length += desc->actual_length;
1720                 } else {
1721                         /* URB was too late */
1722                         desc->status = -EXDEV;
1723                 }
1724         }
1725
1726         /* handle completion now? */
1727         if (likely ((urb_index + 1) != urb->number_of_packets))
1728                 goto done;
1729
1730         /* ASSERT: it's really the last itd for this urb
1731         list_for_each_entry (itd, &stream->td_list, itd_list)
1732                 BUG_ON (itd->urb == urb);
1733          */
1734
1735         /* give urb back to the driver; completion often (re)submits */
1736         dev = urb->dev;
1737         ehci_urb_done(ehci, urb, 0);
1738         retval = true;
1739         urb = NULL;
1740         (void) disable_periodic(ehci);
1741         ehci_to_hcd(ehci)->self.bandwidth_isoc_reqs--;
1742
1743         if (unlikely(list_is_singular(&stream->td_list))) {
1744                 ehci_to_hcd(ehci)->self.bandwidth_allocated
1745                                 -= stream->bandwidth;
1746                 ehci_vdbg (ehci,
1747                         "deschedule devp %s ep%d%s-iso\n",
1748                         dev->devpath, stream->bEndpointAddress & 0x0f,
1749                         (stream->bEndpointAddress & USB_DIR_IN) ? "in" : "out");
1750         }
1751         iso_stream_put (ehci, stream);
1752
1753 done:
1754         itd->urb = NULL;
1755         if (ehci->clock_frame != itd->frame || itd->index[7] != -1) {
1756                 /* OK to recycle this ITD now. */
1757                 itd->stream = NULL;
1758                 list_move(&itd->itd_list, &stream->free_list);
1759                 iso_stream_put(ehci, stream);
1760         } else {
1761                 /* HW might remember this ITD, so we can't recycle it yet.
1762                  * Move it to a safe place until a new frame starts.
1763                  */
1764                 list_move(&itd->itd_list, &ehci->cached_itd_list);
1765                 if (stream->refcount == 2) {
1766                         /* If iso_stream_put() were called here, stream
1767                          * would be freed.  Instead, just prevent reuse.
1768                          */
1769                         stream->ep->hcpriv = NULL;
1770                         stream->ep = NULL;
1771                 }
1772         }
1773         return retval;
1774 }
1775
1776 /*-------------------------------------------------------------------------*/
1777
1778 static int itd_submit (struct ehci_hcd *ehci, struct urb *urb,
1779         gfp_t mem_flags)
1780 {
1781         int                     status = -EINVAL;
1782         unsigned long           flags;
1783         struct ehci_iso_stream  *stream;
1784
1785         /* Get iso_stream head */
1786         stream = iso_stream_find (ehci, urb);
1787         if (unlikely (stream == NULL)) {
1788                 ehci_dbg (ehci, "can't get iso stream\n");
1789                 return -ENOMEM;
1790         }
1791         if (unlikely (urb->interval != stream->interval)) {
1792                 ehci_dbg (ehci, "can't change iso interval %d --> %d\n",
1793                         stream->interval, urb->interval);
1794                 goto done;
1795         }
1796
1797 #ifdef EHCI_URB_TRACE
1798         ehci_dbg (ehci,
1799                 "%s %s urb %p ep%d%s len %d, %d pkts %d uframes [%p]\n",
1800                 __func__, urb->dev->devpath, urb,
1801                 usb_pipeendpoint (urb->pipe),
1802                 usb_pipein (urb->pipe) ? "in" : "out",
1803                 urb->transfer_buffer_length,
1804                 urb->number_of_packets, urb->interval,
1805                 stream);
1806 #endif
1807
1808         /* allocate ITDs w/o locking anything */
1809         status = itd_urb_transaction (stream, ehci, urb, mem_flags);
1810         if (unlikely (status < 0)) {
1811                 ehci_dbg (ehci, "can't init itds\n");
1812                 goto done;
1813         }
1814
1815         /* schedule ... need to lock */
1816         spin_lock_irqsave (&ehci->lock, flags);
1817         if (unlikely(!HCD_HW_ACCESSIBLE(ehci_to_hcd(ehci)))) {
1818                 status = -ESHUTDOWN;
1819                 goto done_not_linked;
1820         }
1821         status = usb_hcd_link_urb_to_ep(ehci_to_hcd(ehci), urb);
1822         if (unlikely(status))
1823                 goto done_not_linked;
1824         status = iso_stream_schedule(ehci, urb, stream);
1825         if (likely (status == 0))
1826                 itd_link_urb (ehci, urb, ehci->periodic_size << 3, stream);
1827         else
1828                 usb_hcd_unlink_urb_from_ep(ehci_to_hcd(ehci), urb);
1829 done_not_linked:
1830         spin_unlock_irqrestore (&ehci->lock, flags);
1831
1832 done:
1833         if (unlikely (status < 0))
1834                 iso_stream_put (ehci, stream);
1835         return status;
1836 }
1837
1838 /*-------------------------------------------------------------------------*/
1839
1840 /*
1841  * "Split ISO TDs" ... used for USB 1.1 devices going through the
1842  * TTs in USB 2.0 hubs.  These need microframe scheduling.
1843  */
1844
1845 static inline void
1846 sitd_sched_init(
1847         struct ehci_hcd         *ehci,
1848         struct ehci_iso_sched   *iso_sched,
1849         struct ehci_iso_stream  *stream,
1850         struct urb              *urb
1851 )
1852 {
1853         unsigned        i;
1854         dma_addr_t      dma = urb->transfer_dma;
1855
1856         /* how many frames are needed for these transfers */
1857         iso_sched->span = urb->number_of_packets * stream->interval;
1858
1859         /* figure out per-frame sitd fields that we'll need later
1860          * when we fit new sitds into the schedule.
1861          */
1862         for (i = 0; i < urb->number_of_packets; i++) {
1863                 struct ehci_iso_packet  *packet = &iso_sched->packet [i];
1864                 unsigned                length;
1865                 dma_addr_t              buf;
1866                 u32                     trans;
1867
1868                 length = urb->iso_frame_desc [i].length & 0x03ff;
1869                 buf = dma + urb->iso_frame_desc [i].offset;
1870
1871                 trans = SITD_STS_ACTIVE;
1872                 if (((i + 1) == urb->number_of_packets)
1873                                 && !(urb->transfer_flags & URB_NO_INTERRUPT))
1874                         trans |= SITD_IOC;
1875                 trans |= length << 16;
1876                 packet->transaction = cpu_to_hc32(ehci, trans);
1877
1878                 /* might need to cross a buffer page within a td */
1879                 packet->bufp = buf;
1880                 packet->buf1 = (buf + length) & ~0x0fff;
1881                 if (packet->buf1 != (buf & ~(u64)0x0fff))
1882                         packet->cross = 1;
1883
1884                 /* OUT uses multiple start-splits */
1885                 if (stream->bEndpointAddress & USB_DIR_IN)
1886                         continue;
1887                 length = (length + 187) / 188;
1888                 if (length > 1) /* BEGIN vs ALL */
1889                         length |= 1 << 3;
1890                 packet->buf1 |= length;
1891         }
1892 }
1893
1894 static int
1895 sitd_urb_transaction (
1896         struct ehci_iso_stream  *stream,
1897         struct ehci_hcd         *ehci,
1898         struct urb              *urb,
1899         gfp_t                   mem_flags
1900 )
1901 {
1902         struct ehci_sitd        *sitd;
1903         dma_addr_t              sitd_dma;
1904         int                     i;
1905         struct ehci_iso_sched   *iso_sched;
1906         unsigned long           flags;
1907
1908         iso_sched = iso_sched_alloc (urb->number_of_packets, mem_flags);
1909         if (iso_sched == NULL)
1910                 return -ENOMEM;
1911
1912         sitd_sched_init(ehci, iso_sched, stream, urb);
1913
1914         /* allocate/init sITDs */
1915         spin_lock_irqsave (&ehci->lock, flags);
1916         for (i = 0; i < urb->number_of_packets; i++) {
1917
1918                 /* NOTE:  for now, we don't try to handle wraparound cases
1919                  * for IN (using sitd->hw_backpointer, like a FSTN), which
1920                  * means we never need two sitds for full speed packets.
1921                  */
1922
1923                 /* free_list.next might be cache-hot ... but maybe
1924                  * the HC caches it too. avoid that issue for now.
1925                  */
1926
1927                 /* prefer previously-allocated sitds */
1928                 if (!list_empty(&stream->free_list)) {
1929                         sitd = list_entry (stream->free_list.prev,
1930                                          struct ehci_sitd, sitd_list);
1931                         list_del (&sitd->sitd_list);
1932                         sitd_dma = sitd->sitd_dma;
1933                 } else {
1934                         spin_unlock_irqrestore (&ehci->lock, flags);
1935                         sitd = dma_pool_alloc (ehci->sitd_pool, mem_flags,
1936                                         &sitd_dma);
1937                         spin_lock_irqsave (&ehci->lock, flags);
1938                         if (!sitd) {
1939                                 iso_sched_free(stream, iso_sched);
1940                                 spin_unlock_irqrestore(&ehci->lock, flags);
1941                                 return -ENOMEM;
1942                         }
1943                 }
1944
1945                 memset (sitd, 0, sizeof *sitd);
1946                 sitd->sitd_dma = sitd_dma;
1947                 list_add (&sitd->sitd_list, &iso_sched->td_list);
1948         }
1949
1950         /* temporarily store schedule info in hcpriv */
1951         urb->hcpriv = iso_sched;
1952         urb->error_count = 0;
1953
1954         spin_unlock_irqrestore (&ehci->lock, flags);
1955         return 0;
1956 }
1957
1958 /*-------------------------------------------------------------------------*/
1959
1960 static inline void
1961 sitd_patch(
1962         struct ehci_hcd         *ehci,
1963         struct ehci_iso_stream  *stream,
1964         struct ehci_sitd        *sitd,
1965         struct ehci_iso_sched   *iso_sched,
1966         unsigned                index
1967 )
1968 {
1969         struct ehci_iso_packet  *uf = &iso_sched->packet [index];
1970         u64                     bufp = uf->bufp;
1971
1972         sitd->hw_next = EHCI_LIST_END(ehci);
1973         sitd->hw_fullspeed_ep = stream->address;
1974         sitd->hw_uframe = stream->splits;
1975         sitd->hw_results = uf->transaction;
1976         sitd->hw_backpointer = EHCI_LIST_END(ehci);
1977
1978         bufp = uf->bufp;
1979         sitd->hw_buf[0] = cpu_to_hc32(ehci, bufp);
1980         sitd->hw_buf_hi[0] = cpu_to_hc32(ehci, bufp >> 32);
1981
1982         sitd->hw_buf[1] = cpu_to_hc32(ehci, uf->buf1);
1983         if (uf->cross)
1984                 bufp += 4096;
1985         sitd->hw_buf_hi[1] = cpu_to_hc32(ehci, bufp >> 32);
1986         sitd->index = index;
1987 }
1988
1989 static inline void
1990 sitd_link (struct ehci_hcd *ehci, unsigned frame, struct ehci_sitd *sitd)
1991 {
1992         /* note: sitd ordering could matter (CSPLIT then SSPLIT) */
1993         sitd->sitd_next = ehci->pshadow [frame];
1994         sitd->hw_next = ehci->periodic [frame];
1995         ehci->pshadow [frame].sitd = sitd;
1996         sitd->frame = frame;
1997         wmb ();
1998         ehci->periodic[frame] = cpu_to_hc32(ehci, sitd->sitd_dma | Q_TYPE_SITD);
1999 }
2000
2001 /* fit urb's sitds into the selected schedule slot; activate as needed */
2002 static int
2003 sitd_link_urb (
2004         struct ehci_hcd         *ehci,
2005         struct urb              *urb,
2006         unsigned                mod,
2007         struct ehci_iso_stream  *stream
2008 )
2009 {
2010         int                     packet;
2011         unsigned                next_uframe;
2012         struct ehci_iso_sched   *sched = urb->hcpriv;
2013         struct ehci_sitd        *sitd;
2014
2015         next_uframe = stream->next_uframe;
2016
2017         if (list_empty(&stream->td_list)) {
2018                 /* usbfs ignores TT bandwidth */
2019                 ehci_to_hcd(ehci)->self.bandwidth_allocated
2020                                 += stream->bandwidth;
2021                 ehci_vdbg (ehci,
2022                         "sched devp %s ep%d%s-iso [%d] %dms/%04x\n",
2023                         urb->dev->devpath, stream->bEndpointAddress & 0x0f,
2024                         (stream->bEndpointAddress & USB_DIR_IN) ? "in" : "out",
2025                         (next_uframe >> 3) % ehci->periodic_size,
2026                         stream->interval, hc32_to_cpu(ehci, stream->splits));
2027                 stream->start = jiffies;
2028         }
2029         ehci_to_hcd(ehci)->self.bandwidth_isoc_reqs++;
2030
2031         /* fill sITDs frame by frame */
2032         for (packet = 0, sitd = NULL;
2033                         packet < urb->number_of_packets;
2034                         packet++) {
2035
2036                 /* ASSERT:  we have all necessary sitds */
2037                 BUG_ON (list_empty (&sched->td_list));
2038
2039                 /* ASSERT:  no itds for this endpoint in this frame */
2040
2041                 sitd = list_entry (sched->td_list.next,
2042                                 struct ehci_sitd, sitd_list);
2043                 list_move_tail (&sitd->sitd_list, &stream->td_list);
2044                 sitd->stream = iso_stream_get (stream);
2045                 sitd->urb = urb;
2046
2047                 sitd_patch(ehci, stream, sitd, sched, packet);
2048                 sitd_link (ehci, (next_uframe >> 3) % ehci->periodic_size,
2049                                 sitd);
2050
2051                 next_uframe += stream->interval << 3;
2052                 stream->depth += stream->interval << 3;
2053         }
2054         stream->next_uframe = next_uframe % mod;
2055
2056         /* don't need that schedule data any more */
2057         iso_sched_free (stream, sched);
2058         urb->hcpriv = NULL;
2059
2060         timer_action (ehci, TIMER_IO_WATCHDOG);
2061         return enable_periodic(ehci);
2062 }
2063
2064 /*-------------------------------------------------------------------------*/
2065
2066 #define SITD_ERRS (SITD_STS_ERR | SITD_STS_DBE | SITD_STS_BABBLE \
2067                                 | SITD_STS_XACT | SITD_STS_MMF)
2068
2069 /* Process and recycle a completed SITD.  Return true iff its urb completed,
2070  * and hence its completion callback probably added things to the hardware
2071  * schedule.
2072  *
2073  * Note that we carefully avoid recycling this descriptor until after any
2074  * completion callback runs, so that it won't be reused quickly.  That is,
2075  * assuming (a) no more than two urbs per frame on this endpoint, and also
2076  * (b) only this endpoint's completions submit URBs.  It seems some silicon
2077  * corrupts things if you reuse completed descriptors very quickly...
2078  */
2079 static unsigned
2080 sitd_complete (
2081         struct ehci_hcd         *ehci,
2082         struct ehci_sitd        *sitd
2083 ) {
2084         struct urb                              *urb = sitd->urb;
2085         struct usb_iso_packet_descriptor        *desc;
2086         u32                                     t;
2087         int                                     urb_index = -1;
2088         struct ehci_iso_stream                  *stream = sitd->stream;
2089         struct usb_device                       *dev;
2090         unsigned                                retval = false;
2091
2092         urb_index = sitd->index;
2093         desc = &urb->iso_frame_desc [urb_index];
2094         t = hc32_to_cpup(ehci, &sitd->hw_results);
2095
2096         /* report transfer status */
2097         if (t & SITD_ERRS) {
2098                 urb->error_count++;
2099                 if (t & SITD_STS_DBE)
2100                         desc->status = usb_pipein (urb->pipe)
2101                                 ? -ENOSR  /* hc couldn't read */
2102                                 : -ECOMM; /* hc couldn't write */
2103                 else if (t & SITD_STS_BABBLE)
2104                         desc->status = -EOVERFLOW;
2105                 else /* XACT, MMF, etc */
2106                         desc->status = -EPROTO;
2107         } else {
2108                 desc->status = 0;
2109                 desc->actual_length = desc->length - SITD_LENGTH(t);
2110                 urb->actual_length += desc->actual_length;
2111         }
2112         stream->depth -= stream->interval << 3;
2113
2114         /* handle completion now? */
2115         if ((urb_index + 1) != urb->number_of_packets)
2116                 goto done;
2117
2118         /* ASSERT: it's really the last sitd for this urb
2119         list_for_each_entry (sitd, &stream->td_list, sitd_list)
2120                 BUG_ON (sitd->urb == urb);
2121          */
2122
2123         /* give urb back to the driver; completion often (re)submits */
2124         dev = urb->dev;
2125         ehci_urb_done(ehci, urb, 0);
2126         retval = true;
2127         urb = NULL;
2128         (void) disable_periodic(ehci);
2129         ehci_to_hcd(ehci)->self.bandwidth_isoc_reqs--;
2130
2131         if (list_is_singular(&stream->td_list)) {
2132                 ehci_to_hcd(ehci)->self.bandwidth_allocated
2133                                 -= stream->bandwidth;
2134                 ehci_vdbg (ehci,
2135                         "deschedule devp %s ep%d%s-iso\n",
2136                         dev->devpath, stream->bEndpointAddress & 0x0f,
2137                         (stream->bEndpointAddress & USB_DIR_IN) ? "in" : "out");
2138         }
2139         iso_stream_put (ehci, stream);
2140
2141 done:
2142         sitd->urb = NULL;
2143         if (ehci->clock_frame != sitd->frame) {
2144                 /* OK to recycle this SITD now. */
2145                 sitd->stream = NULL;
2146                 list_move(&sitd->sitd_list, &stream->free_list);
2147                 iso_stream_put(ehci, stream);
2148         } else {
2149                 /* HW might remember this SITD, so we can't recycle it yet.
2150                  * Move it to a safe place until a new frame starts.
2151                  */
2152                 list_move(&sitd->sitd_list, &ehci->cached_sitd_list);
2153                 if (stream->refcount == 2) {
2154                         /* If iso_stream_put() were called here, stream
2155                          * would be freed.  Instead, just prevent reuse.
2156                          */
2157                         stream->ep->hcpriv = NULL;
2158                         stream->ep = NULL;
2159                 }
2160         }
2161         return retval;
2162 }
2163
2164
2165 static int sitd_submit (struct ehci_hcd *ehci, struct urb *urb,
2166         gfp_t mem_flags)
2167 {
2168         int                     status = -EINVAL;
2169         unsigned long           flags;
2170         struct ehci_iso_stream  *stream;
2171
2172         /* Get iso_stream head */
2173         stream = iso_stream_find (ehci, urb);
2174         if (stream == NULL) {
2175                 ehci_dbg (ehci, "can't get iso stream\n");
2176                 return -ENOMEM;
2177         }
2178         if (urb->interval != stream->interval) {
2179                 ehci_dbg (ehci, "can't change iso interval %d --> %d\n",
2180                         stream->interval, urb->interval);
2181                 goto done;
2182         }
2183
2184 #ifdef EHCI_URB_TRACE
2185         ehci_dbg (ehci,
2186                 "submit %p dev%s ep%d%s-iso len %d\n",
2187                 urb, urb->dev->devpath,
2188                 usb_pipeendpoint (urb->pipe),
2189                 usb_pipein (urb->pipe) ? "in" : "out",
2190                 urb->transfer_buffer_length);
2191 #endif
2192
2193         /* allocate SITDs */
2194         status = sitd_urb_transaction (stream, ehci, urb, mem_flags);
2195         if (status < 0) {
2196                 ehci_dbg (ehci, "can't init sitds\n");
2197                 goto done;
2198         }
2199
2200         /* schedule ... need to lock */
2201         spin_lock_irqsave (&ehci->lock, flags);
2202         if (unlikely(!HCD_HW_ACCESSIBLE(ehci_to_hcd(ehci)))) {
2203                 status = -ESHUTDOWN;
2204                 goto done_not_linked;
2205         }
2206         status = usb_hcd_link_urb_to_ep(ehci_to_hcd(ehci), urb);
2207         if (unlikely(status))
2208                 goto done_not_linked;
2209         status = iso_stream_schedule(ehci, urb, stream);
2210         if (status == 0)
2211                 sitd_link_urb (ehci, urb, ehci->periodic_size << 3, stream);
2212         else
2213                 usb_hcd_unlink_urb_from_ep(ehci_to_hcd(ehci), urb);
2214 done_not_linked:
2215         spin_unlock_irqrestore (&ehci->lock, flags);
2216
2217 done:
2218         if (status < 0)
2219                 iso_stream_put (ehci, stream);
2220         return status;
2221 }
2222
2223 /*-------------------------------------------------------------------------*/
2224
2225 static void free_cached_lists(struct ehci_hcd *ehci)
2226 {
2227         struct ehci_itd *itd, *n;
2228         struct ehci_sitd *sitd, *sn;
2229
2230         list_for_each_entry_safe(itd, n, &ehci->cached_itd_list, itd_list) {
2231                 struct ehci_iso_stream  *stream = itd->stream;
2232                 itd->stream = NULL;
2233                 list_move(&itd->itd_list, &stream->free_list);
2234                 iso_stream_put(ehci, stream);
2235         }
2236
2237         list_for_each_entry_safe(sitd, sn, &ehci->cached_sitd_list, sitd_list) {
2238                 struct ehci_iso_stream  *stream = sitd->stream;
2239                 sitd->stream = NULL;
2240                 list_move(&sitd->sitd_list, &stream->free_list);
2241                 iso_stream_put(ehci, stream);
2242         }
2243 }
2244
2245 /*-------------------------------------------------------------------------*/
2246
2247 static void
2248 scan_periodic (struct ehci_hcd *ehci)
2249 {
2250         unsigned        now_uframe, frame, clock, clock_frame, mod;
2251         unsigned        modified;
2252
2253         mod = ehci->periodic_size << 3;
2254
2255         /*
2256          * When running, scan from last scan point up to "now"
2257          * else clean up by scanning everything that's left.
2258          * Touches as few pages as possible:  cache-friendly.
2259          */
2260         now_uframe = ehci->next_uframe;
2261         if (HC_IS_RUNNING(ehci_to_hcd(ehci)->state)) {
2262                 clock = ehci_readl(ehci, &ehci->regs->frame_index);
2263                 clock_frame = (clock >> 3) % ehci->periodic_size;
2264         } else  {
2265                 clock = now_uframe + mod - 1;
2266                 clock_frame = -1;
2267         }
2268         if (ehci->clock_frame != clock_frame) {
2269                 free_cached_lists(ehci);
2270                 ehci->clock_frame = clock_frame;
2271         }
2272         clock %= mod;
2273         clock_frame = clock >> 3;
2274
2275         for (;;) {
2276                 union ehci_shadow       q, *q_p;
2277                 __hc32                  type, *hw_p;
2278                 unsigned                incomplete = false;
2279
2280                 frame = now_uframe >> 3;
2281
2282 restart:
2283                 /* scan each element in frame's queue for completions */
2284                 q_p = &ehci->pshadow [frame];
2285                 hw_p = &ehci->periodic [frame];
2286                 q.ptr = q_p->ptr;
2287                 type = Q_NEXT_TYPE(ehci, *hw_p);
2288                 modified = 0;
2289
2290                 while (q.ptr != NULL) {
2291                         unsigned                uf;
2292                         union ehci_shadow       temp;
2293                         int                     live;
2294
2295                         live = HC_IS_RUNNING (ehci_to_hcd(ehci)->state);
2296                         switch (hc32_to_cpu(ehci, type)) {
2297                         case Q_TYPE_QH:
2298                                 /* handle any completions */
2299                                 temp.qh = qh_get (q.qh);
2300                                 type = Q_NEXT_TYPE(ehci, q.qh->hw->hw_next);
2301                                 q = q.qh->qh_next;
2302                                 modified = qh_completions (ehci, temp.qh);
2303                                 if (unlikely(list_empty(&temp.qh->qtd_list) ||
2304                                                 temp.qh->needs_rescan))
2305                                         intr_deschedule (ehci, temp.qh);
2306                                 qh_put (temp.qh);
2307                                 break;
2308                         case Q_TYPE_FSTN:
2309                                 /* for "save place" FSTNs, look at QH entries
2310                                  * in the previous frame for completions.
2311                                  */
2312                                 if (q.fstn->hw_prev != EHCI_LIST_END(ehci)) {
2313                                         dbg ("ignoring completions from FSTNs");
2314                                 }
2315                                 type = Q_NEXT_TYPE(ehci, q.fstn->hw_next);
2316                                 q = q.fstn->fstn_next;
2317                                 break;
2318                         case Q_TYPE_ITD:
2319                                 /* If this ITD is still active, leave it for
2320                                  * later processing ... check the next entry.
2321                                  * No need to check for activity unless the
2322                                  * frame is current.
2323                                  */
2324                                 if (frame == clock_frame && live) {
2325                                         rmb();
2326                                         for (uf = 0; uf < 8; uf++) {
2327                                                 if (q.itd->hw_transaction[uf] &
2328                                                             ITD_ACTIVE(ehci))
2329                                                         break;
2330                                         }
2331                                         if (uf < 8) {
2332                                                 incomplete = true;
2333                                                 q_p = &q.itd->itd_next;
2334                                                 hw_p = &q.itd->hw_next;
2335                                                 type = Q_NEXT_TYPE(ehci,
2336                                                         q.itd->hw_next);
2337                                                 q = *q_p;
2338                                                 break;
2339                                         }
2340                                 }
2341
2342                                 /* Take finished ITDs out of the schedule
2343                                  * and process them:  recycle, maybe report
2344                                  * URB completion.  HC won't cache the
2345                                  * pointer for much longer, if at all.
2346                                  */
2347                                 *q_p = q.itd->itd_next;
2348                                 *hw_p = q.itd->hw_next;
2349                                 type = Q_NEXT_TYPE(ehci, q.itd->hw_next);
2350                                 wmb();
2351                                 modified = itd_complete (ehci, q.itd);
2352                                 q = *q_p;
2353                                 break;
2354                         case Q_TYPE_SITD:
2355                                 /* If this SITD is still active, leave it for
2356                                  * later processing ... check the next entry.
2357                                  * No need to check for activity unless the
2358                                  * frame is current.
2359                                  */
2360                                 if (((frame == clock_frame) ||
2361                                      (((frame + 1) % ehci->periodic_size)
2362                                       == clock_frame))
2363                                     && live
2364                                     && (q.sitd->hw_results &
2365                                         SITD_ACTIVE(ehci))) {
2366
2367                                         incomplete = true;
2368                                         q_p = &q.sitd->sitd_next;
2369                                         hw_p = &q.sitd->hw_next;
2370                                         type = Q_NEXT_TYPE(ehci,
2371                                                         q.sitd->hw_next);
2372                                         q = *q_p;
2373                                         break;
2374                                 }
2375
2376                                 /* Take finished SITDs out of the schedule
2377                                  * and process them:  recycle, maybe report
2378                                  * URB completion.
2379                                  */
2380                                 *q_p = q.sitd->sitd_next;
2381                                 *hw_p = q.sitd->hw_next;
2382                                 type = Q_NEXT_TYPE(ehci, q.sitd->hw_next);
2383                                 wmb();
2384                                 modified = sitd_complete (ehci, q.sitd);
2385                                 q = *q_p;
2386                                 break;
2387                         default:
2388                                 dbg ("corrupt type %d frame %d shadow %p",
2389                                         type, frame, q.ptr);
2390                                 // BUG ();
2391                                 q.ptr = NULL;
2392                         }
2393
2394                         /* assume completion callbacks modify the queue */
2395                         if (unlikely (modified)) {
2396                                 if (likely(ehci->periodic_sched > 0))
2397                                         goto restart;
2398                                 /* short-circuit this scan */
2399                                 now_uframe = clock;
2400                                 break;
2401                         }
2402                 }
2403
2404                 /* If we can tell we caught up to the hardware, stop now.
2405                  * We can't advance our scan without collecting the ISO
2406                  * transfers that are still pending in this frame.
2407                  */
2408                 if (incomplete && HC_IS_RUNNING(ehci_to_hcd(ehci)->state)) {
2409                         ehci->next_uframe = now_uframe;
2410                         break;
2411                 }
2412
2413                 // FIXME:  this assumes we won't get lapped when
2414                 // latencies climb; that should be rare, but...
2415                 // detect it, and just go all the way around.
2416                 // FLR might help detect this case, so long as latencies
2417                 // don't exceed periodic_size msec (default 1.024 sec).
2418
2419                 // FIXME:  likewise assumes HC doesn't halt mid-scan
2420
2421                 if (now_uframe == clock) {
2422                         unsigned        now;
2423
2424                         if (!HC_IS_RUNNING (ehci_to_hcd(ehci)->state)
2425                                         || ehci->periodic_sched == 0)
2426                                 break;
2427                         ehci->next_uframe = now_uframe;
2428                         now = ehci_readl(ehci, &ehci->regs->frame_index) % mod;
2429                         if (now_uframe == now)
2430                                 break;
2431
2432                         /* rescan the rest of this frame, then ... */
2433                         clock = now;
2434                         clock_frame = clock >> 3;
2435                         if (ehci->clock_frame != clock_frame) {
2436                                 free_cached_lists(ehci);
2437                                 ehci->clock_frame = clock_frame;
2438                         }
2439                 } else {
2440                         now_uframe++;
2441                         now_uframe %= mod;
2442                 }
2443         }
2444 }