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