Intel xhci: Ignore spurious successful event.
[pandora-kernel.git] / drivers / usb / host / xhci-ring.c
1 /*
2  * xHCI host controller driver
3  *
4  * Copyright (C) 2008 Intel Corp.
5  *
6  * Author: Sarah Sharp
7  * Some code borrowed from the Linux EHCI driver.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16  * for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22
23 /*
24  * Ring initialization rules:
25  * 1. Each segment is initialized to zero, except for link TRBs.
26  * 2. Ring cycle state = 0.  This represents Producer Cycle State (PCS) or
27  *    Consumer Cycle State (CCS), depending on ring function.
28  * 3. Enqueue pointer = dequeue pointer = address of first TRB in the segment.
29  *
30  * Ring behavior rules:
31  * 1. A ring is empty if enqueue == dequeue.  This means there will always be at
32  *    least one free TRB in the ring.  This is useful if you want to turn that
33  *    into a link TRB and expand the ring.
34  * 2. When incrementing an enqueue or dequeue pointer, if the next TRB is a
35  *    link TRB, then load the pointer with the address in the link TRB.  If the
36  *    link TRB had its toggle bit set, you may need to update the ring cycle
37  *    state (see cycle bit rules).  You may have to do this multiple times
38  *    until you reach a non-link TRB.
39  * 3. A ring is full if enqueue++ (for the definition of increment above)
40  *    equals the dequeue pointer.
41  *
42  * Cycle bit rules:
43  * 1. When a consumer increments a dequeue pointer and encounters a toggle bit
44  *    in a link TRB, it must toggle the ring cycle state.
45  * 2. When a producer increments an enqueue pointer and encounters a toggle bit
46  *    in a link TRB, it must toggle the ring cycle state.
47  *
48  * Producer rules:
49  * 1. Check if ring is full before you enqueue.
50  * 2. Write the ring cycle state to the cycle bit in the TRB you're enqueuing.
51  *    Update enqueue pointer between each write (which may update the ring
52  *    cycle state).
53  * 3. Notify consumer.  If SW is producer, it rings the doorbell for command
54  *    and endpoint rings.  If HC is the producer for the event ring,
55  *    and it generates an interrupt according to interrupt modulation rules.
56  *
57  * Consumer rules:
58  * 1. Check if TRB belongs to you.  If the cycle bit == your ring cycle state,
59  *    the TRB is owned by the consumer.
60  * 2. Update dequeue pointer (which may update the ring cycle state) and
61  *    continue processing TRBs until you reach a TRB which is not owned by you.
62  * 3. Notify the producer.  SW is the consumer for the event ring, and it
63  *   updates event ring dequeue pointer.  HC is the consumer for the command and
64  *   endpoint rings; it generates events on the event ring for these.
65  */
66
67 #include <linux/scatterlist.h>
68 #include <linux/slab.h>
69 #include "xhci.h"
70
71 static int handle_cmd_in_cmd_wait_list(struct xhci_hcd *xhci,
72                 struct xhci_virt_device *virt_dev,
73                 struct xhci_event_cmd *event);
74
75 /*
76  * Returns zero if the TRB isn't in this segment, otherwise it returns the DMA
77  * address of the TRB.
78  */
79 dma_addr_t xhci_trb_virt_to_dma(struct xhci_segment *seg,
80                 union xhci_trb *trb)
81 {
82         unsigned long segment_offset;
83
84         if (!seg || !trb || trb < seg->trbs)
85                 return 0;
86         /* offset in TRBs */
87         segment_offset = trb - seg->trbs;
88         if (segment_offset > TRBS_PER_SEGMENT)
89                 return 0;
90         return seg->dma + (segment_offset * sizeof(*trb));
91 }
92
93 /* Does this link TRB point to the first segment in a ring,
94  * or was the previous TRB the last TRB on the last segment in the ERST?
95  */
96 static bool last_trb_on_last_seg(struct xhci_hcd *xhci, struct xhci_ring *ring,
97                 struct xhci_segment *seg, union xhci_trb *trb)
98 {
99         if (ring == xhci->event_ring)
100                 return (trb == &seg->trbs[TRBS_PER_SEGMENT]) &&
101                         (seg->next == xhci->event_ring->first_seg);
102         else
103                 return le32_to_cpu(trb->link.control) & LINK_TOGGLE;
104 }
105
106 /* Is this TRB a link TRB or was the last TRB the last TRB in this event ring
107  * segment?  I.e. would the updated event TRB pointer step off the end of the
108  * event seg?
109  */
110 static int last_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
111                 struct xhci_segment *seg, union xhci_trb *trb)
112 {
113         if (ring == xhci->event_ring)
114                 return trb == &seg->trbs[TRBS_PER_SEGMENT];
115         else
116                 return (le32_to_cpu(trb->link.control) & TRB_TYPE_BITMASK)
117                         == TRB_TYPE(TRB_LINK);
118 }
119
120 static int enqueue_is_link_trb(struct xhci_ring *ring)
121 {
122         struct xhci_link_trb *link = &ring->enqueue->link;
123         return ((le32_to_cpu(link->control) & TRB_TYPE_BITMASK) ==
124                 TRB_TYPE(TRB_LINK));
125 }
126
127 /* Updates trb to point to the next TRB in the ring, and updates seg if the next
128  * TRB is in a new segment.  This does not skip over link TRBs, and it does not
129  * effect the ring dequeue or enqueue pointers.
130  */
131 static void next_trb(struct xhci_hcd *xhci,
132                 struct xhci_ring *ring,
133                 struct xhci_segment **seg,
134                 union xhci_trb **trb)
135 {
136         if (last_trb(xhci, ring, *seg, *trb)) {
137                 *seg = (*seg)->next;
138                 *trb = ((*seg)->trbs);
139         } else {
140                 (*trb)++;
141         }
142 }
143
144 /*
145  * See Cycle bit rules. SW is the consumer for the event ring only.
146  * Don't make a ring full of link TRBs.  That would be dumb and this would loop.
147  */
148 static void inc_deq(struct xhci_hcd *xhci, struct xhci_ring *ring, bool consumer)
149 {
150         union xhci_trb *next = ++(ring->dequeue);
151         unsigned long long addr;
152
153         ring->deq_updates++;
154         /* Update the dequeue pointer further if that was a link TRB or we're at
155          * the end of an event ring segment (which doesn't have link TRBS)
156          */
157         while (last_trb(xhci, ring, ring->deq_seg, next)) {
158                 if (consumer && last_trb_on_last_seg(xhci, ring, ring->deq_seg, next)) {
159                         ring->cycle_state = (ring->cycle_state ? 0 : 1);
160                         if (!in_interrupt())
161                                 xhci_dbg(xhci, "Toggle cycle state for ring %p = %i\n",
162                                                 ring,
163                                                 (unsigned int) ring->cycle_state);
164                 }
165                 ring->deq_seg = ring->deq_seg->next;
166                 ring->dequeue = ring->deq_seg->trbs;
167                 next = ring->dequeue;
168         }
169         addr = (unsigned long long) xhci_trb_virt_to_dma(ring->deq_seg, ring->dequeue);
170 }
171
172 /*
173  * See Cycle bit rules. SW is the consumer for the event ring only.
174  * Don't make a ring full of link TRBs.  That would be dumb and this would loop.
175  *
176  * If we've just enqueued a TRB that is in the middle of a TD (meaning the
177  * chain bit is set), then set the chain bit in all the following link TRBs.
178  * If we've enqueued the last TRB in a TD, make sure the following link TRBs
179  * have their chain bit cleared (so that each Link TRB is a separate TD).
180  *
181  * Section 6.4.4.1 of the 0.95 spec says link TRBs cannot have the chain bit
182  * set, but other sections talk about dealing with the chain bit set.  This was
183  * fixed in the 0.96 specification errata, but we have to assume that all 0.95
184  * xHCI hardware can't handle the chain bit being cleared on a link TRB.
185  *
186  * @more_trbs_coming:   Will you enqueue more TRBs before calling
187  *                      prepare_transfer()?
188  */
189 static void inc_enq(struct xhci_hcd *xhci, struct xhci_ring *ring,
190                 bool consumer, bool more_trbs_coming)
191 {
192         u32 chain;
193         union xhci_trb *next;
194         unsigned long long addr;
195
196         chain = le32_to_cpu(ring->enqueue->generic.field[3]) & TRB_CHAIN;
197         next = ++(ring->enqueue);
198
199         ring->enq_updates++;
200         /* Update the dequeue pointer further if that was a link TRB or we're at
201          * the end of an event ring segment (which doesn't have link TRBS)
202          */
203         while (last_trb(xhci, ring, ring->enq_seg, next)) {
204                 if (!consumer) {
205                         if (ring != xhci->event_ring) {
206                                 /*
207                                  * If the caller doesn't plan on enqueueing more
208                                  * TDs before ringing the doorbell, then we
209                                  * don't want to give the link TRB to the
210                                  * hardware just yet.  We'll give the link TRB
211                                  * back in prepare_ring() just before we enqueue
212                                  * the TD at the top of the ring.
213                                  */
214                                 if (!chain && !more_trbs_coming)
215                                         break;
216
217                                 /* If we're not dealing with 0.95 hardware,
218                                  * carry over the chain bit of the previous TRB
219                                  * (which may mean the chain bit is cleared).
220                                  */
221                                 if (!xhci_link_trb_quirk(xhci)) {
222                                         next->link.control &=
223                                                 cpu_to_le32(~TRB_CHAIN);
224                                         next->link.control |=
225                                                 cpu_to_le32(chain);
226                                 }
227                                 /* Give this link TRB to the hardware */
228                                 wmb();
229                                 next->link.control ^= cpu_to_le32(TRB_CYCLE);
230                         }
231                         /* Toggle the cycle bit after the last ring segment. */
232                         if (last_trb_on_last_seg(xhci, ring, ring->enq_seg, next)) {
233                                 ring->cycle_state = (ring->cycle_state ? 0 : 1);
234                                 if (!in_interrupt())
235                                         xhci_dbg(xhci, "Toggle cycle state for ring %p = %i\n",
236                                                         ring,
237                                                         (unsigned int) ring->cycle_state);
238                         }
239                 }
240                 ring->enq_seg = ring->enq_seg->next;
241                 ring->enqueue = ring->enq_seg->trbs;
242                 next = ring->enqueue;
243         }
244         addr = (unsigned long long) xhci_trb_virt_to_dma(ring->enq_seg, ring->enqueue);
245 }
246
247 /*
248  * Check to see if there's room to enqueue num_trbs on the ring.  See rules
249  * above.
250  * FIXME: this would be simpler and faster if we just kept track of the number
251  * of free TRBs in a ring.
252  */
253 static int room_on_ring(struct xhci_hcd *xhci, struct xhci_ring *ring,
254                 unsigned int num_trbs)
255 {
256         int i;
257         union xhci_trb *enq = ring->enqueue;
258         struct xhci_segment *enq_seg = ring->enq_seg;
259         struct xhci_segment *cur_seg;
260         unsigned int left_on_ring;
261
262         /* If we are currently pointing to a link TRB, advance the
263          * enqueue pointer before checking for space */
264         while (last_trb(xhci, ring, enq_seg, enq)) {
265                 enq_seg = enq_seg->next;
266                 enq = enq_seg->trbs;
267         }
268
269         /* Check if ring is empty */
270         if (enq == ring->dequeue) {
271                 /* Can't use link trbs */
272                 left_on_ring = TRBS_PER_SEGMENT - 1;
273                 for (cur_seg = enq_seg->next; cur_seg != enq_seg;
274                                 cur_seg = cur_seg->next)
275                         left_on_ring += TRBS_PER_SEGMENT - 1;
276
277                 /* Always need one TRB free in the ring. */
278                 left_on_ring -= 1;
279                 if (num_trbs > left_on_ring) {
280                         xhci_warn(xhci, "Not enough room on ring; "
281                                         "need %u TRBs, %u TRBs left\n",
282                                         num_trbs, left_on_ring);
283                         return 0;
284                 }
285                 return 1;
286         }
287         /* Make sure there's an extra empty TRB available */
288         for (i = 0; i <= num_trbs; ++i) {
289                 if (enq == ring->dequeue)
290                         return 0;
291                 enq++;
292                 while (last_trb(xhci, ring, enq_seg, enq)) {
293                         enq_seg = enq_seg->next;
294                         enq = enq_seg->trbs;
295                 }
296         }
297         return 1;
298 }
299
300 /* Ring the host controller doorbell after placing a command on the ring */
301 void xhci_ring_cmd_db(struct xhci_hcd *xhci)
302 {
303         xhci_dbg(xhci, "// Ding dong!\n");
304         xhci_writel(xhci, DB_VALUE_HOST, &xhci->dba->doorbell[0]);
305         /* Flush PCI posted writes */
306         xhci_readl(xhci, &xhci->dba->doorbell[0]);
307 }
308
309 void xhci_ring_ep_doorbell(struct xhci_hcd *xhci,
310                 unsigned int slot_id,
311                 unsigned int ep_index,
312                 unsigned int stream_id)
313 {
314         __le32 __iomem *db_addr = &xhci->dba->doorbell[slot_id];
315         struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index];
316         unsigned int ep_state = ep->ep_state;
317
318         /* Don't ring the doorbell for this endpoint if there are pending
319          * cancellations because we don't want to interrupt processing.
320          * We don't want to restart any stream rings if there's a set dequeue
321          * pointer command pending because the device can choose to start any
322          * stream once the endpoint is on the HW schedule.
323          * FIXME - check all the stream rings for pending cancellations.
324          */
325         if ((ep_state & EP_HALT_PENDING) || (ep_state & SET_DEQ_PENDING) ||
326             (ep_state & EP_HALTED))
327                 return;
328         xhci_writel(xhci, DB_VALUE(ep_index, stream_id), db_addr);
329         /* The CPU has better things to do at this point than wait for a
330          * write-posting flush.  It'll get there soon enough.
331          */
332 }
333
334 /* Ring the doorbell for any rings with pending URBs */
335 static void ring_doorbell_for_active_rings(struct xhci_hcd *xhci,
336                 unsigned int slot_id,
337                 unsigned int ep_index)
338 {
339         unsigned int stream_id;
340         struct xhci_virt_ep *ep;
341
342         ep = &xhci->devs[slot_id]->eps[ep_index];
343
344         /* A ring has pending URBs if its TD list is not empty */
345         if (!(ep->ep_state & EP_HAS_STREAMS)) {
346                 if (!(list_empty(&ep->ring->td_list)))
347                         xhci_ring_ep_doorbell(xhci, slot_id, ep_index, 0);
348                 return;
349         }
350
351         for (stream_id = 1; stream_id < ep->stream_info->num_streams;
352                         stream_id++) {
353                 struct xhci_stream_info *stream_info = ep->stream_info;
354                 if (!list_empty(&stream_info->stream_rings[stream_id]->td_list))
355                         xhci_ring_ep_doorbell(xhci, slot_id, ep_index,
356                                                 stream_id);
357         }
358 }
359
360 /*
361  * Find the segment that trb is in.  Start searching in start_seg.
362  * If we must move past a segment that has a link TRB with a toggle cycle state
363  * bit set, then we will toggle the value pointed at by cycle_state.
364  */
365 static struct xhci_segment *find_trb_seg(
366                 struct xhci_segment *start_seg,
367                 union xhci_trb  *trb, int *cycle_state)
368 {
369         struct xhci_segment *cur_seg = start_seg;
370         struct xhci_generic_trb *generic_trb;
371
372         while (cur_seg->trbs > trb ||
373                         &cur_seg->trbs[TRBS_PER_SEGMENT - 1] < trb) {
374                 generic_trb = &cur_seg->trbs[TRBS_PER_SEGMENT - 1].generic;
375                 if (le32_to_cpu(generic_trb->field[3]) & LINK_TOGGLE)
376                         *cycle_state ^= 0x1;
377                 cur_seg = cur_seg->next;
378                 if (cur_seg == start_seg)
379                         /* Looped over the entire list.  Oops! */
380                         return NULL;
381         }
382         return cur_seg;
383 }
384
385
386 static struct xhci_ring *xhci_triad_to_transfer_ring(struct xhci_hcd *xhci,
387                 unsigned int slot_id, unsigned int ep_index,
388                 unsigned int stream_id)
389 {
390         struct xhci_virt_ep *ep;
391
392         ep = &xhci->devs[slot_id]->eps[ep_index];
393         /* Common case: no streams */
394         if (!(ep->ep_state & EP_HAS_STREAMS))
395                 return ep->ring;
396
397         if (stream_id == 0) {
398                 xhci_warn(xhci,
399                                 "WARN: Slot ID %u, ep index %u has streams, "
400                                 "but URB has no stream ID.\n",
401                                 slot_id, ep_index);
402                 return NULL;
403         }
404
405         if (stream_id < ep->stream_info->num_streams)
406                 return ep->stream_info->stream_rings[stream_id];
407
408         xhci_warn(xhci,
409                         "WARN: Slot ID %u, ep index %u has "
410                         "stream IDs 1 to %u allocated, "
411                         "but stream ID %u is requested.\n",
412                         slot_id, ep_index,
413                         ep->stream_info->num_streams - 1,
414                         stream_id);
415         return NULL;
416 }
417
418 /* Get the right ring for the given URB.
419  * If the endpoint supports streams, boundary check the URB's stream ID.
420  * If the endpoint doesn't support streams, return the singular endpoint ring.
421  */
422 static struct xhci_ring *xhci_urb_to_transfer_ring(struct xhci_hcd *xhci,
423                 struct urb *urb)
424 {
425         return xhci_triad_to_transfer_ring(xhci, urb->dev->slot_id,
426                 xhci_get_endpoint_index(&urb->ep->desc), urb->stream_id);
427 }
428
429 /*
430  * Move the xHC's endpoint ring dequeue pointer past cur_td.
431  * Record the new state of the xHC's endpoint ring dequeue segment,
432  * dequeue pointer, and new consumer cycle state in state.
433  * Update our internal representation of the ring's dequeue pointer.
434  *
435  * We do this in three jumps:
436  *  - First we update our new ring state to be the same as when the xHC stopped.
437  *  - Then we traverse the ring to find the segment that contains
438  *    the last TRB in the TD.  We toggle the xHC's new cycle state when we pass
439  *    any link TRBs with the toggle cycle bit set.
440  *  - Finally we move the dequeue state one TRB further, toggling the cycle bit
441  *    if we've moved it past a link TRB with the toggle cycle bit set.
442  *
443  * Some of the uses of xhci_generic_trb are grotty, but if they're done
444  * with correct __le32 accesses they should work fine.  Only users of this are
445  * in here.
446  */
447 void xhci_find_new_dequeue_state(struct xhci_hcd *xhci,
448                 unsigned int slot_id, unsigned int ep_index,
449                 unsigned int stream_id, struct xhci_td *cur_td,
450                 struct xhci_dequeue_state *state)
451 {
452         struct xhci_virt_device *dev = xhci->devs[slot_id];
453         struct xhci_ring *ep_ring;
454         struct xhci_generic_trb *trb;
455         struct xhci_ep_ctx *ep_ctx;
456         dma_addr_t addr;
457
458         ep_ring = xhci_triad_to_transfer_ring(xhci, slot_id,
459                         ep_index, stream_id);
460         if (!ep_ring) {
461                 xhci_warn(xhci, "WARN can't find new dequeue state "
462                                 "for invalid stream ID %u.\n",
463                                 stream_id);
464                 return;
465         }
466         state->new_cycle_state = 0;
467         xhci_dbg(xhci, "Finding segment containing stopped TRB.\n");
468         state->new_deq_seg = find_trb_seg(cur_td->start_seg,
469                         dev->eps[ep_index].stopped_trb,
470                         &state->new_cycle_state);
471         if (!state->new_deq_seg) {
472                 WARN_ON(1);
473                 return;
474         }
475
476         /* Dig out the cycle state saved by the xHC during the stop ep cmd */
477         xhci_dbg(xhci, "Finding endpoint context\n");
478         ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index);
479         state->new_cycle_state = 0x1 & le64_to_cpu(ep_ctx->deq);
480
481         state->new_deq_ptr = cur_td->last_trb;
482         xhci_dbg(xhci, "Finding segment containing last TRB in TD.\n");
483         state->new_deq_seg = find_trb_seg(state->new_deq_seg,
484                         state->new_deq_ptr,
485                         &state->new_cycle_state);
486         if (!state->new_deq_seg) {
487                 WARN_ON(1);
488                 return;
489         }
490
491         trb = &state->new_deq_ptr->generic;
492         if ((le32_to_cpu(trb->field[3]) & TRB_TYPE_BITMASK) ==
493             TRB_TYPE(TRB_LINK) && (le32_to_cpu(trb->field[3]) & LINK_TOGGLE))
494                 state->new_cycle_state ^= 0x1;
495         next_trb(xhci, ep_ring, &state->new_deq_seg, &state->new_deq_ptr);
496
497         /*
498          * If there is only one segment in a ring, find_trb_seg()'s while loop
499          * will not run, and it will return before it has a chance to see if it
500          * needs to toggle the cycle bit.  It can't tell if the stalled transfer
501          * ended just before the link TRB on a one-segment ring, or if the TD
502          * wrapped around the top of the ring, because it doesn't have the TD in
503          * question.  Look for the one-segment case where stalled TRB's address
504          * is greater than the new dequeue pointer address.
505          */
506         if (ep_ring->first_seg == ep_ring->first_seg->next &&
507                         state->new_deq_ptr < dev->eps[ep_index].stopped_trb)
508                 state->new_cycle_state ^= 0x1;
509         xhci_dbg(xhci, "Cycle state = 0x%x\n", state->new_cycle_state);
510
511         /* Don't update the ring cycle state for the producer (us). */
512         xhci_dbg(xhci, "New dequeue segment = %p (virtual)\n",
513                         state->new_deq_seg);
514         addr = xhci_trb_virt_to_dma(state->new_deq_seg, state->new_deq_ptr);
515         xhci_dbg(xhci, "New dequeue pointer = 0x%llx (DMA)\n",
516                         (unsigned long long) addr);
517 }
518
519 static void td_to_noop(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
520                 struct xhci_td *cur_td)
521 {
522         struct xhci_segment *cur_seg;
523         union xhci_trb *cur_trb;
524
525         for (cur_seg = cur_td->start_seg, cur_trb = cur_td->first_trb;
526                         true;
527                         next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) {
528                 if ((le32_to_cpu(cur_trb->generic.field[3]) & TRB_TYPE_BITMASK)
529                     == TRB_TYPE(TRB_LINK)) {
530                         /* Unchain any chained Link TRBs, but
531                          * leave the pointers intact.
532                          */
533                         cur_trb->generic.field[3] &= cpu_to_le32(~TRB_CHAIN);
534                         xhci_dbg(xhci, "Cancel (unchain) link TRB\n");
535                         xhci_dbg(xhci, "Address = %p (0x%llx dma); "
536                                         "in seg %p (0x%llx dma)\n",
537                                         cur_trb,
538                                         (unsigned long long)xhci_trb_virt_to_dma(cur_seg, cur_trb),
539                                         cur_seg,
540                                         (unsigned long long)cur_seg->dma);
541                 } else {
542                         cur_trb->generic.field[0] = 0;
543                         cur_trb->generic.field[1] = 0;
544                         cur_trb->generic.field[2] = 0;
545                         /* Preserve only the cycle bit of this TRB */
546                         cur_trb->generic.field[3] &= cpu_to_le32(TRB_CYCLE);
547                         cur_trb->generic.field[3] |= cpu_to_le32(
548                                 TRB_TYPE(TRB_TR_NOOP));
549                         xhci_dbg(xhci, "Cancel TRB %p (0x%llx dma) "
550                                         "in seg %p (0x%llx dma)\n",
551                                         cur_trb,
552                                         (unsigned long long)xhci_trb_virt_to_dma(cur_seg, cur_trb),
553                                         cur_seg,
554                                         (unsigned long long)cur_seg->dma);
555                 }
556                 if (cur_trb == cur_td->last_trb)
557                         break;
558         }
559 }
560
561 static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id,
562                 unsigned int ep_index, unsigned int stream_id,
563                 struct xhci_segment *deq_seg,
564                 union xhci_trb *deq_ptr, u32 cycle_state);
565
566 void xhci_queue_new_dequeue_state(struct xhci_hcd *xhci,
567                 unsigned int slot_id, unsigned int ep_index,
568                 unsigned int stream_id,
569                 struct xhci_dequeue_state *deq_state)
570 {
571         struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index];
572
573         xhci_dbg(xhci, "Set TR Deq Ptr cmd, new deq seg = %p (0x%llx dma), "
574                         "new deq ptr = %p (0x%llx dma), new cycle = %u\n",
575                         deq_state->new_deq_seg,
576                         (unsigned long long)deq_state->new_deq_seg->dma,
577                         deq_state->new_deq_ptr,
578                         (unsigned long long)xhci_trb_virt_to_dma(deq_state->new_deq_seg, deq_state->new_deq_ptr),
579                         deq_state->new_cycle_state);
580         queue_set_tr_deq(xhci, slot_id, ep_index, stream_id,
581                         deq_state->new_deq_seg,
582                         deq_state->new_deq_ptr,
583                         (u32) deq_state->new_cycle_state);
584         /* Stop the TD queueing code from ringing the doorbell until
585          * this command completes.  The HC won't set the dequeue pointer
586          * if the ring is running, and ringing the doorbell starts the
587          * ring running.
588          */
589         ep->ep_state |= SET_DEQ_PENDING;
590 }
591
592 static void xhci_stop_watchdog_timer_in_irq(struct xhci_hcd *xhci,
593                 struct xhci_virt_ep *ep)
594 {
595         ep->ep_state &= ~EP_HALT_PENDING;
596         /* Can't del_timer_sync in interrupt, so we attempt to cancel.  If the
597          * timer is running on another CPU, we don't decrement stop_cmds_pending
598          * (since we didn't successfully stop the watchdog timer).
599          */
600         if (del_timer(&ep->stop_cmd_timer))
601                 ep->stop_cmds_pending--;
602 }
603
604 /* Must be called with xhci->lock held in interrupt context */
605 static void xhci_giveback_urb_in_irq(struct xhci_hcd *xhci,
606                 struct xhci_td *cur_td, int status, char *adjective)
607 {
608         struct usb_hcd *hcd;
609         struct urb      *urb;
610         struct urb_priv *urb_priv;
611
612         urb = cur_td->urb;
613         urb_priv = urb->hcpriv;
614         urb_priv->td_cnt++;
615         hcd = bus_to_hcd(urb->dev->bus);
616
617         /* Only giveback urb when this is the last td in urb */
618         if (urb_priv->td_cnt == urb_priv->length) {
619                 if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
620                         xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs--;
621                         if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) {
622                                 if (xhci->quirks & XHCI_AMD_PLL_FIX)
623                                         usb_amd_quirk_pll_enable();
624                         }
625                 }
626                 usb_hcd_unlink_urb_from_ep(hcd, urb);
627
628                 spin_unlock(&xhci->lock);
629                 usb_hcd_giveback_urb(hcd, urb, status);
630                 xhci_urb_free_priv(xhci, urb_priv);
631                 spin_lock(&xhci->lock);
632         }
633 }
634
635 /*
636  * When we get a command completion for a Stop Endpoint Command, we need to
637  * unlink any cancelled TDs from the ring.  There are two ways to do that:
638  *
639  *  1. If the HW was in the middle of processing the TD that needs to be
640  *     cancelled, then we must move the ring's dequeue pointer past the last TRB
641  *     in the TD with a Set Dequeue Pointer Command.
642  *  2. Otherwise, we turn all the TRBs in the TD into No-op TRBs (with the chain
643  *     bit cleared) so that the HW will skip over them.
644  */
645 static void handle_stopped_endpoint(struct xhci_hcd *xhci,
646                 union xhci_trb *trb, struct xhci_event_cmd *event)
647 {
648         unsigned int slot_id;
649         unsigned int ep_index;
650         struct xhci_virt_device *virt_dev;
651         struct xhci_ring *ep_ring;
652         struct xhci_virt_ep *ep;
653         struct list_head *entry;
654         struct xhci_td *cur_td = NULL;
655         struct xhci_td *last_unlinked_td;
656
657         struct xhci_dequeue_state deq_state;
658
659         if (unlikely(TRB_TO_SUSPEND_PORT(
660                              le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])))) {
661                 slot_id = TRB_TO_SLOT_ID(
662                         le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3]));
663                 virt_dev = xhci->devs[slot_id];
664                 if (virt_dev)
665                         handle_cmd_in_cmd_wait_list(xhci, virt_dev,
666                                 event);
667                 else
668                         xhci_warn(xhci, "Stop endpoint command "
669                                 "completion for disabled slot %u\n",
670                                 slot_id);
671                 return;
672         }
673
674         memset(&deq_state, 0, sizeof(deq_state));
675         slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3]));
676         ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
677         ep = &xhci->devs[slot_id]->eps[ep_index];
678
679         if (list_empty(&ep->cancelled_td_list)) {
680                 xhci_stop_watchdog_timer_in_irq(xhci, ep);
681                 ep->stopped_td = NULL;
682                 ep->stopped_trb = NULL;
683                 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
684                 return;
685         }
686
687         /* Fix up the ep ring first, so HW stops executing cancelled TDs.
688          * We have the xHCI lock, so nothing can modify this list until we drop
689          * it.  We're also in the event handler, so we can't get re-interrupted
690          * if another Stop Endpoint command completes
691          */
692         list_for_each(entry, &ep->cancelled_td_list) {
693                 cur_td = list_entry(entry, struct xhci_td, cancelled_td_list);
694                 xhci_dbg(xhci, "Cancelling TD starting at %p, 0x%llx (dma).\n",
695                                 cur_td->first_trb,
696                                 (unsigned long long)xhci_trb_virt_to_dma(cur_td->start_seg, cur_td->first_trb));
697                 ep_ring = xhci_urb_to_transfer_ring(xhci, cur_td->urb);
698                 if (!ep_ring) {
699                         /* This shouldn't happen unless a driver is mucking
700                          * with the stream ID after submission.  This will
701                          * leave the TD on the hardware ring, and the hardware
702                          * will try to execute it, and may access a buffer
703                          * that has already been freed.  In the best case, the
704                          * hardware will execute it, and the event handler will
705                          * ignore the completion event for that TD, since it was
706                          * removed from the td_list for that endpoint.  In
707                          * short, don't muck with the stream ID after
708                          * submission.
709                          */
710                         xhci_warn(xhci, "WARN Cancelled URB %p "
711                                         "has invalid stream ID %u.\n",
712                                         cur_td->urb,
713                                         cur_td->urb->stream_id);
714                         goto remove_finished_td;
715                 }
716                 /*
717                  * If we stopped on the TD we need to cancel, then we have to
718                  * move the xHC endpoint ring dequeue pointer past this TD.
719                  */
720                 if (cur_td == ep->stopped_td)
721                         xhci_find_new_dequeue_state(xhci, slot_id, ep_index,
722                                         cur_td->urb->stream_id,
723                                         cur_td, &deq_state);
724                 else
725                         td_to_noop(xhci, ep_ring, cur_td);
726 remove_finished_td:
727                 /*
728                  * The event handler won't see a completion for this TD anymore,
729                  * so remove it from the endpoint ring's TD list.  Keep it in
730                  * the cancelled TD list for URB completion later.
731                  */
732                 list_del(&cur_td->td_list);
733         }
734         last_unlinked_td = cur_td;
735         xhci_stop_watchdog_timer_in_irq(xhci, ep);
736
737         /* If necessary, queue a Set Transfer Ring Dequeue Pointer command */
738         if (deq_state.new_deq_ptr && deq_state.new_deq_seg) {
739                 xhci_queue_new_dequeue_state(xhci,
740                                 slot_id, ep_index,
741                                 ep->stopped_td->urb->stream_id,
742                                 &deq_state);
743                 xhci_ring_cmd_db(xhci);
744         } else {
745                 /* Otherwise ring the doorbell(s) to restart queued transfers */
746                 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
747         }
748         ep->stopped_td = NULL;
749         ep->stopped_trb = NULL;
750
751         /*
752          * Drop the lock and complete the URBs in the cancelled TD list.
753          * New TDs to be cancelled might be added to the end of the list before
754          * we can complete all the URBs for the TDs we already unlinked.
755          * So stop when we've completed the URB for the last TD we unlinked.
756          */
757         do {
758                 cur_td = list_entry(ep->cancelled_td_list.next,
759                                 struct xhci_td, cancelled_td_list);
760                 list_del(&cur_td->cancelled_td_list);
761
762                 /* Clean up the cancelled URB */
763                 /* Doesn't matter what we pass for status, since the core will
764                  * just overwrite it (because the URB has been unlinked).
765                  */
766                 xhci_giveback_urb_in_irq(xhci, cur_td, 0, "cancelled");
767
768                 /* Stop processing the cancelled list if the watchdog timer is
769                  * running.
770                  */
771                 if (xhci->xhc_state & XHCI_STATE_DYING)
772                         return;
773         } while (cur_td != last_unlinked_td);
774
775         /* Return to the event handler with xhci->lock re-acquired */
776 }
777
778 /* Watchdog timer function for when a stop endpoint command fails to complete.
779  * In this case, we assume the host controller is broken or dying or dead.  The
780  * host may still be completing some other events, so we have to be careful to
781  * let the event ring handler and the URB dequeueing/enqueueing functions know
782  * through xhci->state.
783  *
784  * The timer may also fire if the host takes a very long time to respond to the
785  * command, and the stop endpoint command completion handler cannot delete the
786  * timer before the timer function is called.  Another endpoint cancellation may
787  * sneak in before the timer function can grab the lock, and that may queue
788  * another stop endpoint command and add the timer back.  So we cannot use a
789  * simple flag to say whether there is a pending stop endpoint command for a
790  * particular endpoint.
791  *
792  * Instead we use a combination of that flag and a counter for the number of
793  * pending stop endpoint commands.  If the timer is the tail end of the last
794  * stop endpoint command, and the endpoint's command is still pending, we assume
795  * the host is dying.
796  */
797 void xhci_stop_endpoint_command_watchdog(unsigned long arg)
798 {
799         struct xhci_hcd *xhci;
800         struct xhci_virt_ep *ep;
801         struct xhci_virt_ep *temp_ep;
802         struct xhci_ring *ring;
803         struct xhci_td *cur_td;
804         int ret, i, j;
805
806         ep = (struct xhci_virt_ep *) arg;
807         xhci = ep->xhci;
808
809         spin_lock(&xhci->lock);
810
811         ep->stop_cmds_pending--;
812         if (xhci->xhc_state & XHCI_STATE_DYING) {
813                 xhci_dbg(xhci, "Stop EP timer ran, but another timer marked "
814                                 "xHCI as DYING, exiting.\n");
815                 spin_unlock(&xhci->lock);
816                 return;
817         }
818         if (!(ep->stop_cmds_pending == 0 && (ep->ep_state & EP_HALT_PENDING))) {
819                 xhci_dbg(xhci, "Stop EP timer ran, but no command pending, "
820                                 "exiting.\n");
821                 spin_unlock(&xhci->lock);
822                 return;
823         }
824
825         xhci_warn(xhci, "xHCI host not responding to stop endpoint command.\n");
826         xhci_warn(xhci, "Assuming host is dying, halting host.\n");
827         /* Oops, HC is dead or dying or at least not responding to the stop
828          * endpoint command.
829          */
830         xhci->xhc_state |= XHCI_STATE_DYING;
831         /* Disable interrupts from the host controller and start halting it */
832         xhci_quiesce(xhci);
833         spin_unlock(&xhci->lock);
834
835         ret = xhci_halt(xhci);
836
837         spin_lock(&xhci->lock);
838         if (ret < 0) {
839                 /* This is bad; the host is not responding to commands and it's
840                  * not allowing itself to be halted.  At least interrupts are
841                  * disabled. If we call usb_hc_died(), it will attempt to
842                  * disconnect all device drivers under this host.  Those
843                  * disconnect() methods will wait for all URBs to be unlinked,
844                  * so we must complete them.
845                  */
846                 xhci_warn(xhci, "Non-responsive xHCI host is not halting.\n");
847                 xhci_warn(xhci, "Completing active URBs anyway.\n");
848                 /* We could turn all TDs on the rings to no-ops.  This won't
849                  * help if the host has cached part of the ring, and is slow if
850                  * we want to preserve the cycle bit.  Skip it and hope the host
851                  * doesn't touch the memory.
852                  */
853         }
854         for (i = 0; i < MAX_HC_SLOTS; i++) {
855                 if (!xhci->devs[i])
856                         continue;
857                 for (j = 0; j < 31; j++) {
858                         temp_ep = &xhci->devs[i]->eps[j];
859                         ring = temp_ep->ring;
860                         if (!ring)
861                                 continue;
862                         xhci_dbg(xhci, "Killing URBs for slot ID %u, "
863                                         "ep index %u\n", i, j);
864                         while (!list_empty(&ring->td_list)) {
865                                 cur_td = list_first_entry(&ring->td_list,
866                                                 struct xhci_td,
867                                                 td_list);
868                                 list_del(&cur_td->td_list);
869                                 if (!list_empty(&cur_td->cancelled_td_list))
870                                         list_del(&cur_td->cancelled_td_list);
871                                 xhci_giveback_urb_in_irq(xhci, cur_td,
872                                                 -ESHUTDOWN, "killed");
873                         }
874                         while (!list_empty(&temp_ep->cancelled_td_list)) {
875                                 cur_td = list_first_entry(
876                                                 &temp_ep->cancelled_td_list,
877                                                 struct xhci_td,
878                                                 cancelled_td_list);
879                                 list_del(&cur_td->cancelled_td_list);
880                                 xhci_giveback_urb_in_irq(xhci, cur_td,
881                                                 -ESHUTDOWN, "killed");
882                         }
883                 }
884         }
885         spin_unlock(&xhci->lock);
886         xhci_dbg(xhci, "Calling usb_hc_died()\n");
887         usb_hc_died(xhci_to_hcd(xhci)->primary_hcd);
888         xhci_dbg(xhci, "xHCI host controller is dead.\n");
889 }
890
891 /*
892  * When we get a completion for a Set Transfer Ring Dequeue Pointer command,
893  * we need to clear the set deq pending flag in the endpoint ring state, so that
894  * the TD queueing code can ring the doorbell again.  We also need to ring the
895  * endpoint doorbell to restart the ring, but only if there aren't more
896  * cancellations pending.
897  */
898 static void handle_set_deq_completion(struct xhci_hcd *xhci,
899                 struct xhci_event_cmd *event,
900                 union xhci_trb *trb)
901 {
902         unsigned int slot_id;
903         unsigned int ep_index;
904         unsigned int stream_id;
905         struct xhci_ring *ep_ring;
906         struct xhci_virt_device *dev;
907         struct xhci_ep_ctx *ep_ctx;
908         struct xhci_slot_ctx *slot_ctx;
909
910         slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3]));
911         ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
912         stream_id = TRB_TO_STREAM_ID(le32_to_cpu(trb->generic.field[2]));
913         dev = xhci->devs[slot_id];
914
915         ep_ring = xhci_stream_id_to_ring(dev, ep_index, stream_id);
916         if (!ep_ring) {
917                 xhci_warn(xhci, "WARN Set TR deq ptr command for "
918                                 "freed stream ID %u\n",
919                                 stream_id);
920                 /* XXX: Harmless??? */
921                 dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING;
922                 return;
923         }
924
925         ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index);
926         slot_ctx = xhci_get_slot_ctx(xhci, dev->out_ctx);
927
928         if (GET_COMP_CODE(le32_to_cpu(event->status)) != COMP_SUCCESS) {
929                 unsigned int ep_state;
930                 unsigned int slot_state;
931
932                 switch (GET_COMP_CODE(le32_to_cpu(event->status))) {
933                 case COMP_TRB_ERR:
934                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because "
935                                         "of stream ID configuration\n");
936                         break;
937                 case COMP_CTX_STATE:
938                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due "
939                                         "to incorrect slot or ep state.\n");
940                         ep_state = le32_to_cpu(ep_ctx->ep_info);
941                         ep_state &= EP_STATE_MASK;
942                         slot_state = le32_to_cpu(slot_ctx->dev_state);
943                         slot_state = GET_SLOT_STATE(slot_state);
944                         xhci_dbg(xhci, "Slot state = %u, EP state = %u\n",
945                                         slot_state, ep_state);
946                         break;
947                 case COMP_EBADSLT:
948                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because "
949                                         "slot %u was not enabled.\n", slot_id);
950                         break;
951                 default:
952                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown "
953                                         "completion code of %u.\n",
954                                   GET_COMP_CODE(le32_to_cpu(event->status)));
955                         break;
956                 }
957                 /* OK what do we do now?  The endpoint state is hosed, and we
958                  * should never get to this point if the synchronization between
959                  * queueing, and endpoint state are correct.  This might happen
960                  * if the device gets disconnected after we've finished
961                  * cancelling URBs, which might not be an error...
962                  */
963         } else {
964                 xhci_dbg(xhci, "Successful Set TR Deq Ptr cmd, deq = @%08llx\n",
965                          le64_to_cpu(ep_ctx->deq));
966                 if (xhci_trb_virt_to_dma(dev->eps[ep_index].queued_deq_seg,
967                                          dev->eps[ep_index].queued_deq_ptr) ==
968                     (le64_to_cpu(ep_ctx->deq) & ~(EP_CTX_CYCLE_MASK))) {
969                         /* Update the ring's dequeue segment and dequeue pointer
970                          * to reflect the new position.
971                          */
972                         ep_ring->deq_seg = dev->eps[ep_index].queued_deq_seg;
973                         ep_ring->dequeue = dev->eps[ep_index].queued_deq_ptr;
974                 } else {
975                         xhci_warn(xhci, "Mismatch between completed Set TR Deq "
976                                         "Ptr command & xHCI internal state.\n");
977                         xhci_warn(xhci, "ep deq seg = %p, deq ptr = %p\n",
978                                         dev->eps[ep_index].queued_deq_seg,
979                                         dev->eps[ep_index].queued_deq_ptr);
980                 }
981         }
982
983         dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING;
984         dev->eps[ep_index].queued_deq_seg = NULL;
985         dev->eps[ep_index].queued_deq_ptr = NULL;
986         /* Restart any rings with pending URBs */
987         ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
988 }
989
990 static void handle_reset_ep_completion(struct xhci_hcd *xhci,
991                 struct xhci_event_cmd *event,
992                 union xhci_trb *trb)
993 {
994         int slot_id;
995         unsigned int ep_index;
996
997         slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3]));
998         ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
999         /* This command will only fail if the endpoint wasn't halted,
1000          * but we don't care.
1001          */
1002         xhci_dbg(xhci, "Ignoring reset ep completion code of %u\n",
1003                  (unsigned int) GET_COMP_CODE(le32_to_cpu(event->status)));
1004
1005         /* HW with the reset endpoint quirk needs to have a configure endpoint
1006          * command complete before the endpoint can be used.  Queue that here
1007          * because the HW can't handle two commands being queued in a row.
1008          */
1009         if (xhci->quirks & XHCI_RESET_EP_QUIRK) {
1010                 xhci_dbg(xhci, "Queueing configure endpoint command\n");
1011                 xhci_queue_configure_endpoint(xhci,
1012                                 xhci->devs[slot_id]->in_ctx->dma, slot_id,
1013                                 false);
1014                 xhci_ring_cmd_db(xhci);
1015         } else {
1016                 /* Clear our internal halted state and restart the ring(s) */
1017                 xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED;
1018                 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1019         }
1020 }
1021
1022 /* Check to see if a command in the device's command queue matches this one.
1023  * Signal the completion or free the command, and return 1.  Return 0 if the
1024  * completed command isn't at the head of the command list.
1025  */
1026 static int handle_cmd_in_cmd_wait_list(struct xhci_hcd *xhci,
1027                 struct xhci_virt_device *virt_dev,
1028                 struct xhci_event_cmd *event)
1029 {
1030         struct xhci_command *command;
1031
1032         if (list_empty(&virt_dev->cmd_list))
1033                 return 0;
1034
1035         command = list_entry(virt_dev->cmd_list.next,
1036                         struct xhci_command, cmd_list);
1037         if (xhci->cmd_ring->dequeue != command->command_trb)
1038                 return 0;
1039
1040         command->status = GET_COMP_CODE(le32_to_cpu(event->status));
1041         list_del(&command->cmd_list);
1042         if (command->completion)
1043                 complete(command->completion);
1044         else
1045                 xhci_free_command(xhci, command);
1046         return 1;
1047 }
1048
1049 static void handle_cmd_completion(struct xhci_hcd *xhci,
1050                 struct xhci_event_cmd *event)
1051 {
1052         int slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
1053         u64 cmd_dma;
1054         dma_addr_t cmd_dequeue_dma;
1055         struct xhci_input_control_ctx *ctrl_ctx;
1056         struct xhci_virt_device *virt_dev;
1057         unsigned int ep_index;
1058         struct xhci_ring *ep_ring;
1059         unsigned int ep_state;
1060
1061         cmd_dma = le64_to_cpu(event->cmd_trb);
1062         cmd_dequeue_dma = xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
1063                         xhci->cmd_ring->dequeue);
1064         /* Is the command ring deq ptr out of sync with the deq seg ptr? */
1065         if (cmd_dequeue_dma == 0) {
1066                 xhci->error_bitmask |= 1 << 4;
1067                 return;
1068         }
1069         /* Does the DMA address match our internal dequeue pointer address? */
1070         if (cmd_dma != (u64) cmd_dequeue_dma) {
1071                 xhci->error_bitmask |= 1 << 5;
1072                 return;
1073         }
1074         switch (le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])
1075                 & TRB_TYPE_BITMASK) {
1076         case TRB_TYPE(TRB_ENABLE_SLOT):
1077                 if (GET_COMP_CODE(le32_to_cpu(event->status)) == COMP_SUCCESS)
1078                         xhci->slot_id = slot_id;
1079                 else
1080                         xhci->slot_id = 0;
1081                 complete(&xhci->addr_dev);
1082                 break;
1083         case TRB_TYPE(TRB_DISABLE_SLOT):
1084                 if (xhci->devs[slot_id])
1085                         xhci_free_virt_device(xhci, slot_id);
1086                 break;
1087         case TRB_TYPE(TRB_CONFIG_EP):
1088                 virt_dev = xhci->devs[slot_id];
1089                 if (handle_cmd_in_cmd_wait_list(xhci, virt_dev, event))
1090                         break;
1091                 /*
1092                  * Configure endpoint commands can come from the USB core
1093                  * configuration or alt setting changes, or because the HW
1094                  * needed an extra configure endpoint command after a reset
1095                  * endpoint command or streams were being configured.
1096                  * If the command was for a halted endpoint, the xHCI driver
1097                  * is not waiting on the configure endpoint command.
1098                  */
1099                 ctrl_ctx = xhci_get_input_control_ctx(xhci,
1100                                 virt_dev->in_ctx);
1101                 /* Input ctx add_flags are the endpoint index plus one */
1102                 ep_index = xhci_last_valid_endpoint(le32_to_cpu(ctrl_ctx->add_flags)) - 1;
1103                 /* A usb_set_interface() call directly after clearing a halted
1104                  * condition may race on this quirky hardware.  Not worth
1105                  * worrying about, since this is prototype hardware.  Not sure
1106                  * if this will work for streams, but streams support was
1107                  * untested on this prototype.
1108                  */
1109                 if (xhci->quirks & XHCI_RESET_EP_QUIRK &&
1110                                 ep_index != (unsigned int) -1 &&
1111                     le32_to_cpu(ctrl_ctx->add_flags) - SLOT_FLAG ==
1112                     le32_to_cpu(ctrl_ctx->drop_flags)) {
1113                         ep_ring = xhci->devs[slot_id]->eps[ep_index].ring;
1114                         ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
1115                         if (!(ep_state & EP_HALTED))
1116                                 goto bandwidth_change;
1117                         xhci_dbg(xhci, "Completed config ep cmd - "
1118                                         "last ep index = %d, state = %d\n",
1119                                         ep_index, ep_state);
1120                         /* Clear internal halted state and restart ring(s) */
1121                         xhci->devs[slot_id]->eps[ep_index].ep_state &=
1122                                 ~EP_HALTED;
1123                         ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1124                         break;
1125                 }
1126 bandwidth_change:
1127                 xhci_dbg(xhci, "Completed config ep cmd\n");
1128                 xhci->devs[slot_id]->cmd_status =
1129                         GET_COMP_CODE(le32_to_cpu(event->status));
1130                 complete(&xhci->devs[slot_id]->cmd_completion);
1131                 break;
1132         case TRB_TYPE(TRB_EVAL_CONTEXT):
1133                 virt_dev = xhci->devs[slot_id];
1134                 if (handle_cmd_in_cmd_wait_list(xhci, virt_dev, event))
1135                         break;
1136                 xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status));
1137                 complete(&xhci->devs[slot_id]->cmd_completion);
1138                 break;
1139         case TRB_TYPE(TRB_ADDR_DEV):
1140                 xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status));
1141                 complete(&xhci->addr_dev);
1142                 break;
1143         case TRB_TYPE(TRB_STOP_RING):
1144                 handle_stopped_endpoint(xhci, xhci->cmd_ring->dequeue, event);
1145                 break;
1146         case TRB_TYPE(TRB_SET_DEQ):
1147                 handle_set_deq_completion(xhci, event, xhci->cmd_ring->dequeue);
1148                 break;
1149         case TRB_TYPE(TRB_CMD_NOOP):
1150                 break;
1151         case TRB_TYPE(TRB_RESET_EP):
1152                 handle_reset_ep_completion(xhci, event, xhci->cmd_ring->dequeue);
1153                 break;
1154         case TRB_TYPE(TRB_RESET_DEV):
1155                 xhci_dbg(xhci, "Completed reset device command.\n");
1156                 slot_id = TRB_TO_SLOT_ID(
1157                         le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3]));
1158                 virt_dev = xhci->devs[slot_id];
1159                 if (virt_dev)
1160                         handle_cmd_in_cmd_wait_list(xhci, virt_dev, event);
1161                 else
1162                         xhci_warn(xhci, "Reset device command completion "
1163                                         "for disabled slot %u\n", slot_id);
1164                 break;
1165         case TRB_TYPE(TRB_NEC_GET_FW):
1166                 if (!(xhci->quirks & XHCI_NEC_HOST)) {
1167                         xhci->error_bitmask |= 1 << 6;
1168                         break;
1169                 }
1170                 xhci_dbg(xhci, "NEC firmware version %2x.%02x\n",
1171                          NEC_FW_MAJOR(le32_to_cpu(event->status)),
1172                          NEC_FW_MINOR(le32_to_cpu(event->status)));
1173                 break;
1174         default:
1175                 /* Skip over unknown commands on the event ring */
1176                 xhci->error_bitmask |= 1 << 6;
1177                 break;
1178         }
1179         inc_deq(xhci, xhci->cmd_ring, false);
1180 }
1181
1182 static void handle_vendor_event(struct xhci_hcd *xhci,
1183                 union xhci_trb *event)
1184 {
1185         u32 trb_type;
1186
1187         trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(event->generic.field[3]));
1188         xhci_dbg(xhci, "Vendor specific event TRB type = %u\n", trb_type);
1189         if (trb_type == TRB_NEC_CMD_COMP && (xhci->quirks & XHCI_NEC_HOST))
1190                 handle_cmd_completion(xhci, &event->event_cmd);
1191 }
1192
1193 /* @port_id: the one-based port ID from the hardware (indexed from array of all
1194  * port registers -- USB 3.0 and USB 2.0).
1195  *
1196  * Returns a zero-based port number, which is suitable for indexing into each of
1197  * the split roothubs' port arrays and bus state arrays.
1198  */
1199 static unsigned int find_faked_portnum_from_hw_portnum(struct usb_hcd *hcd,
1200                 struct xhci_hcd *xhci, u32 port_id)
1201 {
1202         unsigned int i;
1203         unsigned int num_similar_speed_ports = 0;
1204
1205         /* port_id from the hardware is 1-based, but port_array[], usb3_ports[],
1206          * and usb2_ports are 0-based indexes.  Count the number of similar
1207          * speed ports, up to 1 port before this port.
1208          */
1209         for (i = 0; i < (port_id - 1); i++) {
1210                 u8 port_speed = xhci->port_array[i];
1211
1212                 /*
1213                  * Skip ports that don't have known speeds, or have duplicate
1214                  * Extended Capabilities port speed entries.
1215                  */
1216                 if (port_speed == 0 || port_speed == DUPLICATE_ENTRY)
1217                         continue;
1218
1219                 /*
1220                  * USB 3.0 ports are always under a USB 3.0 hub.  USB 2.0 and
1221                  * 1.1 ports are under the USB 2.0 hub.  If the port speed
1222                  * matches the device speed, it's a similar speed port.
1223                  */
1224                 if ((port_speed == 0x03) == (hcd->speed == HCD_USB3))
1225                         num_similar_speed_ports++;
1226         }
1227         return num_similar_speed_ports;
1228 }
1229
1230 static void handle_port_status(struct xhci_hcd *xhci,
1231                 union xhci_trb *event)
1232 {
1233         struct usb_hcd *hcd;
1234         u32 port_id;
1235         u32 temp, temp1;
1236         int max_ports;
1237         int slot_id;
1238         unsigned int faked_port_index;
1239         u8 major_revision;
1240         struct xhci_bus_state *bus_state;
1241         __le32 __iomem **port_array;
1242         bool bogus_port_status = false;
1243
1244         /* Port status change events always have a successful completion code */
1245         if (GET_COMP_CODE(le32_to_cpu(event->generic.field[2])) != COMP_SUCCESS) {
1246                 xhci_warn(xhci, "WARN: xHC returned failed port status event\n");
1247                 xhci->error_bitmask |= 1 << 8;
1248         }
1249         port_id = GET_PORT_ID(le32_to_cpu(event->generic.field[0]));
1250         xhci_dbg(xhci, "Port Status Change Event for port %d\n", port_id);
1251
1252         max_ports = HCS_MAX_PORTS(xhci->hcs_params1);
1253         if ((port_id <= 0) || (port_id > max_ports)) {
1254                 xhci_warn(xhci, "Invalid port id %d\n", port_id);
1255                 bogus_port_status = true;
1256                 goto cleanup;
1257         }
1258
1259         /* Figure out which usb_hcd this port is attached to:
1260          * is it a USB 3.0 port or a USB 2.0/1.1 port?
1261          */
1262         major_revision = xhci->port_array[port_id - 1];
1263         if (major_revision == 0) {
1264                 xhci_warn(xhci, "Event for port %u not in "
1265                                 "Extended Capabilities, ignoring.\n",
1266                                 port_id);
1267                 bogus_port_status = true;
1268                 goto cleanup;
1269         }
1270         if (major_revision == DUPLICATE_ENTRY) {
1271                 xhci_warn(xhci, "Event for port %u duplicated in"
1272                                 "Extended Capabilities, ignoring.\n",
1273                                 port_id);
1274                 bogus_port_status = true;
1275                 goto cleanup;
1276         }
1277
1278         /*
1279          * Hardware port IDs reported by a Port Status Change Event include USB
1280          * 3.0 and USB 2.0 ports.  We want to check if the port has reported a
1281          * resume event, but we first need to translate the hardware port ID
1282          * into the index into the ports on the correct split roothub, and the
1283          * correct bus_state structure.
1284          */
1285         /* Find the right roothub. */
1286         hcd = xhci_to_hcd(xhci);
1287         if ((major_revision == 0x03) != (hcd->speed == HCD_USB3))
1288                 hcd = xhci->shared_hcd;
1289         bus_state = &xhci->bus_state[hcd_index(hcd)];
1290         if (hcd->speed == HCD_USB3)
1291                 port_array = xhci->usb3_ports;
1292         else
1293                 port_array = xhci->usb2_ports;
1294         /* Find the faked port hub number */
1295         faked_port_index = find_faked_portnum_from_hw_portnum(hcd, xhci,
1296                         port_id);
1297
1298         temp = xhci_readl(xhci, port_array[faked_port_index]);
1299         if (hcd->state == HC_STATE_SUSPENDED) {
1300                 xhci_dbg(xhci, "resume root hub\n");
1301                 usb_hcd_resume_root_hub(hcd);
1302         }
1303
1304         if ((temp & PORT_PLC) && (temp & PORT_PLS_MASK) == XDEV_RESUME) {
1305                 xhci_dbg(xhci, "port resume event for port %d\n", port_id);
1306
1307                 temp1 = xhci_readl(xhci, &xhci->op_regs->command);
1308                 if (!(temp1 & CMD_RUN)) {
1309                         xhci_warn(xhci, "xHC is not running.\n");
1310                         goto cleanup;
1311                 }
1312
1313                 if (DEV_SUPERSPEED(temp)) {
1314                         xhci_dbg(xhci, "resume SS port %d\n", port_id);
1315                         temp = xhci_port_state_to_neutral(temp);
1316                         temp &= ~PORT_PLS_MASK;
1317                         temp |= PORT_LINK_STROBE | XDEV_U0;
1318                         xhci_writel(xhci, temp, port_array[faked_port_index]);
1319                         slot_id = xhci_find_slot_id_by_port(hcd, xhci,
1320                                         faked_port_index);
1321                         if (!slot_id) {
1322                                 xhci_dbg(xhci, "slot_id is zero\n");
1323                                 goto cleanup;
1324                         }
1325                         xhci_ring_device(xhci, slot_id);
1326                         xhci_dbg(xhci, "resume SS port %d finished\n", port_id);
1327                         /* Clear PORT_PLC */
1328                         temp = xhci_readl(xhci, port_array[faked_port_index]);
1329                         temp = xhci_port_state_to_neutral(temp);
1330                         temp |= PORT_PLC;
1331                         xhci_writel(xhci, temp, port_array[faked_port_index]);
1332                 } else {
1333                         xhci_dbg(xhci, "resume HS port %d\n", port_id);
1334                         bus_state->resume_done[faked_port_index] = jiffies +
1335                                 msecs_to_jiffies(20);
1336                         mod_timer(&hcd->rh_timer,
1337                                   bus_state->resume_done[faked_port_index]);
1338                         /* Do the rest in GetPortStatus */
1339                 }
1340         }
1341
1342 cleanup:
1343         /* Update event ring dequeue pointer before dropping the lock */
1344         inc_deq(xhci, xhci->event_ring, true);
1345
1346         /* Don't make the USB core poll the roothub if we got a bad port status
1347          * change event.  Besides, at that point we can't tell which roothub
1348          * (USB 2.0 or USB 3.0) to kick.
1349          */
1350         if (bogus_port_status)
1351                 return;
1352
1353         spin_unlock(&xhci->lock);
1354         /* Pass this up to the core */
1355         usb_hcd_poll_rh_status(hcd);
1356         spin_lock(&xhci->lock);
1357 }
1358
1359 /*
1360  * This TD is defined by the TRBs starting at start_trb in start_seg and ending
1361  * at end_trb, which may be in another segment.  If the suspect DMA address is a
1362  * TRB in this TD, this function returns that TRB's segment.  Otherwise it
1363  * returns 0.
1364  */
1365 struct xhci_segment *trb_in_td(struct xhci_segment *start_seg,
1366                 union xhci_trb  *start_trb,
1367                 union xhci_trb  *end_trb,
1368                 dma_addr_t      suspect_dma)
1369 {
1370         dma_addr_t start_dma;
1371         dma_addr_t end_seg_dma;
1372         dma_addr_t end_trb_dma;
1373         struct xhci_segment *cur_seg;
1374
1375         start_dma = xhci_trb_virt_to_dma(start_seg, start_trb);
1376         cur_seg = start_seg;
1377
1378         do {
1379                 if (start_dma == 0)
1380                         return NULL;
1381                 /* We may get an event for a Link TRB in the middle of a TD */
1382                 end_seg_dma = xhci_trb_virt_to_dma(cur_seg,
1383                                 &cur_seg->trbs[TRBS_PER_SEGMENT - 1]);
1384                 /* If the end TRB isn't in this segment, this is set to 0 */
1385                 end_trb_dma = xhci_trb_virt_to_dma(cur_seg, end_trb);
1386
1387                 if (end_trb_dma > 0) {
1388                         /* The end TRB is in this segment, so suspect should be here */
1389                         if (start_dma <= end_trb_dma) {
1390                                 if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma)
1391                                         return cur_seg;
1392                         } else {
1393                                 /* Case for one segment with
1394                                  * a TD wrapped around to the top
1395                                  */
1396                                 if ((suspect_dma >= start_dma &&
1397                                                         suspect_dma <= end_seg_dma) ||
1398                                                 (suspect_dma >= cur_seg->dma &&
1399                                                  suspect_dma <= end_trb_dma))
1400                                         return cur_seg;
1401                         }
1402                         return NULL;
1403                 } else {
1404                         /* Might still be somewhere in this segment */
1405                         if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma)
1406                                 return cur_seg;
1407                 }
1408                 cur_seg = cur_seg->next;
1409                 start_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[0]);
1410         } while (cur_seg != start_seg);
1411
1412         return NULL;
1413 }
1414
1415 static void xhci_cleanup_halted_endpoint(struct xhci_hcd *xhci,
1416                 unsigned int slot_id, unsigned int ep_index,
1417                 unsigned int stream_id,
1418                 struct xhci_td *td, union xhci_trb *event_trb)
1419 {
1420         struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index];
1421         ep->ep_state |= EP_HALTED;
1422         ep->stopped_td = td;
1423         ep->stopped_trb = event_trb;
1424         ep->stopped_stream = stream_id;
1425
1426         xhci_queue_reset_ep(xhci, slot_id, ep_index);
1427         xhci_cleanup_stalled_ring(xhci, td->urb->dev, ep_index);
1428
1429         ep->stopped_td = NULL;
1430         ep->stopped_trb = NULL;
1431         ep->stopped_stream = 0;
1432
1433         xhci_ring_cmd_db(xhci);
1434 }
1435
1436 /* Check if an error has halted the endpoint ring.  The class driver will
1437  * cleanup the halt for a non-default control endpoint if we indicate a stall.
1438  * However, a babble and other errors also halt the endpoint ring, and the class
1439  * driver won't clear the halt in that case, so we need to issue a Set Transfer
1440  * Ring Dequeue Pointer command manually.
1441  */
1442 static int xhci_requires_manual_halt_cleanup(struct xhci_hcd *xhci,
1443                 struct xhci_ep_ctx *ep_ctx,
1444                 unsigned int trb_comp_code)
1445 {
1446         /* TRB completion codes that may require a manual halt cleanup */
1447         if (trb_comp_code == COMP_TX_ERR ||
1448                         trb_comp_code == COMP_BABBLE ||
1449                         trb_comp_code == COMP_SPLIT_ERR)
1450                 /* The 0.96 spec says a babbling control endpoint
1451                  * is not halted. The 0.96 spec says it is.  Some HW
1452                  * claims to be 0.95 compliant, but it halts the control
1453                  * endpoint anyway.  Check if a babble halted the
1454                  * endpoint.
1455                  */
1456                 if ((le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK) == EP_STATE_HALTED)
1457                         return 1;
1458
1459         return 0;
1460 }
1461
1462 int xhci_is_vendor_info_code(struct xhci_hcd *xhci, unsigned int trb_comp_code)
1463 {
1464         if (trb_comp_code >= 224 && trb_comp_code <= 255) {
1465                 /* Vendor defined "informational" completion code,
1466                  * treat as not-an-error.
1467                  */
1468                 xhci_dbg(xhci, "Vendor defined info completion code %u\n",
1469                                 trb_comp_code);
1470                 xhci_dbg(xhci, "Treating code as success.\n");
1471                 return 1;
1472         }
1473         return 0;
1474 }
1475
1476 /*
1477  * Finish the td processing, remove the td from td list;
1478  * Return 1 if the urb can be given back.
1479  */
1480 static int finish_td(struct xhci_hcd *xhci, struct xhci_td *td,
1481         union xhci_trb *event_trb, struct xhci_transfer_event *event,
1482         struct xhci_virt_ep *ep, int *status, bool skip)
1483 {
1484         struct xhci_virt_device *xdev;
1485         struct xhci_ring *ep_ring;
1486         unsigned int slot_id;
1487         int ep_index;
1488         struct urb *urb = NULL;
1489         struct xhci_ep_ctx *ep_ctx;
1490         int ret = 0;
1491         struct urb_priv *urb_priv;
1492         u32 trb_comp_code;
1493
1494         slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
1495         xdev = xhci->devs[slot_id];
1496         ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1;
1497         ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer));
1498         ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
1499         trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
1500
1501         if (skip)
1502                 goto td_cleanup;
1503
1504         if (trb_comp_code == COMP_STOP_INVAL ||
1505                         trb_comp_code == COMP_STOP) {
1506                 /* The Endpoint Stop Command completion will take care of any
1507                  * stopped TDs.  A stopped TD may be restarted, so don't update
1508                  * the ring dequeue pointer or take this TD off any lists yet.
1509                  */
1510                 ep->stopped_td = td;
1511                 ep->stopped_trb = event_trb;
1512                 return 0;
1513         } else {
1514                 if (trb_comp_code == COMP_STALL) {
1515                         /* The transfer is completed from the driver's
1516                          * perspective, but we need to issue a set dequeue
1517                          * command for this stalled endpoint to move the dequeue
1518                          * pointer past the TD.  We can't do that here because
1519                          * the halt condition must be cleared first.  Let the
1520                          * USB class driver clear the stall later.
1521                          */
1522                         ep->stopped_td = td;
1523                         ep->stopped_trb = event_trb;
1524                         ep->stopped_stream = ep_ring->stream_id;
1525                 } else if (xhci_requires_manual_halt_cleanup(xhci,
1526                                         ep_ctx, trb_comp_code)) {
1527                         /* Other types of errors halt the endpoint, but the
1528                          * class driver doesn't call usb_reset_endpoint() unless
1529                          * the error is -EPIPE.  Clear the halted status in the
1530                          * xHCI hardware manually.
1531                          */
1532                         xhci_cleanup_halted_endpoint(xhci,
1533                                         slot_id, ep_index, ep_ring->stream_id,
1534                                         td, event_trb);
1535                 } else {
1536                         /* Update ring dequeue pointer */
1537                         while (ep_ring->dequeue != td->last_trb)
1538                                 inc_deq(xhci, ep_ring, false);
1539                         inc_deq(xhci, ep_ring, false);
1540                 }
1541
1542 td_cleanup:
1543                 /* Clean up the endpoint's TD list */
1544                 urb = td->urb;
1545                 urb_priv = urb->hcpriv;
1546
1547                 /* Do one last check of the actual transfer length.
1548                  * If the host controller said we transferred more data than
1549                  * the buffer length, urb->actual_length will be a very big
1550                  * number (since it's unsigned).  Play it safe and say we didn't
1551                  * transfer anything.
1552                  */
1553                 if (urb->actual_length > urb->transfer_buffer_length) {
1554                         xhci_warn(xhci, "URB transfer length is wrong, "
1555                                         "xHC issue? req. len = %u, "
1556                                         "act. len = %u\n",
1557                                         urb->transfer_buffer_length,
1558                                         urb->actual_length);
1559                         urb->actual_length = 0;
1560                         if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1561                                 *status = -EREMOTEIO;
1562                         else
1563                                 *status = 0;
1564                 }
1565                 list_del(&td->td_list);
1566                 /* Was this TD slated to be cancelled but completed anyway? */
1567                 if (!list_empty(&td->cancelled_td_list))
1568                         list_del(&td->cancelled_td_list);
1569
1570                 urb_priv->td_cnt++;
1571                 /* Giveback the urb when all the tds are completed */
1572                 if (urb_priv->td_cnt == urb_priv->length) {
1573                         ret = 1;
1574                         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
1575                                 xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs--;
1576                                 if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs
1577                                         == 0) {
1578                                         if (xhci->quirks & XHCI_AMD_PLL_FIX)
1579                                                 usb_amd_quirk_pll_enable();
1580                                 }
1581                         }
1582                 }
1583         }
1584
1585         return ret;
1586 }
1587
1588 /*
1589  * Process control tds, update urb status and actual_length.
1590  */
1591 static int process_ctrl_td(struct xhci_hcd *xhci, struct xhci_td *td,
1592         union xhci_trb *event_trb, struct xhci_transfer_event *event,
1593         struct xhci_virt_ep *ep, int *status)
1594 {
1595         struct xhci_virt_device *xdev;
1596         struct xhci_ring *ep_ring;
1597         unsigned int slot_id;
1598         int ep_index;
1599         struct xhci_ep_ctx *ep_ctx;
1600         u32 trb_comp_code;
1601
1602         slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
1603         xdev = xhci->devs[slot_id];
1604         ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1;
1605         ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer));
1606         ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
1607         trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
1608
1609         xhci_debug_trb(xhci, xhci->event_ring->dequeue);
1610         switch (trb_comp_code) {
1611         case COMP_SUCCESS:
1612                 if (event_trb == ep_ring->dequeue) {
1613                         xhci_warn(xhci, "WARN: Success on ctrl setup TRB "
1614                                         "without IOC set??\n");
1615                         *status = -ESHUTDOWN;
1616                 } else if (event_trb != td->last_trb) {
1617                         xhci_warn(xhci, "WARN: Success on ctrl data TRB "
1618                                         "without IOC set??\n");
1619                         *status = -ESHUTDOWN;
1620                 } else {
1621                         *status = 0;
1622                 }
1623                 break;
1624         case COMP_SHORT_TX:
1625                 xhci_warn(xhci, "WARN: short transfer on control ep\n");
1626                 if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1627                         *status = -EREMOTEIO;
1628                 else
1629                         *status = 0;
1630                 break;
1631         case COMP_STOP_INVAL:
1632         case COMP_STOP:
1633                 return finish_td(xhci, td, event_trb, event, ep, status, false);
1634         default:
1635                 if (!xhci_requires_manual_halt_cleanup(xhci,
1636                                         ep_ctx, trb_comp_code))
1637                         break;
1638                 xhci_dbg(xhci, "TRB error code %u, "
1639                                 "halted endpoint index = %u\n",
1640                                 trb_comp_code, ep_index);
1641                 /* else fall through */
1642         case COMP_STALL:
1643                 /* Did we transfer part of the data (middle) phase? */
1644                 if (event_trb != ep_ring->dequeue &&
1645                                 event_trb != td->last_trb)
1646                         td->urb->actual_length =
1647                                 td->urb->transfer_buffer_length
1648                                 - TRB_LEN(le32_to_cpu(event->transfer_len));
1649                 else
1650                         td->urb->actual_length = 0;
1651
1652                 xhci_cleanup_halted_endpoint(xhci,
1653                         slot_id, ep_index, 0, td, event_trb);
1654                 return finish_td(xhci, td, event_trb, event, ep, status, true);
1655         }
1656         /*
1657          * Did we transfer any data, despite the errors that might have
1658          * happened?  I.e. did we get past the setup stage?
1659          */
1660         if (event_trb != ep_ring->dequeue) {
1661                 /* The event was for the status stage */
1662                 if (event_trb == td->last_trb) {
1663                         if (td->urb->actual_length != 0) {
1664                                 /* Don't overwrite a previously set error code
1665                                  */
1666                                 if ((*status == -EINPROGRESS || *status == 0) &&
1667                                                 (td->urb->transfer_flags
1668                                                  & URB_SHORT_NOT_OK))
1669                                         /* Did we already see a short data
1670                                          * stage? */
1671                                         *status = -EREMOTEIO;
1672                         } else {
1673                                 td->urb->actual_length =
1674                                         td->urb->transfer_buffer_length;
1675                         }
1676                 } else {
1677                 /* Maybe the event was for the data stage? */
1678                         td->urb->actual_length =
1679                                 td->urb->transfer_buffer_length -
1680                                 TRB_LEN(le32_to_cpu(event->transfer_len));
1681                         xhci_dbg(xhci, "Waiting for status "
1682                                         "stage event\n");
1683                         return 0;
1684                 }
1685         }
1686
1687         return finish_td(xhci, td, event_trb, event, ep, status, false);
1688 }
1689
1690 /*
1691  * Process isochronous tds, update urb packet status and actual_length.
1692  */
1693 static int process_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td,
1694         union xhci_trb *event_trb, struct xhci_transfer_event *event,
1695         struct xhci_virt_ep *ep, int *status)
1696 {
1697         struct xhci_ring *ep_ring;
1698         struct urb_priv *urb_priv;
1699         int idx;
1700         int len = 0;
1701         union xhci_trb *cur_trb;
1702         struct xhci_segment *cur_seg;
1703         struct usb_iso_packet_descriptor *frame;
1704         u32 trb_comp_code;
1705         bool skip_td = false;
1706
1707         ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer));
1708         trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
1709         urb_priv = td->urb->hcpriv;
1710         idx = urb_priv->td_cnt;
1711         frame = &td->urb->iso_frame_desc[idx];
1712
1713         /* handle completion code */
1714         switch (trb_comp_code) {
1715         case COMP_SUCCESS:
1716                 frame->status = 0;
1717                 break;
1718         case COMP_SHORT_TX:
1719                 frame->status = td->urb->transfer_flags & URB_SHORT_NOT_OK ?
1720                                 -EREMOTEIO : 0;
1721                 break;
1722         case COMP_BW_OVER:
1723                 frame->status = -ECOMM;
1724                 skip_td = true;
1725                 break;
1726         case COMP_BUFF_OVER:
1727         case COMP_BABBLE:
1728                 frame->status = -EOVERFLOW;
1729                 skip_td = true;
1730                 break;
1731         case COMP_STALL:
1732                 frame->status = -EPROTO;
1733                 skip_td = true;
1734                 break;
1735         case COMP_STOP:
1736         case COMP_STOP_INVAL:
1737                 break;
1738         default:
1739                 frame->status = -1;
1740                 break;
1741         }
1742
1743         if (trb_comp_code == COMP_SUCCESS || skip_td) {
1744                 frame->actual_length = frame->length;
1745                 td->urb->actual_length += frame->length;
1746         } else {
1747                 for (cur_trb = ep_ring->dequeue,
1748                      cur_seg = ep_ring->deq_seg; cur_trb != event_trb;
1749                      next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) {
1750                         if ((le32_to_cpu(cur_trb->generic.field[3]) &
1751                          TRB_TYPE_BITMASK) != TRB_TYPE(TRB_TR_NOOP) &&
1752                             (le32_to_cpu(cur_trb->generic.field[3]) &
1753                          TRB_TYPE_BITMASK) != TRB_TYPE(TRB_LINK))
1754                                 len += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2]));
1755                 }
1756                 len += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])) -
1757                         TRB_LEN(le32_to_cpu(event->transfer_len));
1758
1759                 if (trb_comp_code != COMP_STOP_INVAL) {
1760                         frame->actual_length = len;
1761                         td->urb->actual_length += len;
1762                 }
1763         }
1764
1765         if ((idx == urb_priv->length - 1) && *status == -EINPROGRESS)
1766                 *status = 0;
1767
1768         return finish_td(xhci, td, event_trb, event, ep, status, false);
1769 }
1770
1771 static int skip_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td,
1772                         struct xhci_transfer_event *event,
1773                         struct xhci_virt_ep *ep, int *status)
1774 {
1775         struct xhci_ring *ep_ring;
1776         struct urb_priv *urb_priv;
1777         struct usb_iso_packet_descriptor *frame;
1778         int idx;
1779
1780         ep_ring = xhci_dma_to_transfer_ring(ep, event->buffer);
1781         urb_priv = td->urb->hcpriv;
1782         idx = urb_priv->td_cnt;
1783         frame = &td->urb->iso_frame_desc[idx];
1784
1785         /* The transfer is partly done */
1786         *status = -EXDEV;
1787         frame->status = -EXDEV;
1788
1789         /* calc actual length */
1790         frame->actual_length = 0;
1791
1792         /* Update ring dequeue pointer */
1793         while (ep_ring->dequeue != td->last_trb)
1794                 inc_deq(xhci, ep_ring, false);
1795         inc_deq(xhci, ep_ring, false);
1796
1797         return finish_td(xhci, td, NULL, event, ep, status, true);
1798 }
1799
1800 /*
1801  * Process bulk and interrupt tds, update urb status and actual_length.
1802  */
1803 static int process_bulk_intr_td(struct xhci_hcd *xhci, struct xhci_td *td,
1804         union xhci_trb *event_trb, struct xhci_transfer_event *event,
1805         struct xhci_virt_ep *ep, int *status)
1806 {
1807         struct xhci_ring *ep_ring;
1808         union xhci_trb *cur_trb;
1809         struct xhci_segment *cur_seg;
1810         u32 trb_comp_code;
1811
1812         ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer));
1813         trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
1814
1815         switch (trb_comp_code) {
1816         case COMP_SUCCESS:
1817                 /* Double check that the HW transferred everything. */
1818                 if (event_trb != td->last_trb) {
1819                         xhci_warn(xhci, "WARN Successful completion "
1820                                         "on short TX\n");
1821                         if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1822                                 *status = -EREMOTEIO;
1823                         else
1824                                 *status = 0;
1825                 } else {
1826                         *status = 0;
1827                 }
1828                 break;
1829         case COMP_SHORT_TX:
1830                 if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1831                         *status = -EREMOTEIO;
1832                 else
1833                         *status = 0;
1834                 break;
1835         default:
1836                 /* Others already handled above */
1837                 break;
1838         }
1839         if (trb_comp_code == COMP_SHORT_TX)
1840                 xhci_dbg(xhci, "ep %#x - asked for %d bytes, "
1841                                 "%d bytes untransferred\n",
1842                                 td->urb->ep->desc.bEndpointAddress,
1843                                 td->urb->transfer_buffer_length,
1844                                 TRB_LEN(le32_to_cpu(event->transfer_len)));
1845         /* Fast path - was this the last TRB in the TD for this URB? */
1846         if (event_trb == td->last_trb) {
1847                 if (TRB_LEN(le32_to_cpu(event->transfer_len)) != 0) {
1848                         td->urb->actual_length =
1849                                 td->urb->transfer_buffer_length -
1850                                 TRB_LEN(le32_to_cpu(event->transfer_len));
1851                         if (td->urb->transfer_buffer_length <
1852                                         td->urb->actual_length) {
1853                                 xhci_warn(xhci, "HC gave bad length "
1854                                                 "of %d bytes left\n",
1855                                           TRB_LEN(le32_to_cpu(event->transfer_len)));
1856                                 td->urb->actual_length = 0;
1857                                 if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1858                                         *status = -EREMOTEIO;
1859                                 else
1860                                         *status = 0;
1861                         }
1862                         /* Don't overwrite a previously set error code */
1863                         if (*status == -EINPROGRESS) {
1864                                 if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1865                                         *status = -EREMOTEIO;
1866                                 else
1867                                         *status = 0;
1868                         }
1869                 } else {
1870                         td->urb->actual_length =
1871                                 td->urb->transfer_buffer_length;
1872                         /* Ignore a short packet completion if the
1873                          * untransferred length was zero.
1874                          */
1875                         if (*status == -EREMOTEIO)
1876                                 *status = 0;
1877                 }
1878         } else {
1879                 /* Slow path - walk the list, starting from the dequeue
1880                  * pointer, to get the actual length transferred.
1881                  */
1882                 td->urb->actual_length = 0;
1883                 for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg;
1884                                 cur_trb != event_trb;
1885                                 next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) {
1886                         if ((le32_to_cpu(cur_trb->generic.field[3]) &
1887                          TRB_TYPE_BITMASK) != TRB_TYPE(TRB_TR_NOOP) &&
1888                             (le32_to_cpu(cur_trb->generic.field[3]) &
1889                          TRB_TYPE_BITMASK) != TRB_TYPE(TRB_LINK))
1890                                 td->urb->actual_length +=
1891                                         TRB_LEN(le32_to_cpu(cur_trb->generic.field[2]));
1892                 }
1893                 /* If the ring didn't stop on a Link or No-op TRB, add
1894                  * in the actual bytes transferred from the Normal TRB
1895                  */
1896                 if (trb_comp_code != COMP_STOP_INVAL)
1897                         td->urb->actual_length +=
1898                                 TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])) -
1899                                 TRB_LEN(le32_to_cpu(event->transfer_len));
1900         }
1901
1902         return finish_td(xhci, td, event_trb, event, ep, status, false);
1903 }
1904
1905 /*
1906  * If this function returns an error condition, it means it got a Transfer
1907  * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address.
1908  * At this point, the host controller is probably hosed and should be reset.
1909  */
1910 static int handle_tx_event(struct xhci_hcd *xhci,
1911                 struct xhci_transfer_event *event)
1912 {
1913         struct xhci_virt_device *xdev;
1914         struct xhci_virt_ep *ep;
1915         struct xhci_ring *ep_ring;
1916         unsigned int slot_id;
1917         int ep_index;
1918         struct xhci_td *td = NULL;
1919         dma_addr_t event_dma;
1920         struct xhci_segment *event_seg;
1921         union xhci_trb *event_trb;
1922         struct urb *urb = NULL;
1923         int status = -EINPROGRESS;
1924         struct urb_priv *urb_priv;
1925         struct xhci_ep_ctx *ep_ctx;
1926         u32 trb_comp_code;
1927         int ret = 0;
1928
1929         slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
1930         xdev = xhci->devs[slot_id];
1931         if (!xdev) {
1932                 xhci_err(xhci, "ERROR Transfer event pointed to bad slot\n");
1933                 return -ENODEV;
1934         }
1935
1936         /* Endpoint ID is 1 based, our index is zero based */
1937         ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1;
1938         ep = &xdev->eps[ep_index];
1939         ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer));
1940         ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
1941         if (!ep_ring ||
1942             (le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK) ==
1943             EP_STATE_DISABLED) {
1944                 xhci_err(xhci, "ERROR Transfer event for disabled endpoint "
1945                                 "or incorrect stream ring\n");
1946                 return -ENODEV;
1947         }
1948
1949         event_dma = le64_to_cpu(event->buffer);
1950         trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
1951         /* Look for common error cases */
1952         switch (trb_comp_code) {
1953         /* Skip codes that require special handling depending on
1954          * transfer type
1955          */
1956         case COMP_SUCCESS:
1957         case COMP_SHORT_TX:
1958                 break;
1959         case COMP_STOP:
1960                 xhci_dbg(xhci, "Stopped on Transfer TRB\n");
1961                 break;
1962         case COMP_STOP_INVAL:
1963                 xhci_dbg(xhci, "Stopped on No-op or Link TRB\n");
1964                 break;
1965         case COMP_STALL:
1966                 xhci_warn(xhci, "WARN: Stalled endpoint\n");
1967                 ep->ep_state |= EP_HALTED;
1968                 status = -EPIPE;
1969                 break;
1970         case COMP_TRB_ERR:
1971                 xhci_warn(xhci, "WARN: TRB error on endpoint\n");
1972                 status = -EILSEQ;
1973                 break;
1974         case COMP_SPLIT_ERR:
1975         case COMP_TX_ERR:
1976                 xhci_warn(xhci, "WARN: transfer error on endpoint\n");
1977                 status = -EPROTO;
1978                 break;
1979         case COMP_BABBLE:
1980                 xhci_warn(xhci, "WARN: babble error on endpoint\n");
1981                 status = -EOVERFLOW;
1982                 break;
1983         case COMP_DB_ERR:
1984                 xhci_warn(xhci, "WARN: HC couldn't access mem fast enough\n");
1985                 status = -ENOSR;
1986                 break;
1987         case COMP_BW_OVER:
1988                 xhci_warn(xhci, "WARN: bandwidth overrun event on endpoint\n");
1989                 break;
1990         case COMP_BUFF_OVER:
1991                 xhci_warn(xhci, "WARN: buffer overrun event on endpoint\n");
1992                 break;
1993         case COMP_UNDERRUN:
1994                 /*
1995                  * When the Isoch ring is empty, the xHC will generate
1996                  * a Ring Overrun Event for IN Isoch endpoint or Ring
1997                  * Underrun Event for OUT Isoch endpoint.
1998                  */
1999                 xhci_dbg(xhci, "underrun event on endpoint\n");
2000                 if (!list_empty(&ep_ring->td_list))
2001                         xhci_dbg(xhci, "Underrun Event for slot %d ep %d "
2002                                         "still with TDs queued?\n",
2003                                  TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2004                                  ep_index);
2005                 goto cleanup;
2006         case COMP_OVERRUN:
2007                 xhci_dbg(xhci, "overrun event on endpoint\n");
2008                 if (!list_empty(&ep_ring->td_list))
2009                         xhci_dbg(xhci, "Overrun Event for slot %d ep %d "
2010                                         "still with TDs queued?\n",
2011                                  TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2012                                  ep_index);
2013                 goto cleanup;
2014         case COMP_MISSED_INT:
2015                 /*
2016                  * When encounter missed service error, one or more isoc tds
2017                  * may be missed by xHC.
2018                  * Set skip flag of the ep_ring; Complete the missed tds as
2019                  * short transfer when process the ep_ring next time.
2020                  */
2021                 ep->skip = true;
2022                 xhci_dbg(xhci, "Miss service interval error, set skip flag\n");
2023                 goto cleanup;
2024         default:
2025                 if (xhci_is_vendor_info_code(xhci, trb_comp_code)) {
2026                         status = 0;
2027                         break;
2028                 }
2029                 xhci_warn(xhci, "ERROR Unknown event condition, HC probably "
2030                                 "busted\n");
2031                 goto cleanup;
2032         }
2033
2034         do {
2035                 /* This TRB should be in the TD at the head of this ring's
2036                  * TD list.
2037                  */
2038                 if (list_empty(&ep_ring->td_list)) {
2039                         xhci_warn(xhci, "WARN Event TRB for slot %d ep %d "
2040                                         "with no TDs queued?\n",
2041                                   TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2042                                   ep_index);
2043                         xhci_dbg(xhci, "Event TRB with TRB type ID %u\n",
2044                                  (unsigned int) (le32_to_cpu(event->flags)
2045                                                  & TRB_TYPE_BITMASK)>>10);
2046                         xhci_print_trb_offsets(xhci, (union xhci_trb *) event);
2047                         if (ep->skip) {
2048                                 ep->skip = false;
2049                                 xhci_dbg(xhci, "td_list is empty while skip "
2050                                                 "flag set. Clear skip flag.\n");
2051                         }
2052                         ret = 0;
2053                         goto cleanup;
2054                 }
2055
2056                 td = list_entry(ep_ring->td_list.next, struct xhci_td, td_list);
2057
2058                 /* Is this a TRB in the currently executing TD? */
2059                 event_seg = trb_in_td(ep_ring->deq_seg, ep_ring->dequeue,
2060                                 td->last_trb, event_dma);
2061                 if (!event_seg) {
2062                         if (!ep->skip ||
2063                             !usb_endpoint_xfer_isoc(&td->urb->ep->desc)) {
2064                                 /* Some host controllers give a spurious
2065                                  * successful event after a short transfer.
2066                                  * Ignore it.
2067                                  */
2068                                 if ((xhci->quirks & XHCI_SPURIOUS_SUCCESS) && 
2069                                                 ep_ring->last_td_was_short) {
2070                                         ep_ring->last_td_was_short = false;
2071                                         ret = 0;
2072                                         goto cleanup;
2073                                 }
2074                                 /* HC is busted, give up! */
2075                                 xhci_err(xhci,
2076                                         "ERROR Transfer event TRB DMA ptr not "
2077                                         "part of current TD\n");
2078                                 return -ESHUTDOWN;
2079                         }
2080
2081                         ret = skip_isoc_td(xhci, td, event, ep, &status);
2082                         goto cleanup;
2083                 }
2084                 if (trb_comp_code == COMP_SHORT_TX)
2085                         ep_ring->last_td_was_short = true;
2086                 else
2087                         ep_ring->last_td_was_short = false;
2088
2089                 if (ep->skip) {
2090                         xhci_dbg(xhci, "Found td. Clear skip flag.\n");
2091                         ep->skip = false;
2092                 }
2093
2094                 event_trb = &event_seg->trbs[(event_dma - event_seg->dma) /
2095                                                 sizeof(*event_trb)];
2096                 /*
2097                  * No-op TRB should not trigger interrupts.
2098                  * If event_trb is a no-op TRB, it means the
2099                  * corresponding TD has been cancelled. Just ignore
2100                  * the TD.
2101                  */
2102                 if ((le32_to_cpu(event_trb->generic.field[3])
2103                              & TRB_TYPE_BITMASK)
2104                                  == TRB_TYPE(TRB_TR_NOOP)) {
2105                         xhci_dbg(xhci,
2106                                  "event_trb is a no-op TRB. Skip it\n");
2107                         goto cleanup;
2108                 }
2109
2110                 /* Now update the urb's actual_length and give back to
2111                  * the core
2112                  */
2113                 if (usb_endpoint_xfer_control(&td->urb->ep->desc))
2114                         ret = process_ctrl_td(xhci, td, event_trb, event, ep,
2115                                                  &status);
2116                 else if (usb_endpoint_xfer_isoc(&td->urb->ep->desc))
2117                         ret = process_isoc_td(xhci, td, event_trb, event, ep,
2118                                                  &status);
2119                 else
2120                         ret = process_bulk_intr_td(xhci, td, event_trb, event,
2121                                                  ep, &status);
2122
2123 cleanup:
2124                 /*
2125                  * Do not update event ring dequeue pointer if ep->skip is set.
2126                  * Will roll back to continue process missed tds.
2127                  */
2128                 if (trb_comp_code == COMP_MISSED_INT || !ep->skip) {
2129                         inc_deq(xhci, xhci->event_ring, true);
2130                 }
2131
2132                 if (ret) {
2133                         urb = td->urb;
2134                         urb_priv = urb->hcpriv;
2135                         /* Leave the TD around for the reset endpoint function
2136                          * to use(but only if it's not a control endpoint,
2137                          * since we already queued the Set TR dequeue pointer
2138                          * command for stalled control endpoints).
2139                          */
2140                         if (usb_endpoint_xfer_control(&urb->ep->desc) ||
2141                                 (trb_comp_code != COMP_STALL &&
2142                                         trb_comp_code != COMP_BABBLE))
2143                                 xhci_urb_free_priv(xhci, urb_priv);
2144
2145                         usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb);
2146                         if ((urb->actual_length != urb->transfer_buffer_length &&
2147                                                 (urb->transfer_flags &
2148                                                  URB_SHORT_NOT_OK)) ||
2149                                         status != 0)
2150                                 xhci_dbg(xhci, "Giveback URB %p, len = %d, "
2151                                                 "expected = %x, status = %d\n",
2152                                                 urb, urb->actual_length,
2153                                                 urb->transfer_buffer_length,
2154                                                 status);
2155                         spin_unlock(&xhci->lock);
2156                         usb_hcd_giveback_urb(bus_to_hcd(urb->dev->bus), urb, status);
2157                         spin_lock(&xhci->lock);
2158                 }
2159
2160         /*
2161          * If ep->skip is set, it means there are missed tds on the
2162          * endpoint ring need to take care of.
2163          * Process them as short transfer until reach the td pointed by
2164          * the event.
2165          */
2166         } while (ep->skip && trb_comp_code != COMP_MISSED_INT);
2167
2168         return 0;
2169 }
2170
2171 /*
2172  * This function handles all OS-owned events on the event ring.  It may drop
2173  * xhci->lock between event processing (e.g. to pass up port status changes).
2174  * Returns >0 for "possibly more events to process" (caller should call again),
2175  * otherwise 0 if done.  In future, <0 returns should indicate error code.
2176  */
2177 static int xhci_handle_event(struct xhci_hcd *xhci)
2178 {
2179         union xhci_trb *event;
2180         int update_ptrs = 1;
2181         int ret;
2182
2183         if (!xhci->event_ring || !xhci->event_ring->dequeue) {
2184                 xhci->error_bitmask |= 1 << 1;
2185                 return 0;
2186         }
2187
2188         event = xhci->event_ring->dequeue;
2189         /* Does the HC or OS own the TRB? */
2190         if ((le32_to_cpu(event->event_cmd.flags) & TRB_CYCLE) !=
2191             xhci->event_ring->cycle_state) {
2192                 xhci->error_bitmask |= 1 << 2;
2193                 return 0;
2194         }
2195
2196         /*
2197          * Barrier between reading the TRB_CYCLE (valid) flag above and any
2198          * speculative reads of the event's flags/data below.
2199          */
2200         rmb();
2201         /* FIXME: Handle more event types. */
2202         switch ((le32_to_cpu(event->event_cmd.flags) & TRB_TYPE_BITMASK)) {
2203         case TRB_TYPE(TRB_COMPLETION):
2204                 handle_cmd_completion(xhci, &event->event_cmd);
2205                 break;
2206         case TRB_TYPE(TRB_PORT_STATUS):
2207                 handle_port_status(xhci, event);
2208                 update_ptrs = 0;
2209                 break;
2210         case TRB_TYPE(TRB_TRANSFER):
2211                 ret = handle_tx_event(xhci, &event->trans_event);
2212                 if (ret < 0)
2213                         xhci->error_bitmask |= 1 << 9;
2214                 else
2215                         update_ptrs = 0;
2216                 break;
2217         default:
2218                 if ((le32_to_cpu(event->event_cmd.flags) & TRB_TYPE_BITMASK) >=
2219                     TRB_TYPE(48))
2220                         handle_vendor_event(xhci, event);
2221                 else
2222                         xhci->error_bitmask |= 1 << 3;
2223         }
2224         /* Any of the above functions may drop and re-acquire the lock, so check
2225          * to make sure a watchdog timer didn't mark the host as non-responsive.
2226          */
2227         if (xhci->xhc_state & XHCI_STATE_DYING) {
2228                 xhci_dbg(xhci, "xHCI host dying, returning from "
2229                                 "event handler.\n");
2230                 return 0;
2231         }
2232
2233         if (update_ptrs)
2234                 /* Update SW event ring dequeue pointer */
2235                 inc_deq(xhci, xhci->event_ring, true);
2236
2237         /* Are there more items on the event ring?  Caller will call us again to
2238          * check.
2239          */
2240         return 1;
2241 }
2242
2243 /*
2244  * xHCI spec says we can get an interrupt, and if the HC has an error condition,
2245  * we might get bad data out of the event ring.  Section 4.10.2.7 has a list of
2246  * indicators of an event TRB error, but we check the status *first* to be safe.
2247  */
2248 irqreturn_t xhci_irq(struct usb_hcd *hcd)
2249 {
2250         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
2251         u32 status;
2252         union xhci_trb *trb;
2253         u64 temp_64;
2254         union xhci_trb *event_ring_deq;
2255         dma_addr_t deq;
2256
2257         spin_lock(&xhci->lock);
2258         trb = xhci->event_ring->dequeue;
2259         /* Check if the xHC generated the interrupt, or the irq is shared */
2260         status = xhci_readl(xhci, &xhci->op_regs->status);
2261         if (status == 0xffffffff)
2262                 goto hw_died;
2263
2264         if (!(status & STS_EINT)) {
2265                 spin_unlock(&xhci->lock);
2266                 return IRQ_NONE;
2267         }
2268         if (status & STS_FATAL) {
2269                 xhci_warn(xhci, "WARNING: Host System Error\n");
2270                 xhci_halt(xhci);
2271 hw_died:
2272                 spin_unlock(&xhci->lock);
2273                 return -ESHUTDOWN;
2274         }
2275
2276         /*
2277          * Clear the op reg interrupt status first,
2278          * so we can receive interrupts from other MSI-X interrupters.
2279          * Write 1 to clear the interrupt status.
2280          */
2281         status |= STS_EINT;
2282         xhci_writel(xhci, status, &xhci->op_regs->status);
2283         /* FIXME when MSI-X is supported and there are multiple vectors */
2284         /* Clear the MSI-X event interrupt status */
2285
2286         if (hcd->irq != -1) {
2287                 u32 irq_pending;
2288                 /* Acknowledge the PCI interrupt */
2289                 irq_pending = xhci_readl(xhci, &xhci->ir_set->irq_pending);
2290                 irq_pending |= 0x3;
2291                 xhci_writel(xhci, irq_pending, &xhci->ir_set->irq_pending);
2292         }
2293
2294         if (xhci->xhc_state & XHCI_STATE_DYING) {
2295                 xhci_dbg(xhci, "xHCI dying, ignoring interrupt. "
2296                                 "Shouldn't IRQs be disabled?\n");
2297                 /* Clear the event handler busy flag (RW1C);
2298                  * the event ring should be empty.
2299                  */
2300                 temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
2301                 xhci_write_64(xhci, temp_64 | ERST_EHB,
2302                                 &xhci->ir_set->erst_dequeue);
2303                 spin_unlock(&xhci->lock);
2304
2305                 return IRQ_HANDLED;
2306         }
2307
2308         event_ring_deq = xhci->event_ring->dequeue;
2309         /* FIXME this should be a delayed service routine
2310          * that clears the EHB.
2311          */
2312         while (xhci_handle_event(xhci) > 0) {}
2313
2314         temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
2315         /* If necessary, update the HW's version of the event ring deq ptr. */
2316         if (event_ring_deq != xhci->event_ring->dequeue) {
2317                 deq = xhci_trb_virt_to_dma(xhci->event_ring->deq_seg,
2318                                 xhci->event_ring->dequeue);
2319                 if (deq == 0)
2320                         xhci_warn(xhci, "WARN something wrong with SW event "
2321                                         "ring dequeue ptr.\n");
2322                 /* Update HC event ring dequeue pointer */
2323                 temp_64 &= ERST_PTR_MASK;
2324                 temp_64 |= ((u64) deq & (u64) ~ERST_PTR_MASK);
2325         }
2326
2327         /* Clear the event handler busy flag (RW1C); event ring is empty. */
2328         temp_64 |= ERST_EHB;
2329         xhci_write_64(xhci, temp_64, &xhci->ir_set->erst_dequeue);
2330
2331         spin_unlock(&xhci->lock);
2332
2333         return IRQ_HANDLED;
2334 }
2335
2336 irqreturn_t xhci_msi_irq(int irq, struct usb_hcd *hcd)
2337 {
2338         irqreturn_t ret;
2339         struct xhci_hcd *xhci;
2340
2341         xhci = hcd_to_xhci(hcd);
2342         set_bit(HCD_FLAG_SAW_IRQ, &hcd->flags);
2343         if (xhci->shared_hcd)
2344                 set_bit(HCD_FLAG_SAW_IRQ, &xhci->shared_hcd->flags);
2345
2346         ret = xhci_irq(hcd);
2347
2348         return ret;
2349 }
2350
2351 /****           Endpoint Ring Operations        ****/
2352
2353 /*
2354  * Generic function for queueing a TRB on a ring.
2355  * The caller must have checked to make sure there's room on the ring.
2356  *
2357  * @more_trbs_coming:   Will you enqueue more TRBs before calling
2358  *                      prepare_transfer()?
2359  */
2360 static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
2361                 bool consumer, bool more_trbs_coming,
2362                 u32 field1, u32 field2, u32 field3, u32 field4)
2363 {
2364         struct xhci_generic_trb *trb;
2365
2366         trb = &ring->enqueue->generic;
2367         trb->field[0] = cpu_to_le32(field1);
2368         trb->field[1] = cpu_to_le32(field2);
2369         trb->field[2] = cpu_to_le32(field3);
2370         trb->field[3] = cpu_to_le32(field4);
2371         inc_enq(xhci, ring, consumer, more_trbs_coming);
2372 }
2373
2374 /*
2375  * Does various checks on the endpoint ring, and makes it ready to queue num_trbs.
2376  * FIXME allocate segments if the ring is full.
2377  */
2378 static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
2379                 u32 ep_state, unsigned int num_trbs, gfp_t mem_flags)
2380 {
2381         /* Make sure the endpoint has been added to xHC schedule */
2382         switch (ep_state) {
2383         case EP_STATE_DISABLED:
2384                 /*
2385                  * USB core changed config/interfaces without notifying us,
2386                  * or hardware is reporting the wrong state.
2387                  */
2388                 xhci_warn(xhci, "WARN urb submitted to disabled ep\n");
2389                 return -ENOENT;
2390         case EP_STATE_ERROR:
2391                 xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n");
2392                 /* FIXME event handling code for error needs to clear it */
2393                 /* XXX not sure if this should be -ENOENT or not */
2394                 return -EINVAL;
2395         case EP_STATE_HALTED:
2396                 xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n");
2397         case EP_STATE_STOPPED:
2398         case EP_STATE_RUNNING:
2399                 break;
2400         default:
2401                 xhci_err(xhci, "ERROR unknown endpoint state for ep\n");
2402                 /*
2403                  * FIXME issue Configure Endpoint command to try to get the HC
2404                  * back into a known state.
2405                  */
2406                 return -EINVAL;
2407         }
2408         if (!room_on_ring(xhci, ep_ring, num_trbs)) {
2409                 /* FIXME allocate more room */
2410                 xhci_err(xhci, "ERROR no room on ep ring\n");
2411                 return -ENOMEM;
2412         }
2413
2414         if (enqueue_is_link_trb(ep_ring)) {
2415                 struct xhci_ring *ring = ep_ring;
2416                 union xhci_trb *next;
2417
2418                 next = ring->enqueue;
2419
2420                 while (last_trb(xhci, ring, ring->enq_seg, next)) {
2421                         /* If we're not dealing with 0.95 hardware,
2422                          * clear the chain bit.
2423                          */
2424                         if (!xhci_link_trb_quirk(xhci))
2425                                 next->link.control &= cpu_to_le32(~TRB_CHAIN);
2426                         else
2427                                 next->link.control |= cpu_to_le32(TRB_CHAIN);
2428
2429                         wmb();
2430                         next->link.control ^= cpu_to_le32((u32) TRB_CYCLE);
2431
2432                         /* Toggle the cycle bit after the last ring segment. */
2433                         if (last_trb_on_last_seg(xhci, ring, ring->enq_seg, next)) {
2434                                 ring->cycle_state = (ring->cycle_state ? 0 : 1);
2435                                 if (!in_interrupt()) {
2436                                         xhci_dbg(xhci, "queue_trb: Toggle cycle "
2437                                                 "state for ring %p = %i\n",
2438                                                 ring, (unsigned int)ring->cycle_state);
2439                                 }
2440                         }
2441                         ring->enq_seg = ring->enq_seg->next;
2442                         ring->enqueue = ring->enq_seg->trbs;
2443                         next = ring->enqueue;
2444                 }
2445         }
2446
2447         return 0;
2448 }
2449
2450 static int prepare_transfer(struct xhci_hcd *xhci,
2451                 struct xhci_virt_device *xdev,
2452                 unsigned int ep_index,
2453                 unsigned int stream_id,
2454                 unsigned int num_trbs,
2455                 struct urb *urb,
2456                 unsigned int td_index,
2457                 gfp_t mem_flags)
2458 {
2459         int ret;
2460         struct urb_priv *urb_priv;
2461         struct xhci_td  *td;
2462         struct xhci_ring *ep_ring;
2463         struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
2464
2465         ep_ring = xhci_stream_id_to_ring(xdev, ep_index, stream_id);
2466         if (!ep_ring) {
2467                 xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n",
2468                                 stream_id);
2469                 return -EINVAL;
2470         }
2471
2472         ret = prepare_ring(xhci, ep_ring,
2473                            le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK,
2474                            num_trbs, mem_flags);
2475         if (ret)
2476                 return ret;
2477
2478         urb_priv = urb->hcpriv;
2479         td = urb_priv->td[td_index];
2480
2481         INIT_LIST_HEAD(&td->td_list);
2482         INIT_LIST_HEAD(&td->cancelled_td_list);
2483
2484         if (td_index == 0) {
2485                 ret = usb_hcd_link_urb_to_ep(bus_to_hcd(urb->dev->bus), urb);
2486                 if (unlikely(ret)) {
2487                         xhci_urb_free_priv(xhci, urb_priv);
2488                         urb->hcpriv = NULL;
2489                         return ret;
2490                 }
2491         }
2492
2493         td->urb = urb;
2494         /* Add this TD to the tail of the endpoint ring's TD list */
2495         list_add_tail(&td->td_list, &ep_ring->td_list);
2496         td->start_seg = ep_ring->enq_seg;
2497         td->first_trb = ep_ring->enqueue;
2498
2499         urb_priv->td[td_index] = td;
2500
2501         return 0;
2502 }
2503
2504 static unsigned int count_sg_trbs_needed(struct xhci_hcd *xhci, struct urb *urb)
2505 {
2506         int num_sgs, num_trbs, running_total, temp, i;
2507         struct scatterlist *sg;
2508
2509         sg = NULL;
2510         num_sgs = urb->num_sgs;
2511         temp = urb->transfer_buffer_length;
2512
2513         xhci_dbg(xhci, "count sg list trbs: \n");
2514         num_trbs = 0;
2515         for_each_sg(urb->sg, sg, num_sgs, i) {
2516                 unsigned int previous_total_trbs = num_trbs;
2517                 unsigned int len = sg_dma_len(sg);
2518
2519                 /* Scatter gather list entries may cross 64KB boundaries */
2520                 running_total = TRB_MAX_BUFF_SIZE -
2521                         (sg_dma_address(sg) & (TRB_MAX_BUFF_SIZE - 1));
2522                 running_total &= TRB_MAX_BUFF_SIZE - 1;
2523                 if (running_total != 0)
2524                         num_trbs++;
2525
2526                 /* How many more 64KB chunks to transfer, how many more TRBs? */
2527                 while (running_total < sg_dma_len(sg) && running_total < temp) {
2528                         num_trbs++;
2529                         running_total += TRB_MAX_BUFF_SIZE;
2530                 }
2531                 xhci_dbg(xhci, " sg #%d: dma = %#llx, len = %#x (%d), num_trbs = %d\n",
2532                                 i, (unsigned long long)sg_dma_address(sg),
2533                                 len, len, num_trbs - previous_total_trbs);
2534
2535                 len = min_t(int, len, temp);
2536                 temp -= len;
2537                 if (temp == 0)
2538                         break;
2539         }
2540         xhci_dbg(xhci, "\n");
2541         if (!in_interrupt())
2542                 xhci_dbg(xhci, "ep %#x - urb len = %d, sglist used, "
2543                                 "num_trbs = %d\n",
2544                                 urb->ep->desc.bEndpointAddress,
2545                                 urb->transfer_buffer_length,
2546                                 num_trbs);
2547         return num_trbs;
2548 }
2549
2550 static void check_trb_math(struct urb *urb, int num_trbs, int running_total)
2551 {
2552         if (num_trbs != 0)
2553                 dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated number of "
2554                                 "TRBs, %d left\n", __func__,
2555                                 urb->ep->desc.bEndpointAddress, num_trbs);
2556         if (running_total != urb->transfer_buffer_length)
2557                 dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, "
2558                                 "queued %#x (%d), asked for %#x (%d)\n",
2559                                 __func__,
2560                                 urb->ep->desc.bEndpointAddress,
2561                                 running_total, running_total,
2562                                 urb->transfer_buffer_length,
2563                                 urb->transfer_buffer_length);
2564 }
2565
2566 static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id,
2567                 unsigned int ep_index, unsigned int stream_id, int start_cycle,
2568                 struct xhci_generic_trb *start_trb)
2569 {
2570         /*
2571          * Pass all the TRBs to the hardware at once and make sure this write
2572          * isn't reordered.
2573          */
2574         wmb();
2575         if (start_cycle)
2576                 start_trb->field[3] |= cpu_to_le32(start_cycle);
2577         else
2578                 start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE);
2579         xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
2580 }
2581
2582 /*
2583  * xHCI uses normal TRBs for both bulk and interrupt.  When the interrupt
2584  * endpoint is to be serviced, the xHC will consume (at most) one TD.  A TD
2585  * (comprised of sg list entries) can take several service intervals to
2586  * transmit.
2587  */
2588 int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
2589                 struct urb *urb, int slot_id, unsigned int ep_index)
2590 {
2591         struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci,
2592                         xhci->devs[slot_id]->out_ctx, ep_index);
2593         int xhci_interval;
2594         int ep_interval;
2595
2596         xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info));
2597         ep_interval = urb->interval;
2598         /* Convert to microframes */
2599         if (urb->dev->speed == USB_SPEED_LOW ||
2600                         urb->dev->speed == USB_SPEED_FULL)
2601                 ep_interval *= 8;
2602         /* FIXME change this to a warning and a suggestion to use the new API
2603          * to set the polling interval (once the API is added).
2604          */
2605         if (xhci_interval != ep_interval) {
2606                 if (printk_ratelimit())
2607                         dev_dbg(&urb->dev->dev, "Driver uses different interval"
2608                                         " (%d microframe%s) than xHCI "
2609                                         "(%d microframe%s)\n",
2610                                         ep_interval,
2611                                         ep_interval == 1 ? "" : "s",
2612                                         xhci_interval,
2613                                         xhci_interval == 1 ? "" : "s");
2614                 urb->interval = xhci_interval;
2615                 /* Convert back to frames for LS/FS devices */
2616                 if (urb->dev->speed == USB_SPEED_LOW ||
2617                                 urb->dev->speed == USB_SPEED_FULL)
2618                         urb->interval /= 8;
2619         }
2620         return xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb, slot_id, ep_index);
2621 }
2622
2623 /*
2624  * The TD size is the number of bytes remaining in the TD (including this TRB),
2625  * right shifted by 10.
2626  * It must fit in bits 21:17, so it can't be bigger than 31.
2627  */
2628 static u32 xhci_td_remainder(unsigned int remainder)
2629 {
2630         u32 max = (1 << (21 - 17 + 1)) - 1;
2631
2632         if ((remainder >> 10) >= max)
2633                 return max << 17;
2634         else
2635                 return (remainder >> 10) << 17;
2636 }
2637
2638 /*
2639  * For xHCI 1.0 host controllers, TD size is the number of packets remaining in
2640  * the TD (*not* including this TRB).
2641  *
2642  * Total TD packet count = total_packet_count =
2643  *     roundup(TD size in bytes / wMaxPacketSize)
2644  *
2645  * Packets transferred up to and including this TRB = packets_transferred =
2646  *     rounddown(total bytes transferred including this TRB / wMaxPacketSize)
2647  *
2648  * TD size = total_packet_count - packets_transferred
2649  *
2650  * It must fit in bits 21:17, so it can't be bigger than 31.
2651  */
2652
2653 static u32 xhci_v1_0_td_remainder(int running_total, int trb_buff_len,
2654                 unsigned int total_packet_count, struct urb *urb)
2655 {
2656         int packets_transferred;
2657
2658         /* All the TRB queueing functions don't count the current TRB in
2659          * running_total.
2660          */
2661         packets_transferred = (running_total + trb_buff_len) /
2662                 le16_to_cpu(urb->ep->desc.wMaxPacketSize);
2663
2664         return xhci_td_remainder(total_packet_count - packets_transferred);
2665 }
2666
2667 static int queue_bulk_sg_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
2668                 struct urb *urb, int slot_id, unsigned int ep_index)
2669 {
2670         struct xhci_ring *ep_ring;
2671         unsigned int num_trbs;
2672         struct urb_priv *urb_priv;
2673         struct xhci_td *td;
2674         struct scatterlist *sg;
2675         int num_sgs;
2676         int trb_buff_len, this_sg_len, running_total;
2677         unsigned int total_packet_count;
2678         bool first_trb;
2679         u64 addr;
2680         bool more_trbs_coming;
2681
2682         struct xhci_generic_trb *start_trb;
2683         int start_cycle;
2684
2685         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
2686         if (!ep_ring)
2687                 return -EINVAL;
2688
2689         num_trbs = count_sg_trbs_needed(xhci, urb);
2690         num_sgs = urb->num_sgs;
2691         total_packet_count = roundup(urb->transfer_buffer_length,
2692                         le16_to_cpu(urb->ep->desc.wMaxPacketSize));
2693
2694         trb_buff_len = prepare_transfer(xhci, xhci->devs[slot_id],
2695                         ep_index, urb->stream_id,
2696                         num_trbs, urb, 0, mem_flags);
2697         if (trb_buff_len < 0)
2698                 return trb_buff_len;
2699
2700         urb_priv = urb->hcpriv;
2701         td = urb_priv->td[0];
2702
2703         /*
2704          * Don't give the first TRB to the hardware (by toggling the cycle bit)
2705          * until we've finished creating all the other TRBs.  The ring's cycle
2706          * state may change as we enqueue the other TRBs, so save it too.
2707          */
2708         start_trb = &ep_ring->enqueue->generic;
2709         start_cycle = ep_ring->cycle_state;
2710
2711         running_total = 0;
2712         /*
2713          * How much data is in the first TRB?
2714          *
2715          * There are three forces at work for TRB buffer pointers and lengths:
2716          * 1. We don't want to walk off the end of this sg-list entry buffer.
2717          * 2. The transfer length that the driver requested may be smaller than
2718          *    the amount of memory allocated for this scatter-gather list.
2719          * 3. TRBs buffers can't cross 64KB boundaries.
2720          */
2721         sg = urb->sg;
2722         addr = (u64) sg_dma_address(sg);
2723         this_sg_len = sg_dma_len(sg);
2724         trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1));
2725         trb_buff_len = min_t(int, trb_buff_len, this_sg_len);
2726         if (trb_buff_len > urb->transfer_buffer_length)
2727                 trb_buff_len = urb->transfer_buffer_length;
2728         xhci_dbg(xhci, "First length to xfer from 1st sglist entry = %u\n",
2729                         trb_buff_len);
2730
2731         first_trb = true;
2732         /* Queue the first TRB, even if it's zero-length */
2733         do {
2734                 u32 field = 0;
2735                 u32 length_field = 0;
2736                 u32 remainder = 0;
2737
2738                 /* Don't change the cycle bit of the first TRB until later */
2739                 if (first_trb) {
2740                         first_trb = false;
2741                         if (start_cycle == 0)
2742                                 field |= 0x1;
2743                 } else
2744                         field |= ep_ring->cycle_state;
2745
2746                 /* Chain all the TRBs together; clear the chain bit in the last
2747                  * TRB to indicate it's the last TRB in the chain.
2748                  */
2749                 if (num_trbs > 1) {
2750                         field |= TRB_CHAIN;
2751                 } else {
2752                         /* FIXME - add check for ZERO_PACKET flag before this */
2753                         td->last_trb = ep_ring->enqueue;
2754                         field |= TRB_IOC;
2755                 }
2756
2757                 /* Only set interrupt on short packet for IN endpoints */
2758                 if (usb_urb_dir_in(urb))
2759                         field |= TRB_ISP;
2760
2761                 xhci_dbg(xhci, " sg entry: dma = %#x, len = %#x (%d), "
2762                                 "64KB boundary at %#x, end dma = %#x\n",
2763                                 (unsigned int) addr, trb_buff_len, trb_buff_len,
2764                                 (unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1),
2765                                 (unsigned int) addr + trb_buff_len);
2766                 if (TRB_MAX_BUFF_SIZE -
2767                                 (addr & (TRB_MAX_BUFF_SIZE - 1)) < trb_buff_len) {
2768                         xhci_warn(xhci, "WARN: sg dma xfer crosses 64KB boundaries!\n");
2769                         xhci_dbg(xhci, "Next boundary at %#x, end dma = %#x\n",
2770                                         (unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1),
2771                                         (unsigned int) addr + trb_buff_len);
2772                 }
2773
2774                 /* Set the TRB length, TD size, and interrupter fields. */
2775                 if (xhci->hci_version < 0x100) {
2776                         remainder = xhci_td_remainder(
2777                                         urb->transfer_buffer_length -
2778                                         running_total);
2779                 } else {
2780                         remainder = xhci_v1_0_td_remainder(running_total,
2781                                         trb_buff_len, total_packet_count, urb);
2782                 }
2783                 length_field = TRB_LEN(trb_buff_len) |
2784                         remainder |
2785                         TRB_INTR_TARGET(0);
2786
2787                 if (num_trbs > 1)
2788                         more_trbs_coming = true;
2789                 else
2790                         more_trbs_coming = false;
2791                 queue_trb(xhci, ep_ring, false, more_trbs_coming,
2792                                 lower_32_bits(addr),
2793                                 upper_32_bits(addr),
2794                                 length_field,
2795                                 field | TRB_TYPE(TRB_NORMAL));
2796                 --num_trbs;
2797                 running_total += trb_buff_len;
2798
2799                 /* Calculate length for next transfer --
2800                  * Are we done queueing all the TRBs for this sg entry?
2801                  */
2802                 this_sg_len -= trb_buff_len;
2803                 if (this_sg_len == 0) {
2804                         --num_sgs;
2805                         if (num_sgs == 0)
2806                                 break;
2807                         sg = sg_next(sg);
2808                         addr = (u64) sg_dma_address(sg);
2809                         this_sg_len = sg_dma_len(sg);
2810                 } else {
2811                         addr += trb_buff_len;
2812                 }
2813
2814                 trb_buff_len = TRB_MAX_BUFF_SIZE -
2815                         (addr & (TRB_MAX_BUFF_SIZE - 1));
2816                 trb_buff_len = min_t(int, trb_buff_len, this_sg_len);
2817                 if (running_total + trb_buff_len > urb->transfer_buffer_length)
2818                         trb_buff_len =
2819                                 urb->transfer_buffer_length - running_total;
2820         } while (running_total < urb->transfer_buffer_length);
2821
2822         check_trb_math(urb, num_trbs, running_total);
2823         giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
2824                         start_cycle, start_trb);
2825         return 0;
2826 }
2827
2828 /* This is very similar to what ehci-q.c qtd_fill() does */
2829 int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
2830                 struct urb *urb, int slot_id, unsigned int ep_index)
2831 {
2832         struct xhci_ring *ep_ring;
2833         struct urb_priv *urb_priv;
2834         struct xhci_td *td;
2835         int num_trbs;
2836         struct xhci_generic_trb *start_trb;
2837         bool first_trb;
2838         bool more_trbs_coming;
2839         int start_cycle;
2840         u32 field, length_field;
2841
2842         int running_total, trb_buff_len, ret;
2843         unsigned int total_packet_count;
2844         u64 addr;
2845
2846         if (urb->num_sgs)
2847                 return queue_bulk_sg_tx(xhci, mem_flags, urb, slot_id, ep_index);
2848
2849         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
2850         if (!ep_ring)
2851                 return -EINVAL;
2852
2853         num_trbs = 0;
2854         /* How much data is (potentially) left before the 64KB boundary? */
2855         running_total = TRB_MAX_BUFF_SIZE -
2856                 (urb->transfer_dma & (TRB_MAX_BUFF_SIZE - 1));
2857         running_total &= TRB_MAX_BUFF_SIZE - 1;
2858
2859         /* If there's some data on this 64KB chunk, or we have to send a
2860          * zero-length transfer, we need at least one TRB
2861          */
2862         if (running_total != 0 || urb->transfer_buffer_length == 0)
2863                 num_trbs++;
2864         /* How many more 64KB chunks to transfer, how many more TRBs? */
2865         while (running_total < urb->transfer_buffer_length) {
2866                 num_trbs++;
2867                 running_total += TRB_MAX_BUFF_SIZE;
2868         }
2869         /* FIXME: this doesn't deal with URB_ZERO_PACKET - need one more */
2870
2871         if (!in_interrupt())
2872                 xhci_dbg(xhci, "ep %#x - urb len = %#x (%d), "
2873                                 "addr = %#llx, num_trbs = %d\n",
2874                                 urb->ep->desc.bEndpointAddress,
2875                                 urb->transfer_buffer_length,
2876                                 urb->transfer_buffer_length,
2877                                 (unsigned long long)urb->transfer_dma,
2878                                 num_trbs);
2879
2880         ret = prepare_transfer(xhci, xhci->devs[slot_id],
2881                         ep_index, urb->stream_id,
2882                         num_trbs, urb, 0, mem_flags);
2883         if (ret < 0)
2884                 return ret;
2885
2886         urb_priv = urb->hcpriv;
2887         td = urb_priv->td[0];
2888
2889         /*
2890          * Don't give the first TRB to the hardware (by toggling the cycle bit)
2891          * until we've finished creating all the other TRBs.  The ring's cycle
2892          * state may change as we enqueue the other TRBs, so save it too.
2893          */
2894         start_trb = &ep_ring->enqueue->generic;
2895         start_cycle = ep_ring->cycle_state;
2896
2897         running_total = 0;
2898         total_packet_count = roundup(urb->transfer_buffer_length,
2899                         le16_to_cpu(urb->ep->desc.wMaxPacketSize));
2900         /* How much data is in the first TRB? */
2901         addr = (u64) urb->transfer_dma;
2902         trb_buff_len = TRB_MAX_BUFF_SIZE -
2903                 (urb->transfer_dma & (TRB_MAX_BUFF_SIZE - 1));
2904         if (trb_buff_len > urb->transfer_buffer_length)
2905                 trb_buff_len = urb->transfer_buffer_length;
2906
2907         first_trb = true;
2908
2909         /* Queue the first TRB, even if it's zero-length */
2910         do {
2911                 u32 remainder = 0;
2912                 field = 0;
2913
2914                 /* Don't change the cycle bit of the first TRB until later */
2915                 if (first_trb) {
2916                         first_trb = false;
2917                         if (start_cycle == 0)
2918                                 field |= 0x1;
2919                 } else
2920                         field |= ep_ring->cycle_state;
2921
2922                 /* Chain all the TRBs together; clear the chain bit in the last
2923                  * TRB to indicate it's the last TRB in the chain.
2924                  */
2925                 if (num_trbs > 1) {
2926                         field |= TRB_CHAIN;
2927                 } else {
2928                         /* FIXME - add check for ZERO_PACKET flag before this */
2929                         td->last_trb = ep_ring->enqueue;
2930                         field |= TRB_IOC;
2931                 }
2932
2933                 /* Only set interrupt on short packet for IN endpoints */
2934                 if (usb_urb_dir_in(urb))
2935                         field |= TRB_ISP;
2936
2937                 /* Set the TRB length, TD size, and interrupter fields. */
2938                 if (xhci->hci_version < 0x100) {
2939                         remainder = xhci_td_remainder(
2940                                         urb->transfer_buffer_length -
2941                                         running_total);
2942                 } else {
2943                         remainder = xhci_v1_0_td_remainder(running_total,
2944                                         trb_buff_len, total_packet_count, urb);
2945                 }
2946                 length_field = TRB_LEN(trb_buff_len) |
2947                         remainder |
2948                         TRB_INTR_TARGET(0);
2949
2950                 if (num_trbs > 1)
2951                         more_trbs_coming = true;
2952                 else
2953                         more_trbs_coming = false;
2954                 queue_trb(xhci, ep_ring, false, more_trbs_coming,
2955                                 lower_32_bits(addr),
2956                                 upper_32_bits(addr),
2957                                 length_field,
2958                                 field | TRB_TYPE(TRB_NORMAL));
2959                 --num_trbs;
2960                 running_total += trb_buff_len;
2961
2962                 /* Calculate length for next transfer */
2963                 addr += trb_buff_len;
2964                 trb_buff_len = urb->transfer_buffer_length - running_total;
2965                 if (trb_buff_len > TRB_MAX_BUFF_SIZE)
2966                         trb_buff_len = TRB_MAX_BUFF_SIZE;
2967         } while (running_total < urb->transfer_buffer_length);
2968
2969         check_trb_math(urb, num_trbs, running_total);
2970         giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
2971                         start_cycle, start_trb);
2972         return 0;
2973 }
2974
2975 /* Caller must have locked xhci->lock */
2976 int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
2977                 struct urb *urb, int slot_id, unsigned int ep_index)
2978 {
2979         struct xhci_ring *ep_ring;
2980         int num_trbs;
2981         int ret;
2982         struct usb_ctrlrequest *setup;
2983         struct xhci_generic_trb *start_trb;
2984         int start_cycle;
2985         u32 field, length_field;
2986         struct urb_priv *urb_priv;
2987         struct xhci_td *td;
2988
2989         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
2990         if (!ep_ring)
2991                 return -EINVAL;
2992
2993         /*
2994          * Need to copy setup packet into setup TRB, so we can't use the setup
2995          * DMA address.
2996          */
2997         if (!urb->setup_packet)
2998                 return -EINVAL;
2999
3000         if (!in_interrupt())
3001                 xhci_dbg(xhci, "Queueing ctrl tx for slot id %d, ep %d\n",
3002                                 slot_id, ep_index);
3003         /* 1 TRB for setup, 1 for status */
3004         num_trbs = 2;
3005         /*
3006          * Don't need to check if we need additional event data and normal TRBs,
3007          * since data in control transfers will never get bigger than 16MB
3008          * XXX: can we get a buffer that crosses 64KB boundaries?
3009          */
3010         if (urb->transfer_buffer_length > 0)
3011                 num_trbs++;
3012         ret = prepare_transfer(xhci, xhci->devs[slot_id],
3013                         ep_index, urb->stream_id,
3014                         num_trbs, urb, 0, mem_flags);
3015         if (ret < 0)
3016                 return ret;
3017
3018         urb_priv = urb->hcpriv;
3019         td = urb_priv->td[0];
3020
3021         /*
3022          * Don't give the first TRB to the hardware (by toggling the cycle bit)
3023          * until we've finished creating all the other TRBs.  The ring's cycle
3024          * state may change as we enqueue the other TRBs, so save it too.
3025          */
3026         start_trb = &ep_ring->enqueue->generic;
3027         start_cycle = ep_ring->cycle_state;
3028
3029         /* Queue setup TRB - see section 6.4.1.2.1 */
3030         /* FIXME better way to translate setup_packet into two u32 fields? */
3031         setup = (struct usb_ctrlrequest *) urb->setup_packet;
3032         field = 0;
3033         field |= TRB_IDT | TRB_TYPE(TRB_SETUP);
3034         if (start_cycle == 0)
3035                 field |= 0x1;
3036
3037         /* xHCI 1.0 6.4.1.2.1: Transfer Type field */
3038         if (xhci->hci_version == 0x100) {
3039                 if (urb->transfer_buffer_length > 0) {
3040                         if (setup->bRequestType & USB_DIR_IN)
3041                                 field |= TRB_TX_TYPE(TRB_DATA_IN);
3042                         else
3043                                 field |= TRB_TX_TYPE(TRB_DATA_OUT);
3044                 }
3045         }
3046
3047         queue_trb(xhci, ep_ring, false, true,
3048                   setup->bRequestType | setup->bRequest << 8 | le16_to_cpu(setup->wValue) << 16,
3049                   le16_to_cpu(setup->wIndex) | le16_to_cpu(setup->wLength) << 16,
3050                   TRB_LEN(8) | TRB_INTR_TARGET(0),
3051                   /* Immediate data in pointer */
3052                   field);
3053
3054         /* If there's data, queue data TRBs */
3055         /* Only set interrupt on short packet for IN endpoints */
3056         if (usb_urb_dir_in(urb))
3057                 field = TRB_ISP | TRB_TYPE(TRB_DATA);
3058         else
3059                 field = TRB_TYPE(TRB_DATA);
3060
3061         length_field = TRB_LEN(urb->transfer_buffer_length) |
3062                 xhci_td_remainder(urb->transfer_buffer_length) |
3063                 TRB_INTR_TARGET(0);
3064         if (urb->transfer_buffer_length > 0) {
3065                 if (setup->bRequestType & USB_DIR_IN)
3066                         field |= TRB_DIR_IN;
3067                 queue_trb(xhci, ep_ring, false, true,
3068                                 lower_32_bits(urb->transfer_dma),
3069                                 upper_32_bits(urb->transfer_dma),
3070                                 length_field,
3071                                 field | ep_ring->cycle_state);
3072         }
3073
3074         /* Save the DMA address of the last TRB in the TD */
3075         td->last_trb = ep_ring->enqueue;
3076
3077         /* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */
3078         /* If the device sent data, the status stage is an OUT transfer */
3079         if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN)
3080                 field = 0;
3081         else
3082                 field = TRB_DIR_IN;
3083         queue_trb(xhci, ep_ring, false, false,
3084                         0,
3085                         0,
3086                         TRB_INTR_TARGET(0),
3087                         /* Event on completion */
3088                         field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state);
3089
3090         giveback_first_trb(xhci, slot_id, ep_index, 0,
3091                         start_cycle, start_trb);
3092         return 0;
3093 }
3094
3095 static int count_isoc_trbs_needed(struct xhci_hcd *xhci,
3096                 struct urb *urb, int i)
3097 {
3098         int num_trbs = 0;
3099         u64 addr, td_len, running_total;
3100
3101         addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset);
3102         td_len = urb->iso_frame_desc[i].length;
3103
3104         running_total = TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1));
3105         running_total &= TRB_MAX_BUFF_SIZE - 1;
3106         if (running_total != 0)
3107                 num_trbs++;
3108
3109         while (running_total < td_len) {
3110                 num_trbs++;
3111                 running_total += TRB_MAX_BUFF_SIZE;
3112         }
3113
3114         return num_trbs;
3115 }
3116
3117 /*
3118  * The transfer burst count field of the isochronous TRB defines the number of
3119  * bursts that are required to move all packets in this TD.  Only SuperSpeed
3120  * devices can burst up to bMaxBurst number of packets per service interval.
3121  * This field is zero based, meaning a value of zero in the field means one
3122  * burst.  Basically, for everything but SuperSpeed devices, this field will be
3123  * zero.  Only xHCI 1.0 host controllers support this field.
3124  */
3125 static unsigned int xhci_get_burst_count(struct xhci_hcd *xhci,
3126                 struct usb_device *udev,
3127                 struct urb *urb, unsigned int total_packet_count)
3128 {
3129         unsigned int max_burst;
3130
3131         if (xhci->hci_version < 0x100 || udev->speed != USB_SPEED_SUPER)
3132                 return 0;
3133
3134         max_burst = urb->ep->ss_ep_comp.bMaxBurst;
3135         return roundup(total_packet_count, max_burst + 1) - 1;
3136 }
3137
3138 /*
3139  * Returns the number of packets in the last "burst" of packets.  This field is
3140  * valid for all speeds of devices.  USB 2.0 devices can only do one "burst", so
3141  * the last burst packet count is equal to the total number of packets in the
3142  * TD.  SuperSpeed endpoints can have up to 3 bursts.  All but the last burst
3143  * must contain (bMaxBurst + 1) number of packets, but the last burst can
3144  * contain 1 to (bMaxBurst + 1) packets.
3145  */
3146 static unsigned int xhci_get_last_burst_packet_count(struct xhci_hcd *xhci,
3147                 struct usb_device *udev,
3148                 struct urb *urb, unsigned int total_packet_count)
3149 {
3150         unsigned int max_burst;
3151         unsigned int residue;
3152
3153         if (xhci->hci_version < 0x100)
3154                 return 0;
3155
3156         switch (udev->speed) {
3157         case USB_SPEED_SUPER:
3158                 /* bMaxBurst is zero based: 0 means 1 packet per burst */
3159                 max_burst = urb->ep->ss_ep_comp.bMaxBurst;
3160                 residue = total_packet_count % (max_burst + 1);
3161                 /* If residue is zero, the last burst contains (max_burst + 1)
3162                  * number of packets, but the TLBPC field is zero-based.
3163                  */
3164                 if (residue == 0)
3165                         return max_burst;
3166                 return residue - 1;
3167         default:
3168                 if (total_packet_count == 0)
3169                         return 0;
3170                 return total_packet_count - 1;
3171         }
3172 }
3173
3174 /* This is for isoc transfer */
3175 static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3176                 struct urb *urb, int slot_id, unsigned int ep_index)
3177 {
3178         struct xhci_ring *ep_ring;
3179         struct urb_priv *urb_priv;
3180         struct xhci_td *td;
3181         int num_tds, trbs_per_td;
3182         struct xhci_generic_trb *start_trb;
3183         bool first_trb;
3184         int start_cycle;
3185         u32 field, length_field;
3186         int running_total, trb_buff_len, td_len, td_remain_len, ret;
3187         u64 start_addr, addr;
3188         int i, j;
3189         bool more_trbs_coming;
3190
3191         ep_ring = xhci->devs[slot_id]->eps[ep_index].ring;
3192
3193         num_tds = urb->number_of_packets;
3194         if (num_tds < 1) {
3195                 xhci_dbg(xhci, "Isoc URB with zero packets?\n");
3196                 return -EINVAL;
3197         }
3198
3199         if (!in_interrupt())
3200                 xhci_dbg(xhci, "ep %#x - urb len = %#x (%d),"
3201                                 " addr = %#llx, num_tds = %d\n",
3202                                 urb->ep->desc.bEndpointAddress,
3203                                 urb->transfer_buffer_length,
3204                                 urb->transfer_buffer_length,
3205                                 (unsigned long long)urb->transfer_dma,
3206                                 num_tds);
3207
3208         start_addr = (u64) urb->transfer_dma;
3209         start_trb = &ep_ring->enqueue->generic;
3210         start_cycle = ep_ring->cycle_state;
3211
3212         /* Queue the first TRB, even if it's zero-length */
3213         for (i = 0; i < num_tds; i++) {
3214                 unsigned int total_packet_count;
3215                 unsigned int burst_count;
3216                 unsigned int residue;
3217
3218                 first_trb = true;
3219                 running_total = 0;
3220                 addr = start_addr + urb->iso_frame_desc[i].offset;
3221                 td_len = urb->iso_frame_desc[i].length;
3222                 td_remain_len = td_len;
3223                 /* FIXME: Ignoring zero-length packets, can those happen? */
3224                 total_packet_count = roundup(td_len,
3225                                 le16_to_cpu(urb->ep->desc.wMaxPacketSize));
3226                 burst_count = xhci_get_burst_count(xhci, urb->dev, urb,
3227                                 total_packet_count);
3228                 residue = xhci_get_last_burst_packet_count(xhci,
3229                                 urb->dev, urb, total_packet_count);
3230
3231                 trbs_per_td = count_isoc_trbs_needed(xhci, urb, i);
3232
3233                 ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index,
3234                                 urb->stream_id, trbs_per_td, urb, i, mem_flags);
3235                 if (ret < 0)
3236                         return ret;
3237
3238                 urb_priv = urb->hcpriv;
3239                 td = urb_priv->td[i];
3240
3241                 for (j = 0; j < trbs_per_td; j++) {
3242                         u32 remainder = 0;
3243                         field = TRB_TBC(burst_count) | TRB_TLBPC(residue);
3244
3245                         if (first_trb) {
3246                                 /* Queue the isoc TRB */
3247                                 field |= TRB_TYPE(TRB_ISOC);
3248                                 /* Assume URB_ISO_ASAP is set */
3249                                 field |= TRB_SIA;
3250                                 if (i == 0) {
3251                                         if (start_cycle == 0)
3252                                                 field |= 0x1;
3253                                 } else
3254                                         field |= ep_ring->cycle_state;
3255                                 first_trb = false;
3256                         } else {
3257                                 /* Queue other normal TRBs */
3258                                 field |= TRB_TYPE(TRB_NORMAL);
3259                                 field |= ep_ring->cycle_state;
3260                         }
3261
3262                         /* Only set interrupt on short packet for IN EPs */
3263                         if (usb_urb_dir_in(urb))
3264                                 field |= TRB_ISP;
3265
3266                         /* Chain all the TRBs together; clear the chain bit in
3267                          * the last TRB to indicate it's the last TRB in the
3268                          * chain.
3269                          */
3270                         if (j < trbs_per_td - 1) {
3271                                 field |= TRB_CHAIN;
3272                                 more_trbs_coming = true;
3273                         } else {
3274                                 td->last_trb = ep_ring->enqueue;
3275                                 field |= TRB_IOC;
3276                                 if (xhci->hci_version == 0x100) {
3277                                         /* Set BEI bit except for the last td */
3278                                         if (i < num_tds - 1)
3279                                                 field |= TRB_BEI;
3280                                 }
3281                                 more_trbs_coming = false;
3282                         }
3283
3284                         /* Calculate TRB length */
3285                         trb_buff_len = TRB_MAX_BUFF_SIZE -
3286                                 (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
3287                         if (trb_buff_len > td_remain_len)
3288                                 trb_buff_len = td_remain_len;
3289
3290                         /* Set the TRB length, TD size, & interrupter fields. */
3291                         if (xhci->hci_version < 0x100) {
3292                                 remainder = xhci_td_remainder(
3293                                                 td_len - running_total);
3294                         } else {
3295                                 remainder = xhci_v1_0_td_remainder(
3296                                                 running_total, trb_buff_len,
3297                                                 total_packet_count, urb);
3298                         }
3299                         length_field = TRB_LEN(trb_buff_len) |
3300                                 remainder |
3301                                 TRB_INTR_TARGET(0);
3302
3303                         queue_trb(xhci, ep_ring, false, more_trbs_coming,
3304                                 lower_32_bits(addr),
3305                                 upper_32_bits(addr),
3306                                 length_field,
3307                                 field);
3308                         running_total += trb_buff_len;
3309
3310                         addr += trb_buff_len;
3311                         td_remain_len -= trb_buff_len;
3312                 }
3313
3314                 /* Check TD length */
3315                 if (running_total != td_len) {
3316                         xhci_err(xhci, "ISOC TD length unmatch\n");
3317                         return -EINVAL;
3318                 }
3319         }
3320
3321         if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) {
3322                 if (xhci->quirks & XHCI_AMD_PLL_FIX)
3323                         usb_amd_quirk_pll_disable();
3324         }
3325         xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs++;
3326
3327         giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
3328                         start_cycle, start_trb);
3329         return 0;
3330 }
3331
3332 /*
3333  * Check transfer ring to guarantee there is enough room for the urb.
3334  * Update ISO URB start_frame and interval.
3335  * Update interval as xhci_queue_intr_tx does. Just use xhci frame_index to
3336  * update the urb->start_frame by now.
3337  * Always assume URB_ISO_ASAP set, and NEVER use urb->start_frame as input.
3338  */
3339 int xhci_queue_isoc_tx_prepare(struct xhci_hcd *xhci, gfp_t mem_flags,
3340                 struct urb *urb, int slot_id, unsigned int ep_index)
3341 {
3342         struct xhci_virt_device *xdev;
3343         struct xhci_ring *ep_ring;
3344         struct xhci_ep_ctx *ep_ctx;
3345         int start_frame;
3346         int xhci_interval;
3347         int ep_interval;
3348         int num_tds, num_trbs, i;
3349         int ret;
3350
3351         xdev = xhci->devs[slot_id];
3352         ep_ring = xdev->eps[ep_index].ring;
3353         ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
3354
3355         num_trbs = 0;
3356         num_tds = urb->number_of_packets;
3357         for (i = 0; i < num_tds; i++)
3358                 num_trbs += count_isoc_trbs_needed(xhci, urb, i);
3359
3360         /* Check the ring to guarantee there is enough room for the whole urb.
3361          * Do not insert any td of the urb to the ring if the check failed.
3362          */
3363         ret = prepare_ring(xhci, ep_ring, le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK,
3364                            num_trbs, mem_flags);
3365         if (ret)
3366                 return ret;
3367
3368         start_frame = xhci_readl(xhci, &xhci->run_regs->microframe_index);
3369         start_frame &= 0x3fff;
3370
3371         urb->start_frame = start_frame;
3372         if (urb->dev->speed == USB_SPEED_LOW ||
3373                         urb->dev->speed == USB_SPEED_FULL)
3374                 urb->start_frame >>= 3;
3375
3376         xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info));
3377         ep_interval = urb->interval;
3378         /* Convert to microframes */
3379         if (urb->dev->speed == USB_SPEED_LOW ||
3380                         urb->dev->speed == USB_SPEED_FULL)
3381                 ep_interval *= 8;
3382         /* FIXME change this to a warning and a suggestion to use the new API
3383          * to set the polling interval (once the API is added).
3384          */
3385         if (xhci_interval != ep_interval) {
3386                 if (printk_ratelimit())
3387                         dev_dbg(&urb->dev->dev, "Driver uses different interval"
3388                                         " (%d microframe%s) than xHCI "
3389                                         "(%d microframe%s)\n",
3390                                         ep_interval,
3391                                         ep_interval == 1 ? "" : "s",
3392                                         xhci_interval,
3393                                         xhci_interval == 1 ? "" : "s");
3394                 urb->interval = xhci_interval;
3395                 /* Convert back to frames for LS/FS devices */
3396                 if (urb->dev->speed == USB_SPEED_LOW ||
3397                                 urb->dev->speed == USB_SPEED_FULL)
3398                         urb->interval /= 8;
3399         }
3400         return xhci_queue_isoc_tx(xhci, GFP_ATOMIC, urb, slot_id, ep_index);
3401 }
3402
3403 /****           Command Ring Operations         ****/
3404
3405 /* Generic function for queueing a command TRB on the command ring.
3406  * Check to make sure there's room on the command ring for one command TRB.
3407  * Also check that there's room reserved for commands that must not fail.
3408  * If this is a command that must not fail, meaning command_must_succeed = TRUE,
3409  * then only check for the number of reserved spots.
3410  * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB
3411  * because the command event handler may want to resubmit a failed command.
3412  */
3413 static int queue_command(struct xhci_hcd *xhci, u32 field1, u32 field2,
3414                 u32 field3, u32 field4, bool command_must_succeed)
3415 {
3416         int reserved_trbs = xhci->cmd_ring_reserved_trbs;
3417         int ret;
3418
3419         if (!command_must_succeed)
3420                 reserved_trbs++;
3421
3422         ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING,
3423                         reserved_trbs, GFP_ATOMIC);
3424         if (ret < 0) {
3425                 xhci_err(xhci, "ERR: No room for command on command ring\n");
3426                 if (command_must_succeed)
3427                         xhci_err(xhci, "ERR: Reserved TRB counting for "
3428                                         "unfailable commands failed.\n");
3429                 return ret;
3430         }
3431         queue_trb(xhci, xhci->cmd_ring, false, false, field1, field2, field3,
3432                         field4 | xhci->cmd_ring->cycle_state);
3433         return 0;
3434 }
3435
3436 /* Queue a slot enable or disable request on the command ring */
3437 int xhci_queue_slot_control(struct xhci_hcd *xhci, u32 trb_type, u32 slot_id)
3438 {
3439         return queue_command(xhci, 0, 0, 0,
3440                         TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false);
3441 }
3442
3443 /* Queue an address device command TRB */
3444 int xhci_queue_address_device(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
3445                 u32 slot_id)
3446 {
3447         return queue_command(xhci, lower_32_bits(in_ctx_ptr),
3448                         upper_32_bits(in_ctx_ptr), 0,
3449                         TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id),
3450                         false);
3451 }
3452
3453 int xhci_queue_vendor_command(struct xhci_hcd *xhci,
3454                 u32 field1, u32 field2, u32 field3, u32 field4)
3455 {
3456         return queue_command(xhci, field1, field2, field3, field4, false);
3457 }
3458
3459 /* Queue a reset device command TRB */
3460 int xhci_queue_reset_device(struct xhci_hcd *xhci, u32 slot_id)
3461 {
3462         return queue_command(xhci, 0, 0, 0,
3463                         TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id),
3464                         false);
3465 }
3466
3467 /* Queue a configure endpoint command TRB */
3468 int xhci_queue_configure_endpoint(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
3469                 u32 slot_id, bool command_must_succeed)
3470 {
3471         return queue_command(xhci, lower_32_bits(in_ctx_ptr),
3472                         upper_32_bits(in_ctx_ptr), 0,
3473                         TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id),
3474                         command_must_succeed);
3475 }
3476
3477 /* Queue an evaluate context command TRB */
3478 int xhci_queue_evaluate_context(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
3479                 u32 slot_id)
3480 {
3481         return queue_command(xhci, lower_32_bits(in_ctx_ptr),
3482                         upper_32_bits(in_ctx_ptr), 0,
3483                         TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id),
3484                         false);
3485 }
3486
3487 /*
3488  * Suspend is set to indicate "Stop Endpoint Command" is being issued to stop
3489  * activity on an endpoint that is about to be suspended.
3490  */
3491 int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, int slot_id,
3492                 unsigned int ep_index, int suspend)
3493 {
3494         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
3495         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
3496         u32 type = TRB_TYPE(TRB_STOP_RING);
3497         u32 trb_suspend = SUSPEND_PORT_FOR_TRB(suspend);
3498
3499         return queue_command(xhci, 0, 0, 0,
3500                         trb_slot_id | trb_ep_index | type | trb_suspend, false);
3501 }
3502
3503 /* Set Transfer Ring Dequeue Pointer command.
3504  * This should not be used for endpoints that have streams enabled.
3505  */
3506 static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id,
3507                 unsigned int ep_index, unsigned int stream_id,
3508                 struct xhci_segment *deq_seg,
3509                 union xhci_trb *deq_ptr, u32 cycle_state)
3510 {
3511         dma_addr_t addr;
3512         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
3513         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
3514         u32 trb_stream_id = STREAM_ID_FOR_TRB(stream_id);
3515         u32 type = TRB_TYPE(TRB_SET_DEQ);
3516         struct xhci_virt_ep *ep;
3517
3518         addr = xhci_trb_virt_to_dma(deq_seg, deq_ptr);
3519         if (addr == 0) {
3520                 xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n");
3521                 xhci_warn(xhci, "WARN deq seg = %p, deq pt = %p\n",
3522                                 deq_seg, deq_ptr);
3523                 return 0;
3524         }
3525         ep = &xhci->devs[slot_id]->eps[ep_index];
3526         if ((ep->ep_state & SET_DEQ_PENDING)) {
3527                 xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n");
3528                 xhci_warn(xhci, "A Set TR Deq Ptr command is pending.\n");
3529                 return 0;
3530         }
3531         ep->queued_deq_seg = deq_seg;
3532         ep->queued_deq_ptr = deq_ptr;
3533         return queue_command(xhci, lower_32_bits(addr) | cycle_state,
3534                         upper_32_bits(addr), trb_stream_id,
3535                         trb_slot_id | trb_ep_index | type, false);
3536 }
3537
3538 int xhci_queue_reset_ep(struct xhci_hcd *xhci, int slot_id,
3539                 unsigned int ep_index)
3540 {
3541         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
3542         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
3543         u32 type = TRB_TYPE(TRB_RESET_EP);
3544
3545         return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type,
3546                         false);
3547 }