USB: xhci: Set stream ID to 0 after cleaning up stalls.
[linux-drm-fsl-dcu.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 /* Updates trb to point to the next TRB in the ring, and updates seg if the next
116  * TRB is in a new segment.  This does not skip over link TRBs, and it does not
117  * effect the ring dequeue or enqueue pointers.
118  */
119 static void next_trb(struct xhci_hcd *xhci,
120                 struct xhci_ring *ring,
121                 struct xhci_segment **seg,
122                 union xhci_trb **trb)
123 {
124         if (last_trb(xhci, ring, *seg, *trb)) {
125                 *seg = (*seg)->next;
126                 *trb = ((*seg)->trbs);
127         } else {
128                 *trb = (*trb)++;
129         }
130 }
131
132 /*
133  * See Cycle bit rules. SW is the consumer for the event ring only.
134  * Don't make a ring full of link TRBs.  That would be dumb and this would loop.
135  */
136 static void inc_deq(struct xhci_hcd *xhci, struct xhci_ring *ring, bool consumer)
137 {
138         union xhci_trb *next = ++(ring->dequeue);
139         unsigned long long addr;
140
141         ring->deq_updates++;
142         /* Update the dequeue pointer further if that was a link TRB or we're at
143          * the end of an event ring segment (which doesn't have link TRBS)
144          */
145         while (last_trb(xhci, ring, ring->deq_seg, next)) {
146                 if (consumer && last_trb_on_last_seg(xhci, ring, ring->deq_seg, next)) {
147                         ring->cycle_state = (ring->cycle_state ? 0 : 1);
148                         if (!in_interrupt())
149                                 xhci_dbg(xhci, "Toggle cycle state for ring %p = %i\n",
150                                                 ring,
151                                                 (unsigned int) ring->cycle_state);
152                 }
153                 ring->deq_seg = ring->deq_seg->next;
154                 ring->dequeue = ring->deq_seg->trbs;
155                 next = ring->dequeue;
156         }
157         addr = (unsigned long long) xhci_trb_virt_to_dma(ring->deq_seg, ring->dequeue);
158         if (ring == xhci->event_ring)
159                 xhci_dbg(xhci, "Event ring deq = 0x%llx (DMA)\n", addr);
160         else if (ring == xhci->cmd_ring)
161                 xhci_dbg(xhci, "Command ring deq = 0x%llx (DMA)\n", addr);
162         else
163                 xhci_dbg(xhci, "Ring deq = 0x%llx (DMA)\n", addr);
164 }
165
166 /*
167  * See Cycle bit rules. SW is the consumer for the event ring only.
168  * Don't make a ring full of link TRBs.  That would be dumb and this would loop.
169  *
170  * If we've just enqueued a TRB that is in the middle of a TD (meaning the
171  * chain bit is set), then set the chain bit in all the following link TRBs.
172  * If we've enqueued the last TRB in a TD, make sure the following link TRBs
173  * have their chain bit cleared (so that each Link TRB is a separate TD).
174  *
175  * Section 6.4.4.1 of the 0.95 spec says link TRBs cannot have the chain bit
176  * set, but other sections talk about dealing with the chain bit set.  This was
177  * fixed in the 0.96 specification errata, but we have to assume that all 0.95
178  * xHCI hardware can't handle the chain bit being cleared on a link TRB.
179  */
180 static void inc_enq(struct xhci_hcd *xhci, struct xhci_ring *ring, bool consumer)
181 {
182         u32 chain;
183         union xhci_trb *next;
184         unsigned long long addr;
185
186         chain = ring->enqueue->generic.field[3] & TRB_CHAIN;
187         next = ++(ring->enqueue);
188
189         ring->enq_updates++;
190         /* Update the dequeue pointer further if that was a link TRB or we're at
191          * the end of an event ring segment (which doesn't have link TRBS)
192          */
193         while (last_trb(xhci, ring, ring->enq_seg, next)) {
194                 if (!consumer) {
195                         if (ring != xhci->event_ring) {
196                                 /* If we're not dealing with 0.95 hardware,
197                                  * carry over the chain bit of the previous TRB
198                                  * (which may mean the chain bit is cleared).
199                                  */
200                                 if (!xhci_link_trb_quirk(xhci)) {
201                                         next->link.control &= ~TRB_CHAIN;
202                                         next->link.control |= chain;
203                                 }
204                                 /* Give this link TRB to the hardware */
205                                 wmb();
206                                 if (next->link.control & TRB_CYCLE)
207                                         next->link.control &= (u32) ~TRB_CYCLE;
208                                 else
209                                         next->link.control |= (u32) TRB_CYCLE;
210                         }
211                         /* Toggle the cycle bit after the last ring segment. */
212                         if (last_trb_on_last_seg(xhci, ring, ring->enq_seg, next)) {
213                                 ring->cycle_state = (ring->cycle_state ? 0 : 1);
214                                 if (!in_interrupt())
215                                         xhci_dbg(xhci, "Toggle cycle state for ring %p = %i\n",
216                                                         ring,
217                                                         (unsigned int) ring->cycle_state);
218                         }
219                 }
220                 ring->enq_seg = ring->enq_seg->next;
221                 ring->enqueue = ring->enq_seg->trbs;
222                 next = ring->enqueue;
223         }
224         addr = (unsigned long long) xhci_trb_virt_to_dma(ring->enq_seg, ring->enqueue);
225         if (ring == xhci->event_ring)
226                 xhci_dbg(xhci, "Event ring enq = 0x%llx (DMA)\n", addr);
227         else if (ring == xhci->cmd_ring)
228                 xhci_dbg(xhci, "Command ring enq = 0x%llx (DMA)\n", addr);
229         else
230                 xhci_dbg(xhci, "Ring enq = 0x%llx (DMA)\n", addr);
231 }
232
233 /*
234  * Check to see if there's room to enqueue num_trbs on the ring.  See rules
235  * above.
236  * FIXME: this would be simpler and faster if we just kept track of the number
237  * of free TRBs in a ring.
238  */
239 static int room_on_ring(struct xhci_hcd *xhci, struct xhci_ring *ring,
240                 unsigned int num_trbs)
241 {
242         int i;
243         union xhci_trb *enq = ring->enqueue;
244         struct xhci_segment *enq_seg = ring->enq_seg;
245         struct xhci_segment *cur_seg;
246         unsigned int left_on_ring;
247
248         /* Check if ring is empty */
249         if (enq == ring->dequeue) {
250                 /* Can't use link trbs */
251                 left_on_ring = TRBS_PER_SEGMENT - 1;
252                 for (cur_seg = enq_seg->next; cur_seg != enq_seg;
253                                 cur_seg = cur_seg->next)
254                         left_on_ring += TRBS_PER_SEGMENT - 1;
255
256                 /* Always need one TRB free in the ring. */
257                 left_on_ring -= 1;
258                 if (num_trbs > left_on_ring) {
259                         xhci_warn(xhci, "Not enough room on ring; "
260                                         "need %u TRBs, %u TRBs left\n",
261                                         num_trbs, left_on_ring);
262                         return 0;
263                 }
264                 return 1;
265         }
266         /* Make sure there's an extra empty TRB available */
267         for (i = 0; i <= num_trbs; ++i) {
268                 if (enq == ring->dequeue)
269                         return 0;
270                 enq++;
271                 while (last_trb(xhci, ring, enq_seg, enq)) {
272                         enq_seg = enq_seg->next;
273                         enq = enq_seg->trbs;
274                 }
275         }
276         return 1;
277 }
278
279 void xhci_set_hc_event_deq(struct xhci_hcd *xhci)
280 {
281         u64 temp;
282         dma_addr_t deq;
283
284         deq = xhci_trb_virt_to_dma(xhci->event_ring->deq_seg,
285                         xhci->event_ring->dequeue);
286         if (deq == 0 && !in_interrupt())
287                 xhci_warn(xhci, "WARN something wrong with SW event ring "
288                                 "dequeue ptr.\n");
289         /* Update HC event ring dequeue pointer */
290         temp = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
291         temp &= ERST_PTR_MASK;
292         /* Don't clear the EHB bit (which is RW1C) because
293          * there might be more events to service.
294          */
295         temp &= ~ERST_EHB;
296         xhci_dbg(xhci, "// Write event ring dequeue pointer, preserving EHB bit\n");
297         xhci_write_64(xhci, ((u64) deq & (u64) ~ERST_PTR_MASK) | temp,
298                         &xhci->ir_set->erst_dequeue);
299 }
300
301 /* Ring the host controller doorbell after placing a command on the ring */
302 void xhci_ring_cmd_db(struct xhci_hcd *xhci)
303 {
304         u32 temp;
305
306         xhci_dbg(xhci, "// Ding dong!\n");
307         temp = xhci_readl(xhci, &xhci->dba->doorbell[0]) & DB_MASK;
308         xhci_writel(xhci, temp | DB_TARGET_HOST, &xhci->dba->doorbell[0]);
309         /* Flush PCI posted writes */
310         xhci_readl(xhci, &xhci->dba->doorbell[0]);
311 }
312
313 static void ring_ep_doorbell(struct xhci_hcd *xhci,
314                 unsigned int slot_id,
315                 unsigned int ep_index,
316                 unsigned int stream_id)
317 {
318         struct xhci_virt_ep *ep;
319         unsigned int ep_state;
320         u32 field;
321         __u32 __iomem *db_addr = &xhci->dba->doorbell[slot_id];
322
323         ep = &xhci->devs[slot_id]->eps[ep_index];
324         ep_state = ep->ep_state;
325         /* Don't ring the doorbell for this endpoint if there are pending
326          * cancellations because the we don't want to interrupt processing.
327          * We don't want to restart any stream rings if there's a set dequeue
328          * pointer command pending because the device can choose to start any
329          * stream once the endpoint is on the HW schedule.
330          * FIXME - check all the stream rings for pending cancellations.
331          */
332         if (!(ep_state & EP_HALT_PENDING) && !(ep_state & SET_DEQ_PENDING)
333                         && !(ep_state & EP_HALTED)) {
334                 field = xhci_readl(xhci, db_addr) & DB_MASK;
335                 field |= EPI_TO_DB(ep_index) | STREAM_ID_TO_DB(stream_id);
336                 xhci_writel(xhci, field, db_addr);
337                 /* Flush PCI posted writes - FIXME Matthew Wilcox says this
338                  * isn't time-critical and we shouldn't make the CPU wait for
339                  * the flush.
340                  */
341                 xhci_readl(xhci, db_addr);
342         }
343 }
344
345 /* Ring the doorbell for any rings with pending URBs */
346 static void ring_doorbell_for_active_rings(struct xhci_hcd *xhci,
347                 unsigned int slot_id,
348                 unsigned int ep_index)
349 {
350         unsigned int stream_id;
351         struct xhci_virt_ep *ep;
352
353         ep = &xhci->devs[slot_id]->eps[ep_index];
354
355         /* A ring has pending URBs if its TD list is not empty */
356         if (!(ep->ep_state & EP_HAS_STREAMS)) {
357                 if (!(list_empty(&ep->ring->td_list)))
358                         ring_ep_doorbell(xhci, slot_id, ep_index, 0);
359                 return;
360         }
361
362         for (stream_id = 1; stream_id < ep->stream_info->num_streams;
363                         stream_id++) {
364                 struct xhci_stream_info *stream_info = ep->stream_info;
365                 if (!list_empty(&stream_info->stream_rings[stream_id]->td_list))
366                         ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
367         }
368 }
369
370 /*
371  * Find the segment that trb is in.  Start searching in start_seg.
372  * If we must move past a segment that has a link TRB with a toggle cycle state
373  * bit set, then we will toggle the value pointed at by cycle_state.
374  */
375 static struct xhci_segment *find_trb_seg(
376                 struct xhci_segment *start_seg,
377                 union xhci_trb  *trb, int *cycle_state)
378 {
379         struct xhci_segment *cur_seg = start_seg;
380         struct xhci_generic_trb *generic_trb;
381
382         while (cur_seg->trbs > trb ||
383                         &cur_seg->trbs[TRBS_PER_SEGMENT - 1] < trb) {
384                 generic_trb = &cur_seg->trbs[TRBS_PER_SEGMENT - 1].generic;
385                 if (TRB_TYPE(generic_trb->field[3]) == TRB_LINK &&
386                                 (generic_trb->field[3] & LINK_TOGGLE))
387                         *cycle_state = ~(*cycle_state) & 0x1;
388                 cur_seg = cur_seg->next;
389                 if (cur_seg == start_seg)
390                         /* Looped over the entire list.  Oops! */
391                         return NULL;
392         }
393         return cur_seg;
394 }
395
396 /*
397  * Move the xHC's endpoint ring dequeue pointer past cur_td.
398  * Record the new state of the xHC's endpoint ring dequeue segment,
399  * dequeue pointer, and new consumer cycle state in state.
400  * Update our internal representation of the ring's dequeue pointer.
401  *
402  * We do this in three jumps:
403  *  - First we update our new ring state to be the same as when the xHC stopped.
404  *  - Then we traverse the ring to find the segment that contains
405  *    the last TRB in the TD.  We toggle the xHC's new cycle state when we pass
406  *    any link TRBs with the toggle cycle bit set.
407  *  - Finally we move the dequeue state one TRB further, toggling the cycle bit
408  *    if we've moved it past a link TRB with the toggle cycle bit set.
409  */
410 void xhci_find_new_dequeue_state(struct xhci_hcd *xhci,
411                 unsigned int slot_id, unsigned int ep_index,
412                 unsigned int stream_id, struct xhci_td *cur_td,
413                 struct xhci_dequeue_state *state)
414 {
415         struct xhci_virt_device *dev = xhci->devs[slot_id];
416         struct xhci_ring *ep_ring;
417         struct xhci_generic_trb *trb;
418         struct xhci_ep_ctx *ep_ctx;
419         dma_addr_t addr;
420
421         ep_ring = xhci_triad_to_transfer_ring(xhci, slot_id,
422                         ep_index, stream_id);
423         if (!ep_ring) {
424                 xhci_warn(xhci, "WARN can't find new dequeue state "
425                                 "for invalid stream ID %u.\n",
426                                 stream_id);
427                 return;
428         }
429         state->new_cycle_state = 0;
430         xhci_dbg(xhci, "Finding segment containing stopped TRB.\n");
431         state->new_deq_seg = find_trb_seg(cur_td->start_seg,
432                         dev->eps[ep_index].stopped_trb,
433                         &state->new_cycle_state);
434         if (!state->new_deq_seg)
435                 BUG();
436         /* Dig out the cycle state saved by the xHC during the stop ep cmd */
437         xhci_dbg(xhci, "Finding endpoint context\n");
438         ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index);
439         state->new_cycle_state = 0x1 & ep_ctx->deq;
440
441         state->new_deq_ptr = cur_td->last_trb;
442         xhci_dbg(xhci, "Finding segment containing last TRB in TD.\n");
443         state->new_deq_seg = find_trb_seg(state->new_deq_seg,
444                         state->new_deq_ptr,
445                         &state->new_cycle_state);
446         if (!state->new_deq_seg)
447                 BUG();
448
449         trb = &state->new_deq_ptr->generic;
450         if (TRB_TYPE(trb->field[3]) == TRB_LINK &&
451                                 (trb->field[3] & LINK_TOGGLE))
452                 state->new_cycle_state = ~(state->new_cycle_state) & 0x1;
453         next_trb(xhci, ep_ring, &state->new_deq_seg, &state->new_deq_ptr);
454
455         /* Don't update the ring cycle state for the producer (us). */
456         xhci_dbg(xhci, "New dequeue segment = %p (virtual)\n",
457                         state->new_deq_seg);
458         addr = xhci_trb_virt_to_dma(state->new_deq_seg, state->new_deq_ptr);
459         xhci_dbg(xhci, "New dequeue pointer = 0x%llx (DMA)\n",
460                         (unsigned long long) addr);
461         xhci_dbg(xhci, "Setting dequeue pointer in internal ring state.\n");
462         ep_ring->dequeue = state->new_deq_ptr;
463         ep_ring->deq_seg = state->new_deq_seg;
464 }
465
466 static void td_to_noop(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
467                 struct xhci_td *cur_td)
468 {
469         struct xhci_segment *cur_seg;
470         union xhci_trb *cur_trb;
471
472         for (cur_seg = cur_td->start_seg, cur_trb = cur_td->first_trb;
473                         true;
474                         next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) {
475                 if ((cur_trb->generic.field[3] & TRB_TYPE_BITMASK) ==
476                                 TRB_TYPE(TRB_LINK)) {
477                         /* Unchain any chained Link TRBs, but
478                          * leave the pointers intact.
479                          */
480                         cur_trb->generic.field[3] &= ~TRB_CHAIN;
481                         xhci_dbg(xhci, "Cancel (unchain) link TRB\n");
482                         xhci_dbg(xhci, "Address = %p (0x%llx dma); "
483                                         "in seg %p (0x%llx dma)\n",
484                                         cur_trb,
485                                         (unsigned long long)xhci_trb_virt_to_dma(cur_seg, cur_trb),
486                                         cur_seg,
487                                         (unsigned long long)cur_seg->dma);
488                 } else {
489                         cur_trb->generic.field[0] = 0;
490                         cur_trb->generic.field[1] = 0;
491                         cur_trb->generic.field[2] = 0;
492                         /* Preserve only the cycle bit of this TRB */
493                         cur_trb->generic.field[3] &= TRB_CYCLE;
494                         cur_trb->generic.field[3] |= TRB_TYPE(TRB_TR_NOOP);
495                         xhci_dbg(xhci, "Cancel TRB %p (0x%llx dma) "
496                                         "in seg %p (0x%llx dma)\n",
497                                         cur_trb,
498                                         (unsigned long long)xhci_trb_virt_to_dma(cur_seg, cur_trb),
499                                         cur_seg,
500                                         (unsigned long long)cur_seg->dma);
501                 }
502                 if (cur_trb == cur_td->last_trb)
503                         break;
504         }
505 }
506
507 static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id,
508                 unsigned int ep_index, unsigned int stream_id,
509                 struct xhci_segment *deq_seg,
510                 union xhci_trb *deq_ptr, u32 cycle_state);
511
512 void xhci_queue_new_dequeue_state(struct xhci_hcd *xhci,
513                 unsigned int slot_id, unsigned int ep_index,
514                 unsigned int stream_id,
515                 struct xhci_dequeue_state *deq_state)
516 {
517         struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index];
518
519         xhci_dbg(xhci, "Set TR Deq Ptr cmd, new deq seg = %p (0x%llx dma), "
520                         "new deq ptr = %p (0x%llx dma), new cycle = %u\n",
521                         deq_state->new_deq_seg,
522                         (unsigned long long)deq_state->new_deq_seg->dma,
523                         deq_state->new_deq_ptr,
524                         (unsigned long long)xhci_trb_virt_to_dma(deq_state->new_deq_seg, deq_state->new_deq_ptr),
525                         deq_state->new_cycle_state);
526         queue_set_tr_deq(xhci, slot_id, ep_index, stream_id,
527                         deq_state->new_deq_seg,
528                         deq_state->new_deq_ptr,
529                         (u32) deq_state->new_cycle_state);
530         /* Stop the TD queueing code from ringing the doorbell until
531          * this command completes.  The HC won't set the dequeue pointer
532          * if the ring is running, and ringing the doorbell starts the
533          * ring running.
534          */
535         ep->ep_state |= SET_DEQ_PENDING;
536 }
537
538 static inline void xhci_stop_watchdog_timer_in_irq(struct xhci_hcd *xhci,
539                 struct xhci_virt_ep *ep)
540 {
541         ep->ep_state &= ~EP_HALT_PENDING;
542         /* Can't del_timer_sync in interrupt, so we attempt to cancel.  If the
543          * timer is running on another CPU, we don't decrement stop_cmds_pending
544          * (since we didn't successfully stop the watchdog timer).
545          */
546         if (del_timer(&ep->stop_cmd_timer))
547                 ep->stop_cmds_pending--;
548 }
549
550 /* Must be called with xhci->lock held in interrupt context */
551 static void xhci_giveback_urb_in_irq(struct xhci_hcd *xhci,
552                 struct xhci_td *cur_td, int status, char *adjective)
553 {
554         struct usb_hcd *hcd = xhci_to_hcd(xhci);
555
556         cur_td->urb->hcpriv = NULL;
557         usb_hcd_unlink_urb_from_ep(hcd, cur_td->urb);
558         xhci_dbg(xhci, "Giveback %s URB %p\n", adjective, cur_td->urb);
559
560         spin_unlock(&xhci->lock);
561         usb_hcd_giveback_urb(hcd, cur_td->urb, status);
562         kfree(cur_td);
563         spin_lock(&xhci->lock);
564         xhci_dbg(xhci, "%s URB given back\n", adjective);
565 }
566
567 /*
568  * When we get a command completion for a Stop Endpoint Command, we need to
569  * unlink any cancelled TDs from the ring.  There are two ways to do that:
570  *
571  *  1. If the HW was in the middle of processing the TD that needs to be
572  *     cancelled, then we must move the ring's dequeue pointer past the last TRB
573  *     in the TD with a Set Dequeue Pointer Command.
574  *  2. Otherwise, we turn all the TRBs in the TD into No-op TRBs (with the chain
575  *     bit cleared) so that the HW will skip over them.
576  */
577 static void handle_stopped_endpoint(struct xhci_hcd *xhci,
578                 union xhci_trb *trb)
579 {
580         unsigned int slot_id;
581         unsigned int ep_index;
582         struct xhci_ring *ep_ring;
583         struct xhci_virt_ep *ep;
584         struct list_head *entry;
585         struct xhci_td *cur_td = NULL;
586         struct xhci_td *last_unlinked_td;
587
588         struct xhci_dequeue_state deq_state;
589
590         memset(&deq_state, 0, sizeof(deq_state));
591         slot_id = TRB_TO_SLOT_ID(trb->generic.field[3]);
592         ep_index = TRB_TO_EP_INDEX(trb->generic.field[3]);
593         ep = &xhci->devs[slot_id]->eps[ep_index];
594
595         if (list_empty(&ep->cancelled_td_list)) {
596                 xhci_stop_watchdog_timer_in_irq(xhci, ep);
597                 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
598                 return;
599         }
600
601         /* Fix up the ep ring first, so HW stops executing cancelled TDs.
602          * We have the xHCI lock, so nothing can modify this list until we drop
603          * it.  We're also in the event handler, so we can't get re-interrupted
604          * if another Stop Endpoint command completes
605          */
606         list_for_each(entry, &ep->cancelled_td_list) {
607                 cur_td = list_entry(entry, struct xhci_td, cancelled_td_list);
608                 xhci_dbg(xhci, "Cancelling TD starting at %p, 0x%llx (dma).\n",
609                                 cur_td->first_trb,
610                                 (unsigned long long)xhci_trb_virt_to_dma(cur_td->start_seg, cur_td->first_trb));
611                 ep_ring = xhci_urb_to_transfer_ring(xhci, cur_td->urb);
612                 if (!ep_ring) {
613                         /* This shouldn't happen unless a driver is mucking
614                          * with the stream ID after submission.  This will
615                          * leave the TD on the hardware ring, and the hardware
616                          * will try to execute it, and may access a buffer
617                          * that has already been freed.  In the best case, the
618                          * hardware will execute it, and the event handler will
619                          * ignore the completion event for that TD, since it was
620                          * removed from the td_list for that endpoint.  In
621                          * short, don't muck with the stream ID after
622                          * submission.
623                          */
624                         xhci_warn(xhci, "WARN Cancelled URB %p "
625                                         "has invalid stream ID %u.\n",
626                                         cur_td->urb,
627                                         cur_td->urb->stream_id);
628                         goto remove_finished_td;
629                 }
630                 /*
631                  * If we stopped on the TD we need to cancel, then we have to
632                  * move the xHC endpoint ring dequeue pointer past this TD.
633                  */
634                 if (cur_td == ep->stopped_td)
635                         xhci_find_new_dequeue_state(xhci, slot_id, ep_index,
636                                         cur_td->urb->stream_id,
637                                         cur_td, &deq_state);
638                 else
639                         td_to_noop(xhci, ep_ring, cur_td);
640 remove_finished_td:
641                 /*
642                  * The event handler won't see a completion for this TD anymore,
643                  * so remove it from the endpoint ring's TD list.  Keep it in
644                  * the cancelled TD list for URB completion later.
645                  */
646                 list_del(&cur_td->td_list);
647         }
648         last_unlinked_td = cur_td;
649         xhci_stop_watchdog_timer_in_irq(xhci, ep);
650
651         /* If necessary, queue a Set Transfer Ring Dequeue Pointer command */
652         if (deq_state.new_deq_ptr && deq_state.new_deq_seg) {
653                 xhci_queue_new_dequeue_state(xhci,
654                                 slot_id, ep_index,
655                                 ep->stopped_td->urb->stream_id,
656                                 &deq_state);
657                 xhci_ring_cmd_db(xhci);
658         } else {
659                 /* Otherwise ring the doorbell(s) to restart queued transfers */
660                 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
661         }
662         ep->stopped_td = NULL;
663         ep->stopped_trb = NULL;
664
665         /*
666          * Drop the lock and complete the URBs in the cancelled TD list.
667          * New TDs to be cancelled might be added to the end of the list before
668          * we can complete all the URBs for the TDs we already unlinked.
669          * So stop when we've completed the URB for the last TD we unlinked.
670          */
671         do {
672                 cur_td = list_entry(ep->cancelled_td_list.next,
673                                 struct xhci_td, cancelled_td_list);
674                 list_del(&cur_td->cancelled_td_list);
675
676                 /* Clean up the cancelled URB */
677                 /* Doesn't matter what we pass for status, since the core will
678                  * just overwrite it (because the URB has been unlinked).
679                  */
680                 xhci_giveback_urb_in_irq(xhci, cur_td, 0, "cancelled");
681
682                 /* Stop processing the cancelled list if the watchdog timer is
683                  * running.
684                  */
685                 if (xhci->xhc_state & XHCI_STATE_DYING)
686                         return;
687         } while (cur_td != last_unlinked_td);
688
689         /* Return to the event handler with xhci->lock re-acquired */
690 }
691
692 /* Watchdog timer function for when a stop endpoint command fails to complete.
693  * In this case, we assume the host controller is broken or dying or dead.  The
694  * host may still be completing some other events, so we have to be careful to
695  * let the event ring handler and the URB dequeueing/enqueueing functions know
696  * through xhci->state.
697  *
698  * The timer may also fire if the host takes a very long time to respond to the
699  * command, and the stop endpoint command completion handler cannot delete the
700  * timer before the timer function is called.  Another endpoint cancellation may
701  * sneak in before the timer function can grab the lock, and that may queue
702  * another stop endpoint command and add the timer back.  So we cannot use a
703  * simple flag to say whether there is a pending stop endpoint command for a
704  * particular endpoint.
705  *
706  * Instead we use a combination of that flag and a counter for the number of
707  * pending stop endpoint commands.  If the timer is the tail end of the last
708  * stop endpoint command, and the endpoint's command is still pending, we assume
709  * the host is dying.
710  */
711 void xhci_stop_endpoint_command_watchdog(unsigned long arg)
712 {
713         struct xhci_hcd *xhci;
714         struct xhci_virt_ep *ep;
715         struct xhci_virt_ep *temp_ep;
716         struct xhci_ring *ring;
717         struct xhci_td *cur_td;
718         int ret, i, j;
719
720         ep = (struct xhci_virt_ep *) arg;
721         xhci = ep->xhci;
722
723         spin_lock(&xhci->lock);
724
725         ep->stop_cmds_pending--;
726         if (xhci->xhc_state & XHCI_STATE_DYING) {
727                 xhci_dbg(xhci, "Stop EP timer ran, but another timer marked "
728                                 "xHCI as DYING, exiting.\n");
729                 spin_unlock(&xhci->lock);
730                 return;
731         }
732         if (!(ep->stop_cmds_pending == 0 && (ep->ep_state & EP_HALT_PENDING))) {
733                 xhci_dbg(xhci, "Stop EP timer ran, but no command pending, "
734                                 "exiting.\n");
735                 spin_unlock(&xhci->lock);
736                 return;
737         }
738
739         xhci_warn(xhci, "xHCI host not responding to stop endpoint command.\n");
740         xhci_warn(xhci, "Assuming host is dying, halting host.\n");
741         /* Oops, HC is dead or dying or at least not responding to the stop
742          * endpoint command.
743          */
744         xhci->xhc_state |= XHCI_STATE_DYING;
745         /* Disable interrupts from the host controller and start halting it */
746         xhci_quiesce(xhci);
747         spin_unlock(&xhci->lock);
748
749         ret = xhci_halt(xhci);
750
751         spin_lock(&xhci->lock);
752         if (ret < 0) {
753                 /* This is bad; the host is not responding to commands and it's
754                  * not allowing itself to be halted.  At least interrupts are
755                  * disabled, so we can set HC_STATE_HALT and notify the
756                  * USB core.  But if we call usb_hc_died(), it will attempt to
757                  * disconnect all device drivers under this host.  Those
758                  * disconnect() methods will wait for all URBs to be unlinked,
759                  * so we must complete them.
760                  */
761                 xhci_warn(xhci, "Non-responsive xHCI host is not halting.\n");
762                 xhci_warn(xhci, "Completing active URBs anyway.\n");
763                 /* We could turn all TDs on the rings to no-ops.  This won't
764                  * help if the host has cached part of the ring, and is slow if
765                  * we want to preserve the cycle bit.  Skip it and hope the host
766                  * doesn't touch the memory.
767                  */
768         }
769         for (i = 0; i < MAX_HC_SLOTS; i++) {
770                 if (!xhci->devs[i])
771                         continue;
772                 for (j = 0; j < 31; j++) {
773                         temp_ep = &xhci->devs[i]->eps[j];
774                         ring = temp_ep->ring;
775                         if (!ring)
776                                 continue;
777                         xhci_dbg(xhci, "Killing URBs for slot ID %u, "
778                                         "ep index %u\n", i, j);
779                         while (!list_empty(&ring->td_list)) {
780                                 cur_td = list_first_entry(&ring->td_list,
781                                                 struct xhci_td,
782                                                 td_list);
783                                 list_del(&cur_td->td_list);
784                                 if (!list_empty(&cur_td->cancelled_td_list))
785                                         list_del(&cur_td->cancelled_td_list);
786                                 xhci_giveback_urb_in_irq(xhci, cur_td,
787                                                 -ESHUTDOWN, "killed");
788                         }
789                         while (!list_empty(&temp_ep->cancelled_td_list)) {
790                                 cur_td = list_first_entry(
791                                                 &temp_ep->cancelled_td_list,
792                                                 struct xhci_td,
793                                                 cancelled_td_list);
794                                 list_del(&cur_td->cancelled_td_list);
795                                 xhci_giveback_urb_in_irq(xhci, cur_td,
796                                                 -ESHUTDOWN, "killed");
797                         }
798                 }
799         }
800         spin_unlock(&xhci->lock);
801         xhci_to_hcd(xhci)->state = HC_STATE_HALT;
802         xhci_dbg(xhci, "Calling usb_hc_died()\n");
803         usb_hc_died(xhci_to_hcd(xhci));
804         xhci_dbg(xhci, "xHCI host controller is dead.\n");
805 }
806
807 /*
808  * When we get a completion for a Set Transfer Ring Dequeue Pointer command,
809  * we need to clear the set deq pending flag in the endpoint ring state, so that
810  * the TD queueing code can ring the doorbell again.  We also need to ring the
811  * endpoint doorbell to restart the ring, but only if there aren't more
812  * cancellations pending.
813  */
814 static void handle_set_deq_completion(struct xhci_hcd *xhci,
815                 struct xhci_event_cmd *event,
816                 union xhci_trb *trb)
817 {
818         unsigned int slot_id;
819         unsigned int ep_index;
820         unsigned int stream_id;
821         struct xhci_ring *ep_ring;
822         struct xhci_virt_device *dev;
823         struct xhci_ep_ctx *ep_ctx;
824         struct xhci_slot_ctx *slot_ctx;
825
826         slot_id = TRB_TO_SLOT_ID(trb->generic.field[3]);
827         ep_index = TRB_TO_EP_INDEX(trb->generic.field[3]);
828         stream_id = TRB_TO_STREAM_ID(trb->generic.field[2]);
829         dev = xhci->devs[slot_id];
830
831         ep_ring = xhci_stream_id_to_ring(dev, ep_index, stream_id);
832         if (!ep_ring) {
833                 xhci_warn(xhci, "WARN Set TR deq ptr command for "
834                                 "freed stream ID %u\n",
835                                 stream_id);
836                 /* XXX: Harmless??? */
837                 dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING;
838                 return;
839         }
840
841         ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index);
842         slot_ctx = xhci_get_slot_ctx(xhci, dev->out_ctx);
843
844         if (GET_COMP_CODE(event->status) != COMP_SUCCESS) {
845                 unsigned int ep_state;
846                 unsigned int slot_state;
847
848                 switch (GET_COMP_CODE(event->status)) {
849                 case COMP_TRB_ERR:
850                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because "
851                                         "of stream ID configuration\n");
852                         break;
853                 case COMP_CTX_STATE:
854                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due "
855                                         "to incorrect slot or ep state.\n");
856                         ep_state = ep_ctx->ep_info;
857                         ep_state &= EP_STATE_MASK;
858                         slot_state = slot_ctx->dev_state;
859                         slot_state = GET_SLOT_STATE(slot_state);
860                         xhci_dbg(xhci, "Slot state = %u, EP state = %u\n",
861                                         slot_state, ep_state);
862                         break;
863                 case COMP_EBADSLT:
864                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because "
865                                         "slot %u was not enabled.\n", slot_id);
866                         break;
867                 default:
868                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown "
869                                         "completion code of %u.\n",
870                                         GET_COMP_CODE(event->status));
871                         break;
872                 }
873                 /* OK what do we do now?  The endpoint state is hosed, and we
874                  * should never get to this point if the synchronization between
875                  * queueing, and endpoint state are correct.  This might happen
876                  * if the device gets disconnected after we've finished
877                  * cancelling URBs, which might not be an error...
878                  */
879         } else {
880                 xhci_dbg(xhci, "Successful Set TR Deq Ptr cmd, deq = @%08llx\n",
881                                 ep_ctx->deq);
882         }
883
884         dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING;
885         /* Restart any rings with pending URBs */
886         ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
887 }
888
889 static void handle_reset_ep_completion(struct xhci_hcd *xhci,
890                 struct xhci_event_cmd *event,
891                 union xhci_trb *trb)
892 {
893         int slot_id;
894         unsigned int ep_index;
895
896         slot_id = TRB_TO_SLOT_ID(trb->generic.field[3]);
897         ep_index = TRB_TO_EP_INDEX(trb->generic.field[3]);
898         /* This command will only fail if the endpoint wasn't halted,
899          * but we don't care.
900          */
901         xhci_dbg(xhci, "Ignoring reset ep completion code of %u\n",
902                         (unsigned int) GET_COMP_CODE(event->status));
903
904         /* HW with the reset endpoint quirk needs to have a configure endpoint
905          * command complete before the endpoint can be used.  Queue that here
906          * because the HW can't handle two commands being queued in a row.
907          */
908         if (xhci->quirks & XHCI_RESET_EP_QUIRK) {
909                 xhci_dbg(xhci, "Queueing configure endpoint command\n");
910                 xhci_queue_configure_endpoint(xhci,
911                                 xhci->devs[slot_id]->in_ctx->dma, slot_id,
912                                 false);
913                 xhci_ring_cmd_db(xhci);
914         } else {
915                 /* Clear our internal halted state and restart the ring(s) */
916                 xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED;
917                 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
918         }
919 }
920
921 /* Check to see if a command in the device's command queue matches this one.
922  * Signal the completion or free the command, and return 1.  Return 0 if the
923  * completed command isn't at the head of the command list.
924  */
925 static int handle_cmd_in_cmd_wait_list(struct xhci_hcd *xhci,
926                 struct xhci_virt_device *virt_dev,
927                 struct xhci_event_cmd *event)
928 {
929         struct xhci_command *command;
930
931         if (list_empty(&virt_dev->cmd_list))
932                 return 0;
933
934         command = list_entry(virt_dev->cmd_list.next,
935                         struct xhci_command, cmd_list);
936         if (xhci->cmd_ring->dequeue != command->command_trb)
937                 return 0;
938
939         command->status =
940                 GET_COMP_CODE(event->status);
941         list_del(&command->cmd_list);
942         if (command->completion)
943                 complete(command->completion);
944         else
945                 xhci_free_command(xhci, command);
946         return 1;
947 }
948
949 static void handle_cmd_completion(struct xhci_hcd *xhci,
950                 struct xhci_event_cmd *event)
951 {
952         int slot_id = TRB_TO_SLOT_ID(event->flags);
953         u64 cmd_dma;
954         dma_addr_t cmd_dequeue_dma;
955         struct xhci_input_control_ctx *ctrl_ctx;
956         struct xhci_virt_device *virt_dev;
957         unsigned int ep_index;
958         struct xhci_ring *ep_ring;
959         unsigned int ep_state;
960
961         cmd_dma = event->cmd_trb;
962         cmd_dequeue_dma = xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
963                         xhci->cmd_ring->dequeue);
964         /* Is the command ring deq ptr out of sync with the deq seg ptr? */
965         if (cmd_dequeue_dma == 0) {
966                 xhci->error_bitmask |= 1 << 4;
967                 return;
968         }
969         /* Does the DMA address match our internal dequeue pointer address? */
970         if (cmd_dma != (u64) cmd_dequeue_dma) {
971                 xhci->error_bitmask |= 1 << 5;
972                 return;
973         }
974         switch (xhci->cmd_ring->dequeue->generic.field[3] & TRB_TYPE_BITMASK) {
975         case TRB_TYPE(TRB_ENABLE_SLOT):
976                 if (GET_COMP_CODE(event->status) == COMP_SUCCESS)
977                         xhci->slot_id = slot_id;
978                 else
979                         xhci->slot_id = 0;
980                 complete(&xhci->addr_dev);
981                 break;
982         case TRB_TYPE(TRB_DISABLE_SLOT):
983                 if (xhci->devs[slot_id])
984                         xhci_free_virt_device(xhci, slot_id);
985                 break;
986         case TRB_TYPE(TRB_CONFIG_EP):
987                 virt_dev = xhci->devs[slot_id];
988                 if (handle_cmd_in_cmd_wait_list(xhci, virt_dev, event))
989                         break;
990                 /*
991                  * Configure endpoint commands can come from the USB core
992                  * configuration or alt setting changes, or because the HW
993                  * needed an extra configure endpoint command after a reset
994                  * endpoint command or streams were being configured.
995                  * If the command was for a halted endpoint, the xHCI driver
996                  * is not waiting on the configure endpoint command.
997                  */
998                 ctrl_ctx = xhci_get_input_control_ctx(xhci,
999                                 virt_dev->in_ctx);
1000                 /* Input ctx add_flags are the endpoint index plus one */
1001                 ep_index = xhci_last_valid_endpoint(ctrl_ctx->add_flags) - 1;
1002                 /* A usb_set_interface() call directly after clearing a halted
1003                  * condition may race on this quirky hardware.  Not worth
1004                  * worrying about, since this is prototype hardware.  Not sure
1005                  * if this will work for streams, but streams support was
1006                  * untested on this prototype.
1007                  */
1008                 if (xhci->quirks & XHCI_RESET_EP_QUIRK &&
1009                                 ep_index != (unsigned int) -1 &&
1010                                 ctrl_ctx->add_flags - SLOT_FLAG ==
1011                                         ctrl_ctx->drop_flags) {
1012                         ep_ring = xhci->devs[slot_id]->eps[ep_index].ring;
1013                         ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
1014                         if (!(ep_state & EP_HALTED))
1015                                 goto bandwidth_change;
1016                         xhci_dbg(xhci, "Completed config ep cmd - "
1017                                         "last ep index = %d, state = %d\n",
1018                                         ep_index, ep_state);
1019                         /* Clear internal halted state and restart ring(s) */
1020                         xhci->devs[slot_id]->eps[ep_index].ep_state &=
1021                                 ~EP_HALTED;
1022                         ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1023                         break;
1024                 }
1025 bandwidth_change:
1026                 xhci_dbg(xhci, "Completed config ep cmd\n");
1027                 xhci->devs[slot_id]->cmd_status =
1028                         GET_COMP_CODE(event->status);
1029                 complete(&xhci->devs[slot_id]->cmd_completion);
1030                 break;
1031         case TRB_TYPE(TRB_EVAL_CONTEXT):
1032                 virt_dev = xhci->devs[slot_id];
1033                 if (handle_cmd_in_cmd_wait_list(xhci, virt_dev, event))
1034                         break;
1035                 xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(event->status);
1036                 complete(&xhci->devs[slot_id]->cmd_completion);
1037                 break;
1038         case TRB_TYPE(TRB_ADDR_DEV):
1039                 xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(event->status);
1040                 complete(&xhci->addr_dev);
1041                 break;
1042         case TRB_TYPE(TRB_STOP_RING):
1043                 handle_stopped_endpoint(xhci, xhci->cmd_ring->dequeue);
1044                 break;
1045         case TRB_TYPE(TRB_SET_DEQ):
1046                 handle_set_deq_completion(xhci, event, xhci->cmd_ring->dequeue);
1047                 break;
1048         case TRB_TYPE(TRB_CMD_NOOP):
1049                 ++xhci->noops_handled;
1050                 break;
1051         case TRB_TYPE(TRB_RESET_EP):
1052                 handle_reset_ep_completion(xhci, event, xhci->cmd_ring->dequeue);
1053                 break;
1054         case TRB_TYPE(TRB_RESET_DEV):
1055                 xhci_dbg(xhci, "Completed reset device command.\n");
1056                 slot_id = TRB_TO_SLOT_ID(
1057                                 xhci->cmd_ring->dequeue->generic.field[3]);
1058                 virt_dev = xhci->devs[slot_id];
1059                 if (virt_dev)
1060                         handle_cmd_in_cmd_wait_list(xhci, virt_dev, event);
1061                 else
1062                         xhci_warn(xhci, "Reset device command completion "
1063                                         "for disabled slot %u\n", slot_id);
1064                 break;
1065         default:
1066                 /* Skip over unknown commands on the event ring */
1067                 xhci->error_bitmask |= 1 << 6;
1068                 break;
1069         }
1070         inc_deq(xhci, xhci->cmd_ring, false);
1071 }
1072
1073 static void handle_port_status(struct xhci_hcd *xhci,
1074                 union xhci_trb *event)
1075 {
1076         u32 port_id;
1077
1078         /* Port status change events always have a successful completion code */
1079         if (GET_COMP_CODE(event->generic.field[2]) != COMP_SUCCESS) {
1080                 xhci_warn(xhci, "WARN: xHC returned failed port status event\n");
1081                 xhci->error_bitmask |= 1 << 8;
1082         }
1083         /* FIXME: core doesn't care about all port link state changes yet */
1084         port_id = GET_PORT_ID(event->generic.field[0]);
1085         xhci_dbg(xhci, "Port Status Change Event for port %d\n", port_id);
1086
1087         /* Update event ring dequeue pointer before dropping the lock */
1088         inc_deq(xhci, xhci->event_ring, true);
1089         xhci_set_hc_event_deq(xhci);
1090
1091         spin_unlock(&xhci->lock);
1092         /* Pass this up to the core */
1093         usb_hcd_poll_rh_status(xhci_to_hcd(xhci));
1094         spin_lock(&xhci->lock);
1095 }
1096
1097 /*
1098  * This TD is defined by the TRBs starting at start_trb in start_seg and ending
1099  * at end_trb, which may be in another segment.  If the suspect DMA address is a
1100  * TRB in this TD, this function returns that TRB's segment.  Otherwise it
1101  * returns 0.
1102  */
1103 struct xhci_segment *trb_in_td(struct xhci_segment *start_seg,
1104                 union xhci_trb  *start_trb,
1105                 union xhci_trb  *end_trb,
1106                 dma_addr_t      suspect_dma)
1107 {
1108         dma_addr_t start_dma;
1109         dma_addr_t end_seg_dma;
1110         dma_addr_t end_trb_dma;
1111         struct xhci_segment *cur_seg;
1112
1113         start_dma = xhci_trb_virt_to_dma(start_seg, start_trb);
1114         cur_seg = start_seg;
1115
1116         do {
1117                 if (start_dma == 0)
1118                         return NULL;
1119                 /* We may get an event for a Link TRB in the middle of a TD */
1120                 end_seg_dma = xhci_trb_virt_to_dma(cur_seg,
1121                                 &cur_seg->trbs[TRBS_PER_SEGMENT - 1]);
1122                 /* If the end TRB isn't in this segment, this is set to 0 */
1123                 end_trb_dma = xhci_trb_virt_to_dma(cur_seg, end_trb);
1124
1125                 if (end_trb_dma > 0) {
1126                         /* The end TRB is in this segment, so suspect should be here */
1127                         if (start_dma <= end_trb_dma) {
1128                                 if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma)
1129                                         return cur_seg;
1130                         } else {
1131                                 /* Case for one segment with
1132                                  * a TD wrapped around to the top
1133                                  */
1134                                 if ((suspect_dma >= start_dma &&
1135                                                         suspect_dma <= end_seg_dma) ||
1136                                                 (suspect_dma >= cur_seg->dma &&
1137                                                  suspect_dma <= end_trb_dma))
1138                                         return cur_seg;
1139                         }
1140                         return NULL;
1141                 } else {
1142                         /* Might still be somewhere in this segment */
1143                         if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma)
1144                                 return cur_seg;
1145                 }
1146                 cur_seg = cur_seg->next;
1147                 start_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[0]);
1148         } while (cur_seg != start_seg);
1149
1150         return NULL;
1151 }
1152
1153 static void xhci_cleanup_halted_endpoint(struct xhci_hcd *xhci,
1154                 unsigned int slot_id, unsigned int ep_index,
1155                 unsigned int stream_id,
1156                 struct xhci_td *td, union xhci_trb *event_trb)
1157 {
1158         struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index];
1159         ep->ep_state |= EP_HALTED;
1160         ep->stopped_td = td;
1161         ep->stopped_trb = event_trb;
1162         ep->stopped_stream = stream_id;
1163
1164         xhci_queue_reset_ep(xhci, slot_id, ep_index);
1165         xhci_cleanup_stalled_ring(xhci, td->urb->dev, ep_index);
1166
1167         ep->stopped_td = NULL;
1168         ep->stopped_trb = NULL;
1169         ep->stopped_stream = 0;
1170
1171         xhci_ring_cmd_db(xhci);
1172 }
1173
1174 /* Check if an error has halted the endpoint ring.  The class driver will
1175  * cleanup the halt for a non-default control endpoint if we indicate a stall.
1176  * However, a babble and other errors also halt the endpoint ring, and the class
1177  * driver won't clear the halt in that case, so we need to issue a Set Transfer
1178  * Ring Dequeue Pointer command manually.
1179  */
1180 static int xhci_requires_manual_halt_cleanup(struct xhci_hcd *xhci,
1181                 struct xhci_ep_ctx *ep_ctx,
1182                 unsigned int trb_comp_code)
1183 {
1184         /* TRB completion codes that may require a manual halt cleanup */
1185         if (trb_comp_code == COMP_TX_ERR ||
1186                         trb_comp_code == COMP_BABBLE ||
1187                         trb_comp_code == COMP_SPLIT_ERR)
1188                 /* The 0.96 spec says a babbling control endpoint
1189                  * is not halted. The 0.96 spec says it is.  Some HW
1190                  * claims to be 0.95 compliant, but it halts the control
1191                  * endpoint anyway.  Check if a babble halted the
1192                  * endpoint.
1193                  */
1194                 if ((ep_ctx->ep_info & EP_STATE_MASK) == EP_STATE_HALTED)
1195                         return 1;
1196
1197         return 0;
1198 }
1199
1200 int xhci_is_vendor_info_code(struct xhci_hcd *xhci, unsigned int trb_comp_code)
1201 {
1202         if (trb_comp_code >= 224 && trb_comp_code <= 255) {
1203                 /* Vendor defined "informational" completion code,
1204                  * treat as not-an-error.
1205                  */
1206                 xhci_dbg(xhci, "Vendor defined info completion code %u\n",
1207                                 trb_comp_code);
1208                 xhci_dbg(xhci, "Treating code as success.\n");
1209                 return 1;
1210         }
1211         return 0;
1212 }
1213
1214 /*
1215  * If this function returns an error condition, it means it got a Transfer
1216  * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address.
1217  * At this point, the host controller is probably hosed and should be reset.
1218  */
1219 static int handle_tx_event(struct xhci_hcd *xhci,
1220                 struct xhci_transfer_event *event)
1221 {
1222         struct xhci_virt_device *xdev;
1223         struct xhci_virt_ep *ep;
1224         struct xhci_ring *ep_ring;
1225         unsigned int slot_id;
1226         int ep_index;
1227         struct xhci_td *td = NULL;
1228         dma_addr_t event_dma;
1229         struct xhci_segment *event_seg;
1230         union xhci_trb *event_trb;
1231         struct urb *urb = NULL;
1232         int status = -EINPROGRESS;
1233         struct xhci_ep_ctx *ep_ctx;
1234         u32 trb_comp_code;
1235
1236         xhci_dbg(xhci, "In %s\n", __func__);
1237         slot_id = TRB_TO_SLOT_ID(event->flags);
1238         xdev = xhci->devs[slot_id];
1239         if (!xdev) {
1240                 xhci_err(xhci, "ERROR Transfer event pointed to bad slot\n");
1241                 return -ENODEV;
1242         }
1243
1244         /* Endpoint ID is 1 based, our index is zero based */
1245         ep_index = TRB_TO_EP_ID(event->flags) - 1;
1246         xhci_dbg(xhci, "%s - ep index = %d\n", __func__, ep_index);
1247         ep = &xdev->eps[ep_index];
1248         ep_ring = xhci_dma_to_transfer_ring(ep, event->buffer);
1249         ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
1250         if (!ep_ring || (ep_ctx->ep_info & EP_STATE_MASK) == EP_STATE_DISABLED) {
1251                 xhci_err(xhci, "ERROR Transfer event for disabled endpoint "
1252                                 "or incorrect stream ring\n");
1253                 return -ENODEV;
1254         }
1255
1256         event_dma = event->buffer;
1257         /* This TRB should be in the TD at the head of this ring's TD list */
1258         xhci_dbg(xhci, "%s - checking for list empty\n", __func__);
1259         if (list_empty(&ep_ring->td_list)) {
1260                 xhci_warn(xhci, "WARN Event TRB for slot %d ep %d with no TDs queued?\n",
1261                                 TRB_TO_SLOT_ID(event->flags), ep_index);
1262                 xhci_dbg(xhci, "Event TRB with TRB type ID %u\n",
1263                                 (unsigned int) (event->flags & TRB_TYPE_BITMASK)>>10);
1264                 xhci_print_trb_offsets(xhci, (union xhci_trb *) event);
1265                 urb = NULL;
1266                 goto cleanup;
1267         }
1268         xhci_dbg(xhci, "%s - getting list entry\n", __func__);
1269         td = list_entry(ep_ring->td_list.next, struct xhci_td, td_list);
1270
1271         /* Is this a TRB in the currently executing TD? */
1272         xhci_dbg(xhci, "%s - looking for TD\n", __func__);
1273         event_seg = trb_in_td(ep_ring->deq_seg, ep_ring->dequeue,
1274                         td->last_trb, event_dma);
1275         xhci_dbg(xhci, "%s - found event_seg = %p\n", __func__, event_seg);
1276         if (!event_seg) {
1277                 /* HC is busted, give up! */
1278                 xhci_err(xhci, "ERROR Transfer event TRB DMA ptr not part of current TD\n");
1279                 return -ESHUTDOWN;
1280         }
1281         event_trb = &event_seg->trbs[(event_dma - event_seg->dma) / sizeof(*event_trb)];
1282         xhci_dbg(xhci, "Event TRB with TRB type ID %u\n",
1283                         (unsigned int) (event->flags & TRB_TYPE_BITMASK)>>10);
1284         xhci_dbg(xhci, "Offset 0x00 (buffer lo) = 0x%x\n",
1285                         lower_32_bits(event->buffer));
1286         xhci_dbg(xhci, "Offset 0x04 (buffer hi) = 0x%x\n",
1287                         upper_32_bits(event->buffer));
1288         xhci_dbg(xhci, "Offset 0x08 (transfer length) = 0x%x\n",
1289                         (unsigned int) event->transfer_len);
1290         xhci_dbg(xhci, "Offset 0x0C (flags) = 0x%x\n",
1291                         (unsigned int) event->flags);
1292
1293         /* Look for common error cases */
1294         trb_comp_code = GET_COMP_CODE(event->transfer_len);
1295         switch (trb_comp_code) {
1296         /* Skip codes that require special handling depending on
1297          * transfer type
1298          */
1299         case COMP_SUCCESS:
1300         case COMP_SHORT_TX:
1301                 break;
1302         case COMP_STOP:
1303                 xhci_dbg(xhci, "Stopped on Transfer TRB\n");
1304                 break;
1305         case COMP_STOP_INVAL:
1306                 xhci_dbg(xhci, "Stopped on No-op or Link TRB\n");
1307                 break;
1308         case COMP_STALL:
1309                 xhci_warn(xhci, "WARN: Stalled endpoint\n");
1310                 ep->ep_state |= EP_HALTED;
1311                 status = -EPIPE;
1312                 break;
1313         case COMP_TRB_ERR:
1314                 xhci_warn(xhci, "WARN: TRB error on endpoint\n");
1315                 status = -EILSEQ;
1316                 break;
1317         case COMP_SPLIT_ERR:
1318         case COMP_TX_ERR:
1319                 xhci_warn(xhci, "WARN: transfer error on endpoint\n");
1320                 status = -EPROTO;
1321                 break;
1322         case COMP_BABBLE:
1323                 xhci_warn(xhci, "WARN: babble error on endpoint\n");
1324                 status = -EOVERFLOW;
1325                 break;
1326         case COMP_DB_ERR:
1327                 xhci_warn(xhci, "WARN: HC couldn't access mem fast enough\n");
1328                 status = -ENOSR;
1329                 break;
1330         default:
1331                 if (xhci_is_vendor_info_code(xhci, trb_comp_code)) {
1332                         status = 0;
1333                         break;
1334                 }
1335                 xhci_warn(xhci, "ERROR Unknown event condition, HC probably busted\n");
1336                 urb = NULL;
1337                 goto cleanup;
1338         }
1339         /* Now update the urb's actual_length and give back to the core */
1340         /* Was this a control transfer? */
1341         if (usb_endpoint_xfer_control(&td->urb->ep->desc)) {
1342                 xhci_debug_trb(xhci, xhci->event_ring->dequeue);
1343                 switch (trb_comp_code) {
1344                 case COMP_SUCCESS:
1345                         if (event_trb == ep_ring->dequeue) {
1346                                 xhci_warn(xhci, "WARN: Success on ctrl setup TRB without IOC set??\n");
1347                                 status = -ESHUTDOWN;
1348                         } else if (event_trb != td->last_trb) {
1349                                 xhci_warn(xhci, "WARN: Success on ctrl data TRB without IOC set??\n");
1350                                 status = -ESHUTDOWN;
1351                         } else {
1352                                 xhci_dbg(xhci, "Successful control transfer!\n");
1353                                 status = 0;
1354                         }
1355                         break;
1356                 case COMP_SHORT_TX:
1357                         xhci_warn(xhci, "WARN: short transfer on control ep\n");
1358                         if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1359                                 status = -EREMOTEIO;
1360                         else
1361                                 status = 0;
1362                         break;
1363
1364                 default:
1365                         if (!xhci_requires_manual_halt_cleanup(xhci,
1366                                                 ep_ctx, trb_comp_code))
1367                                 break;
1368                         xhci_dbg(xhci, "TRB error code %u, "
1369                                         "halted endpoint index = %u\n",
1370                                         trb_comp_code, ep_index);
1371                         /* else fall through */
1372                 case COMP_STALL:
1373                         /* Did we transfer part of the data (middle) phase? */
1374                         if (event_trb != ep_ring->dequeue &&
1375                                         event_trb != td->last_trb)
1376                                 td->urb->actual_length =
1377                                         td->urb->transfer_buffer_length
1378                                         - TRB_LEN(event->transfer_len);
1379                         else
1380                                 td->urb->actual_length = 0;
1381
1382                         xhci_cleanup_halted_endpoint(xhci,
1383                                         slot_id, ep_index, 0, td, event_trb);
1384                         goto td_cleanup;
1385                 }
1386                 /*
1387                  * Did we transfer any data, despite the errors that might have
1388                  * happened?  I.e. did we get past the setup stage?
1389                  */
1390                 if (event_trb != ep_ring->dequeue) {
1391                         /* The event was for the status stage */
1392                         if (event_trb == td->last_trb) {
1393                                 if (td->urb->actual_length != 0) {
1394                                         /* Don't overwrite a previously set error code */
1395                                         if ((status == -EINPROGRESS ||
1396                                                                 status == 0) &&
1397                                                         (td->urb->transfer_flags
1398                                                          & URB_SHORT_NOT_OK))
1399                                                 /* Did we already see a short data stage? */
1400                                                 status = -EREMOTEIO;
1401                                 } else {
1402                                         td->urb->actual_length =
1403                                                 td->urb->transfer_buffer_length;
1404                                 }
1405                         } else {
1406                         /* Maybe the event was for the data stage? */
1407                                 if (trb_comp_code != COMP_STOP_INVAL) {
1408                                         /* We didn't stop on a link TRB in the middle */
1409                                         td->urb->actual_length =
1410                                                 td->urb->transfer_buffer_length -
1411                                                 TRB_LEN(event->transfer_len);
1412                                         xhci_dbg(xhci, "Waiting for status stage event\n");
1413                                         urb = NULL;
1414                                         goto cleanup;
1415                                 }
1416                         }
1417                 }
1418         } else {
1419                 switch (trb_comp_code) {
1420                 case COMP_SUCCESS:
1421                         /* Double check that the HW transferred everything. */
1422                         if (event_trb != td->last_trb) {
1423                                 xhci_warn(xhci, "WARN Successful completion "
1424                                                 "on short TX\n");
1425                                 if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1426                                         status = -EREMOTEIO;
1427                                 else
1428                                         status = 0;
1429                         } else {
1430                                 if (usb_endpoint_xfer_bulk(&td->urb->ep->desc))
1431                                         xhci_dbg(xhci, "Successful bulk "
1432                                                         "transfer!\n");
1433                                 else
1434                                         xhci_dbg(xhci, "Successful interrupt "
1435                                                         "transfer!\n");
1436                                 status = 0;
1437                         }
1438                         break;
1439                 case COMP_SHORT_TX:
1440                         if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1441                                 status = -EREMOTEIO;
1442                         else
1443                                 status = 0;
1444                         break;
1445                 default:
1446                         /* Others already handled above */
1447                         break;
1448                 }
1449                 dev_dbg(&td->urb->dev->dev,
1450                                 "ep %#x - asked for %d bytes, "
1451                                 "%d bytes untransferred\n",
1452                                 td->urb->ep->desc.bEndpointAddress,
1453                                 td->urb->transfer_buffer_length,
1454                                 TRB_LEN(event->transfer_len));
1455                 /* Fast path - was this the last TRB in the TD for this URB? */
1456                 if (event_trb == td->last_trb) {
1457                         if (TRB_LEN(event->transfer_len) != 0) {
1458                                 td->urb->actual_length =
1459                                         td->urb->transfer_buffer_length -
1460                                         TRB_LEN(event->transfer_len);
1461                                 if (td->urb->transfer_buffer_length <
1462                                                 td->urb->actual_length) {
1463                                         xhci_warn(xhci, "HC gave bad length "
1464                                                         "of %d bytes left\n",
1465                                                         TRB_LEN(event->transfer_len));
1466                                         td->urb->actual_length = 0;
1467                                         if (td->urb->transfer_flags &
1468                                                         URB_SHORT_NOT_OK)
1469                                                 status = -EREMOTEIO;
1470                                         else
1471                                                 status = 0;
1472                                 }
1473                                 /* Don't overwrite a previously set error code */
1474                                 if (status == -EINPROGRESS) {
1475                                         if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1476                                                 status = -EREMOTEIO;
1477                                         else
1478                                                 status = 0;
1479                                 }
1480                         } else {
1481                                 td->urb->actual_length = td->urb->transfer_buffer_length;
1482                                 /* Ignore a short packet completion if the
1483                                  * untransferred length was zero.
1484                                  */
1485                                 if (status == -EREMOTEIO)
1486                                         status = 0;
1487                         }
1488                 } else {
1489                         /* Slow path - walk the list, starting from the dequeue
1490                          * pointer, to get the actual length transferred.
1491                          */
1492                         union xhci_trb *cur_trb;
1493                         struct xhci_segment *cur_seg;
1494
1495                         td->urb->actual_length = 0;
1496                         for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg;
1497                                         cur_trb != event_trb;
1498                                         next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) {
1499                                 if (TRB_TYPE(cur_trb->generic.field[3]) != TRB_TR_NOOP &&
1500                                                 TRB_TYPE(cur_trb->generic.field[3]) != TRB_LINK)
1501                                         td->urb->actual_length +=
1502                                                 TRB_LEN(cur_trb->generic.field[2]);
1503                         }
1504                         /* If the ring didn't stop on a Link or No-op TRB, add
1505                          * in the actual bytes transferred from the Normal TRB
1506                          */
1507                         if (trb_comp_code != COMP_STOP_INVAL)
1508                                 td->urb->actual_length +=
1509                                         TRB_LEN(cur_trb->generic.field[2]) -
1510                                         TRB_LEN(event->transfer_len);
1511                 }
1512         }
1513         if (trb_comp_code == COMP_STOP_INVAL ||
1514                         trb_comp_code == COMP_STOP) {
1515                 /* The Endpoint Stop Command completion will take care of any
1516                  * stopped TDs.  A stopped TD may be restarted, so don't update
1517                  * the ring dequeue pointer or take this TD off any lists yet.
1518                  */
1519                 ep->stopped_td = td;
1520                 ep->stopped_trb = event_trb;
1521         } else {
1522                 if (trb_comp_code == COMP_STALL) {
1523                         /* The transfer is completed from the driver's
1524                          * perspective, but we need to issue a set dequeue
1525                          * command for this stalled endpoint to move the dequeue
1526                          * pointer past the TD.  We can't do that here because
1527                          * the halt condition must be cleared first.  Let the
1528                          * USB class driver clear the stall later.
1529                          */
1530                         ep->stopped_td = td;
1531                         ep->stopped_trb = event_trb;
1532                         ep->stopped_stream = ep_ring->stream_id;
1533                 } else if (xhci_requires_manual_halt_cleanup(xhci,
1534                                         ep_ctx, trb_comp_code)) {
1535                         /* Other types of errors halt the endpoint, but the
1536                          * class driver doesn't call usb_reset_endpoint() unless
1537                          * the error is -EPIPE.  Clear the halted status in the
1538                          * xHCI hardware manually.
1539                          */
1540                         xhci_cleanup_halted_endpoint(xhci,
1541                                         slot_id, ep_index, ep_ring->stream_id, td, event_trb);
1542                 } else {
1543                         /* Update ring dequeue pointer */
1544                         while (ep_ring->dequeue != td->last_trb)
1545                                 inc_deq(xhci, ep_ring, false);
1546                         inc_deq(xhci, ep_ring, false);
1547                 }
1548
1549 td_cleanup:
1550                 /* Clean up the endpoint's TD list */
1551                 urb = td->urb;
1552                 /* Do one last check of the actual transfer length.
1553                  * If the host controller said we transferred more data than
1554                  * the buffer length, urb->actual_length will be a very big
1555                  * number (since it's unsigned).  Play it safe and say we didn't
1556                  * transfer anything.
1557                  */
1558                 if (urb->actual_length > urb->transfer_buffer_length) {
1559                         xhci_warn(xhci, "URB transfer length is wrong, "
1560                                         "xHC issue? req. len = %u, "
1561                                         "act. len = %u\n",
1562                                         urb->transfer_buffer_length,
1563                                         urb->actual_length);
1564                         urb->actual_length = 0;
1565                         if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1566                                 status = -EREMOTEIO;
1567                         else
1568                                 status = 0;
1569                 }
1570                 list_del(&td->td_list);
1571                 /* Was this TD slated to be cancelled but completed anyway? */
1572                 if (!list_empty(&td->cancelled_td_list))
1573                         list_del(&td->cancelled_td_list);
1574
1575                 /* Leave the TD around for the reset endpoint function to use
1576                  * (but only if it's not a control endpoint, since we already
1577                  * queued the Set TR dequeue pointer command for stalled
1578                  * control endpoints).
1579                  */
1580                 if (usb_endpoint_xfer_control(&urb->ep->desc) ||
1581                         (trb_comp_code != COMP_STALL &&
1582                                 trb_comp_code != COMP_BABBLE)) {
1583                         kfree(td);
1584                 }
1585                 urb->hcpriv = NULL;
1586         }
1587 cleanup:
1588         inc_deq(xhci, xhci->event_ring, true);
1589         xhci_set_hc_event_deq(xhci);
1590
1591         /* FIXME for multi-TD URBs (who have buffers bigger than 64MB) */
1592         if (urb) {
1593                 usb_hcd_unlink_urb_from_ep(xhci_to_hcd(xhci), urb);
1594                 xhci_dbg(xhci, "Giveback URB %p, len = %d, status = %d\n",
1595                                 urb, urb->actual_length, status);
1596                 spin_unlock(&xhci->lock);
1597                 usb_hcd_giveback_urb(xhci_to_hcd(xhci), urb, status);
1598                 spin_lock(&xhci->lock);
1599         }
1600         return 0;
1601 }
1602
1603 /*
1604  * This function handles all OS-owned events on the event ring.  It may drop
1605  * xhci->lock between event processing (e.g. to pass up port status changes).
1606  */
1607 void xhci_handle_event(struct xhci_hcd *xhci)
1608 {
1609         union xhci_trb *event;
1610         int update_ptrs = 1;
1611         int ret;
1612
1613         xhci_dbg(xhci, "In %s\n", __func__);
1614         if (!xhci->event_ring || !xhci->event_ring->dequeue) {
1615                 xhci->error_bitmask |= 1 << 1;
1616                 return;
1617         }
1618
1619         event = xhci->event_ring->dequeue;
1620         /* Does the HC or OS own the TRB? */
1621         if ((event->event_cmd.flags & TRB_CYCLE) !=
1622                         xhci->event_ring->cycle_state) {
1623                 xhci->error_bitmask |= 1 << 2;
1624                 return;
1625         }
1626         xhci_dbg(xhci, "%s - OS owns TRB\n", __func__);
1627
1628         /* FIXME: Handle more event types. */
1629         switch ((event->event_cmd.flags & TRB_TYPE_BITMASK)) {
1630         case TRB_TYPE(TRB_COMPLETION):
1631                 xhci_dbg(xhci, "%s - calling handle_cmd_completion\n", __func__);
1632                 handle_cmd_completion(xhci, &event->event_cmd);
1633                 xhci_dbg(xhci, "%s - returned from handle_cmd_completion\n", __func__);
1634                 break;
1635         case TRB_TYPE(TRB_PORT_STATUS):
1636                 xhci_dbg(xhci, "%s - calling handle_port_status\n", __func__);
1637                 handle_port_status(xhci, event);
1638                 xhci_dbg(xhci, "%s - returned from handle_port_status\n", __func__);
1639                 update_ptrs = 0;
1640                 break;
1641         case TRB_TYPE(TRB_TRANSFER):
1642                 xhci_dbg(xhci, "%s - calling handle_tx_event\n", __func__);
1643                 ret = handle_tx_event(xhci, &event->trans_event);
1644                 xhci_dbg(xhci, "%s - returned from handle_tx_event\n", __func__);
1645                 if (ret < 0)
1646                         xhci->error_bitmask |= 1 << 9;
1647                 else
1648                         update_ptrs = 0;
1649                 break;
1650         default:
1651                 xhci->error_bitmask |= 1 << 3;
1652         }
1653         /* Any of the above functions may drop and re-acquire the lock, so check
1654          * to make sure a watchdog timer didn't mark the host as non-responsive.
1655          */
1656         if (xhci->xhc_state & XHCI_STATE_DYING) {
1657                 xhci_dbg(xhci, "xHCI host dying, returning from "
1658                                 "event handler.\n");
1659                 return;
1660         }
1661
1662         if (update_ptrs) {
1663                 /* Update SW and HC event ring dequeue pointer */
1664                 inc_deq(xhci, xhci->event_ring, true);
1665                 xhci_set_hc_event_deq(xhci);
1666         }
1667         /* Are there more items on the event ring? */
1668         xhci_handle_event(xhci);
1669 }
1670
1671 /****           Endpoint Ring Operations        ****/
1672
1673 /*
1674  * Generic function for queueing a TRB on a ring.
1675  * The caller must have checked to make sure there's room on the ring.
1676  */
1677 static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
1678                 bool consumer,
1679                 u32 field1, u32 field2, u32 field3, u32 field4)
1680 {
1681         struct xhci_generic_trb *trb;
1682
1683         trb = &ring->enqueue->generic;
1684         trb->field[0] = field1;
1685         trb->field[1] = field2;
1686         trb->field[2] = field3;
1687         trb->field[3] = field4;
1688         inc_enq(xhci, ring, consumer);
1689 }
1690
1691 /*
1692  * Does various checks on the endpoint ring, and makes it ready to queue num_trbs.
1693  * FIXME allocate segments if the ring is full.
1694  */
1695 static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
1696                 u32 ep_state, unsigned int num_trbs, gfp_t mem_flags)
1697 {
1698         /* Make sure the endpoint has been added to xHC schedule */
1699         xhci_dbg(xhci, "Endpoint state = 0x%x\n", ep_state);
1700         switch (ep_state) {
1701         case EP_STATE_DISABLED:
1702                 /*
1703                  * USB core changed config/interfaces without notifying us,
1704                  * or hardware is reporting the wrong state.
1705                  */
1706                 xhci_warn(xhci, "WARN urb submitted to disabled ep\n");
1707                 return -ENOENT;
1708         case EP_STATE_ERROR:
1709                 xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n");
1710                 /* FIXME event handling code for error needs to clear it */
1711                 /* XXX not sure if this should be -ENOENT or not */
1712                 return -EINVAL;
1713         case EP_STATE_HALTED:
1714                 xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n");
1715         case EP_STATE_STOPPED:
1716         case EP_STATE_RUNNING:
1717                 break;
1718         default:
1719                 xhci_err(xhci, "ERROR unknown endpoint state for ep\n");
1720                 /*
1721                  * FIXME issue Configure Endpoint command to try to get the HC
1722                  * back into a known state.
1723                  */
1724                 return -EINVAL;
1725         }
1726         if (!room_on_ring(xhci, ep_ring, num_trbs)) {
1727                 /* FIXME allocate more room */
1728                 xhci_err(xhci, "ERROR no room on ep ring\n");
1729                 return -ENOMEM;
1730         }
1731         return 0;
1732 }
1733
1734 static int prepare_transfer(struct xhci_hcd *xhci,
1735                 struct xhci_virt_device *xdev,
1736                 unsigned int ep_index,
1737                 unsigned int stream_id,
1738                 unsigned int num_trbs,
1739                 struct urb *urb,
1740                 struct xhci_td **td,
1741                 gfp_t mem_flags)
1742 {
1743         int ret;
1744         struct xhci_ring *ep_ring;
1745         struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
1746
1747         ep_ring = xhci_stream_id_to_ring(xdev, ep_index, stream_id);
1748         if (!ep_ring) {
1749                 xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n",
1750                                 stream_id);
1751                 return -EINVAL;
1752         }
1753
1754         ret = prepare_ring(xhci, ep_ring,
1755                         ep_ctx->ep_info & EP_STATE_MASK,
1756                         num_trbs, mem_flags);
1757         if (ret)
1758                 return ret;
1759         *td = kzalloc(sizeof(struct xhci_td), mem_flags);
1760         if (!*td)
1761                 return -ENOMEM;
1762         INIT_LIST_HEAD(&(*td)->td_list);
1763         INIT_LIST_HEAD(&(*td)->cancelled_td_list);
1764
1765         ret = usb_hcd_link_urb_to_ep(xhci_to_hcd(xhci), urb);
1766         if (unlikely(ret)) {
1767                 kfree(*td);
1768                 return ret;
1769         }
1770
1771         (*td)->urb = urb;
1772         urb->hcpriv = (void *) (*td);
1773         /* Add this TD to the tail of the endpoint ring's TD list */
1774         list_add_tail(&(*td)->td_list, &ep_ring->td_list);
1775         (*td)->start_seg = ep_ring->enq_seg;
1776         (*td)->first_trb = ep_ring->enqueue;
1777
1778         return 0;
1779 }
1780
1781 static unsigned int count_sg_trbs_needed(struct xhci_hcd *xhci, struct urb *urb)
1782 {
1783         int num_sgs, num_trbs, running_total, temp, i;
1784         struct scatterlist *sg;
1785
1786         sg = NULL;
1787         num_sgs = urb->num_sgs;
1788         temp = urb->transfer_buffer_length;
1789
1790         xhci_dbg(xhci, "count sg list trbs: \n");
1791         num_trbs = 0;
1792         for_each_sg(urb->sg, sg, num_sgs, i) {
1793                 unsigned int previous_total_trbs = num_trbs;
1794                 unsigned int len = sg_dma_len(sg);
1795
1796                 /* Scatter gather list entries may cross 64KB boundaries */
1797                 running_total = TRB_MAX_BUFF_SIZE -
1798                         (sg_dma_address(sg) & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
1799                 if (running_total != 0)
1800                         num_trbs++;
1801
1802                 /* How many more 64KB chunks to transfer, how many more TRBs? */
1803                 while (running_total < sg_dma_len(sg)) {
1804                         num_trbs++;
1805                         running_total += TRB_MAX_BUFF_SIZE;
1806                 }
1807                 xhci_dbg(xhci, " sg #%d: dma = %#llx, len = %#x (%d), num_trbs = %d\n",
1808                                 i, (unsigned long long)sg_dma_address(sg),
1809                                 len, len, num_trbs - previous_total_trbs);
1810
1811                 len = min_t(int, len, temp);
1812                 temp -= len;
1813                 if (temp == 0)
1814                         break;
1815         }
1816         xhci_dbg(xhci, "\n");
1817         if (!in_interrupt())
1818                 dev_dbg(&urb->dev->dev, "ep %#x - urb len = %d, sglist used, num_trbs = %d\n",
1819                                 urb->ep->desc.bEndpointAddress,
1820                                 urb->transfer_buffer_length,
1821                                 num_trbs);
1822         return num_trbs;
1823 }
1824
1825 static void check_trb_math(struct urb *urb, int num_trbs, int running_total)
1826 {
1827         if (num_trbs != 0)
1828                 dev_dbg(&urb->dev->dev, "%s - ep %#x - Miscalculated number of "
1829                                 "TRBs, %d left\n", __func__,
1830                                 urb->ep->desc.bEndpointAddress, num_trbs);
1831         if (running_total != urb->transfer_buffer_length)
1832                 dev_dbg(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, "
1833                                 "queued %#x (%d), asked for %#x (%d)\n",
1834                                 __func__,
1835                                 urb->ep->desc.bEndpointAddress,
1836                                 running_total, running_total,
1837                                 urb->transfer_buffer_length,
1838                                 urb->transfer_buffer_length);
1839 }
1840
1841 static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id,
1842                 unsigned int ep_index, unsigned int stream_id, int start_cycle,
1843                 struct xhci_generic_trb *start_trb, struct xhci_td *td)
1844 {
1845         /*
1846          * Pass all the TRBs to the hardware at once and make sure this write
1847          * isn't reordered.
1848          */
1849         wmb();
1850         start_trb->field[3] |= start_cycle;
1851         ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
1852 }
1853
1854 /*
1855  * xHCI uses normal TRBs for both bulk and interrupt.  When the interrupt
1856  * endpoint is to be serviced, the xHC will consume (at most) one TD.  A TD
1857  * (comprised of sg list entries) can take several service intervals to
1858  * transmit.
1859  */
1860 int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
1861                 struct urb *urb, int slot_id, unsigned int ep_index)
1862 {
1863         struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci,
1864                         xhci->devs[slot_id]->out_ctx, ep_index);
1865         int xhci_interval;
1866         int ep_interval;
1867
1868         xhci_interval = EP_INTERVAL_TO_UFRAMES(ep_ctx->ep_info);
1869         ep_interval = urb->interval;
1870         /* Convert to microframes */
1871         if (urb->dev->speed == USB_SPEED_LOW ||
1872                         urb->dev->speed == USB_SPEED_FULL)
1873                 ep_interval *= 8;
1874         /* FIXME change this to a warning and a suggestion to use the new API
1875          * to set the polling interval (once the API is added).
1876          */
1877         if (xhci_interval != ep_interval) {
1878                 if (!printk_ratelimit())
1879                         dev_dbg(&urb->dev->dev, "Driver uses different interval"
1880                                         " (%d microframe%s) than xHCI "
1881                                         "(%d microframe%s)\n",
1882                                         ep_interval,
1883                                         ep_interval == 1 ? "" : "s",
1884                                         xhci_interval,
1885                                         xhci_interval == 1 ? "" : "s");
1886                 urb->interval = xhci_interval;
1887                 /* Convert back to frames for LS/FS devices */
1888                 if (urb->dev->speed == USB_SPEED_LOW ||
1889                                 urb->dev->speed == USB_SPEED_FULL)
1890                         urb->interval /= 8;
1891         }
1892         return xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb, slot_id, ep_index);
1893 }
1894
1895 /*
1896  * The TD size is the number of bytes remaining in the TD (including this TRB),
1897  * right shifted by 10.
1898  * It must fit in bits 21:17, so it can't be bigger than 31.
1899  */
1900 static u32 xhci_td_remainder(unsigned int remainder)
1901 {
1902         u32 max = (1 << (21 - 17 + 1)) - 1;
1903
1904         if ((remainder >> 10) >= max)
1905                 return max << 17;
1906         else
1907                 return (remainder >> 10) << 17;
1908 }
1909
1910 static int queue_bulk_sg_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
1911                 struct urb *urb, int slot_id, unsigned int ep_index)
1912 {
1913         struct xhci_ring *ep_ring;
1914         unsigned int num_trbs;
1915         struct xhci_td *td;
1916         struct scatterlist *sg;
1917         int num_sgs;
1918         int trb_buff_len, this_sg_len, running_total;
1919         bool first_trb;
1920         u64 addr;
1921
1922         struct xhci_generic_trb *start_trb;
1923         int start_cycle;
1924
1925         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1926         if (!ep_ring)
1927                 return -EINVAL;
1928
1929         num_trbs = count_sg_trbs_needed(xhci, urb);
1930         num_sgs = urb->num_sgs;
1931
1932         trb_buff_len = prepare_transfer(xhci, xhci->devs[slot_id],
1933                         ep_index, urb->stream_id,
1934                         num_trbs, urb, &td, mem_flags);
1935         if (trb_buff_len < 0)
1936                 return trb_buff_len;
1937         /*
1938          * Don't give the first TRB to the hardware (by toggling the cycle bit)
1939          * until we've finished creating all the other TRBs.  The ring's cycle
1940          * state may change as we enqueue the other TRBs, so save it too.
1941          */
1942         start_trb = &ep_ring->enqueue->generic;
1943         start_cycle = ep_ring->cycle_state;
1944
1945         running_total = 0;
1946         /*
1947          * How much data is in the first TRB?
1948          *
1949          * There are three forces at work for TRB buffer pointers and lengths:
1950          * 1. We don't want to walk off the end of this sg-list entry buffer.
1951          * 2. The transfer length that the driver requested may be smaller than
1952          *    the amount of memory allocated for this scatter-gather list.
1953          * 3. TRBs buffers can't cross 64KB boundaries.
1954          */
1955         sg = urb->sg;
1956         addr = (u64) sg_dma_address(sg);
1957         this_sg_len = sg_dma_len(sg);
1958         trb_buff_len = TRB_MAX_BUFF_SIZE -
1959                 (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
1960         trb_buff_len = min_t(int, trb_buff_len, this_sg_len);
1961         if (trb_buff_len > urb->transfer_buffer_length)
1962                 trb_buff_len = urb->transfer_buffer_length;
1963         xhci_dbg(xhci, "First length to xfer from 1st sglist entry = %u\n",
1964                         trb_buff_len);
1965
1966         first_trb = true;
1967         /* Queue the first TRB, even if it's zero-length */
1968         do {
1969                 u32 field = 0;
1970                 u32 length_field = 0;
1971                 u32 remainder = 0;
1972
1973                 /* Don't change the cycle bit of the first TRB until later */
1974                 if (first_trb)
1975                         first_trb = false;
1976                 else
1977                         field |= ep_ring->cycle_state;
1978
1979                 /* Chain all the TRBs together; clear the chain bit in the last
1980                  * TRB to indicate it's the last TRB in the chain.
1981                  */
1982                 if (num_trbs > 1) {
1983                         field |= TRB_CHAIN;
1984                 } else {
1985                         /* FIXME - add check for ZERO_PACKET flag before this */
1986                         td->last_trb = ep_ring->enqueue;
1987                         field |= TRB_IOC;
1988                 }
1989                 xhci_dbg(xhci, " sg entry: dma = %#x, len = %#x (%d), "
1990                                 "64KB boundary at %#x, end dma = %#x\n",
1991                                 (unsigned int) addr, trb_buff_len, trb_buff_len,
1992                                 (unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1),
1993                                 (unsigned int) addr + trb_buff_len);
1994                 if (TRB_MAX_BUFF_SIZE -
1995                                 (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1)) < trb_buff_len) {
1996                         xhci_warn(xhci, "WARN: sg dma xfer crosses 64KB boundaries!\n");
1997                         xhci_dbg(xhci, "Next boundary at %#x, end dma = %#x\n",
1998                                         (unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1),
1999                                         (unsigned int) addr + trb_buff_len);
2000                 }
2001                 remainder = xhci_td_remainder(urb->transfer_buffer_length -
2002                                 running_total) ;
2003                 length_field = TRB_LEN(trb_buff_len) |
2004                         remainder |
2005                         TRB_INTR_TARGET(0);
2006                 queue_trb(xhci, ep_ring, false,
2007                                 lower_32_bits(addr),
2008                                 upper_32_bits(addr),
2009                                 length_field,
2010                                 /* We always want to know if the TRB was short,
2011                                  * or we won't get an event when it completes.
2012                                  * (Unless we use event data TRBs, which are a
2013                                  * waste of space and HC resources.)
2014                                  */
2015                                 field | TRB_ISP | TRB_TYPE(TRB_NORMAL));
2016                 --num_trbs;
2017                 running_total += trb_buff_len;
2018
2019                 /* Calculate length for next transfer --
2020                  * Are we done queueing all the TRBs for this sg entry?
2021                  */
2022                 this_sg_len -= trb_buff_len;
2023                 if (this_sg_len == 0) {
2024                         --num_sgs;
2025                         if (num_sgs == 0)
2026                                 break;
2027                         sg = sg_next(sg);
2028                         addr = (u64) sg_dma_address(sg);
2029                         this_sg_len = sg_dma_len(sg);
2030                 } else {
2031                         addr += trb_buff_len;
2032                 }
2033
2034                 trb_buff_len = TRB_MAX_BUFF_SIZE -
2035                         (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
2036                 trb_buff_len = min_t(int, trb_buff_len, this_sg_len);
2037                 if (running_total + trb_buff_len > urb->transfer_buffer_length)
2038                         trb_buff_len =
2039                                 urb->transfer_buffer_length - running_total;
2040         } while (running_total < urb->transfer_buffer_length);
2041
2042         check_trb_math(urb, num_trbs, running_total);
2043         giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
2044                         start_cycle, start_trb, td);
2045         return 0;
2046 }
2047
2048 /* This is very similar to what ehci-q.c qtd_fill() does */
2049 int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
2050                 struct urb *urb, int slot_id, unsigned int ep_index)
2051 {
2052         struct xhci_ring *ep_ring;
2053         struct xhci_td *td;
2054         int num_trbs;
2055         struct xhci_generic_trb *start_trb;
2056         bool first_trb;
2057         int start_cycle;
2058         u32 field, length_field;
2059
2060         int running_total, trb_buff_len, ret;
2061         u64 addr;
2062
2063         if (urb->num_sgs)
2064                 return queue_bulk_sg_tx(xhci, mem_flags, urb, slot_id, ep_index);
2065
2066         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
2067         if (!ep_ring)
2068                 return -EINVAL;
2069
2070         num_trbs = 0;
2071         /* How much data is (potentially) left before the 64KB boundary? */
2072         running_total = TRB_MAX_BUFF_SIZE -
2073                 (urb->transfer_dma & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
2074
2075         /* If there's some data on this 64KB chunk, or we have to send a
2076          * zero-length transfer, we need at least one TRB
2077          */
2078         if (running_total != 0 || urb->transfer_buffer_length == 0)
2079                 num_trbs++;
2080         /* How many more 64KB chunks to transfer, how many more TRBs? */
2081         while (running_total < urb->transfer_buffer_length) {
2082                 num_trbs++;
2083                 running_total += TRB_MAX_BUFF_SIZE;
2084         }
2085         /* FIXME: this doesn't deal with URB_ZERO_PACKET - need one more */
2086
2087         if (!in_interrupt())
2088                 dev_dbg(&urb->dev->dev, "ep %#x - urb len = %#x (%d), addr = %#llx, num_trbs = %d\n",
2089                                 urb->ep->desc.bEndpointAddress,
2090                                 urb->transfer_buffer_length,
2091                                 urb->transfer_buffer_length,
2092                                 (unsigned long long)urb->transfer_dma,
2093                                 num_trbs);
2094
2095         ret = prepare_transfer(xhci, xhci->devs[slot_id],
2096                         ep_index, urb->stream_id,
2097                         num_trbs, urb, &td, mem_flags);
2098         if (ret < 0)
2099                 return ret;
2100
2101         /*
2102          * Don't give the first TRB to the hardware (by toggling the cycle bit)
2103          * until we've finished creating all the other TRBs.  The ring's cycle
2104          * state may change as we enqueue the other TRBs, so save it too.
2105          */
2106         start_trb = &ep_ring->enqueue->generic;
2107         start_cycle = ep_ring->cycle_state;
2108
2109         running_total = 0;
2110         /* How much data is in the first TRB? */
2111         addr = (u64) urb->transfer_dma;
2112         trb_buff_len = TRB_MAX_BUFF_SIZE -
2113                 (urb->transfer_dma & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
2114         if (urb->transfer_buffer_length < trb_buff_len)
2115                 trb_buff_len = urb->transfer_buffer_length;
2116
2117         first_trb = true;
2118
2119         /* Queue the first TRB, even if it's zero-length */
2120         do {
2121                 u32 remainder = 0;
2122                 field = 0;
2123
2124                 /* Don't change the cycle bit of the first TRB until later */
2125                 if (first_trb)
2126                         first_trb = false;
2127                 else
2128                         field |= ep_ring->cycle_state;
2129
2130                 /* Chain all the TRBs together; clear the chain bit in the last
2131                  * TRB to indicate it's the last TRB in the chain.
2132                  */
2133                 if (num_trbs > 1) {
2134                         field |= TRB_CHAIN;
2135                 } else {
2136                         /* FIXME - add check for ZERO_PACKET flag before this */
2137                         td->last_trb = ep_ring->enqueue;
2138                         field |= TRB_IOC;
2139                 }
2140                 remainder = xhci_td_remainder(urb->transfer_buffer_length -
2141                                 running_total);
2142                 length_field = TRB_LEN(trb_buff_len) |
2143                         remainder |
2144                         TRB_INTR_TARGET(0);
2145                 queue_trb(xhci, ep_ring, false,
2146                                 lower_32_bits(addr),
2147                                 upper_32_bits(addr),
2148                                 length_field,
2149                                 /* We always want to know if the TRB was short,
2150                                  * or we won't get an event when it completes.
2151                                  * (Unless we use event data TRBs, which are a
2152                                  * waste of space and HC resources.)
2153                                  */
2154                                 field | TRB_ISP | TRB_TYPE(TRB_NORMAL));
2155                 --num_trbs;
2156                 running_total += trb_buff_len;
2157
2158                 /* Calculate length for next transfer */
2159                 addr += trb_buff_len;
2160                 trb_buff_len = urb->transfer_buffer_length - running_total;
2161                 if (trb_buff_len > TRB_MAX_BUFF_SIZE)
2162                         trb_buff_len = TRB_MAX_BUFF_SIZE;
2163         } while (running_total < urb->transfer_buffer_length);
2164
2165         check_trb_math(urb, num_trbs, running_total);
2166         giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
2167                         start_cycle, start_trb, td);
2168         return 0;
2169 }
2170
2171 /* Caller must have locked xhci->lock */
2172 int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
2173                 struct urb *urb, int slot_id, unsigned int ep_index)
2174 {
2175         struct xhci_ring *ep_ring;
2176         int num_trbs;
2177         int ret;
2178         struct usb_ctrlrequest *setup;
2179         struct xhci_generic_trb *start_trb;
2180         int start_cycle;
2181         u32 field, length_field;
2182         struct xhci_td *td;
2183
2184         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
2185         if (!ep_ring)
2186                 return -EINVAL;
2187
2188         /*
2189          * Need to copy setup packet into setup TRB, so we can't use the setup
2190          * DMA address.
2191          */
2192         if (!urb->setup_packet)
2193                 return -EINVAL;
2194
2195         if (!in_interrupt())
2196                 xhci_dbg(xhci, "Queueing ctrl tx for slot id %d, ep %d\n",
2197                                 slot_id, ep_index);
2198         /* 1 TRB for setup, 1 for status */
2199         num_trbs = 2;
2200         /*
2201          * Don't need to check if we need additional event data and normal TRBs,
2202          * since data in control transfers will never get bigger than 16MB
2203          * XXX: can we get a buffer that crosses 64KB boundaries?
2204          */
2205         if (urb->transfer_buffer_length > 0)
2206                 num_trbs++;
2207         ret = prepare_transfer(xhci, xhci->devs[slot_id],
2208                         ep_index, urb->stream_id,
2209                         num_trbs, urb, &td, mem_flags);
2210         if (ret < 0)
2211                 return ret;
2212
2213         /*
2214          * Don't give the first TRB to the hardware (by toggling the cycle bit)
2215          * until we've finished creating all the other TRBs.  The ring's cycle
2216          * state may change as we enqueue the other TRBs, so save it too.
2217          */
2218         start_trb = &ep_ring->enqueue->generic;
2219         start_cycle = ep_ring->cycle_state;
2220
2221         /* Queue setup TRB - see section 6.4.1.2.1 */
2222         /* FIXME better way to translate setup_packet into two u32 fields? */
2223         setup = (struct usb_ctrlrequest *) urb->setup_packet;
2224         queue_trb(xhci, ep_ring, false,
2225                         /* FIXME endianness is probably going to bite my ass here. */
2226                         setup->bRequestType | setup->bRequest << 8 | setup->wValue << 16,
2227                         setup->wIndex | setup->wLength << 16,
2228                         TRB_LEN(8) | TRB_INTR_TARGET(0),
2229                         /* Immediate data in pointer */
2230                         TRB_IDT | TRB_TYPE(TRB_SETUP));
2231
2232         /* If there's data, queue data TRBs */
2233         field = 0;
2234         length_field = TRB_LEN(urb->transfer_buffer_length) |
2235                 xhci_td_remainder(urb->transfer_buffer_length) |
2236                 TRB_INTR_TARGET(0);
2237         if (urb->transfer_buffer_length > 0) {
2238                 if (setup->bRequestType & USB_DIR_IN)
2239                         field |= TRB_DIR_IN;
2240                 queue_trb(xhci, ep_ring, false,
2241                                 lower_32_bits(urb->transfer_dma),
2242                                 upper_32_bits(urb->transfer_dma),
2243                                 length_field,
2244                                 /* Event on short tx */
2245                                 field | TRB_ISP | TRB_TYPE(TRB_DATA) | ep_ring->cycle_state);
2246         }
2247
2248         /* Save the DMA address of the last TRB in the TD */
2249         td->last_trb = ep_ring->enqueue;
2250
2251         /* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */
2252         /* If the device sent data, the status stage is an OUT transfer */
2253         if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN)
2254                 field = 0;
2255         else
2256                 field = TRB_DIR_IN;
2257         queue_trb(xhci, ep_ring, false,
2258                         0,
2259                         0,
2260                         TRB_INTR_TARGET(0),
2261                         /* Event on completion */
2262                         field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state);
2263
2264         giveback_first_trb(xhci, slot_id, ep_index, 0,
2265                         start_cycle, start_trb, td);
2266         return 0;
2267 }
2268
2269 /****           Command Ring Operations         ****/
2270
2271 /* Generic function for queueing a command TRB on the command ring.
2272  * Check to make sure there's room on the command ring for one command TRB.
2273  * Also check that there's room reserved for commands that must not fail.
2274  * If this is a command that must not fail, meaning command_must_succeed = TRUE,
2275  * then only check for the number of reserved spots.
2276  * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB
2277  * because the command event handler may want to resubmit a failed command.
2278  */
2279 static int queue_command(struct xhci_hcd *xhci, u32 field1, u32 field2,
2280                 u32 field3, u32 field4, bool command_must_succeed)
2281 {
2282         int reserved_trbs = xhci->cmd_ring_reserved_trbs;
2283         if (!command_must_succeed)
2284                 reserved_trbs++;
2285
2286         if (!room_on_ring(xhci, xhci->cmd_ring, reserved_trbs)) {
2287                 if (!in_interrupt())
2288                         xhci_err(xhci, "ERR: No room for command on command ring\n");
2289                 if (command_must_succeed)
2290                         xhci_err(xhci, "ERR: Reserved TRB counting for "
2291                                         "unfailable commands failed.\n");
2292                 return -ENOMEM;
2293         }
2294         queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3,
2295                         field4 | xhci->cmd_ring->cycle_state);
2296         return 0;
2297 }
2298
2299 /* Queue a no-op command on the command ring */
2300 static int queue_cmd_noop(struct xhci_hcd *xhci)
2301 {
2302         return queue_command(xhci, 0, 0, 0, TRB_TYPE(TRB_CMD_NOOP), false);
2303 }
2304
2305 /*
2306  * Place a no-op command on the command ring to test the command and
2307  * event ring.
2308  */
2309 void *xhci_setup_one_noop(struct xhci_hcd *xhci)
2310 {
2311         if (queue_cmd_noop(xhci) < 0)
2312                 return NULL;
2313         xhci->noops_submitted++;
2314         return xhci_ring_cmd_db;
2315 }
2316
2317 /* Queue a slot enable or disable request on the command ring */
2318 int xhci_queue_slot_control(struct xhci_hcd *xhci, u32 trb_type, u32 slot_id)
2319 {
2320         return queue_command(xhci, 0, 0, 0,
2321                         TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false);
2322 }
2323
2324 /* Queue an address device command TRB */
2325 int xhci_queue_address_device(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
2326                 u32 slot_id)
2327 {
2328         return queue_command(xhci, lower_32_bits(in_ctx_ptr),
2329                         upper_32_bits(in_ctx_ptr), 0,
2330                         TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id),
2331                         false);
2332 }
2333
2334 /* Queue a reset device command TRB */
2335 int xhci_queue_reset_device(struct xhci_hcd *xhci, u32 slot_id)
2336 {
2337         return queue_command(xhci, 0, 0, 0,
2338                         TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id),
2339                         false);
2340 }
2341
2342 /* Queue a configure endpoint command TRB */
2343 int xhci_queue_configure_endpoint(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
2344                 u32 slot_id, bool command_must_succeed)
2345 {
2346         return queue_command(xhci, lower_32_bits(in_ctx_ptr),
2347                         upper_32_bits(in_ctx_ptr), 0,
2348                         TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id),
2349                         command_must_succeed);
2350 }
2351
2352 /* Queue an evaluate context command TRB */
2353 int xhci_queue_evaluate_context(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
2354                 u32 slot_id)
2355 {
2356         return queue_command(xhci, lower_32_bits(in_ctx_ptr),
2357                         upper_32_bits(in_ctx_ptr), 0,
2358                         TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id),
2359                         false);
2360 }
2361
2362 int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, int slot_id,
2363                 unsigned int ep_index)
2364 {
2365         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
2366         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
2367         u32 type = TRB_TYPE(TRB_STOP_RING);
2368
2369         return queue_command(xhci, 0, 0, 0,
2370                         trb_slot_id | trb_ep_index | type, false);
2371 }
2372
2373 /* Set Transfer Ring Dequeue Pointer command.
2374  * This should not be used for endpoints that have streams enabled.
2375  */
2376 static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id,
2377                 unsigned int ep_index, unsigned int stream_id,
2378                 struct xhci_segment *deq_seg,
2379                 union xhci_trb *deq_ptr, u32 cycle_state)
2380 {
2381         dma_addr_t addr;
2382         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
2383         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
2384         u32 trb_stream_id = STREAM_ID_FOR_TRB(stream_id);
2385         u32 type = TRB_TYPE(TRB_SET_DEQ);
2386
2387         addr = xhci_trb_virt_to_dma(deq_seg, deq_ptr);
2388         if (addr == 0) {
2389                 xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n");
2390                 xhci_warn(xhci, "WARN deq seg = %p, deq pt = %p\n",
2391                                 deq_seg, deq_ptr);
2392                 return 0;
2393         }
2394         return queue_command(xhci, lower_32_bits(addr) | cycle_state,
2395                         upper_32_bits(addr), trb_stream_id,
2396                         trb_slot_id | trb_ep_index | type, false);
2397 }
2398
2399 int xhci_queue_reset_ep(struct xhci_hcd *xhci, int slot_id,
2400                 unsigned int ep_index)
2401 {
2402         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
2403         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
2404         u32 type = TRB_TYPE(TRB_RESET_EP);
2405
2406         return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type,
2407                         false);
2408 }