9e27eb0c7004d31e03f4cc63fde93b99ddf08137
[firefly-linux-kernel-4.4.55.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
1170         xhci_ring_cmd_db(xhci);
1171 }
1172
1173 /* Check if an error has halted the endpoint ring.  The class driver will
1174  * cleanup the halt for a non-default control endpoint if we indicate a stall.
1175  * However, a babble and other errors also halt the endpoint ring, and the class
1176  * driver won't clear the halt in that case, so we need to issue a Set Transfer
1177  * Ring Dequeue Pointer command manually.
1178  */
1179 static int xhci_requires_manual_halt_cleanup(struct xhci_hcd *xhci,
1180                 struct xhci_ep_ctx *ep_ctx,
1181                 unsigned int trb_comp_code)
1182 {
1183         /* TRB completion codes that may require a manual halt cleanup */
1184         if (trb_comp_code == COMP_TX_ERR ||
1185                         trb_comp_code == COMP_BABBLE ||
1186                         trb_comp_code == COMP_SPLIT_ERR)
1187                 /* The 0.96 spec says a babbling control endpoint
1188                  * is not halted. The 0.96 spec says it is.  Some HW
1189                  * claims to be 0.95 compliant, but it halts the control
1190                  * endpoint anyway.  Check if a babble halted the
1191                  * endpoint.
1192                  */
1193                 if ((ep_ctx->ep_info & EP_STATE_MASK) == EP_STATE_HALTED)
1194                         return 1;
1195
1196         return 0;
1197 }
1198
1199 int xhci_is_vendor_info_code(struct xhci_hcd *xhci, unsigned int trb_comp_code)
1200 {
1201         if (trb_comp_code >= 224 && trb_comp_code <= 255) {
1202                 /* Vendor defined "informational" completion code,
1203                  * treat as not-an-error.
1204                  */
1205                 xhci_dbg(xhci, "Vendor defined info completion code %u\n",
1206                                 trb_comp_code);
1207                 xhci_dbg(xhci, "Treating code as success.\n");
1208                 return 1;
1209         }
1210         return 0;
1211 }
1212
1213 /*
1214  * If this function returns an error condition, it means it got a Transfer
1215  * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address.
1216  * At this point, the host controller is probably hosed and should be reset.
1217  */
1218 static int handle_tx_event(struct xhci_hcd *xhci,
1219                 struct xhci_transfer_event *event)
1220 {
1221         struct xhci_virt_device *xdev;
1222         struct xhci_virt_ep *ep;
1223         struct xhci_ring *ep_ring;
1224         unsigned int slot_id;
1225         int ep_index;
1226         struct xhci_td *td = NULL;
1227         dma_addr_t event_dma;
1228         struct xhci_segment *event_seg;
1229         union xhci_trb *event_trb;
1230         struct urb *urb = NULL;
1231         int status = -EINPROGRESS;
1232         struct xhci_ep_ctx *ep_ctx;
1233         u32 trb_comp_code;
1234
1235         xhci_dbg(xhci, "In %s\n", __func__);
1236         slot_id = TRB_TO_SLOT_ID(event->flags);
1237         xdev = xhci->devs[slot_id];
1238         if (!xdev) {
1239                 xhci_err(xhci, "ERROR Transfer event pointed to bad slot\n");
1240                 return -ENODEV;
1241         }
1242
1243         /* Endpoint ID is 1 based, our index is zero based */
1244         ep_index = TRB_TO_EP_ID(event->flags) - 1;
1245         xhci_dbg(xhci, "%s - ep index = %d\n", __func__, ep_index);
1246         ep = &xdev->eps[ep_index];
1247         ep_ring = xhci_dma_to_transfer_ring(ep, event->buffer);
1248         ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
1249         if (!ep_ring || (ep_ctx->ep_info & EP_STATE_MASK) == EP_STATE_DISABLED) {
1250                 xhci_err(xhci, "ERROR Transfer event for disabled endpoint "
1251                                 "or incorrect stream ring\n");
1252                 return -ENODEV;
1253         }
1254
1255         event_dma = event->buffer;
1256         /* This TRB should be in the TD at the head of this ring's TD list */
1257         xhci_dbg(xhci, "%s - checking for list empty\n", __func__);
1258         if (list_empty(&ep_ring->td_list)) {
1259                 xhci_warn(xhci, "WARN Event TRB for slot %d ep %d with no TDs queued?\n",
1260                                 TRB_TO_SLOT_ID(event->flags), ep_index);
1261                 xhci_dbg(xhci, "Event TRB with TRB type ID %u\n",
1262                                 (unsigned int) (event->flags & TRB_TYPE_BITMASK)>>10);
1263                 xhci_print_trb_offsets(xhci, (union xhci_trb *) event);
1264                 urb = NULL;
1265                 goto cleanup;
1266         }
1267         xhci_dbg(xhci, "%s - getting list entry\n", __func__);
1268         td = list_entry(ep_ring->td_list.next, struct xhci_td, td_list);
1269
1270         /* Is this a TRB in the currently executing TD? */
1271         xhci_dbg(xhci, "%s - looking for TD\n", __func__);
1272         event_seg = trb_in_td(ep_ring->deq_seg, ep_ring->dequeue,
1273                         td->last_trb, event_dma);
1274         xhci_dbg(xhci, "%s - found event_seg = %p\n", __func__, event_seg);
1275         if (!event_seg) {
1276                 /* HC is busted, give up! */
1277                 xhci_err(xhci, "ERROR Transfer event TRB DMA ptr not part of current TD\n");
1278                 return -ESHUTDOWN;
1279         }
1280         event_trb = &event_seg->trbs[(event_dma - event_seg->dma) / sizeof(*event_trb)];
1281         xhci_dbg(xhci, "Event TRB with TRB type ID %u\n",
1282                         (unsigned int) (event->flags & TRB_TYPE_BITMASK)>>10);
1283         xhci_dbg(xhci, "Offset 0x00 (buffer lo) = 0x%x\n",
1284                         lower_32_bits(event->buffer));
1285         xhci_dbg(xhci, "Offset 0x04 (buffer hi) = 0x%x\n",
1286                         upper_32_bits(event->buffer));
1287         xhci_dbg(xhci, "Offset 0x08 (transfer length) = 0x%x\n",
1288                         (unsigned int) event->transfer_len);
1289         xhci_dbg(xhci, "Offset 0x0C (flags) = 0x%x\n",
1290                         (unsigned int) event->flags);
1291
1292         /* Look for common error cases */
1293         trb_comp_code = GET_COMP_CODE(event->transfer_len);
1294         switch (trb_comp_code) {
1295         /* Skip codes that require special handling depending on
1296          * transfer type
1297          */
1298         case COMP_SUCCESS:
1299         case COMP_SHORT_TX:
1300                 break;
1301         case COMP_STOP:
1302                 xhci_dbg(xhci, "Stopped on Transfer TRB\n");
1303                 break;
1304         case COMP_STOP_INVAL:
1305                 xhci_dbg(xhci, "Stopped on No-op or Link TRB\n");
1306                 break;
1307         case COMP_STALL:
1308                 xhci_warn(xhci, "WARN: Stalled endpoint\n");
1309                 ep->ep_state |= EP_HALTED;
1310                 status = -EPIPE;
1311                 break;
1312         case COMP_TRB_ERR:
1313                 xhci_warn(xhci, "WARN: TRB error on endpoint\n");
1314                 status = -EILSEQ;
1315                 break;
1316         case COMP_SPLIT_ERR:
1317         case COMP_TX_ERR:
1318                 xhci_warn(xhci, "WARN: transfer error on endpoint\n");
1319                 status = -EPROTO;
1320                 break;
1321         case COMP_BABBLE:
1322                 xhci_warn(xhci, "WARN: babble error on endpoint\n");
1323                 status = -EOVERFLOW;
1324                 break;
1325         case COMP_DB_ERR:
1326                 xhci_warn(xhci, "WARN: HC couldn't access mem fast enough\n");
1327                 status = -ENOSR;
1328                 break;
1329         default:
1330                 if (xhci_is_vendor_info_code(xhci, trb_comp_code)) {
1331                         status = 0;
1332                         break;
1333                 }
1334                 xhci_warn(xhci, "ERROR Unknown event condition, HC probably busted\n");
1335                 urb = NULL;
1336                 goto cleanup;
1337         }
1338         /* Now update the urb's actual_length and give back to the core */
1339         /* Was this a control transfer? */
1340         if (usb_endpoint_xfer_control(&td->urb->ep->desc)) {
1341                 xhci_debug_trb(xhci, xhci->event_ring->dequeue);
1342                 switch (trb_comp_code) {
1343                 case COMP_SUCCESS:
1344                         if (event_trb == ep_ring->dequeue) {
1345                                 xhci_warn(xhci, "WARN: Success on ctrl setup TRB without IOC set??\n");
1346                                 status = -ESHUTDOWN;
1347                         } else if (event_trb != td->last_trb) {
1348                                 xhci_warn(xhci, "WARN: Success on ctrl data TRB without IOC set??\n");
1349                                 status = -ESHUTDOWN;
1350                         } else {
1351                                 xhci_dbg(xhci, "Successful control transfer!\n");
1352                                 status = 0;
1353                         }
1354                         break;
1355                 case COMP_SHORT_TX:
1356                         xhci_warn(xhci, "WARN: short transfer on control ep\n");
1357                         if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1358                                 status = -EREMOTEIO;
1359                         else
1360                                 status = 0;
1361                         break;
1362
1363                 default:
1364                         if (!xhci_requires_manual_halt_cleanup(xhci,
1365                                                 ep_ctx, trb_comp_code))
1366                                 break;
1367                         xhci_dbg(xhci, "TRB error code %u, "
1368                                         "halted endpoint index = %u\n",
1369                                         trb_comp_code, ep_index);
1370                         /* else fall through */
1371                 case COMP_STALL:
1372                         /* Did we transfer part of the data (middle) phase? */
1373                         if (event_trb != ep_ring->dequeue &&
1374                                         event_trb != td->last_trb)
1375                                 td->urb->actual_length =
1376                                         td->urb->transfer_buffer_length
1377                                         - TRB_LEN(event->transfer_len);
1378                         else
1379                                 td->urb->actual_length = 0;
1380
1381                         xhci_cleanup_halted_endpoint(xhci,
1382                                         slot_id, ep_index, 0, td, event_trb);
1383                         goto td_cleanup;
1384                 }
1385                 /*
1386                  * Did we transfer any data, despite the errors that might have
1387                  * happened?  I.e. did we get past the setup stage?
1388                  */
1389                 if (event_trb != ep_ring->dequeue) {
1390                         /* The event was for the status stage */
1391                         if (event_trb == td->last_trb) {
1392                                 if (td->urb->actual_length != 0) {
1393                                         /* Don't overwrite a previously set error code */
1394                                         if ((status == -EINPROGRESS ||
1395                                                                 status == 0) &&
1396                                                         (td->urb->transfer_flags
1397                                                          & URB_SHORT_NOT_OK))
1398                                                 /* Did we already see a short data stage? */
1399                                                 status = -EREMOTEIO;
1400                                 } else {
1401                                         td->urb->actual_length =
1402                                                 td->urb->transfer_buffer_length;
1403                                 }
1404                         } else {
1405                         /* Maybe the event was for the data stage? */
1406                                 if (trb_comp_code != COMP_STOP_INVAL) {
1407                                         /* We didn't stop on a link TRB in the middle */
1408                                         td->urb->actual_length =
1409                                                 td->urb->transfer_buffer_length -
1410                                                 TRB_LEN(event->transfer_len);
1411                                         xhci_dbg(xhci, "Waiting for status stage event\n");
1412                                         urb = NULL;
1413                                         goto cleanup;
1414                                 }
1415                         }
1416                 }
1417         } else {
1418                 switch (trb_comp_code) {
1419                 case COMP_SUCCESS:
1420                         /* Double check that the HW transferred everything. */
1421                         if (event_trb != td->last_trb) {
1422                                 xhci_warn(xhci, "WARN Successful completion "
1423                                                 "on short TX\n");
1424                                 if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1425                                         status = -EREMOTEIO;
1426                                 else
1427                                         status = 0;
1428                         } else {
1429                                 if (usb_endpoint_xfer_bulk(&td->urb->ep->desc))
1430                                         xhci_dbg(xhci, "Successful bulk "
1431                                                         "transfer!\n");
1432                                 else
1433                                         xhci_dbg(xhci, "Successful interrupt "
1434                                                         "transfer!\n");
1435                                 status = 0;
1436                         }
1437                         break;
1438                 case COMP_SHORT_TX:
1439                         if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1440                                 status = -EREMOTEIO;
1441                         else
1442                                 status = 0;
1443                         break;
1444                 default:
1445                         /* Others already handled above */
1446                         break;
1447                 }
1448                 dev_dbg(&td->urb->dev->dev,
1449                                 "ep %#x - asked for %d bytes, "
1450                                 "%d bytes untransferred\n",
1451                                 td->urb->ep->desc.bEndpointAddress,
1452                                 td->urb->transfer_buffer_length,
1453                                 TRB_LEN(event->transfer_len));
1454                 /* Fast path - was this the last TRB in the TD for this URB? */
1455                 if (event_trb == td->last_trb) {
1456                         if (TRB_LEN(event->transfer_len) != 0) {
1457                                 td->urb->actual_length =
1458                                         td->urb->transfer_buffer_length -
1459                                         TRB_LEN(event->transfer_len);
1460                                 if (td->urb->transfer_buffer_length <
1461                                                 td->urb->actual_length) {
1462                                         xhci_warn(xhci, "HC gave bad length "
1463                                                         "of %d bytes left\n",
1464                                                         TRB_LEN(event->transfer_len));
1465                                         td->urb->actual_length = 0;
1466                                         if (td->urb->transfer_flags &
1467                                                         URB_SHORT_NOT_OK)
1468                                                 status = -EREMOTEIO;
1469                                         else
1470                                                 status = 0;
1471                                 }
1472                                 /* Don't overwrite a previously set error code */
1473                                 if (status == -EINPROGRESS) {
1474                                         if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1475                                                 status = -EREMOTEIO;
1476                                         else
1477                                                 status = 0;
1478                                 }
1479                         } else {
1480                                 td->urb->actual_length = td->urb->transfer_buffer_length;
1481                                 /* Ignore a short packet completion if the
1482                                  * untransferred length was zero.
1483                                  */
1484                                 if (status == -EREMOTEIO)
1485                                         status = 0;
1486                         }
1487                 } else {
1488                         /* Slow path - walk the list, starting from the dequeue
1489                          * pointer, to get the actual length transferred.
1490                          */
1491                         union xhci_trb *cur_trb;
1492                         struct xhci_segment *cur_seg;
1493
1494                         td->urb->actual_length = 0;
1495                         for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg;
1496                                         cur_trb != event_trb;
1497                                         next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) {
1498                                 if (TRB_TYPE(cur_trb->generic.field[3]) != TRB_TR_NOOP &&
1499                                                 TRB_TYPE(cur_trb->generic.field[3]) != TRB_LINK)
1500                                         td->urb->actual_length +=
1501                                                 TRB_LEN(cur_trb->generic.field[2]);
1502                         }
1503                         /* If the ring didn't stop on a Link or No-op TRB, add
1504                          * in the actual bytes transferred from the Normal TRB
1505                          */
1506                         if (trb_comp_code != COMP_STOP_INVAL)
1507                                 td->urb->actual_length +=
1508                                         TRB_LEN(cur_trb->generic.field[2]) -
1509                                         TRB_LEN(event->transfer_len);
1510                 }
1511         }
1512         if (trb_comp_code == COMP_STOP_INVAL ||
1513                         trb_comp_code == COMP_STOP) {
1514                 /* The Endpoint Stop Command completion will take care of any
1515                  * stopped TDs.  A stopped TD may be restarted, so don't update
1516                  * the ring dequeue pointer or take this TD off any lists yet.
1517                  */
1518                 ep->stopped_td = td;
1519                 ep->stopped_trb = event_trb;
1520         } else {
1521                 if (trb_comp_code == COMP_STALL) {
1522                         /* The transfer is completed from the driver's
1523                          * perspective, but we need to issue a set dequeue
1524                          * command for this stalled endpoint to move the dequeue
1525                          * pointer past the TD.  We can't do that here because
1526                          * the halt condition must be cleared first.  Let the
1527                          * USB class driver clear the stall later.
1528                          */
1529                         ep->stopped_td = td;
1530                         ep->stopped_trb = event_trb;
1531                         ep->stopped_stream = ep_ring->stream_id;
1532                 } else if (xhci_requires_manual_halt_cleanup(xhci,
1533                                         ep_ctx, trb_comp_code)) {
1534                         /* Other types of errors halt the endpoint, but the
1535                          * class driver doesn't call usb_reset_endpoint() unless
1536                          * the error is -EPIPE.  Clear the halted status in the
1537                          * xHCI hardware manually.
1538                          */
1539                         xhci_cleanup_halted_endpoint(xhci,
1540                                         slot_id, ep_index, ep_ring->stream_id, td, event_trb);
1541                 } else {
1542                         /* Update ring dequeue pointer */
1543                         while (ep_ring->dequeue != td->last_trb)
1544                                 inc_deq(xhci, ep_ring, false);
1545                         inc_deq(xhci, ep_ring, false);
1546                 }
1547
1548 td_cleanup:
1549                 /* Clean up the endpoint's TD list */
1550                 urb = td->urb;
1551                 /* Do one last check of the actual transfer length.
1552                  * If the host controller said we transferred more data than
1553                  * the buffer length, urb->actual_length will be a very big
1554                  * number (since it's unsigned).  Play it safe and say we didn't
1555                  * transfer anything.
1556                  */
1557                 if (urb->actual_length > urb->transfer_buffer_length) {
1558                         xhci_warn(xhci, "URB transfer length is wrong, "
1559                                         "xHC issue? req. len = %u, "
1560                                         "act. len = %u\n",
1561                                         urb->transfer_buffer_length,
1562                                         urb->actual_length);
1563                         urb->actual_length = 0;
1564                         if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
1565                                 status = -EREMOTEIO;
1566                         else
1567                                 status = 0;
1568                 }
1569                 list_del(&td->td_list);
1570                 /* Was this TD slated to be cancelled but completed anyway? */
1571                 if (!list_empty(&td->cancelled_td_list))
1572                         list_del(&td->cancelled_td_list);
1573
1574                 /* Leave the TD around for the reset endpoint function to use
1575                  * (but only if it's not a control endpoint, since we already
1576                  * queued the Set TR dequeue pointer command for stalled
1577                  * control endpoints).
1578                  */
1579                 if (usb_endpoint_xfer_control(&urb->ep->desc) ||
1580                         (trb_comp_code != COMP_STALL &&
1581                                 trb_comp_code != COMP_BABBLE)) {
1582                         kfree(td);
1583                 }
1584                 urb->hcpriv = NULL;
1585         }
1586 cleanup:
1587         inc_deq(xhci, xhci->event_ring, true);
1588         xhci_set_hc_event_deq(xhci);
1589
1590         /* FIXME for multi-TD URBs (who have buffers bigger than 64MB) */
1591         if (urb) {
1592                 usb_hcd_unlink_urb_from_ep(xhci_to_hcd(xhci), urb);
1593                 xhci_dbg(xhci, "Giveback URB %p, len = %d, status = %d\n",
1594                                 urb, urb->actual_length, status);
1595                 spin_unlock(&xhci->lock);
1596                 usb_hcd_giveback_urb(xhci_to_hcd(xhci), urb, status);
1597                 spin_lock(&xhci->lock);
1598         }
1599         return 0;
1600 }
1601
1602 /*
1603  * This function handles all OS-owned events on the event ring.  It may drop
1604  * xhci->lock between event processing (e.g. to pass up port status changes).
1605  */
1606 void xhci_handle_event(struct xhci_hcd *xhci)
1607 {
1608         union xhci_trb *event;
1609         int update_ptrs = 1;
1610         int ret;
1611
1612         xhci_dbg(xhci, "In %s\n", __func__);
1613         if (!xhci->event_ring || !xhci->event_ring->dequeue) {
1614                 xhci->error_bitmask |= 1 << 1;
1615                 return;
1616         }
1617
1618         event = xhci->event_ring->dequeue;
1619         /* Does the HC or OS own the TRB? */
1620         if ((event->event_cmd.flags & TRB_CYCLE) !=
1621                         xhci->event_ring->cycle_state) {
1622                 xhci->error_bitmask |= 1 << 2;
1623                 return;
1624         }
1625         xhci_dbg(xhci, "%s - OS owns TRB\n", __func__);
1626
1627         /* FIXME: Handle more event types. */
1628         switch ((event->event_cmd.flags & TRB_TYPE_BITMASK)) {
1629         case TRB_TYPE(TRB_COMPLETION):
1630                 xhci_dbg(xhci, "%s - calling handle_cmd_completion\n", __func__);
1631                 handle_cmd_completion(xhci, &event->event_cmd);
1632                 xhci_dbg(xhci, "%s - returned from handle_cmd_completion\n", __func__);
1633                 break;
1634         case TRB_TYPE(TRB_PORT_STATUS):
1635                 xhci_dbg(xhci, "%s - calling handle_port_status\n", __func__);
1636                 handle_port_status(xhci, event);
1637                 xhci_dbg(xhci, "%s - returned from handle_port_status\n", __func__);
1638                 update_ptrs = 0;
1639                 break;
1640         case TRB_TYPE(TRB_TRANSFER):
1641                 xhci_dbg(xhci, "%s - calling handle_tx_event\n", __func__);
1642                 ret = handle_tx_event(xhci, &event->trans_event);
1643                 xhci_dbg(xhci, "%s - returned from handle_tx_event\n", __func__);
1644                 if (ret < 0)
1645                         xhci->error_bitmask |= 1 << 9;
1646                 else
1647                         update_ptrs = 0;
1648                 break;
1649         default:
1650                 xhci->error_bitmask |= 1 << 3;
1651         }
1652         /* Any of the above functions may drop and re-acquire the lock, so check
1653          * to make sure a watchdog timer didn't mark the host as non-responsive.
1654          */
1655         if (xhci->xhc_state & XHCI_STATE_DYING) {
1656                 xhci_dbg(xhci, "xHCI host dying, returning from "
1657                                 "event handler.\n");
1658                 return;
1659         }
1660
1661         if (update_ptrs) {
1662                 /* Update SW and HC event ring dequeue pointer */
1663                 inc_deq(xhci, xhci->event_ring, true);
1664                 xhci_set_hc_event_deq(xhci);
1665         }
1666         /* Are there more items on the event ring? */
1667         xhci_handle_event(xhci);
1668 }
1669
1670 /****           Endpoint Ring Operations        ****/
1671
1672 /*
1673  * Generic function for queueing a TRB on a ring.
1674  * The caller must have checked to make sure there's room on the ring.
1675  */
1676 static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
1677                 bool consumer,
1678                 u32 field1, u32 field2, u32 field3, u32 field4)
1679 {
1680         struct xhci_generic_trb *trb;
1681
1682         trb = &ring->enqueue->generic;
1683         trb->field[0] = field1;
1684         trb->field[1] = field2;
1685         trb->field[2] = field3;
1686         trb->field[3] = field4;
1687         inc_enq(xhci, ring, consumer);
1688 }
1689
1690 /*
1691  * Does various checks on the endpoint ring, and makes it ready to queue num_trbs.
1692  * FIXME allocate segments if the ring is full.
1693  */
1694 static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
1695                 u32 ep_state, unsigned int num_trbs, gfp_t mem_flags)
1696 {
1697         /* Make sure the endpoint has been added to xHC schedule */
1698         xhci_dbg(xhci, "Endpoint state = 0x%x\n", ep_state);
1699         switch (ep_state) {
1700         case EP_STATE_DISABLED:
1701                 /*
1702                  * USB core changed config/interfaces without notifying us,
1703                  * or hardware is reporting the wrong state.
1704                  */
1705                 xhci_warn(xhci, "WARN urb submitted to disabled ep\n");
1706                 return -ENOENT;
1707         case EP_STATE_ERROR:
1708                 xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n");
1709                 /* FIXME event handling code for error needs to clear it */
1710                 /* XXX not sure if this should be -ENOENT or not */
1711                 return -EINVAL;
1712         case EP_STATE_HALTED:
1713                 xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n");
1714         case EP_STATE_STOPPED:
1715         case EP_STATE_RUNNING:
1716                 break;
1717         default:
1718                 xhci_err(xhci, "ERROR unknown endpoint state for ep\n");
1719                 /*
1720                  * FIXME issue Configure Endpoint command to try to get the HC
1721                  * back into a known state.
1722                  */
1723                 return -EINVAL;
1724         }
1725         if (!room_on_ring(xhci, ep_ring, num_trbs)) {
1726                 /* FIXME allocate more room */
1727                 xhci_err(xhci, "ERROR no room on ep ring\n");
1728                 return -ENOMEM;
1729         }
1730         return 0;
1731 }
1732
1733 static int prepare_transfer(struct xhci_hcd *xhci,
1734                 struct xhci_virt_device *xdev,
1735                 unsigned int ep_index,
1736                 unsigned int stream_id,
1737                 unsigned int num_trbs,
1738                 struct urb *urb,
1739                 struct xhci_td **td,
1740                 gfp_t mem_flags)
1741 {
1742         int ret;
1743         struct xhci_ring *ep_ring;
1744         struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
1745
1746         ep_ring = xhci_stream_id_to_ring(xdev, ep_index, stream_id);
1747         if (!ep_ring) {
1748                 xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n",
1749                                 stream_id);
1750                 return -EINVAL;
1751         }
1752
1753         ret = prepare_ring(xhci, ep_ring,
1754                         ep_ctx->ep_info & EP_STATE_MASK,
1755                         num_trbs, mem_flags);
1756         if (ret)
1757                 return ret;
1758         *td = kzalloc(sizeof(struct xhci_td), mem_flags);
1759         if (!*td)
1760                 return -ENOMEM;
1761         INIT_LIST_HEAD(&(*td)->td_list);
1762         INIT_LIST_HEAD(&(*td)->cancelled_td_list);
1763
1764         ret = usb_hcd_link_urb_to_ep(xhci_to_hcd(xhci), urb);
1765         if (unlikely(ret)) {
1766                 kfree(*td);
1767                 return ret;
1768         }
1769
1770         (*td)->urb = urb;
1771         urb->hcpriv = (void *) (*td);
1772         /* Add this TD to the tail of the endpoint ring's TD list */
1773         list_add_tail(&(*td)->td_list, &ep_ring->td_list);
1774         (*td)->start_seg = ep_ring->enq_seg;
1775         (*td)->first_trb = ep_ring->enqueue;
1776
1777         return 0;
1778 }
1779
1780 static unsigned int count_sg_trbs_needed(struct xhci_hcd *xhci, struct urb *urb)
1781 {
1782         int num_sgs, num_trbs, running_total, temp, i;
1783         struct scatterlist *sg;
1784
1785         sg = NULL;
1786         num_sgs = urb->num_sgs;
1787         temp = urb->transfer_buffer_length;
1788
1789         xhci_dbg(xhci, "count sg list trbs: \n");
1790         num_trbs = 0;
1791         for_each_sg(urb->sg->sg, sg, num_sgs, i) {
1792                 unsigned int previous_total_trbs = num_trbs;
1793                 unsigned int len = sg_dma_len(sg);
1794
1795                 /* Scatter gather list entries may cross 64KB boundaries */
1796                 running_total = TRB_MAX_BUFF_SIZE -
1797                         (sg_dma_address(sg) & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
1798                 if (running_total != 0)
1799                         num_trbs++;
1800
1801                 /* How many more 64KB chunks to transfer, how many more TRBs? */
1802                 while (running_total < sg_dma_len(sg)) {
1803                         num_trbs++;
1804                         running_total += TRB_MAX_BUFF_SIZE;
1805                 }
1806                 xhci_dbg(xhci, " sg #%d: dma = %#llx, len = %#x (%d), num_trbs = %d\n",
1807                                 i, (unsigned long long)sg_dma_address(sg),
1808                                 len, len, num_trbs - previous_total_trbs);
1809
1810                 len = min_t(int, len, temp);
1811                 temp -= len;
1812                 if (temp == 0)
1813                         break;
1814         }
1815         xhci_dbg(xhci, "\n");
1816         if (!in_interrupt())
1817                 dev_dbg(&urb->dev->dev, "ep %#x - urb len = %d, sglist used, num_trbs = %d\n",
1818                                 urb->ep->desc.bEndpointAddress,
1819                                 urb->transfer_buffer_length,
1820                                 num_trbs);
1821         return num_trbs;
1822 }
1823
1824 static void check_trb_math(struct urb *urb, int num_trbs, int running_total)
1825 {
1826         if (num_trbs != 0)
1827                 dev_dbg(&urb->dev->dev, "%s - ep %#x - Miscalculated number of "
1828                                 "TRBs, %d left\n", __func__,
1829                                 urb->ep->desc.bEndpointAddress, num_trbs);
1830         if (running_total != urb->transfer_buffer_length)
1831                 dev_dbg(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, "
1832                                 "queued %#x (%d), asked for %#x (%d)\n",
1833                                 __func__,
1834                                 urb->ep->desc.bEndpointAddress,
1835                                 running_total, running_total,
1836                                 urb->transfer_buffer_length,
1837                                 urb->transfer_buffer_length);
1838 }
1839
1840 static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id,
1841                 unsigned int ep_index, unsigned int stream_id, int start_cycle,
1842                 struct xhci_generic_trb *start_trb, struct xhci_td *td)
1843 {
1844         /*
1845          * Pass all the TRBs to the hardware at once and make sure this write
1846          * isn't reordered.
1847          */
1848         wmb();
1849         start_trb->field[3] |= start_cycle;
1850         ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
1851 }
1852
1853 /*
1854  * xHCI uses normal TRBs for both bulk and interrupt.  When the interrupt
1855  * endpoint is to be serviced, the xHC will consume (at most) one TD.  A TD
1856  * (comprised of sg list entries) can take several service intervals to
1857  * transmit.
1858  */
1859 int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
1860                 struct urb *urb, int slot_id, unsigned int ep_index)
1861 {
1862         struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci,
1863                         xhci->devs[slot_id]->out_ctx, ep_index);
1864         int xhci_interval;
1865         int ep_interval;
1866
1867         xhci_interval = EP_INTERVAL_TO_UFRAMES(ep_ctx->ep_info);
1868         ep_interval = urb->interval;
1869         /* Convert to microframes */
1870         if (urb->dev->speed == USB_SPEED_LOW ||
1871                         urb->dev->speed == USB_SPEED_FULL)
1872                 ep_interval *= 8;
1873         /* FIXME change this to a warning and a suggestion to use the new API
1874          * to set the polling interval (once the API is added).
1875          */
1876         if (xhci_interval != ep_interval) {
1877                 if (!printk_ratelimit())
1878                         dev_dbg(&urb->dev->dev, "Driver uses different interval"
1879                                         " (%d microframe%s) than xHCI "
1880                                         "(%d microframe%s)\n",
1881                                         ep_interval,
1882                                         ep_interval == 1 ? "" : "s",
1883                                         xhci_interval,
1884                                         xhci_interval == 1 ? "" : "s");
1885                 urb->interval = xhci_interval;
1886                 /* Convert back to frames for LS/FS devices */
1887                 if (urb->dev->speed == USB_SPEED_LOW ||
1888                                 urb->dev->speed == USB_SPEED_FULL)
1889                         urb->interval /= 8;
1890         }
1891         return xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb, slot_id, ep_index);
1892 }
1893
1894 /*
1895  * The TD size is the number of bytes remaining in the TD (including this TRB),
1896  * right shifted by 10.
1897  * It must fit in bits 21:17, so it can't be bigger than 31.
1898  */
1899 static u32 xhci_td_remainder(unsigned int remainder)
1900 {
1901         u32 max = (1 << (21 - 17 + 1)) - 1;
1902
1903         if ((remainder >> 10) >= max)
1904                 return max << 17;
1905         else
1906                 return (remainder >> 10) << 17;
1907 }
1908
1909 static int queue_bulk_sg_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
1910                 struct urb *urb, int slot_id, unsigned int ep_index)
1911 {
1912         struct xhci_ring *ep_ring;
1913         unsigned int num_trbs;
1914         struct xhci_td *td;
1915         struct scatterlist *sg;
1916         int num_sgs;
1917         int trb_buff_len, this_sg_len, running_total;
1918         bool first_trb;
1919         u64 addr;
1920
1921         struct xhci_generic_trb *start_trb;
1922         int start_cycle;
1923
1924         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1925         if (!ep_ring)
1926                 return -EINVAL;
1927
1928         num_trbs = count_sg_trbs_needed(xhci, urb);
1929         num_sgs = urb->num_sgs;
1930
1931         trb_buff_len = prepare_transfer(xhci, xhci->devs[slot_id],
1932                         ep_index, urb->stream_id,
1933                         num_trbs, urb, &td, mem_flags);
1934         if (trb_buff_len < 0)
1935                 return trb_buff_len;
1936         /*
1937          * Don't give the first TRB to the hardware (by toggling the cycle bit)
1938          * until we've finished creating all the other TRBs.  The ring's cycle
1939          * state may change as we enqueue the other TRBs, so save it too.
1940          */
1941         start_trb = &ep_ring->enqueue->generic;
1942         start_cycle = ep_ring->cycle_state;
1943
1944         running_total = 0;
1945         /*
1946          * How much data is in the first TRB?
1947          *
1948          * There are three forces at work for TRB buffer pointers and lengths:
1949          * 1. We don't want to walk off the end of this sg-list entry buffer.
1950          * 2. The transfer length that the driver requested may be smaller than
1951          *    the amount of memory allocated for this scatter-gather list.
1952          * 3. TRBs buffers can't cross 64KB boundaries.
1953          */
1954         sg = urb->sg->sg;
1955         addr = (u64) sg_dma_address(sg);
1956         this_sg_len = sg_dma_len(sg);
1957         trb_buff_len = TRB_MAX_BUFF_SIZE -
1958                 (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
1959         trb_buff_len = min_t(int, trb_buff_len, this_sg_len);
1960         if (trb_buff_len > urb->transfer_buffer_length)
1961                 trb_buff_len = urb->transfer_buffer_length;
1962         xhci_dbg(xhci, "First length to xfer from 1st sglist entry = %u\n",
1963                         trb_buff_len);
1964
1965         first_trb = true;
1966         /* Queue the first TRB, even if it's zero-length */
1967         do {
1968                 u32 field = 0;
1969                 u32 length_field = 0;
1970                 u32 remainder = 0;
1971
1972                 /* Don't change the cycle bit of the first TRB until later */
1973                 if (first_trb)
1974                         first_trb = false;
1975                 else
1976                         field |= ep_ring->cycle_state;
1977
1978                 /* Chain all the TRBs together; clear the chain bit in the last
1979                  * TRB to indicate it's the last TRB in the chain.
1980                  */
1981                 if (num_trbs > 1) {
1982                         field |= TRB_CHAIN;
1983                 } else {
1984                         /* FIXME - add check for ZERO_PACKET flag before this */
1985                         td->last_trb = ep_ring->enqueue;
1986                         field |= TRB_IOC;
1987                 }
1988                 xhci_dbg(xhci, " sg entry: dma = %#x, len = %#x (%d), "
1989                                 "64KB boundary at %#x, end dma = %#x\n",
1990                                 (unsigned int) addr, trb_buff_len, trb_buff_len,
1991                                 (unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1),
1992                                 (unsigned int) addr + trb_buff_len);
1993                 if (TRB_MAX_BUFF_SIZE -
1994                                 (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1)) < trb_buff_len) {
1995                         xhci_warn(xhci, "WARN: sg dma xfer crosses 64KB boundaries!\n");
1996                         xhci_dbg(xhci, "Next boundary at %#x, end dma = %#x\n",
1997                                         (unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1),
1998                                         (unsigned int) addr + trb_buff_len);
1999                 }
2000                 remainder = xhci_td_remainder(urb->transfer_buffer_length -
2001                                 running_total) ;
2002                 length_field = TRB_LEN(trb_buff_len) |
2003                         remainder |
2004                         TRB_INTR_TARGET(0);
2005                 queue_trb(xhci, ep_ring, false,
2006                                 lower_32_bits(addr),
2007                                 upper_32_bits(addr),
2008                                 length_field,
2009                                 /* We always want to know if the TRB was short,
2010                                  * or we won't get an event when it completes.
2011                                  * (Unless we use event data TRBs, which are a
2012                                  * waste of space and HC resources.)
2013                                  */
2014                                 field | TRB_ISP | TRB_TYPE(TRB_NORMAL));
2015                 --num_trbs;
2016                 running_total += trb_buff_len;
2017
2018                 /* Calculate length for next transfer --
2019                  * Are we done queueing all the TRBs for this sg entry?
2020                  */
2021                 this_sg_len -= trb_buff_len;
2022                 if (this_sg_len == 0) {
2023                         --num_sgs;
2024                         if (num_sgs == 0)
2025                                 break;
2026                         sg = sg_next(sg);
2027                         addr = (u64) sg_dma_address(sg);
2028                         this_sg_len = sg_dma_len(sg);
2029                 } else {
2030                         addr += trb_buff_len;
2031                 }
2032
2033                 trb_buff_len = TRB_MAX_BUFF_SIZE -
2034                         (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
2035                 trb_buff_len = min_t(int, trb_buff_len, this_sg_len);
2036                 if (running_total + trb_buff_len > urb->transfer_buffer_length)
2037                         trb_buff_len =
2038                                 urb->transfer_buffer_length - running_total;
2039         } while (running_total < urb->transfer_buffer_length);
2040
2041         check_trb_math(urb, num_trbs, running_total);
2042         giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
2043                         start_cycle, start_trb, td);
2044         return 0;
2045 }
2046
2047 /* This is very similar to what ehci-q.c qtd_fill() does */
2048 int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
2049                 struct urb *urb, int slot_id, unsigned int ep_index)
2050 {
2051         struct xhci_ring *ep_ring;
2052         struct xhci_td *td;
2053         int num_trbs;
2054         struct xhci_generic_trb *start_trb;
2055         bool first_trb;
2056         int start_cycle;
2057         u32 field, length_field;
2058
2059         int running_total, trb_buff_len, ret;
2060         u64 addr;
2061
2062         if (urb->num_sgs)
2063                 return queue_bulk_sg_tx(xhci, mem_flags, urb, slot_id, ep_index);
2064
2065         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
2066         if (!ep_ring)
2067                 return -EINVAL;
2068
2069         num_trbs = 0;
2070         /* How much data is (potentially) left before the 64KB boundary? */
2071         running_total = TRB_MAX_BUFF_SIZE -
2072                 (urb->transfer_dma & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
2073
2074         /* If there's some data on this 64KB chunk, or we have to send a
2075          * zero-length transfer, we need at least one TRB
2076          */
2077         if (running_total != 0 || urb->transfer_buffer_length == 0)
2078                 num_trbs++;
2079         /* How many more 64KB chunks to transfer, how many more TRBs? */
2080         while (running_total < urb->transfer_buffer_length) {
2081                 num_trbs++;
2082                 running_total += TRB_MAX_BUFF_SIZE;
2083         }
2084         /* FIXME: this doesn't deal with URB_ZERO_PACKET - need one more */
2085
2086         if (!in_interrupt())
2087                 dev_dbg(&urb->dev->dev, "ep %#x - urb len = %#x (%d), addr = %#llx, num_trbs = %d\n",
2088                                 urb->ep->desc.bEndpointAddress,
2089                                 urb->transfer_buffer_length,
2090                                 urb->transfer_buffer_length,
2091                                 (unsigned long long)urb->transfer_dma,
2092                                 num_trbs);
2093
2094         ret = prepare_transfer(xhci, xhci->devs[slot_id],
2095                         ep_index, urb->stream_id,
2096                         num_trbs, urb, &td, mem_flags);
2097         if (ret < 0)
2098                 return ret;
2099
2100         /*
2101          * Don't give the first TRB to the hardware (by toggling the cycle bit)
2102          * until we've finished creating all the other TRBs.  The ring's cycle
2103          * state may change as we enqueue the other TRBs, so save it too.
2104          */
2105         start_trb = &ep_ring->enqueue->generic;
2106         start_cycle = ep_ring->cycle_state;
2107
2108         running_total = 0;
2109         /* How much data is in the first TRB? */
2110         addr = (u64) urb->transfer_dma;
2111         trb_buff_len = TRB_MAX_BUFF_SIZE -
2112                 (urb->transfer_dma & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
2113         if (urb->transfer_buffer_length < trb_buff_len)
2114                 trb_buff_len = urb->transfer_buffer_length;
2115
2116         first_trb = true;
2117
2118         /* Queue the first TRB, even if it's zero-length */
2119         do {
2120                 u32 remainder = 0;
2121                 field = 0;
2122
2123                 /* Don't change the cycle bit of the first TRB until later */
2124                 if (first_trb)
2125                         first_trb = false;
2126                 else
2127                         field |= ep_ring->cycle_state;
2128
2129                 /* Chain all the TRBs together; clear the chain bit in the last
2130                  * TRB to indicate it's the last TRB in the chain.
2131                  */
2132                 if (num_trbs > 1) {
2133                         field |= TRB_CHAIN;
2134                 } else {
2135                         /* FIXME - add check for ZERO_PACKET flag before this */
2136                         td->last_trb = ep_ring->enqueue;
2137                         field |= TRB_IOC;
2138                 }
2139                 remainder = xhci_td_remainder(urb->transfer_buffer_length -
2140                                 running_total);
2141                 length_field = TRB_LEN(trb_buff_len) |
2142                         remainder |
2143                         TRB_INTR_TARGET(0);
2144                 queue_trb(xhci, ep_ring, false,
2145                                 lower_32_bits(addr),
2146                                 upper_32_bits(addr),
2147                                 length_field,
2148                                 /* We always want to know if the TRB was short,
2149                                  * or we won't get an event when it completes.
2150                                  * (Unless we use event data TRBs, which are a
2151                                  * waste of space and HC resources.)
2152                                  */
2153                                 field | TRB_ISP | TRB_TYPE(TRB_NORMAL));
2154                 --num_trbs;
2155                 running_total += trb_buff_len;
2156
2157                 /* Calculate length for next transfer */
2158                 addr += trb_buff_len;
2159                 trb_buff_len = urb->transfer_buffer_length - running_total;
2160                 if (trb_buff_len > TRB_MAX_BUFF_SIZE)
2161                         trb_buff_len = TRB_MAX_BUFF_SIZE;
2162         } while (running_total < urb->transfer_buffer_length);
2163
2164         check_trb_math(urb, num_trbs, running_total);
2165         giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
2166                         start_cycle, start_trb, td);
2167         return 0;
2168 }
2169
2170 /* Caller must have locked xhci->lock */
2171 int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
2172                 struct urb *urb, int slot_id, unsigned int ep_index)
2173 {
2174         struct xhci_ring *ep_ring;
2175         int num_trbs;
2176         int ret;
2177         struct usb_ctrlrequest *setup;
2178         struct xhci_generic_trb *start_trb;
2179         int start_cycle;
2180         u32 field, length_field;
2181         struct xhci_td *td;
2182
2183         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
2184         if (!ep_ring)
2185                 return -EINVAL;
2186
2187         /*
2188          * Need to copy setup packet into setup TRB, so we can't use the setup
2189          * DMA address.
2190          */
2191         if (!urb->setup_packet)
2192                 return -EINVAL;
2193
2194         if (!in_interrupt())
2195                 xhci_dbg(xhci, "Queueing ctrl tx for slot id %d, ep %d\n",
2196                                 slot_id, ep_index);
2197         /* 1 TRB for setup, 1 for status */
2198         num_trbs = 2;
2199         /*
2200          * Don't need to check if we need additional event data and normal TRBs,
2201          * since data in control transfers will never get bigger than 16MB
2202          * XXX: can we get a buffer that crosses 64KB boundaries?
2203          */
2204         if (urb->transfer_buffer_length > 0)
2205                 num_trbs++;
2206         ret = prepare_transfer(xhci, xhci->devs[slot_id],
2207                         ep_index, urb->stream_id,
2208                         num_trbs, urb, &td, mem_flags);
2209         if (ret < 0)
2210                 return ret;
2211
2212         /*
2213          * Don't give the first TRB to the hardware (by toggling the cycle bit)
2214          * until we've finished creating all the other TRBs.  The ring's cycle
2215          * state may change as we enqueue the other TRBs, so save it too.
2216          */
2217         start_trb = &ep_ring->enqueue->generic;
2218         start_cycle = ep_ring->cycle_state;
2219
2220         /* Queue setup TRB - see section 6.4.1.2.1 */
2221         /* FIXME better way to translate setup_packet into two u32 fields? */
2222         setup = (struct usb_ctrlrequest *) urb->setup_packet;
2223         queue_trb(xhci, ep_ring, false,
2224                         /* FIXME endianness is probably going to bite my ass here. */
2225                         setup->bRequestType | setup->bRequest << 8 | setup->wValue << 16,
2226                         setup->wIndex | setup->wLength << 16,
2227                         TRB_LEN(8) | TRB_INTR_TARGET(0),
2228                         /* Immediate data in pointer */
2229                         TRB_IDT | TRB_TYPE(TRB_SETUP));
2230
2231         /* If there's data, queue data TRBs */
2232         field = 0;
2233         length_field = TRB_LEN(urb->transfer_buffer_length) |
2234                 xhci_td_remainder(urb->transfer_buffer_length) |
2235                 TRB_INTR_TARGET(0);
2236         if (urb->transfer_buffer_length > 0) {
2237                 if (setup->bRequestType & USB_DIR_IN)
2238                         field |= TRB_DIR_IN;
2239                 queue_trb(xhci, ep_ring, false,
2240                                 lower_32_bits(urb->transfer_dma),
2241                                 upper_32_bits(urb->transfer_dma),
2242                                 length_field,
2243                                 /* Event on short tx */
2244                                 field | TRB_ISP | TRB_TYPE(TRB_DATA) | ep_ring->cycle_state);
2245         }
2246
2247         /* Save the DMA address of the last TRB in the TD */
2248         td->last_trb = ep_ring->enqueue;
2249
2250         /* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */
2251         /* If the device sent data, the status stage is an OUT transfer */
2252         if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN)
2253                 field = 0;
2254         else
2255                 field = TRB_DIR_IN;
2256         queue_trb(xhci, ep_ring, false,
2257                         0,
2258                         0,
2259                         TRB_INTR_TARGET(0),
2260                         /* Event on completion */
2261                         field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state);
2262
2263         giveback_first_trb(xhci, slot_id, ep_index, 0,
2264                         start_cycle, start_trb, td);
2265         return 0;
2266 }
2267
2268 /****           Command Ring Operations         ****/
2269
2270 /* Generic function for queueing a command TRB on the command ring.
2271  * Check to make sure there's room on the command ring for one command TRB.
2272  * Also check that there's room reserved for commands that must not fail.
2273  * If this is a command that must not fail, meaning command_must_succeed = TRUE,
2274  * then only check for the number of reserved spots.
2275  * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB
2276  * because the command event handler may want to resubmit a failed command.
2277  */
2278 static int queue_command(struct xhci_hcd *xhci, u32 field1, u32 field2,
2279                 u32 field3, u32 field4, bool command_must_succeed)
2280 {
2281         int reserved_trbs = xhci->cmd_ring_reserved_trbs;
2282         if (!command_must_succeed)
2283                 reserved_trbs++;
2284
2285         if (!room_on_ring(xhci, xhci->cmd_ring, reserved_trbs)) {
2286                 if (!in_interrupt())
2287                         xhci_err(xhci, "ERR: No room for command on command ring\n");
2288                 if (command_must_succeed)
2289                         xhci_err(xhci, "ERR: Reserved TRB counting for "
2290                                         "unfailable commands failed.\n");
2291                 return -ENOMEM;
2292         }
2293         queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3,
2294                         field4 | xhci->cmd_ring->cycle_state);
2295         return 0;
2296 }
2297
2298 /* Queue a no-op command on the command ring */
2299 static int queue_cmd_noop(struct xhci_hcd *xhci)
2300 {
2301         return queue_command(xhci, 0, 0, 0, TRB_TYPE(TRB_CMD_NOOP), false);
2302 }
2303
2304 /*
2305  * Place a no-op command on the command ring to test the command and
2306  * event ring.
2307  */
2308 void *xhci_setup_one_noop(struct xhci_hcd *xhci)
2309 {
2310         if (queue_cmd_noop(xhci) < 0)
2311                 return NULL;
2312         xhci->noops_submitted++;
2313         return xhci_ring_cmd_db;
2314 }
2315
2316 /* Queue a slot enable or disable request on the command ring */
2317 int xhci_queue_slot_control(struct xhci_hcd *xhci, u32 trb_type, u32 slot_id)
2318 {
2319         return queue_command(xhci, 0, 0, 0,
2320                         TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false);
2321 }
2322
2323 /* Queue an address device command TRB */
2324 int xhci_queue_address_device(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
2325                 u32 slot_id)
2326 {
2327         return queue_command(xhci, lower_32_bits(in_ctx_ptr),
2328                         upper_32_bits(in_ctx_ptr), 0,
2329                         TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id),
2330                         false);
2331 }
2332
2333 /* Queue a reset device command TRB */
2334 int xhci_queue_reset_device(struct xhci_hcd *xhci, u32 slot_id)
2335 {
2336         return queue_command(xhci, 0, 0, 0,
2337                         TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id),
2338                         false);
2339 }
2340
2341 /* Queue a configure endpoint command TRB */
2342 int xhci_queue_configure_endpoint(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
2343                 u32 slot_id, bool command_must_succeed)
2344 {
2345         return queue_command(xhci, lower_32_bits(in_ctx_ptr),
2346                         upper_32_bits(in_ctx_ptr), 0,
2347                         TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id),
2348                         command_must_succeed);
2349 }
2350
2351 /* Queue an evaluate context command TRB */
2352 int xhci_queue_evaluate_context(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
2353                 u32 slot_id)
2354 {
2355         return queue_command(xhci, lower_32_bits(in_ctx_ptr),
2356                         upper_32_bits(in_ctx_ptr), 0,
2357                         TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id),
2358                         false);
2359 }
2360
2361 int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, int slot_id,
2362                 unsigned int ep_index)
2363 {
2364         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
2365         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
2366         u32 type = TRB_TYPE(TRB_STOP_RING);
2367
2368         return queue_command(xhci, 0, 0, 0,
2369                         trb_slot_id | trb_ep_index | type, false);
2370 }
2371
2372 /* Set Transfer Ring Dequeue Pointer command.
2373  * This should not be used for endpoints that have streams enabled.
2374  */
2375 static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id,
2376                 unsigned int ep_index, unsigned int stream_id,
2377                 struct xhci_segment *deq_seg,
2378                 union xhci_trb *deq_ptr, u32 cycle_state)
2379 {
2380         dma_addr_t addr;
2381         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
2382         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
2383         u32 trb_stream_id = STREAM_ID_FOR_TRB(stream_id);
2384         u32 type = TRB_TYPE(TRB_SET_DEQ);
2385
2386         addr = xhci_trb_virt_to_dma(deq_seg, deq_ptr);
2387         if (addr == 0) {
2388                 xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n");
2389                 xhci_warn(xhci, "WARN deq seg = %p, deq pt = %p\n",
2390                                 deq_seg, deq_ptr);
2391                 return 0;
2392         }
2393         return queue_command(xhci, lower_32_bits(addr) | cycle_state,
2394                         upper_32_bits(addr), trb_stream_id,
2395                         trb_slot_id | trb_ep_index | type, false);
2396 }
2397
2398 int xhci_queue_reset_ep(struct xhci_hcd *xhci, int slot_id,
2399                 unsigned int ep_index)
2400 {
2401         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
2402         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
2403         u32 type = TRB_TYPE(TRB_RESET_EP);
2404
2405         return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type,
2406                         false);
2407 }