Mention branches and keyring.
[releases.git] / host / xhci-ring.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * xHCI host controller driver
4  *
5  * Copyright (C) 2008 Intel Corp.
6  *
7  * Author: Sarah Sharp
8  * Some code borrowed from the Linux EHCI driver.
9  */
10
11 /*
12  * Ring initialization rules:
13  * 1. Each segment is initialized to zero, except for link TRBs.
14  * 2. Ring cycle state = 0.  This represents Producer Cycle State (PCS) or
15  *    Consumer Cycle State (CCS), depending on ring function.
16  * 3. Enqueue pointer = dequeue pointer = address of first TRB in the segment.
17  *
18  * Ring behavior rules:
19  * 1. A ring is empty if enqueue == dequeue.  This means there will always be at
20  *    least one free TRB in the ring.  This is useful if you want to turn that
21  *    into a link TRB and expand the ring.
22  * 2. When incrementing an enqueue or dequeue pointer, if the next TRB is a
23  *    link TRB, then load the pointer with the address in the link TRB.  If the
24  *    link TRB had its toggle bit set, you may need to update the ring cycle
25  *    state (see cycle bit rules).  You may have to do this multiple times
26  *    until you reach a non-link TRB.
27  * 3. A ring is full if enqueue++ (for the definition of increment above)
28  *    equals the dequeue pointer.
29  *
30  * Cycle bit rules:
31  * 1. When a consumer increments a dequeue pointer and encounters a toggle bit
32  *    in a link TRB, it must toggle the ring cycle state.
33  * 2. When a producer increments an enqueue pointer and encounters a toggle bit
34  *    in a link TRB, it must toggle the ring cycle state.
35  *
36  * Producer rules:
37  * 1. Check if ring is full before you enqueue.
38  * 2. Write the ring cycle state to the cycle bit in the TRB you're enqueuing.
39  *    Update enqueue pointer between each write (which may update the ring
40  *    cycle state).
41  * 3. Notify consumer.  If SW is producer, it rings the doorbell for command
42  *    and endpoint rings.  If HC is the producer for the event ring,
43  *    and it generates an interrupt according to interrupt modulation rules.
44  *
45  * Consumer rules:
46  * 1. Check if TRB belongs to you.  If the cycle bit == your ring cycle state,
47  *    the TRB is owned by the consumer.
48  * 2. Update dequeue pointer (which may update the ring cycle state) and
49  *    continue processing TRBs until you reach a TRB which is not owned by you.
50  * 3. Notify the producer.  SW is the consumer for the event ring, and it
51  *   updates event ring dequeue pointer.  HC is the consumer for the command and
52  *   endpoint rings; it generates events on the event ring for these.
53  */
54
55 #include <linux/scatterlist.h>
56 #include <linux/slab.h>
57 #include <linux/dma-mapping.h>
58 #include "xhci.h"
59 #include "xhci-trace.h"
60
61 static int queue_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
62                          u32 field1, u32 field2,
63                          u32 field3, u32 field4, bool command_must_succeed);
64
65 /*
66  * Returns zero if the TRB isn't in this segment, otherwise it returns the DMA
67  * address of the TRB.
68  */
69 dma_addr_t xhci_trb_virt_to_dma(struct xhci_segment *seg,
70                 union xhci_trb *trb)
71 {
72         unsigned long segment_offset;
73
74         if (!seg || !trb || trb < seg->trbs)
75                 return 0;
76         /* offset in TRBs */
77         segment_offset = trb - seg->trbs;
78         if (segment_offset >= TRBS_PER_SEGMENT)
79                 return 0;
80         return seg->dma + (segment_offset * sizeof(*trb));
81 }
82
83 static bool trb_is_noop(union xhci_trb *trb)
84 {
85         return TRB_TYPE_NOOP_LE32(trb->generic.field[3]);
86 }
87
88 static bool trb_is_link(union xhci_trb *trb)
89 {
90         return TRB_TYPE_LINK_LE32(trb->link.control);
91 }
92
93 static bool last_trb_on_seg(struct xhci_segment *seg, union xhci_trb *trb)
94 {
95         return trb == &seg->trbs[TRBS_PER_SEGMENT - 1];
96 }
97
98 static bool last_trb_on_ring(struct xhci_ring *ring,
99                         struct xhci_segment *seg, union xhci_trb *trb)
100 {
101         return last_trb_on_seg(seg, trb) && (seg->next == ring->first_seg);
102 }
103
104 static bool link_trb_toggles_cycle(union xhci_trb *trb)
105 {
106         return le32_to_cpu(trb->link.control) & LINK_TOGGLE;
107 }
108
109 static bool last_td_in_urb(struct xhci_td *td)
110 {
111         struct urb_priv *urb_priv = td->urb->hcpriv;
112
113         return urb_priv->num_tds_done == urb_priv->num_tds;
114 }
115
116 static void inc_td_cnt(struct urb *urb)
117 {
118         struct urb_priv *urb_priv = urb->hcpriv;
119
120         urb_priv->num_tds_done++;
121 }
122
123 static void trb_to_noop(union xhci_trb *trb, u32 noop_type)
124 {
125         if (trb_is_link(trb)) {
126                 /* unchain chained link TRBs */
127                 trb->link.control &= cpu_to_le32(~TRB_CHAIN);
128         } else {
129                 trb->generic.field[0] = 0;
130                 trb->generic.field[1] = 0;
131                 trb->generic.field[2] = 0;
132                 /* Preserve only the cycle bit of this TRB */
133                 trb->generic.field[3] &= cpu_to_le32(TRB_CYCLE);
134                 trb->generic.field[3] |= cpu_to_le32(TRB_TYPE(noop_type));
135         }
136 }
137
138 /* Updates trb to point to the next TRB in the ring, and updates seg if the next
139  * TRB is in a new segment.  This does not skip over link TRBs, and it does not
140  * effect the ring dequeue or enqueue pointers.
141  */
142 static void next_trb(struct xhci_hcd *xhci,
143                 struct xhci_ring *ring,
144                 struct xhci_segment **seg,
145                 union xhci_trb **trb)
146 {
147         if (trb_is_link(*trb) || last_trb_on_seg(*seg, *trb)) {
148                 *seg = (*seg)->next;
149                 *trb = ((*seg)->trbs);
150         } else {
151                 (*trb)++;
152         }
153 }
154
155 /*
156  * See Cycle bit rules. SW is the consumer for the event ring only.
157  */
158 void inc_deq(struct xhci_hcd *xhci, struct xhci_ring *ring)
159 {
160         unsigned int link_trb_count = 0;
161
162         /* event ring doesn't have link trbs, check for last trb */
163         if (ring->type == TYPE_EVENT) {
164                 if (!last_trb_on_seg(ring->deq_seg, ring->dequeue)) {
165                         ring->dequeue++;
166                         goto out;
167                 }
168                 if (last_trb_on_ring(ring, ring->deq_seg, ring->dequeue))
169                         ring->cycle_state ^= 1;
170                 ring->deq_seg = ring->deq_seg->next;
171                 ring->dequeue = ring->deq_seg->trbs;
172                 goto out;
173         }
174
175         /* All other rings have link trbs */
176         if (!trb_is_link(ring->dequeue)) {
177                 if (last_trb_on_seg(ring->deq_seg, ring->dequeue))
178                         xhci_warn(xhci, "Missing link TRB at end of segment\n");
179                 else
180                         ring->dequeue++;
181         }
182
183         while (trb_is_link(ring->dequeue)) {
184                 ring->deq_seg = ring->deq_seg->next;
185                 ring->dequeue = ring->deq_seg->trbs;
186
187                 if (link_trb_count++ > ring->num_segs) {
188                         xhci_warn(xhci, "Ring is an endless link TRB loop\n");
189                         break;
190                 }
191         }
192 out:
193         trace_xhci_inc_deq(ring);
194
195         return;
196 }
197
198 /*
199  * See Cycle bit rules. SW is the consumer for the event ring only.
200  *
201  * If we've just enqueued a TRB that is in the middle of a TD (meaning the
202  * chain bit is set), then set the chain bit in all the following link TRBs.
203  * If we've enqueued the last TRB in a TD, make sure the following link TRBs
204  * have their chain bit cleared (so that each Link TRB is a separate TD).
205  *
206  * Section 6.4.4.1 of the 0.95 spec says link TRBs cannot have the chain bit
207  * set, but other sections talk about dealing with the chain bit set.  This was
208  * fixed in the 0.96 specification errata, but we have to assume that all 0.95
209  * xHCI hardware can't handle the chain bit being cleared on a link TRB.
210  *
211  * @more_trbs_coming:   Will you enqueue more TRBs before calling
212  *                      prepare_transfer()?
213  */
214 static void inc_enq(struct xhci_hcd *xhci, struct xhci_ring *ring,
215                         bool more_trbs_coming)
216 {
217         u32 chain;
218         union xhci_trb *next;
219         unsigned int link_trb_count = 0;
220
221         chain = le32_to_cpu(ring->enqueue->generic.field[3]) & TRB_CHAIN;
222
223         if (last_trb_on_seg(ring->enq_seg, ring->enqueue)) {
224                 xhci_err(xhci, "Tried to move enqueue past ring segment\n");
225                 return;
226         }
227
228         next = ++(ring->enqueue);
229
230         /* Update the dequeue pointer further if that was a link TRB */
231         while (trb_is_link(next)) {
232
233                 /*
234                  * If the caller doesn't plan on enqueueing more TDs before
235                  * ringing the doorbell, then we don't want to give the link TRB
236                  * to the hardware just yet. We'll give the link TRB back in
237                  * prepare_ring() just before we enqueue the TD at the top of
238                  * the ring.
239                  */
240                 if (!chain && !more_trbs_coming)
241                         break;
242
243                 /* If we're not dealing with 0.95 hardware or isoc rings on
244                  * AMD 0.96 host, carry over the chain bit of the previous TRB
245                  * (which may mean the chain bit is cleared).
246                  */
247                 if (!(ring->type == TYPE_ISOC &&
248                       (xhci->quirks & XHCI_AMD_0x96_HOST)) &&
249                     !xhci_link_trb_quirk(xhci)) {
250                         next->link.control &= cpu_to_le32(~TRB_CHAIN);
251                         next->link.control |= cpu_to_le32(chain);
252                 }
253                 /* Give this link TRB to the hardware */
254                 wmb();
255                 next->link.control ^= cpu_to_le32(TRB_CYCLE);
256
257                 /* Toggle the cycle bit after the last ring segment. */
258                 if (link_trb_toggles_cycle(next))
259                         ring->cycle_state ^= 1;
260
261                 ring->enq_seg = ring->enq_seg->next;
262                 ring->enqueue = ring->enq_seg->trbs;
263                 next = ring->enqueue;
264
265                 if (link_trb_count++ > ring->num_segs) {
266                         xhci_warn(xhci, "%s: Ring link TRB loop\n", __func__);
267                         break;
268                 }
269         }
270
271         trace_xhci_inc_enq(ring);
272 }
273
274 /*
275  * Return number of free normal TRBs from enqueue to dequeue pointer on ring.
276  * Not counting an assumed link TRB at end of each TRBS_PER_SEGMENT sized segment.
277  * Only for transfer and command rings where driver is the producer, not for
278  * event rings.
279  */
280 static unsigned int xhci_num_trbs_free(struct xhci_hcd *xhci, struct xhci_ring *ring)
281 {
282         struct xhci_segment *enq_seg = ring->enq_seg;
283         union xhci_trb *enq = ring->enqueue;
284         union xhci_trb *last_on_seg;
285         unsigned int free = 0;
286         int i = 0;
287
288         /* Ring might be empty even if enq != deq if enq is left on a link trb */
289         if (trb_is_link(enq)) {
290                 enq_seg = enq_seg->next;
291                 enq = enq_seg->trbs;
292         }
293
294         /* Empty ring, common case, don't walk the segments */
295         if (enq == ring->dequeue)
296                 return ring->num_segs * (TRBS_PER_SEGMENT - 1);
297
298         do {
299                 if (ring->deq_seg == enq_seg && ring->dequeue >= enq)
300                         return free + (ring->dequeue - enq);
301                 last_on_seg = &enq_seg->trbs[TRBS_PER_SEGMENT - 1];
302                 free += last_on_seg - enq;
303                 enq_seg = enq_seg->next;
304                 enq = enq_seg->trbs;
305         } while (i++ <= ring->num_segs);
306
307         return free;
308 }
309
310 /*
311  * Check to see if there's room to enqueue num_trbs on the ring and make sure
312  * enqueue pointer will not advance into dequeue segment. See rules above.
313  * return number of new segments needed to ensure this.
314  */
315
316 static unsigned int xhci_ring_expansion_needed(struct xhci_hcd *xhci, struct xhci_ring *ring,
317                                                unsigned int num_trbs)
318 {
319         struct xhci_segment *seg;
320         int trbs_past_seg;
321         int enq_used;
322         int new_segs;
323
324         enq_used = ring->enqueue - ring->enq_seg->trbs;
325
326         /* how many trbs will be queued past the enqueue segment? */
327         trbs_past_seg = enq_used + num_trbs - (TRBS_PER_SEGMENT - 1);
328
329         if (trbs_past_seg <= 0)
330                 return 0;
331
332         /* Empty ring special case, enqueue stuck on link trb while dequeue advanced */
333         if (trb_is_link(ring->enqueue) && ring->enq_seg->next->trbs == ring->dequeue)
334                 return 0;
335
336         new_segs = 1 + (trbs_past_seg / (TRBS_PER_SEGMENT - 1));
337         seg = ring->enq_seg;
338
339         while (new_segs > 0) {
340                 seg = seg->next;
341                 if (seg == ring->deq_seg) {
342                         xhci_dbg(xhci, "Ring expansion by %d segments needed\n",
343                                  new_segs);
344                         xhci_dbg(xhci, "Adding %d trbs moves enq %d trbs into deq seg\n",
345                                  num_trbs, trbs_past_seg % TRBS_PER_SEGMENT);
346                         return new_segs;
347                 }
348                 new_segs--;
349         }
350
351         return 0;
352 }
353
354 /* Ring the host controller doorbell after placing a command on the ring */
355 void xhci_ring_cmd_db(struct xhci_hcd *xhci)
356 {
357         if (!(xhci->cmd_ring_state & CMD_RING_STATE_RUNNING))
358                 return;
359
360         xhci_dbg(xhci, "// Ding dong!\n");
361
362         trace_xhci_ring_host_doorbell(0, DB_VALUE_HOST);
363
364         writel(DB_VALUE_HOST, &xhci->dba->doorbell[0]);
365         /* Flush PCI posted writes */
366         readl(&xhci->dba->doorbell[0]);
367 }
368
369 static bool xhci_mod_cmd_timer(struct xhci_hcd *xhci, unsigned long delay)
370 {
371         return mod_delayed_work(system_wq, &xhci->cmd_timer, delay);
372 }
373
374 static struct xhci_command *xhci_next_queued_cmd(struct xhci_hcd *xhci)
375 {
376         return list_first_entry_or_null(&xhci->cmd_list, struct xhci_command,
377                                         cmd_list);
378 }
379
380 /*
381  * Turn all commands on command ring with status set to "aborted" to no-op trbs.
382  * If there are other commands waiting then restart the ring and kick the timer.
383  * This must be called with command ring stopped and xhci->lock held.
384  */
385 static void xhci_handle_stopped_cmd_ring(struct xhci_hcd *xhci,
386                                          struct xhci_command *cur_cmd)
387 {
388         struct xhci_command *i_cmd;
389
390         /* Turn all aborted commands in list to no-ops, then restart */
391         list_for_each_entry(i_cmd, &xhci->cmd_list, cmd_list) {
392
393                 if (i_cmd->status != COMP_COMMAND_ABORTED)
394                         continue;
395
396                 i_cmd->status = COMP_COMMAND_RING_STOPPED;
397
398                 xhci_dbg(xhci, "Turn aborted command %p to no-op\n",
399                          i_cmd->command_trb);
400
401                 trb_to_noop(i_cmd->command_trb, TRB_CMD_NOOP);
402
403                 /*
404                  * caller waiting for completion is called when command
405                  *  completion event is received for these no-op commands
406                  */
407         }
408
409         xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
410
411         /* ring command ring doorbell to restart the command ring */
412         if ((xhci->cmd_ring->dequeue != xhci->cmd_ring->enqueue) &&
413             !(xhci->xhc_state & XHCI_STATE_DYING)) {
414                 xhci->current_cmd = cur_cmd;
415                 xhci_mod_cmd_timer(xhci, XHCI_CMD_DEFAULT_TIMEOUT);
416                 xhci_ring_cmd_db(xhci);
417         }
418 }
419
420 /* Must be called with xhci->lock held, releases and aquires lock back */
421 static int xhci_abort_cmd_ring(struct xhci_hcd *xhci, unsigned long flags)
422 {
423         struct xhci_segment *new_seg    = xhci->cmd_ring->deq_seg;
424         union xhci_trb *new_deq         = xhci->cmd_ring->dequeue;
425         u64 crcr;
426         int ret;
427
428         xhci_dbg(xhci, "Abort command ring\n");
429
430         reinit_completion(&xhci->cmd_ring_stop_completion);
431
432         /*
433          * The control bits like command stop, abort are located in lower
434          * dword of the command ring control register.
435          * Some controllers require all 64 bits to be written to abort the ring.
436          * Make sure the upper dword is valid, pointing to the next command,
437          * avoiding corrupting the command ring pointer in case the command ring
438          * is stopped by the time the upper dword is written.
439          */
440         next_trb(xhci, NULL, &new_seg, &new_deq);
441         if (trb_is_link(new_deq))
442                 next_trb(xhci, NULL, &new_seg, &new_deq);
443
444         crcr = xhci_trb_virt_to_dma(new_seg, new_deq);
445         xhci_write_64(xhci, crcr | CMD_RING_ABORT, &xhci->op_regs->cmd_ring);
446
447         /* Section 4.6.1.2 of xHCI 1.0 spec says software should also time the
448          * completion of the Command Abort operation. If CRR is not negated in 5
449          * seconds then driver handles it as if host died (-ENODEV).
450          * In the future we should distinguish between -ENODEV and -ETIMEDOUT
451          * and try to recover a -ETIMEDOUT with a host controller reset.
452          */
453         ret = xhci_handshake_check_state(xhci, &xhci->op_regs->cmd_ring,
454                         CMD_RING_RUNNING, 0, 5 * 1000 * 1000,
455                         XHCI_STATE_REMOVING);
456         if (ret < 0) {
457                 xhci_err(xhci, "Abort failed to stop command ring: %d\n", ret);
458                 xhci_halt(xhci);
459                 xhci_hc_died(xhci);
460                 return ret;
461         }
462         /*
463          * Writing the CMD_RING_ABORT bit should cause a cmd completion event,
464          * however on some host hw the CMD_RING_RUNNING bit is correctly cleared
465          * but the completion event in never sent. Wait 2 secs (arbitrary
466          * number) to handle those cases after negation of CMD_RING_RUNNING.
467          */
468         spin_unlock_irqrestore(&xhci->lock, flags);
469         ret = wait_for_completion_timeout(&xhci->cmd_ring_stop_completion,
470                                           msecs_to_jiffies(2000));
471         spin_lock_irqsave(&xhci->lock, flags);
472         if (!ret) {
473                 xhci_dbg(xhci, "No stop event for abort, ring start fail?\n");
474                 xhci_cleanup_command_queue(xhci);
475         } else {
476                 xhci_handle_stopped_cmd_ring(xhci, xhci_next_queued_cmd(xhci));
477         }
478         return 0;
479 }
480
481 void xhci_ring_ep_doorbell(struct xhci_hcd *xhci,
482                 unsigned int slot_id,
483                 unsigned int ep_index,
484                 unsigned int stream_id)
485 {
486         __le32 __iomem *db_addr = &xhci->dba->doorbell[slot_id];
487         struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index];
488         unsigned int ep_state = ep->ep_state;
489
490         /* Don't ring the doorbell for this endpoint if there are pending
491          * cancellations because we don't want to interrupt processing.
492          * We don't want to restart any stream rings if there's a set dequeue
493          * pointer command pending because the device can choose to start any
494          * stream once the endpoint is on the HW schedule.
495          */
496         if ((ep_state & EP_STOP_CMD_PENDING) || (ep_state & SET_DEQ_PENDING) ||
497             (ep_state & EP_HALTED) || (ep_state & EP_CLEARING_TT))
498                 return;
499
500         trace_xhci_ring_ep_doorbell(slot_id, DB_VALUE(ep_index, stream_id));
501
502         writel(DB_VALUE(ep_index, stream_id), db_addr);
503         /* flush the write */
504         readl(db_addr);
505 }
506
507 /* Ring the doorbell for any rings with pending URBs */
508 static void ring_doorbell_for_active_rings(struct xhci_hcd *xhci,
509                 unsigned int slot_id,
510                 unsigned int ep_index)
511 {
512         unsigned int stream_id;
513         struct xhci_virt_ep *ep;
514
515         ep = &xhci->devs[slot_id]->eps[ep_index];
516
517         /* A ring has pending URBs if its TD list is not empty */
518         if (!(ep->ep_state & EP_HAS_STREAMS)) {
519                 if (ep->ring && !(list_empty(&ep->ring->td_list)))
520                         xhci_ring_ep_doorbell(xhci, slot_id, ep_index, 0);
521                 return;
522         }
523
524         for (stream_id = 1; stream_id < ep->stream_info->num_streams;
525                         stream_id++) {
526                 struct xhci_stream_info *stream_info = ep->stream_info;
527                 if (!list_empty(&stream_info->stream_rings[stream_id]->td_list))
528                         xhci_ring_ep_doorbell(xhci, slot_id, ep_index,
529                                                 stream_id);
530         }
531 }
532
533 void xhci_ring_doorbell_for_active_rings(struct xhci_hcd *xhci,
534                 unsigned int slot_id,
535                 unsigned int ep_index)
536 {
537         ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
538 }
539
540 static struct xhci_virt_ep *xhci_get_virt_ep(struct xhci_hcd *xhci,
541                                              unsigned int slot_id,
542                                              unsigned int ep_index)
543 {
544         if (slot_id == 0 || slot_id >= MAX_HC_SLOTS) {
545                 xhci_warn(xhci, "Invalid slot_id %u\n", slot_id);
546                 return NULL;
547         }
548         if (ep_index >= EP_CTX_PER_DEV) {
549                 xhci_warn(xhci, "Invalid endpoint index %u\n", ep_index);
550                 return NULL;
551         }
552         if (!xhci->devs[slot_id]) {
553                 xhci_warn(xhci, "No xhci virt device for slot_id %u\n", slot_id);
554                 return NULL;
555         }
556
557         return &xhci->devs[slot_id]->eps[ep_index];
558 }
559
560 static struct xhci_ring *xhci_virt_ep_to_ring(struct xhci_hcd *xhci,
561                                               struct xhci_virt_ep *ep,
562                                               unsigned int stream_id)
563 {
564         /* common case, no streams */
565         if (!(ep->ep_state & EP_HAS_STREAMS))
566                 return ep->ring;
567
568         if (!ep->stream_info)
569                 return NULL;
570
571         if (stream_id == 0 || stream_id >= ep->stream_info->num_streams) {
572                 xhci_warn(xhci, "Invalid stream_id %u request for slot_id %u ep_index %u\n",
573                           stream_id, ep->vdev->slot_id, ep->ep_index);
574                 return NULL;
575         }
576
577         return ep->stream_info->stream_rings[stream_id];
578 }
579
580 /* Get the right ring for the given slot_id, ep_index and stream_id.
581  * If the endpoint supports streams, boundary check the URB's stream ID.
582  * If the endpoint doesn't support streams, return the singular endpoint ring.
583  */
584 struct xhci_ring *xhci_triad_to_transfer_ring(struct xhci_hcd *xhci,
585                 unsigned int slot_id, unsigned int ep_index,
586                 unsigned int stream_id)
587 {
588         struct xhci_virt_ep *ep;
589
590         ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
591         if (!ep)
592                 return NULL;
593
594         return xhci_virt_ep_to_ring(xhci, ep, stream_id);
595 }
596
597
598 /*
599  * Get the hw dequeue pointer xHC stopped on, either directly from the
600  * endpoint context, or if streams are in use from the stream context.
601  * The returned hw_dequeue contains the lowest four bits with cycle state
602  * and possbile stream context type.
603  */
604 static u64 xhci_get_hw_deq(struct xhci_hcd *xhci, struct xhci_virt_device *vdev,
605                            unsigned int ep_index, unsigned int stream_id)
606 {
607         struct xhci_ep_ctx *ep_ctx;
608         struct xhci_stream_ctx *st_ctx;
609         struct xhci_virt_ep *ep;
610
611         ep = &vdev->eps[ep_index];
612
613         if (ep->ep_state & EP_HAS_STREAMS) {
614                 st_ctx = &ep->stream_info->stream_ctx_array[stream_id];
615                 return le64_to_cpu(st_ctx->stream_ring);
616         }
617         ep_ctx = xhci_get_ep_ctx(xhci, vdev->out_ctx, ep_index);
618         return le64_to_cpu(ep_ctx->deq);
619 }
620
621 static int xhci_move_dequeue_past_td(struct xhci_hcd *xhci,
622                                 unsigned int slot_id, unsigned int ep_index,
623                                 unsigned int stream_id, struct xhci_td *td)
624 {
625         struct xhci_virt_device *dev = xhci->devs[slot_id];
626         struct xhci_virt_ep *ep = &dev->eps[ep_index];
627         struct xhci_ring *ep_ring;
628         struct xhci_command *cmd;
629         struct xhci_segment *new_seg;
630         union xhci_trb *new_deq;
631         int new_cycle;
632         dma_addr_t addr;
633         u64 hw_dequeue;
634         bool cycle_found = false;
635         bool td_last_trb_found = false;
636         u32 trb_sct = 0;
637         int ret;
638
639         ep_ring = xhci_triad_to_transfer_ring(xhci, slot_id,
640                         ep_index, stream_id);
641         if (!ep_ring) {
642                 xhci_warn(xhci, "WARN can't find new dequeue, invalid stream ID %u\n",
643                           stream_id);
644                 return -ENODEV;
645         }
646         /*
647          * A cancelled TD can complete with a stall if HW cached the trb.
648          * In this case driver can't find td, but if the ring is empty we
649          * can move the dequeue pointer to the current enqueue position.
650          * We shouldn't hit this anymore as cached cancelled TRBs are given back
651          * after clearing the cache, but be on the safe side and keep it anyway
652          */
653         if (!td) {
654                 if (list_empty(&ep_ring->td_list)) {
655                         new_seg = ep_ring->enq_seg;
656                         new_deq = ep_ring->enqueue;
657                         new_cycle = ep_ring->cycle_state;
658                         xhci_dbg(xhci, "ep ring empty, Set new dequeue = enqueue");
659                         goto deq_found;
660                 } else {
661                         xhci_warn(xhci, "Can't find new dequeue state, missing td\n");
662                         return -EINVAL;
663                 }
664         }
665
666         hw_dequeue = xhci_get_hw_deq(xhci, dev, ep_index, stream_id);
667         new_seg = ep_ring->deq_seg;
668         new_deq = ep_ring->dequeue;
669         new_cycle = hw_dequeue & 0x1;
670
671         /*
672          * We want to find the pointer, segment and cycle state of the new trb
673          * (the one after current TD's last_trb). We know the cycle state at
674          * hw_dequeue, so walk the ring until both hw_dequeue and last_trb are
675          * found.
676          */
677         do {
678                 if (!cycle_found && xhci_trb_virt_to_dma(new_seg, new_deq)
679                     == (dma_addr_t)(hw_dequeue & ~0xf)) {
680                         cycle_found = true;
681                         if (td_last_trb_found)
682                                 break;
683                 }
684                 if (new_deq == td->last_trb)
685                         td_last_trb_found = true;
686
687                 if (cycle_found && trb_is_link(new_deq) &&
688                     link_trb_toggles_cycle(new_deq))
689                         new_cycle ^= 0x1;
690
691                 next_trb(xhci, ep_ring, &new_seg, &new_deq);
692
693                 /* Search wrapped around, bail out */
694                 if (new_deq == ep->ring->dequeue) {
695                         xhci_err(xhci, "Error: Failed finding new dequeue state\n");
696                         return -EINVAL;
697                 }
698
699         } while (!cycle_found || !td_last_trb_found);
700
701 deq_found:
702
703         /* Don't update the ring cycle state for the producer (us). */
704         addr = xhci_trb_virt_to_dma(new_seg, new_deq);
705         if (addr == 0) {
706                 xhci_warn(xhci, "Can't find dma of new dequeue ptr\n");
707                 xhci_warn(xhci, "deq seg = %p, deq ptr = %p\n", new_seg, new_deq);
708                 return -EINVAL;
709         }
710
711         if ((ep->ep_state & SET_DEQ_PENDING)) {
712                 xhci_warn(xhci, "Set TR Deq already pending, don't submit for 0x%pad\n",
713                           &addr);
714                 return -EBUSY;
715         }
716
717         /* This function gets called from contexts where it cannot sleep */
718         cmd = xhci_alloc_command(xhci, false, GFP_ATOMIC);
719         if (!cmd) {
720                 xhci_warn(xhci, "Can't alloc Set TR Deq cmd 0x%pad\n", &addr);
721                 return -ENOMEM;
722         }
723
724         if (stream_id)
725                 trb_sct = SCT_FOR_TRB(SCT_PRI_TR);
726         ret = queue_command(xhci, cmd,
727                 lower_32_bits(addr) | trb_sct | new_cycle,
728                 upper_32_bits(addr),
729                 STREAM_ID_FOR_TRB(stream_id), SLOT_ID_FOR_TRB(slot_id) |
730                 EP_ID_FOR_TRB(ep_index) | TRB_TYPE(TRB_SET_DEQ), false);
731         if (ret < 0) {
732                 xhci_free_command(xhci, cmd);
733                 return ret;
734         }
735         ep->queued_deq_seg = new_seg;
736         ep->queued_deq_ptr = new_deq;
737
738         xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
739                        "Set TR Deq ptr 0x%llx, cycle %u\n", addr, new_cycle);
740
741         /* Stop the TD queueing code from ringing the doorbell until
742          * this command completes.  The HC won't set the dequeue pointer
743          * if the ring is running, and ringing the doorbell starts the
744          * ring running.
745          */
746         ep->ep_state |= SET_DEQ_PENDING;
747         xhci_ring_cmd_db(xhci);
748         return 0;
749 }
750
751 /* flip_cycle means flip the cycle bit of all but the first and last TRB.
752  * (The last TRB actually points to the ring enqueue pointer, which is not part
753  * of this TD.)  This is used to remove partially enqueued isoc TDs from a ring.
754  */
755 static void td_to_noop(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
756                        struct xhci_td *td, bool flip_cycle)
757 {
758         struct xhci_segment *seg        = td->start_seg;
759         union xhci_trb *trb             = td->first_trb;
760
761         while (1) {
762                 trb_to_noop(trb, TRB_TR_NOOP);
763
764                 /* flip cycle if asked to */
765                 if (flip_cycle && trb != td->first_trb && trb != td->last_trb)
766                         trb->generic.field[3] ^= cpu_to_le32(TRB_CYCLE);
767
768                 if (trb == td->last_trb)
769                         break;
770
771                 next_trb(xhci, ep_ring, &seg, &trb);
772         }
773 }
774
775 /*
776  * Must be called with xhci->lock held in interrupt context,
777  * releases and re-acquires xhci->lock
778  */
779 static void xhci_giveback_urb_in_irq(struct xhci_hcd *xhci,
780                                      struct xhci_td *cur_td, int status)
781 {
782         struct urb      *urb            = cur_td->urb;
783         struct urb_priv *urb_priv       = urb->hcpriv;
784         struct usb_hcd  *hcd            = bus_to_hcd(urb->dev->bus);
785
786         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
787                 xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs--;
788                 if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) {
789                         if (xhci->quirks & XHCI_AMD_PLL_FIX)
790                                 usb_amd_quirk_pll_enable();
791                 }
792         }
793         xhci_urb_free_priv(urb_priv);
794         usb_hcd_unlink_urb_from_ep(hcd, urb);
795         trace_xhci_urb_giveback(urb);
796         usb_hcd_giveback_urb(hcd, urb, status);
797 }
798
799 static void xhci_unmap_td_bounce_buffer(struct xhci_hcd *xhci,
800                 struct xhci_ring *ring, struct xhci_td *td)
801 {
802         struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
803         struct xhci_segment *seg = td->bounce_seg;
804         struct urb *urb = td->urb;
805         size_t len;
806
807         if (!ring || !seg || !urb)
808                 return;
809
810         if (usb_urb_dir_out(urb)) {
811                 dma_unmap_single(dev, seg->bounce_dma, ring->bounce_buf_len,
812                                  DMA_TO_DEVICE);
813                 return;
814         }
815
816         dma_unmap_single(dev, seg->bounce_dma, ring->bounce_buf_len,
817                          DMA_FROM_DEVICE);
818         /* for in tranfers we need to copy the data from bounce to sg */
819         if (urb->num_sgs) {
820                 len = sg_pcopy_from_buffer(urb->sg, urb->num_sgs, seg->bounce_buf,
821                                            seg->bounce_len, seg->bounce_offs);
822                 if (len != seg->bounce_len)
823                         xhci_warn(xhci, "WARN Wrong bounce buffer read length: %zu != %d\n",
824                                   len, seg->bounce_len);
825         } else {
826                 memcpy(urb->transfer_buffer + seg->bounce_offs, seg->bounce_buf,
827                        seg->bounce_len);
828         }
829         seg->bounce_len = 0;
830         seg->bounce_offs = 0;
831 }
832
833 static int xhci_td_cleanup(struct xhci_hcd *xhci, struct xhci_td *td,
834                            struct xhci_ring *ep_ring, int status)
835 {
836         struct urb *urb = NULL;
837
838         /* Clean up the endpoint's TD list */
839         urb = td->urb;
840
841         /* if a bounce buffer was used to align this td then unmap it */
842         xhci_unmap_td_bounce_buffer(xhci, ep_ring, td);
843
844         /* Do one last check of the actual transfer length.
845          * If the host controller said we transferred more data than the buffer
846          * length, urb->actual_length will be a very big number (since it's
847          * unsigned).  Play it safe and say we didn't transfer anything.
848          */
849         if (urb->actual_length > urb->transfer_buffer_length) {
850                 xhci_warn(xhci, "URB req %u and actual %u transfer length mismatch\n",
851                           urb->transfer_buffer_length, urb->actual_length);
852                 urb->actual_length = 0;
853                 status = 0;
854         }
855         /* TD might be removed from td_list if we are giving back a cancelled URB */
856         if (!list_empty(&td->td_list))
857                 list_del_init(&td->td_list);
858         /* Giving back a cancelled URB, or if a slated TD completed anyway */
859         if (!list_empty(&td->cancelled_td_list))
860                 list_del_init(&td->cancelled_td_list);
861
862         inc_td_cnt(urb);
863         /* Giveback the urb when all the tds are completed */
864         if (last_td_in_urb(td)) {
865                 if ((urb->actual_length != urb->transfer_buffer_length &&
866                      (urb->transfer_flags & URB_SHORT_NOT_OK)) ||
867                     (status != 0 && !usb_endpoint_xfer_isoc(&urb->ep->desc)))
868                         xhci_dbg(xhci, "Giveback URB %p, len = %d, expected = %d, status = %d\n",
869                                  urb, urb->actual_length,
870                                  urb->transfer_buffer_length, status);
871
872                 /* set isoc urb status to 0 just as EHCI, UHCI, and OHCI */
873                 if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS)
874                         status = 0;
875                 xhci_giveback_urb_in_irq(xhci, td, status);
876         }
877
878         return 0;
879 }
880
881
882 /* Complete the cancelled URBs we unlinked from td_list. */
883 static void xhci_giveback_invalidated_tds(struct xhci_virt_ep *ep)
884 {
885         struct xhci_ring *ring;
886         struct xhci_td *td, *tmp_td;
887
888         list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list,
889                                  cancelled_td_list) {
890
891                 ring = xhci_urb_to_transfer_ring(ep->xhci, td->urb);
892
893                 if (td->cancel_status == TD_CLEARED) {
894                         xhci_dbg(ep->xhci, "%s: Giveback cancelled URB %p TD\n",
895                                  __func__, td->urb);
896                         xhci_td_cleanup(ep->xhci, td, ring, td->status);
897                 } else {
898                         xhci_dbg(ep->xhci, "%s: Keep cancelled URB %p TD as cancel_status is %d\n",
899                                  __func__, td->urb, td->cancel_status);
900                 }
901                 if (ep->xhci->xhc_state & XHCI_STATE_DYING)
902                         return;
903         }
904 }
905
906 static int xhci_reset_halted_ep(struct xhci_hcd *xhci, unsigned int slot_id,
907                                 unsigned int ep_index, enum xhci_ep_reset_type reset_type)
908 {
909         struct xhci_command *command;
910         int ret = 0;
911
912         command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
913         if (!command) {
914                 ret = -ENOMEM;
915                 goto done;
916         }
917
918         xhci_dbg(xhci, "%s-reset ep %u, slot %u\n",
919                  (reset_type == EP_HARD_RESET) ? "Hard" : "Soft",
920                  ep_index, slot_id);
921
922         ret = xhci_queue_reset_ep(xhci, command, slot_id, ep_index, reset_type);
923 done:
924         if (ret)
925                 xhci_err(xhci, "ERROR queuing reset endpoint for slot %d ep_index %d, %d\n",
926                          slot_id, ep_index, ret);
927         return ret;
928 }
929
930 static int xhci_handle_halted_endpoint(struct xhci_hcd *xhci,
931                                 struct xhci_virt_ep *ep,
932                                 struct xhci_td *td,
933                                 enum xhci_ep_reset_type reset_type)
934 {
935         unsigned int slot_id = ep->vdev->slot_id;
936         int err;
937
938         /*
939          * Avoid resetting endpoint if link is inactive. Can cause host hang.
940          * Device will be reset soon to recover the link so don't do anything
941          */
942         if (ep->vdev->flags & VDEV_PORT_ERROR)
943                 return -ENODEV;
944
945         /* add td to cancelled list and let reset ep handler take care of it */
946         if (reset_type == EP_HARD_RESET) {
947                 ep->ep_state |= EP_HARD_CLEAR_TOGGLE;
948                 if (td && list_empty(&td->cancelled_td_list)) {
949                         list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
950                         td->cancel_status = TD_HALTED;
951                 }
952         }
953
954         if (ep->ep_state & EP_HALTED) {
955                 xhci_dbg(xhci, "Reset ep command for ep_index %d already pending\n",
956                          ep->ep_index);
957                 return 0;
958         }
959
960         err = xhci_reset_halted_ep(xhci, slot_id, ep->ep_index, reset_type);
961         if (err)
962                 return err;
963
964         ep->ep_state |= EP_HALTED;
965
966         xhci_ring_cmd_db(xhci);
967
968         return 0;
969 }
970
971 /*
972  * Fix up the ep ring first, so HW stops executing cancelled TDs.
973  * We have the xHCI lock, so nothing can modify this list until we drop it.
974  * We're also in the event handler, so we can't get re-interrupted if another
975  * Stop Endpoint command completes.
976  *
977  * only call this when ring is not in a running state
978  */
979
980 static int xhci_invalidate_cancelled_tds(struct xhci_virt_ep *ep)
981 {
982         struct xhci_hcd         *xhci;
983         struct xhci_td          *td = NULL;
984         struct xhci_td          *tmp_td = NULL;
985         struct xhci_td          *cached_td = NULL;
986         struct xhci_ring        *ring;
987         u64                     hw_deq;
988         unsigned int            slot_id = ep->vdev->slot_id;
989         int                     err;
990
991         xhci = ep->xhci;
992
993         list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list, cancelled_td_list) {
994                 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
995                                "Removing canceled TD starting at 0x%llx (dma) in stream %u URB %p",
996                                (unsigned long long)xhci_trb_virt_to_dma(
997                                        td->start_seg, td->first_trb),
998                                td->urb->stream_id, td->urb);
999                 list_del_init(&td->td_list);
1000                 ring = xhci_urb_to_transfer_ring(xhci, td->urb);
1001                 if (!ring) {
1002                         xhci_warn(xhci, "WARN Cancelled URB %p has invalid stream ID %u.\n",
1003                                   td->urb, td->urb->stream_id);
1004                         continue;
1005                 }
1006                 /*
1007                  * If a ring stopped on the TD we need to cancel then we have to
1008                  * move the xHC endpoint ring dequeue pointer past this TD.
1009                  * Rings halted due to STALL may show hw_deq is past the stalled
1010                  * TD, but still require a set TR Deq command to flush xHC cache.
1011                  */
1012                 hw_deq = xhci_get_hw_deq(xhci, ep->vdev, ep->ep_index,
1013                                          td->urb->stream_id);
1014                 hw_deq &= ~0xf;
1015
1016                 if (td->cancel_status == TD_HALTED ||
1017                     trb_in_td(xhci, td->start_seg, td->first_trb, td->last_trb, hw_deq, false)) {
1018                         switch (td->cancel_status) {
1019                         case TD_CLEARED: /* TD is already no-op */
1020                         case TD_CLEARING_CACHE: /* set TR deq command already queued */
1021                                 break;
1022                         case TD_DIRTY: /* TD is cached, clear it */
1023                         case TD_HALTED:
1024                                 td->cancel_status = TD_CLEARING_CACHE;
1025                                 if (cached_td)
1026                                         /* FIXME  stream case, several stopped rings */
1027                                         xhci_dbg(xhci,
1028                                                  "Move dq past stream %u URB %p instead of stream %u URB %p\n",
1029                                                  td->urb->stream_id, td->urb,
1030                                                  cached_td->urb->stream_id, cached_td->urb);
1031                                 cached_td = td;
1032                                 break;
1033                         }
1034                 } else {
1035                         td_to_noop(xhci, ring, td, false);
1036                         td->cancel_status = TD_CLEARED;
1037                 }
1038         }
1039
1040         /* If there's no need to move the dequeue pointer then we're done */
1041         if (!cached_td)
1042                 return 0;
1043
1044         err = xhci_move_dequeue_past_td(xhci, slot_id, ep->ep_index,
1045                                         cached_td->urb->stream_id,
1046                                         cached_td);
1047         if (err) {
1048                 /* Failed to move past cached td, just set cached TDs to no-op */
1049                 list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list, cancelled_td_list) {
1050                         if (td->cancel_status != TD_CLEARING_CACHE)
1051                                 continue;
1052                         xhci_dbg(xhci, "Failed to clear cancelled cached URB %p, mark clear anyway\n",
1053                                  td->urb);
1054                         td_to_noop(xhci, ring, td, false);
1055                         td->cancel_status = TD_CLEARED;
1056                 }
1057         }
1058         return 0;
1059 }
1060
1061 /*
1062  * Returns the TD the endpoint ring halted on.
1063  * Only call for non-running rings without streams.
1064  */
1065 static struct xhci_td *find_halted_td(struct xhci_virt_ep *ep)
1066 {
1067         struct xhci_td  *td;
1068         u64             hw_deq;
1069
1070         if (!list_empty(&ep->ring->td_list)) { /* Not streams compatible */
1071                 hw_deq = xhci_get_hw_deq(ep->xhci, ep->vdev, ep->ep_index, 0);
1072                 hw_deq &= ~0xf;
1073                 td = list_first_entry(&ep->ring->td_list, struct xhci_td, td_list);
1074                 if (trb_in_td(ep->xhci, td->start_seg, td->first_trb,
1075                                 td->last_trb, hw_deq, false))
1076                         return td;
1077         }
1078         return NULL;
1079 }
1080
1081 /*
1082  * When we get a command completion for a Stop Endpoint Command, we need to
1083  * unlink any cancelled TDs from the ring.  There are two ways to do that:
1084  *
1085  *  1. If the HW was in the middle of processing the TD that needs to be
1086  *     cancelled, then we must move the ring's dequeue pointer past the last TRB
1087  *     in the TD with a Set Dequeue Pointer Command.
1088  *  2. Otherwise, we turn all the TRBs in the TD into No-op TRBs (with the chain
1089  *     bit cleared) so that the HW will skip over them.
1090  */
1091 static void xhci_handle_cmd_stop_ep(struct xhci_hcd *xhci, int slot_id,
1092                                     union xhci_trb *trb, u32 comp_code)
1093 {
1094         unsigned int ep_index;
1095         struct xhci_virt_ep *ep;
1096         struct xhci_ep_ctx *ep_ctx;
1097         struct xhci_td *td = NULL;
1098         enum xhci_ep_reset_type reset_type;
1099         struct xhci_command *command;
1100         int err;
1101
1102         if (unlikely(TRB_TO_SUSPEND_PORT(le32_to_cpu(trb->generic.field[3])))) {
1103                 if (!xhci->devs[slot_id])
1104                         xhci_warn(xhci, "Stop endpoint command completion for disabled slot %u\n",
1105                                   slot_id);
1106                 return;
1107         }
1108
1109         ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1110         ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1111         if (!ep)
1112                 return;
1113
1114         ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1115
1116         trace_xhci_handle_cmd_stop_ep(ep_ctx);
1117
1118         if (comp_code == COMP_CONTEXT_STATE_ERROR) {
1119         /*
1120          * If stop endpoint command raced with a halting endpoint we need to
1121          * reset the host side endpoint first.
1122          * If the TD we halted on isn't cancelled the TD should be given back
1123          * with a proper error code, and the ring dequeue moved past the TD.
1124          * If streams case we can't find hw_deq, or the TD we halted on so do a
1125          * soft reset.
1126          *
1127          * Proper error code is unknown here, it would be -EPIPE if device side
1128          * of enadpoit halted (aka STALL), and -EPROTO if not (transaction error)
1129          * We use -EPROTO, if device is stalled it should return a stall error on
1130          * next transfer, which then will return -EPIPE, and device side stall is
1131          * noted and cleared by class driver.
1132          */
1133                 switch (GET_EP_CTX_STATE(ep_ctx)) {
1134                 case EP_STATE_HALTED:
1135                         xhci_dbg(xhci, "Stop ep completion raced with stall, reset ep\n");
1136                         if (ep->ep_state & EP_HAS_STREAMS) {
1137                                 reset_type = EP_SOFT_RESET;
1138                         } else {
1139                                 reset_type = EP_HARD_RESET;
1140                                 td = find_halted_td(ep);
1141                                 if (td)
1142                                         td->status = -EPROTO;
1143                         }
1144                         /* reset ep, reset handler cleans up cancelled tds */
1145                         err = xhci_handle_halted_endpoint(xhci, ep, td, reset_type);
1146                         if (err)
1147                                 break;
1148                         ep->ep_state &= ~EP_STOP_CMD_PENDING;
1149                         return;
1150                 case EP_STATE_RUNNING:
1151                         /* Race, HW handled stop ep cmd before ep was running */
1152                         xhci_dbg(xhci, "Stop ep completion ctx error, ep is running\n");
1153
1154                         command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
1155                         if (!command) {
1156                                 ep->ep_state &= ~EP_STOP_CMD_PENDING;
1157                                 return;
1158                         }
1159                         xhci_queue_stop_endpoint(xhci, command, slot_id, ep_index, 0);
1160                         xhci_ring_cmd_db(xhci);
1161
1162                         return;
1163                 default:
1164                         break;
1165                 }
1166         }
1167
1168         /* will queue a set TR deq if stopped on a cancelled, uncleared TD */
1169         xhci_invalidate_cancelled_tds(ep);
1170         ep->ep_state &= ~EP_STOP_CMD_PENDING;
1171
1172         /* Otherwise ring the doorbell(s) to restart queued transfers */
1173         xhci_giveback_invalidated_tds(ep);
1174         ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1175 }
1176
1177 static void xhci_kill_ring_urbs(struct xhci_hcd *xhci, struct xhci_ring *ring)
1178 {
1179         struct xhci_td *cur_td;
1180         struct xhci_td *tmp;
1181
1182         list_for_each_entry_safe(cur_td, tmp, &ring->td_list, td_list) {
1183                 list_del_init(&cur_td->td_list);
1184
1185                 if (!list_empty(&cur_td->cancelled_td_list))
1186                         list_del_init(&cur_td->cancelled_td_list);
1187
1188                 xhci_unmap_td_bounce_buffer(xhci, ring, cur_td);
1189
1190                 inc_td_cnt(cur_td->urb);
1191                 if (last_td_in_urb(cur_td))
1192                         xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN);
1193         }
1194 }
1195
1196 static void xhci_kill_endpoint_urbs(struct xhci_hcd *xhci,
1197                 int slot_id, int ep_index)
1198 {
1199         struct xhci_td *cur_td;
1200         struct xhci_td *tmp;
1201         struct xhci_virt_ep *ep;
1202         struct xhci_ring *ring;
1203
1204         ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1205         if (!ep)
1206                 return;
1207
1208         if ((ep->ep_state & EP_HAS_STREAMS) ||
1209                         (ep->ep_state & EP_GETTING_NO_STREAMS)) {
1210                 int stream_id;
1211
1212                 for (stream_id = 1; stream_id < ep->stream_info->num_streams;
1213                                 stream_id++) {
1214                         ring = ep->stream_info->stream_rings[stream_id];
1215                         if (!ring)
1216                                 continue;
1217
1218                         xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1219                                         "Killing URBs for slot ID %u, ep index %u, stream %u",
1220                                         slot_id, ep_index, stream_id);
1221                         xhci_kill_ring_urbs(xhci, ring);
1222                 }
1223         } else {
1224                 ring = ep->ring;
1225                 if (!ring)
1226                         return;
1227                 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1228                                 "Killing URBs for slot ID %u, ep index %u",
1229                                 slot_id, ep_index);
1230                 xhci_kill_ring_urbs(xhci, ring);
1231         }
1232
1233         list_for_each_entry_safe(cur_td, tmp, &ep->cancelled_td_list,
1234                         cancelled_td_list) {
1235                 list_del_init(&cur_td->cancelled_td_list);
1236                 inc_td_cnt(cur_td->urb);
1237
1238                 if (last_td_in_urb(cur_td))
1239                         xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN);
1240         }
1241 }
1242
1243 /*
1244  * host controller died, register read returns 0xffffffff
1245  * Complete pending commands, mark them ABORTED.
1246  * URBs need to be given back as usb core might be waiting with device locks
1247  * held for the URBs to finish during device disconnect, blocking host remove.
1248  *
1249  * Call with xhci->lock held.
1250  * lock is relased and re-acquired while giving back urb.
1251  */
1252 void xhci_hc_died(struct xhci_hcd *xhci)
1253 {
1254         int i, j;
1255
1256         if (xhci->xhc_state & XHCI_STATE_DYING)
1257                 return;
1258
1259         xhci_err(xhci, "xHCI host controller not responding, assume dead\n");
1260         xhci->xhc_state |= XHCI_STATE_DYING;
1261
1262         xhci_cleanup_command_queue(xhci);
1263
1264         /* return any pending urbs, remove may be waiting for them */
1265         for (i = 0; i <= HCS_MAX_SLOTS(xhci->hcs_params1); i++) {
1266                 if (!xhci->devs[i])
1267                         continue;
1268                 for (j = 0; j < 31; j++)
1269                         xhci_kill_endpoint_urbs(xhci, i, j);
1270         }
1271
1272         /* inform usb core hc died if PCI remove isn't already handling it */
1273         if (!(xhci->xhc_state & XHCI_STATE_REMOVING))
1274                 usb_hc_died(xhci_to_hcd(xhci));
1275 }
1276
1277 static void update_ring_for_set_deq_completion(struct xhci_hcd *xhci,
1278                 struct xhci_virt_device *dev,
1279                 struct xhci_ring *ep_ring,
1280                 unsigned int ep_index)
1281 {
1282         union xhci_trb *dequeue_temp;
1283
1284         dequeue_temp = ep_ring->dequeue;
1285
1286         /* If we get two back-to-back stalls, and the first stalled transfer
1287          * ends just before a link TRB, the dequeue pointer will be left on
1288          * the link TRB by the code in the while loop.  So we have to update
1289          * the dequeue pointer one segment further, or we'll jump off
1290          * the segment into la-la-land.
1291          */
1292         if (trb_is_link(ep_ring->dequeue)) {
1293                 ep_ring->deq_seg = ep_ring->deq_seg->next;
1294                 ep_ring->dequeue = ep_ring->deq_seg->trbs;
1295         }
1296
1297         while (ep_ring->dequeue != dev->eps[ep_index].queued_deq_ptr) {
1298                 /* We have more usable TRBs */
1299                 ep_ring->dequeue++;
1300                 if (trb_is_link(ep_ring->dequeue)) {
1301                         if (ep_ring->dequeue ==
1302                                         dev->eps[ep_index].queued_deq_ptr)
1303                                 break;
1304                         ep_ring->deq_seg = ep_ring->deq_seg->next;
1305                         ep_ring->dequeue = ep_ring->deq_seg->trbs;
1306                 }
1307                 if (ep_ring->dequeue == dequeue_temp) {
1308                         xhci_dbg(xhci, "Unable to find new dequeue pointer\n");
1309                         break;
1310                 }
1311         }
1312 }
1313
1314 /*
1315  * When we get a completion for a Set Transfer Ring Dequeue Pointer command,
1316  * we need to clear the set deq pending flag in the endpoint ring state, so that
1317  * the TD queueing code can ring the doorbell again.  We also need to ring the
1318  * endpoint doorbell to restart the ring, but only if there aren't more
1319  * cancellations pending.
1320  */
1321 static void xhci_handle_cmd_set_deq(struct xhci_hcd *xhci, int slot_id,
1322                 union xhci_trb *trb, u32 cmd_comp_code)
1323 {
1324         unsigned int ep_index;
1325         unsigned int stream_id;
1326         struct xhci_ring *ep_ring;
1327         struct xhci_virt_ep *ep;
1328         struct xhci_ep_ctx *ep_ctx;
1329         struct xhci_slot_ctx *slot_ctx;
1330         struct xhci_td *td, *tmp_td;
1331
1332         ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1333         stream_id = TRB_TO_STREAM_ID(le32_to_cpu(trb->generic.field[2]));
1334         ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1335         if (!ep)
1336                 return;
1337
1338         ep_ring = xhci_virt_ep_to_ring(xhci, ep, stream_id);
1339         if (!ep_ring) {
1340                 xhci_warn(xhci, "WARN Set TR deq ptr command for freed stream ID %u\n",
1341                                 stream_id);
1342                 /* XXX: Harmless??? */
1343                 goto cleanup;
1344         }
1345
1346         ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1347         slot_ctx = xhci_get_slot_ctx(xhci, ep->vdev->out_ctx);
1348         trace_xhci_handle_cmd_set_deq(slot_ctx);
1349         trace_xhci_handle_cmd_set_deq_ep(ep_ctx);
1350
1351         if (cmd_comp_code != COMP_SUCCESS) {
1352                 unsigned int ep_state;
1353                 unsigned int slot_state;
1354
1355                 switch (cmd_comp_code) {
1356                 case COMP_TRB_ERROR:
1357                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because of stream ID configuration\n");
1358                         break;
1359                 case COMP_CONTEXT_STATE_ERROR:
1360                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due to incorrect slot or ep state.\n");
1361                         ep_state = GET_EP_CTX_STATE(ep_ctx);
1362                         slot_state = le32_to_cpu(slot_ctx->dev_state);
1363                         slot_state = GET_SLOT_STATE(slot_state);
1364                         xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1365                                         "Slot state = %u, EP state = %u",
1366                                         slot_state, ep_state);
1367                         break;
1368                 case COMP_SLOT_NOT_ENABLED_ERROR:
1369                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because slot %u was not enabled.\n",
1370                                         slot_id);
1371                         break;
1372                 default:
1373                         xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown completion code of %u.\n",
1374                                         cmd_comp_code);
1375                         break;
1376                 }
1377                 /* OK what do we do now?  The endpoint state is hosed, and we
1378                  * should never get to this point if the synchronization between
1379                  * queueing, and endpoint state are correct.  This might happen
1380                  * if the device gets disconnected after we've finished
1381                  * cancelling URBs, which might not be an error...
1382                  */
1383         } else {
1384                 u64 deq;
1385                 /* 4.6.10 deq ptr is written to the stream ctx for streams */
1386                 if (ep->ep_state & EP_HAS_STREAMS) {
1387                         struct xhci_stream_ctx *ctx =
1388                                 &ep->stream_info->stream_ctx_array[stream_id];
1389                         deq = le64_to_cpu(ctx->stream_ring) & SCTX_DEQ_MASK;
1390                 } else {
1391                         deq = le64_to_cpu(ep_ctx->deq) & ~EP_CTX_CYCLE_MASK;
1392                 }
1393                 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1394                         "Successful Set TR Deq Ptr cmd, deq = @%08llx", deq);
1395                 if (xhci_trb_virt_to_dma(ep->queued_deq_seg,
1396                                          ep->queued_deq_ptr) == deq) {
1397                         /* Update the ring's dequeue segment and dequeue pointer
1398                          * to reflect the new position.
1399                          */
1400                         update_ring_for_set_deq_completion(xhci, ep->vdev,
1401                                 ep_ring, ep_index);
1402                 } else {
1403                         xhci_warn(xhci, "Mismatch between completed Set TR Deq Ptr command & xHCI internal state.\n");
1404                         xhci_warn(xhci, "ep deq seg = %p, deq ptr = %p\n",
1405                                   ep->queued_deq_seg, ep->queued_deq_ptr);
1406                 }
1407         }
1408         /* HW cached TDs cleared from cache, give them back */
1409         list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list,
1410                                  cancelled_td_list) {
1411                 ep_ring = xhci_urb_to_transfer_ring(ep->xhci, td->urb);
1412                 if (td->cancel_status == TD_CLEARING_CACHE) {
1413                         td->cancel_status = TD_CLEARED;
1414                         xhci_dbg(ep->xhci, "%s: Giveback cancelled URB %p TD\n",
1415                                  __func__, td->urb);
1416                         xhci_td_cleanup(ep->xhci, td, ep_ring, td->status);
1417                 } else {
1418                         xhci_dbg(ep->xhci, "%s: Keep cancelled URB %p TD as cancel_status is %d\n",
1419                                  __func__, td->urb, td->cancel_status);
1420                 }
1421         }
1422 cleanup:
1423         ep->ep_state &= ~SET_DEQ_PENDING;
1424         ep->queued_deq_seg = NULL;
1425         ep->queued_deq_ptr = NULL;
1426         /* Restart any rings with pending URBs */
1427         ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1428 }
1429
1430 static void xhci_handle_cmd_reset_ep(struct xhci_hcd *xhci, int slot_id,
1431                 union xhci_trb *trb, u32 cmd_comp_code)
1432 {
1433         struct xhci_virt_ep *ep;
1434         struct xhci_ep_ctx *ep_ctx;
1435         unsigned int ep_index;
1436
1437         ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1438         ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1439         if (!ep)
1440                 return;
1441
1442         ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1443         trace_xhci_handle_cmd_reset_ep(ep_ctx);
1444
1445         /* This command will only fail if the endpoint wasn't halted,
1446          * but we don't care.
1447          */
1448         xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
1449                 "Ignoring reset ep completion code of %u", cmd_comp_code);
1450
1451         /* Cleanup cancelled TDs as ep is stopped. May queue a Set TR Deq cmd */
1452         xhci_invalidate_cancelled_tds(ep);
1453
1454         /* Clear our internal halted state */
1455         ep->ep_state &= ~EP_HALTED;
1456
1457         xhci_giveback_invalidated_tds(ep);
1458
1459         /* if this was a soft reset, then restart */
1460         if ((le32_to_cpu(trb->generic.field[3])) & TRB_TSP)
1461                 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1462 }
1463
1464 static void xhci_handle_cmd_enable_slot(struct xhci_hcd *xhci, int slot_id,
1465                 struct xhci_command *command, u32 cmd_comp_code)
1466 {
1467         if (cmd_comp_code == COMP_SUCCESS)
1468                 command->slot_id = slot_id;
1469         else
1470                 command->slot_id = 0;
1471 }
1472
1473 static void xhci_handle_cmd_disable_slot(struct xhci_hcd *xhci, int slot_id)
1474 {
1475         struct xhci_virt_device *virt_dev;
1476         struct xhci_slot_ctx *slot_ctx;
1477
1478         virt_dev = xhci->devs[slot_id];
1479         if (!virt_dev)
1480                 return;
1481
1482         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
1483         trace_xhci_handle_cmd_disable_slot(slot_ctx);
1484
1485         if (xhci->quirks & XHCI_EP_LIMIT_QUIRK)
1486                 /* Delete default control endpoint resources */
1487                 xhci_free_device_endpoint_resources(xhci, virt_dev, true);
1488 }
1489
1490 static void xhci_handle_cmd_config_ep(struct xhci_hcd *xhci, int slot_id,
1491                 u32 cmd_comp_code)
1492 {
1493         struct xhci_virt_device *virt_dev;
1494         struct xhci_input_control_ctx *ctrl_ctx;
1495         struct xhci_ep_ctx *ep_ctx;
1496         unsigned int ep_index;
1497         u32 add_flags;
1498
1499         /*
1500          * Configure endpoint commands can come from the USB core configuration
1501          * or alt setting changes, or when streams were being configured.
1502          */
1503
1504         virt_dev = xhci->devs[slot_id];
1505         if (!virt_dev)
1506                 return;
1507         ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1508         if (!ctrl_ctx) {
1509                 xhci_warn(xhci, "Could not get input context, bad type.\n");
1510                 return;
1511         }
1512
1513         add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1514
1515         /* Input ctx add_flags are the endpoint index plus one */
1516         ep_index = xhci_last_valid_endpoint(add_flags) - 1;
1517
1518         ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->out_ctx, ep_index);
1519         trace_xhci_handle_cmd_config_ep(ep_ctx);
1520
1521         return;
1522 }
1523
1524 static void xhci_handle_cmd_addr_dev(struct xhci_hcd *xhci, int slot_id)
1525 {
1526         struct xhci_virt_device *vdev;
1527         struct xhci_slot_ctx *slot_ctx;
1528
1529         vdev = xhci->devs[slot_id];
1530         if (!vdev)
1531                 return;
1532         slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
1533         trace_xhci_handle_cmd_addr_dev(slot_ctx);
1534 }
1535
1536 static void xhci_handle_cmd_reset_dev(struct xhci_hcd *xhci, int slot_id)
1537 {
1538         struct xhci_virt_device *vdev;
1539         struct xhci_slot_ctx *slot_ctx;
1540
1541         vdev = xhci->devs[slot_id];
1542         if (!vdev) {
1543                 xhci_warn(xhci, "Reset device command completion for disabled slot %u\n",
1544                           slot_id);
1545                 return;
1546         }
1547         slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
1548         trace_xhci_handle_cmd_reset_dev(slot_ctx);
1549
1550         xhci_dbg(xhci, "Completed reset device command.\n");
1551 }
1552
1553 static void xhci_handle_cmd_nec_get_fw(struct xhci_hcd *xhci,
1554                 struct xhci_event_cmd *event)
1555 {
1556         if (!(xhci->quirks & XHCI_NEC_HOST)) {
1557                 xhci_warn(xhci, "WARN NEC_GET_FW command on non-NEC host\n");
1558                 return;
1559         }
1560         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1561                         "NEC firmware version %2x.%02x",
1562                         NEC_FW_MAJOR(le32_to_cpu(event->status)),
1563                         NEC_FW_MINOR(le32_to_cpu(event->status)));
1564 }
1565
1566 static void xhci_complete_del_and_free_cmd(struct xhci_command *cmd, u32 status)
1567 {
1568         list_del(&cmd->cmd_list);
1569
1570         if (cmd->completion) {
1571                 cmd->status = status;
1572                 complete(cmd->completion);
1573         } else {
1574                 kfree(cmd);
1575         }
1576 }
1577
1578 void xhci_cleanup_command_queue(struct xhci_hcd *xhci)
1579 {
1580         struct xhci_command *cur_cmd, *tmp_cmd;
1581         xhci->current_cmd = NULL;
1582         list_for_each_entry_safe(cur_cmd, tmp_cmd, &xhci->cmd_list, cmd_list)
1583                 xhci_complete_del_and_free_cmd(cur_cmd, COMP_COMMAND_ABORTED);
1584 }
1585
1586 void xhci_handle_command_timeout(struct work_struct *work)
1587 {
1588         struct xhci_hcd *xhci;
1589         unsigned long   flags;
1590         char            str[XHCI_MSG_MAX];
1591         u64             hw_ring_state;
1592         u32             cmd_field3;
1593         u32             usbsts;
1594
1595         xhci = container_of(to_delayed_work(work), struct xhci_hcd, cmd_timer);
1596
1597         spin_lock_irqsave(&xhci->lock, flags);
1598
1599         /*
1600          * If timeout work is pending, or current_cmd is NULL, it means we
1601          * raced with command completion. Command is handled so just return.
1602          */
1603         if (!xhci->current_cmd || delayed_work_pending(&xhci->cmd_timer)) {
1604                 spin_unlock_irqrestore(&xhci->lock, flags);
1605                 return;
1606         }
1607
1608         cmd_field3 = le32_to_cpu(xhci->current_cmd->command_trb->generic.field[3]);
1609         usbsts = readl(&xhci->op_regs->status);
1610         xhci_dbg(xhci, "Command timeout, USBSTS:%s\n", xhci_decode_usbsts(str, usbsts));
1611
1612         /* Bail out and tear down xhci if a stop endpoint command failed */
1613         if (TRB_FIELD_TO_TYPE(cmd_field3) == TRB_STOP_RING) {
1614                 struct xhci_virt_ep     *ep;
1615
1616                 xhci_warn(xhci, "xHCI host not responding to stop endpoint command\n");
1617
1618                 ep = xhci_get_virt_ep(xhci, TRB_TO_SLOT_ID(cmd_field3),
1619                                       TRB_TO_EP_INDEX(cmd_field3));
1620                 if (ep)
1621                         ep->ep_state &= ~EP_STOP_CMD_PENDING;
1622
1623                 xhci_halt(xhci);
1624                 xhci_hc_died(xhci);
1625                 goto time_out_completed;
1626         }
1627
1628         /* mark this command to be cancelled */
1629         xhci->current_cmd->status = COMP_COMMAND_ABORTED;
1630
1631         /* Make sure command ring is running before aborting it */
1632         hw_ring_state = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
1633         if (hw_ring_state == ~(u64)0) {
1634                 xhci_hc_died(xhci);
1635                 goto time_out_completed;
1636         }
1637
1638         if ((xhci->cmd_ring_state & CMD_RING_STATE_RUNNING) &&
1639             (hw_ring_state & CMD_RING_RUNNING))  {
1640                 /* Prevent new doorbell, and start command abort */
1641                 xhci->cmd_ring_state = CMD_RING_STATE_ABORTED;
1642                 xhci_dbg(xhci, "Command timeout\n");
1643                 xhci_abort_cmd_ring(xhci, flags);
1644                 goto time_out_completed;
1645         }
1646
1647         /* host removed. Bail out */
1648         if (xhci->xhc_state & XHCI_STATE_REMOVING) {
1649                 xhci_dbg(xhci, "host removed, ring start fail?\n");
1650                 xhci_cleanup_command_queue(xhci);
1651
1652                 goto time_out_completed;
1653         }
1654
1655         /* command timeout on stopped ring, ring can't be aborted */
1656         xhci_dbg(xhci, "Command timeout on stopped ring\n");
1657         xhci_handle_stopped_cmd_ring(xhci, xhci->current_cmd);
1658
1659 time_out_completed:
1660         spin_unlock_irqrestore(&xhci->lock, flags);
1661         return;
1662 }
1663
1664 static void handle_cmd_completion(struct xhci_hcd *xhci,
1665                 struct xhci_event_cmd *event)
1666 {
1667         unsigned int slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
1668         u64 cmd_dma;
1669         dma_addr_t cmd_dequeue_dma;
1670         u32 cmd_comp_code;
1671         union xhci_trb *cmd_trb;
1672         struct xhci_command *cmd;
1673         u32 cmd_type;
1674
1675         if (slot_id >= MAX_HC_SLOTS) {
1676                 xhci_warn(xhci, "Invalid slot_id %u\n", slot_id);
1677                 return;
1678         }
1679
1680         cmd_dma = le64_to_cpu(event->cmd_trb);
1681         cmd_trb = xhci->cmd_ring->dequeue;
1682
1683         trace_xhci_handle_command(xhci->cmd_ring, &cmd_trb->generic);
1684
1685         cmd_dequeue_dma = xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
1686                         cmd_trb);
1687         /*
1688          * Check whether the completion event is for our internal kept
1689          * command.
1690          */
1691         if (!cmd_dequeue_dma || cmd_dma != (u64)cmd_dequeue_dma) {
1692                 xhci_warn(xhci,
1693                           "ERROR mismatched command completion event\n");
1694                 return;
1695         }
1696
1697         cmd = list_first_entry(&xhci->cmd_list, struct xhci_command, cmd_list);
1698
1699         cancel_delayed_work(&xhci->cmd_timer);
1700
1701         cmd_comp_code = GET_COMP_CODE(le32_to_cpu(event->status));
1702
1703         /* If CMD ring stopped we own the trbs between enqueue and dequeue */
1704         if (cmd_comp_code == COMP_COMMAND_RING_STOPPED) {
1705                 complete_all(&xhci->cmd_ring_stop_completion);
1706                 return;
1707         }
1708
1709         if (cmd->command_trb != xhci->cmd_ring->dequeue) {
1710                 xhci_err(xhci,
1711                          "Command completion event does not match command\n");
1712                 return;
1713         }
1714
1715         /*
1716          * Host aborted the command ring, check if the current command was
1717          * supposed to be aborted, otherwise continue normally.
1718          * The command ring is stopped now, but the xHC will issue a Command
1719          * Ring Stopped event which will cause us to restart it.
1720          */
1721         if (cmd_comp_code == COMP_COMMAND_ABORTED) {
1722                 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
1723                 if (cmd->status == COMP_COMMAND_ABORTED) {
1724                         if (xhci->current_cmd == cmd)
1725                                 xhci->current_cmd = NULL;
1726                         goto event_handled;
1727                 }
1728         }
1729
1730         cmd_type = TRB_FIELD_TO_TYPE(le32_to_cpu(cmd_trb->generic.field[3]));
1731         switch (cmd_type) {
1732         case TRB_ENABLE_SLOT:
1733                 xhci_handle_cmd_enable_slot(xhci, slot_id, cmd, cmd_comp_code);
1734                 break;
1735         case TRB_DISABLE_SLOT:
1736                 xhci_handle_cmd_disable_slot(xhci, slot_id);
1737                 break;
1738         case TRB_CONFIG_EP:
1739                 if (!cmd->completion)
1740                         xhci_handle_cmd_config_ep(xhci, slot_id, cmd_comp_code);
1741                 break;
1742         case TRB_EVAL_CONTEXT:
1743                 break;
1744         case TRB_ADDR_DEV:
1745                 xhci_handle_cmd_addr_dev(xhci, slot_id);
1746                 break;
1747         case TRB_STOP_RING:
1748                 WARN_ON(slot_id != TRB_TO_SLOT_ID(
1749                                 le32_to_cpu(cmd_trb->generic.field[3])));
1750                 if (!cmd->completion)
1751                         xhci_handle_cmd_stop_ep(xhci, slot_id, cmd_trb,
1752                                                 cmd_comp_code);
1753                 break;
1754         case TRB_SET_DEQ:
1755                 WARN_ON(slot_id != TRB_TO_SLOT_ID(
1756                                 le32_to_cpu(cmd_trb->generic.field[3])));
1757                 xhci_handle_cmd_set_deq(xhci, slot_id, cmd_trb, cmd_comp_code);
1758                 break;
1759         case TRB_CMD_NOOP:
1760                 /* Is this an aborted command turned to NO-OP? */
1761                 if (cmd->status == COMP_COMMAND_RING_STOPPED)
1762                         cmd_comp_code = COMP_COMMAND_RING_STOPPED;
1763                 break;
1764         case TRB_RESET_EP:
1765                 WARN_ON(slot_id != TRB_TO_SLOT_ID(
1766                                 le32_to_cpu(cmd_trb->generic.field[3])));
1767                 xhci_handle_cmd_reset_ep(xhci, slot_id, cmd_trb, cmd_comp_code);
1768                 break;
1769         case TRB_RESET_DEV:
1770                 /* SLOT_ID field in reset device cmd completion event TRB is 0.
1771                  * Use the SLOT_ID from the command TRB instead (xhci 4.6.11)
1772                  */
1773                 slot_id = TRB_TO_SLOT_ID(
1774                                 le32_to_cpu(cmd_trb->generic.field[3]));
1775                 xhci_handle_cmd_reset_dev(xhci, slot_id);
1776                 break;
1777         case TRB_NEC_GET_FW:
1778                 xhci_handle_cmd_nec_get_fw(xhci, event);
1779                 break;
1780         default:
1781                 /* Skip over unknown commands on the event ring */
1782                 xhci_info(xhci, "INFO unknown command type %d\n", cmd_type);
1783                 break;
1784         }
1785
1786         /* restart timer if this wasn't the last command */
1787         if (!list_is_singular(&xhci->cmd_list)) {
1788                 xhci->current_cmd = list_first_entry(&cmd->cmd_list,
1789                                                 struct xhci_command, cmd_list);
1790                 xhci_mod_cmd_timer(xhci, XHCI_CMD_DEFAULT_TIMEOUT);
1791         } else if (xhci->current_cmd == cmd) {
1792                 xhci->current_cmd = NULL;
1793         }
1794
1795 event_handled:
1796         xhci_complete_del_and_free_cmd(cmd, cmd_comp_code);
1797
1798         inc_deq(xhci, xhci->cmd_ring);
1799 }
1800
1801 static void handle_vendor_event(struct xhci_hcd *xhci,
1802                                 union xhci_trb *event, u32 trb_type)
1803 {
1804         xhci_dbg(xhci, "Vendor specific event TRB type = %u\n", trb_type);
1805         if (trb_type == TRB_NEC_CMD_COMP && (xhci->quirks & XHCI_NEC_HOST))
1806                 handle_cmd_completion(xhci, &event->event_cmd);
1807 }
1808
1809 static void handle_device_notification(struct xhci_hcd *xhci,
1810                 union xhci_trb *event)
1811 {
1812         u32 slot_id;
1813         struct usb_device *udev;
1814
1815         slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->generic.field[3]));
1816         if (!xhci->devs[slot_id]) {
1817                 xhci_warn(xhci, "Device Notification event for "
1818                                 "unused slot %u\n", slot_id);
1819                 return;
1820         }
1821
1822         xhci_dbg(xhci, "Device Wake Notification event for slot ID %u\n",
1823                         slot_id);
1824         udev = xhci->devs[slot_id]->udev;
1825         if (udev && udev->parent)
1826                 usb_wakeup_notification(udev->parent, udev->portnum);
1827 }
1828
1829 /*
1830  * Quirk hanlder for errata seen on Cavium ThunderX2 processor XHCI
1831  * Controller.
1832  * As per ThunderX2errata-129 USB 2 device may come up as USB 1
1833  * If a connection to a USB 1 device is followed by another connection
1834  * to a USB 2 device.
1835  *
1836  * Reset the PHY after the USB device is disconnected if device speed
1837  * is less than HCD_USB3.
1838  * Retry the reset sequence max of 4 times checking the PLL lock status.
1839  *
1840  */
1841 static void xhci_cavium_reset_phy_quirk(struct xhci_hcd *xhci)
1842 {
1843         struct usb_hcd *hcd = xhci_to_hcd(xhci);
1844         u32 pll_lock_check;
1845         u32 retry_count = 4;
1846
1847         do {
1848                 /* Assert PHY reset */
1849                 writel(0x6F, hcd->regs + 0x1048);
1850                 udelay(10);
1851                 /* De-assert the PHY reset */
1852                 writel(0x7F, hcd->regs + 0x1048);
1853                 udelay(200);
1854                 pll_lock_check = readl(hcd->regs + 0x1070);
1855         } while (!(pll_lock_check & 0x1) && --retry_count);
1856 }
1857
1858 static void handle_port_status(struct xhci_hcd *xhci,
1859                                struct xhci_interrupter *ir,
1860                                union xhci_trb *event)
1861 {
1862         struct usb_hcd *hcd;
1863         u32 port_id;
1864         u32 portsc, cmd_reg;
1865         int max_ports;
1866         int slot_id;
1867         unsigned int hcd_portnum;
1868         struct xhci_bus_state *bus_state;
1869         bool bogus_port_status = false;
1870         struct xhci_port *port;
1871
1872         /* Port status change events always have a successful completion code */
1873         if (GET_COMP_CODE(le32_to_cpu(event->generic.field[2])) != COMP_SUCCESS)
1874                 xhci_warn(xhci,
1875                           "WARN: xHC returned failed port status event\n");
1876
1877         port_id = GET_PORT_ID(le32_to_cpu(event->generic.field[0]));
1878         max_ports = HCS_MAX_PORTS(xhci->hcs_params1);
1879
1880         if ((port_id <= 0) || (port_id > max_ports)) {
1881                 xhci_warn(xhci, "Port change event with invalid port ID %d\n",
1882                           port_id);
1883                 return;
1884         }
1885
1886         port = &xhci->hw_ports[port_id - 1];
1887         if (!port || !port->rhub || port->hcd_portnum == DUPLICATE_ENTRY) {
1888                 xhci_warn(xhci, "Port change event, no port for port ID %u\n",
1889                           port_id);
1890                 bogus_port_status = true;
1891                 goto cleanup;
1892         }
1893
1894         /* We might get interrupts after shared_hcd is removed */
1895         if (port->rhub == &xhci->usb3_rhub && xhci->shared_hcd == NULL) {
1896                 xhci_dbg(xhci, "ignore port event for removed USB3 hcd\n");
1897                 bogus_port_status = true;
1898                 goto cleanup;
1899         }
1900
1901         hcd = port->rhub->hcd;
1902         bus_state = &port->rhub->bus_state;
1903         hcd_portnum = port->hcd_portnum;
1904         portsc = readl(port->addr);
1905
1906         xhci_dbg(xhci, "Port change event, %d-%d, id %d, portsc: 0x%x\n",
1907                  hcd->self.busnum, hcd_portnum + 1, port_id, portsc);
1908
1909         trace_xhci_handle_port_status(port, portsc);
1910
1911         if (hcd->state == HC_STATE_SUSPENDED) {
1912                 xhci_dbg(xhci, "resume root hub\n");
1913                 usb_hcd_resume_root_hub(hcd);
1914         }
1915
1916         if (hcd->speed >= HCD_USB3 &&
1917             (portsc & PORT_PLS_MASK) == XDEV_INACTIVE) {
1918                 slot_id = xhci_find_slot_id_by_port(hcd, xhci, hcd_portnum + 1);
1919                 if (slot_id && xhci->devs[slot_id])
1920                         xhci->devs[slot_id]->flags |= VDEV_PORT_ERROR;
1921         }
1922
1923         if ((portsc & PORT_PLC) && (portsc & PORT_PLS_MASK) == XDEV_RESUME) {
1924                 xhci_dbg(xhci, "port resume event for port %d\n", port_id);
1925
1926                 cmd_reg = readl(&xhci->op_regs->command);
1927                 if (!(cmd_reg & CMD_RUN)) {
1928                         xhci_warn(xhci, "xHC is not running.\n");
1929                         goto cleanup;
1930                 }
1931
1932                 if (DEV_SUPERSPEED_ANY(portsc)) {
1933                         xhci_dbg(xhci, "remote wake SS port %d\n", port_id);
1934                         /* Set a flag to say the port signaled remote wakeup,
1935                          * so we can tell the difference between the end of
1936                          * device and host initiated resume.
1937                          */
1938                         bus_state->port_remote_wakeup |= 1 << hcd_portnum;
1939                         xhci_test_and_clear_bit(xhci, port, PORT_PLC);
1940                         usb_hcd_start_port_resume(&hcd->self, hcd_portnum);
1941                         xhci_set_link_state(xhci, port, XDEV_U0);
1942                         /* Need to wait until the next link state change
1943                          * indicates the device is actually in U0.
1944                          */
1945                         bogus_port_status = true;
1946                         goto cleanup;
1947                 } else if (!test_bit(hcd_portnum, &bus_state->resuming_ports)) {
1948                         xhci_dbg(xhci, "resume HS port %d\n", port_id);
1949                         port->resume_timestamp = jiffies +
1950                                 msecs_to_jiffies(USB_RESUME_TIMEOUT);
1951                         set_bit(hcd_portnum, &bus_state->resuming_ports);
1952                         /* Do the rest in GetPortStatus after resume time delay.
1953                          * Avoid polling roothub status before that so that a
1954                          * usb device auto-resume latency around ~40ms.
1955                          */
1956                         set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1957                         mod_timer(&hcd->rh_timer,
1958                                   port->resume_timestamp);
1959                         usb_hcd_start_port_resume(&hcd->self, hcd_portnum);
1960                         bogus_port_status = true;
1961                 }
1962         }
1963
1964         if ((portsc & PORT_PLC) &&
1965             DEV_SUPERSPEED_ANY(portsc) &&
1966             ((portsc & PORT_PLS_MASK) == XDEV_U0 ||
1967              (portsc & PORT_PLS_MASK) == XDEV_U1 ||
1968              (portsc & PORT_PLS_MASK) == XDEV_U2)) {
1969                 xhci_dbg(xhci, "resume SS port %d finished\n", port_id);
1970                 complete(&port->u3exit_done);
1971                 /* We've just brought the device into U0/1/2 through either the
1972                  * Resume state after a device remote wakeup, or through the
1973                  * U3Exit state after a host-initiated resume.  If it's a device
1974                  * initiated remote wake, don't pass up the link state change,
1975                  * so the roothub behavior is consistent with external
1976                  * USB 3.0 hub behavior.
1977                  */
1978                 slot_id = xhci_find_slot_id_by_port(hcd, xhci, hcd_portnum + 1);
1979                 if (slot_id && xhci->devs[slot_id])
1980                         xhci_ring_device(xhci, slot_id);
1981                 if (bus_state->port_remote_wakeup & (1 << hcd_portnum)) {
1982                         xhci_test_and_clear_bit(xhci, port, PORT_PLC);
1983                         usb_wakeup_notification(hcd->self.root_hub,
1984                                         hcd_portnum + 1);
1985                         bogus_port_status = true;
1986                         goto cleanup;
1987                 }
1988         }
1989
1990         /*
1991          * Check to see if xhci-hub.c is waiting on RExit to U0 transition (or
1992          * RExit to a disconnect state).  If so, let the driver know it's
1993          * out of the RExit state.
1994          */
1995         if (hcd->speed < HCD_USB3 && port->rexit_active) {
1996                 complete(&port->rexit_done);
1997                 port->rexit_active = false;
1998                 bogus_port_status = true;
1999                 goto cleanup;
2000         }
2001
2002         if (hcd->speed < HCD_USB3) {
2003                 xhci_test_and_clear_bit(xhci, port, PORT_PLC);
2004                 if ((xhci->quirks & XHCI_RESET_PLL_ON_DISCONNECT) &&
2005                     (portsc & PORT_CSC) && !(portsc & PORT_CONNECT))
2006                         xhci_cavium_reset_phy_quirk(xhci);
2007         }
2008
2009 cleanup:
2010
2011         /* Don't make the USB core poll the roothub if we got a bad port status
2012          * change event.  Besides, at that point we can't tell which roothub
2013          * (USB 2.0 or USB 3.0) to kick.
2014          */
2015         if (bogus_port_status)
2016                 return;
2017
2018         /*
2019          * xHCI port-status-change events occur when the "or" of all the
2020          * status-change bits in the portsc register changes from 0 to 1.
2021          * New status changes won't cause an event if any other change
2022          * bits are still set.  When an event occurs, switch over to
2023          * polling to avoid losing status changes.
2024          */
2025         xhci_dbg(xhci, "%s: starting usb%d port polling.\n",
2026                  __func__, hcd->self.busnum);
2027         set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2028         spin_unlock(&xhci->lock);
2029         /* Pass this up to the core */
2030         usb_hcd_poll_rh_status(hcd);
2031         spin_lock(&xhci->lock);
2032 }
2033
2034 /*
2035  * This TD is defined by the TRBs starting at start_trb in start_seg and ending
2036  * at end_trb, which may be in another segment.  If the suspect DMA address is a
2037  * TRB in this TD, this function returns that TRB's segment.  Otherwise it
2038  * returns 0.
2039  */
2040 struct xhci_segment *trb_in_td(struct xhci_hcd *xhci,
2041                 struct xhci_segment *start_seg,
2042                 union xhci_trb  *start_trb,
2043                 union xhci_trb  *end_trb,
2044                 dma_addr_t      suspect_dma,
2045                 bool            debug)
2046 {
2047         dma_addr_t start_dma;
2048         dma_addr_t end_seg_dma;
2049         dma_addr_t end_trb_dma;
2050         struct xhci_segment *cur_seg;
2051
2052         start_dma = xhci_trb_virt_to_dma(start_seg, start_trb);
2053         cur_seg = start_seg;
2054
2055         do {
2056                 if (start_dma == 0)
2057                         return NULL;
2058                 /* We may get an event for a Link TRB in the middle of a TD */
2059                 end_seg_dma = xhci_trb_virt_to_dma(cur_seg,
2060                                 &cur_seg->trbs[TRBS_PER_SEGMENT - 1]);
2061                 /* If the end TRB isn't in this segment, this is set to 0 */
2062                 end_trb_dma = xhci_trb_virt_to_dma(cur_seg, end_trb);
2063
2064                 if (debug)
2065                         xhci_warn(xhci,
2066                                 "Looking for event-dma %016llx trb-start %016llx trb-end %016llx seg-start %016llx seg-end %016llx\n",
2067                                 (unsigned long long)suspect_dma,
2068                                 (unsigned long long)start_dma,
2069                                 (unsigned long long)end_trb_dma,
2070                                 (unsigned long long)cur_seg->dma,
2071                                 (unsigned long long)end_seg_dma);
2072
2073                 if (end_trb_dma > 0) {
2074                         /* The end TRB is in this segment, so suspect should be here */
2075                         if (start_dma <= end_trb_dma) {
2076                                 if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma)
2077                                         return cur_seg;
2078                         } else {
2079                                 /* Case for one segment with
2080                                  * a TD wrapped around to the top
2081                                  */
2082                                 if ((suspect_dma >= start_dma &&
2083                                                         suspect_dma <= end_seg_dma) ||
2084                                                 (suspect_dma >= cur_seg->dma &&
2085                                                  suspect_dma <= end_trb_dma))
2086                                         return cur_seg;
2087                         }
2088                         return NULL;
2089                 } else {
2090                         /* Might still be somewhere in this segment */
2091                         if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma)
2092                                 return cur_seg;
2093                 }
2094                 cur_seg = cur_seg->next;
2095                 start_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[0]);
2096         } while (cur_seg != start_seg);
2097
2098         return NULL;
2099 }
2100
2101 static void xhci_clear_hub_tt_buffer(struct xhci_hcd *xhci, struct xhci_td *td,
2102                 struct xhci_virt_ep *ep)
2103 {
2104         /*
2105          * As part of low/full-speed endpoint-halt processing
2106          * we must clear the TT buffer (USB 2.0 specification 11.17.5).
2107          */
2108         if (td->urb->dev->tt && !usb_pipeint(td->urb->pipe) &&
2109             (td->urb->dev->tt->hub != xhci_to_hcd(xhci)->self.root_hub) &&
2110             !(ep->ep_state & EP_CLEARING_TT)) {
2111                 ep->ep_state |= EP_CLEARING_TT;
2112                 td->urb->ep->hcpriv = td->urb->dev;
2113                 if (usb_hub_clear_tt_buffer(td->urb))
2114                         ep->ep_state &= ~EP_CLEARING_TT;
2115         }
2116 }
2117
2118 /* Check if an error has halted the endpoint ring.  The class driver will
2119  * cleanup the halt for a non-default control endpoint if we indicate a stall.
2120  * However, a babble and other errors also halt the endpoint ring, and the class
2121  * driver won't clear the halt in that case, so we need to issue a Set Transfer
2122  * Ring Dequeue Pointer command manually.
2123  */
2124 static int xhci_requires_manual_halt_cleanup(struct xhci_hcd *xhci,
2125                 struct xhci_ep_ctx *ep_ctx,
2126                 unsigned int trb_comp_code)
2127 {
2128         /* TRB completion codes that may require a manual halt cleanup */
2129         if (trb_comp_code == COMP_USB_TRANSACTION_ERROR ||
2130                         trb_comp_code == COMP_BABBLE_DETECTED_ERROR ||
2131                         trb_comp_code == COMP_SPLIT_TRANSACTION_ERROR)
2132                 /* The 0.95 spec says a babbling control endpoint
2133                  * is not halted. The 0.96 spec says it is.  Some HW
2134                  * claims to be 0.95 compliant, but it halts the control
2135                  * endpoint anyway.  Check if a babble halted the
2136                  * endpoint.
2137                  */
2138                 if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_HALTED)
2139                         return 1;
2140
2141         return 0;
2142 }
2143
2144 int xhci_is_vendor_info_code(struct xhci_hcd *xhci, unsigned int trb_comp_code)
2145 {
2146         if (trb_comp_code >= 224 && trb_comp_code <= 255) {
2147                 /* Vendor defined "informational" completion code,
2148                  * treat as not-an-error.
2149                  */
2150                 xhci_dbg(xhci, "Vendor defined info completion code %u\n",
2151                                 trb_comp_code);
2152                 xhci_dbg(xhci, "Treating code as success.\n");
2153                 return 1;
2154         }
2155         return 0;
2156 }
2157
2158 static int finish_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2159                      struct xhci_ring *ep_ring, struct xhci_td *td,
2160                      u32 trb_comp_code)
2161 {
2162         struct xhci_ep_ctx *ep_ctx;
2163
2164         ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep->ep_index);
2165
2166         switch (trb_comp_code) {
2167         case COMP_STOPPED_LENGTH_INVALID:
2168         case COMP_STOPPED_SHORT_PACKET:
2169         case COMP_STOPPED:
2170                 /*
2171                  * The "Stop Endpoint" completion will take care of any
2172                  * stopped TDs. A stopped TD may be restarted, so don't update
2173                  * the ring dequeue pointer or take this TD off any lists yet.
2174                  */
2175                 return 0;
2176         case COMP_USB_TRANSACTION_ERROR:
2177         case COMP_BABBLE_DETECTED_ERROR:
2178         case COMP_SPLIT_TRANSACTION_ERROR:
2179                 /*
2180                  * If endpoint context state is not halted we might be
2181                  * racing with a reset endpoint command issued by a unsuccessful
2182                  * stop endpoint completion (context error). In that case the
2183                  * td should be on the cancelled list, and EP_HALTED flag set.
2184                  *
2185                  * Or then it's not halted due to the 0.95 spec stating that a
2186                  * babbling control endpoint should not halt. The 0.96 spec
2187                  * again says it should.  Some HW claims to be 0.95 compliant,
2188                  * but it halts the control endpoint anyway.
2189                  */
2190                 if (GET_EP_CTX_STATE(ep_ctx) != EP_STATE_HALTED) {
2191                         /*
2192                          * If EP_HALTED is set and TD is on the cancelled list
2193                          * the TD and dequeue pointer will be handled by reset
2194                          * ep command completion
2195                          */
2196                         if ((ep->ep_state & EP_HALTED) &&
2197                             !list_empty(&td->cancelled_td_list)) {
2198                                 xhci_dbg(xhci, "Already resolving halted ep for 0x%llx\n",
2199                                          (unsigned long long)xhci_trb_virt_to_dma(
2200                                                  td->start_seg, td->first_trb));
2201                                 return 0;
2202                         }
2203                         /* endpoint not halted, don't reset it */
2204                         break;
2205                 }
2206                 /* Almost same procedure as for STALL_ERROR below */
2207                 xhci_clear_hub_tt_buffer(xhci, td, ep);
2208                 xhci_handle_halted_endpoint(xhci, ep, td, EP_HARD_RESET);
2209                 return 0;
2210         case COMP_STALL_ERROR:
2211                 /*
2212                  * xhci internal endpoint state will go to a "halt" state for
2213                  * any stall, including default control pipe protocol stall.
2214                  * To clear the host side halt we need to issue a reset endpoint
2215                  * command, followed by a set dequeue command to move past the
2216                  * TD.
2217                  * Class drivers clear the device side halt from a functional
2218                  * stall later. Hub TT buffer should only be cleared for FS/LS
2219                  * devices behind HS hubs for functional stalls.
2220                  */
2221                 if (ep->ep_index != 0)
2222                         xhci_clear_hub_tt_buffer(xhci, td, ep);
2223
2224                 xhci_handle_halted_endpoint(xhci, ep, td, EP_HARD_RESET);
2225
2226                 return 0; /* xhci_handle_halted_endpoint marked td cancelled */
2227         default:
2228                 break;
2229         }
2230
2231         /* Update ring dequeue pointer */
2232         ep_ring->dequeue = td->last_trb;
2233         ep_ring->deq_seg = td->last_trb_seg;
2234         inc_deq(xhci, ep_ring);
2235
2236         return xhci_td_cleanup(xhci, td, ep_ring, td->status);
2237 }
2238
2239 /* sum trb lengths from ring dequeue up to stop_trb, _excluding_ stop_trb */
2240 static int sum_trb_lengths(struct xhci_hcd *xhci, struct xhci_ring *ring,
2241                            union xhci_trb *stop_trb)
2242 {
2243         u32 sum;
2244         union xhci_trb *trb = ring->dequeue;
2245         struct xhci_segment *seg = ring->deq_seg;
2246
2247         for (sum = 0; trb != stop_trb; next_trb(xhci, ring, &seg, &trb)) {
2248                 if (!trb_is_noop(trb) && !trb_is_link(trb))
2249                         sum += TRB_LEN(le32_to_cpu(trb->generic.field[2]));
2250         }
2251         return sum;
2252 }
2253
2254 /*
2255  * Process control tds, update urb status and actual_length.
2256  */
2257 static int process_ctrl_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2258                 struct xhci_ring *ep_ring,  struct xhci_td *td,
2259                            union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2260 {
2261         struct xhci_ep_ctx *ep_ctx;
2262         u32 trb_comp_code;
2263         u32 remaining, requested;
2264         u32 trb_type;
2265
2266         trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(ep_trb->generic.field[3]));
2267         ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep->ep_index);
2268         trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2269         requested = td->urb->transfer_buffer_length;
2270         remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2271
2272         switch (trb_comp_code) {
2273         case COMP_SUCCESS:
2274                 if (trb_type != TRB_STATUS) {
2275                         xhci_warn(xhci, "WARN: Success on ctrl %s TRB without IOC set?\n",
2276                                   (trb_type == TRB_DATA) ? "data" : "setup");
2277                         td->status = -ESHUTDOWN;
2278                         break;
2279                 }
2280                 td->status = 0;
2281                 break;
2282         case COMP_SHORT_PACKET:
2283                 td->status = 0;
2284                 break;
2285         case COMP_STOPPED_SHORT_PACKET:
2286                 if (trb_type == TRB_DATA || trb_type == TRB_NORMAL)
2287                         td->urb->actual_length = remaining;
2288                 else
2289                         xhci_warn(xhci, "WARN: Stopped Short Packet on ctrl setup or status TRB\n");
2290                 goto finish_td;
2291         case COMP_STOPPED:
2292                 switch (trb_type) {
2293                 case TRB_SETUP:
2294                         td->urb->actual_length = 0;
2295                         goto finish_td;
2296                 case TRB_DATA:
2297                 case TRB_NORMAL:
2298                         td->urb->actual_length = requested - remaining;
2299                         goto finish_td;
2300                 case TRB_STATUS:
2301                         td->urb->actual_length = requested;
2302                         goto finish_td;
2303                 default:
2304                         xhci_warn(xhci, "WARN: unexpected TRB Type %d\n",
2305                                   trb_type);
2306                         goto finish_td;
2307                 }
2308         case COMP_STOPPED_LENGTH_INVALID:
2309                 goto finish_td;
2310         default:
2311                 if (!xhci_requires_manual_halt_cleanup(xhci,
2312                                                        ep_ctx, trb_comp_code))
2313                         break;
2314                 xhci_dbg(xhci, "TRB error %u, halted endpoint index = %u\n",
2315                          trb_comp_code, ep->ep_index);
2316                 fallthrough;
2317         case COMP_STALL_ERROR:
2318                 /* Did we transfer part of the data (middle) phase? */
2319                 if (trb_type == TRB_DATA || trb_type == TRB_NORMAL)
2320                         td->urb->actual_length = requested - remaining;
2321                 else if (!td->urb_length_set)
2322                         td->urb->actual_length = 0;
2323                 goto finish_td;
2324         }
2325
2326         /* stopped at setup stage, no data transferred */
2327         if (trb_type == TRB_SETUP)
2328                 goto finish_td;
2329
2330         /*
2331          * if on data stage then update the actual_length of the URB and flag it
2332          * as set, so it won't be overwritten in the event for the last TRB.
2333          */
2334         if (trb_type == TRB_DATA ||
2335                 trb_type == TRB_NORMAL) {
2336                 td->urb_length_set = true;
2337                 td->urb->actual_length = requested - remaining;
2338                 xhci_dbg(xhci, "Waiting for status stage event\n");
2339                 return 0;
2340         }
2341
2342         /* at status stage */
2343         if (!td->urb_length_set)
2344                 td->urb->actual_length = requested;
2345
2346 finish_td:
2347         return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2348 }
2349
2350 /*
2351  * Process isochronous tds, update urb packet status and actual_length.
2352  */
2353 static int process_isoc_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2354                 struct xhci_ring *ep_ring, struct xhci_td *td,
2355                 union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2356 {
2357         struct urb_priv *urb_priv;
2358         int idx;
2359         struct usb_iso_packet_descriptor *frame;
2360         u32 trb_comp_code;
2361         bool sum_trbs_for_length = false;
2362         u32 remaining, requested, ep_trb_len;
2363         int short_framestatus;
2364
2365         trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2366         urb_priv = td->urb->hcpriv;
2367         idx = urb_priv->num_tds_done;
2368         frame = &td->urb->iso_frame_desc[idx];
2369         requested = frame->length;
2370         remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2371         ep_trb_len = TRB_LEN(le32_to_cpu(ep_trb->generic.field[2]));
2372         short_framestatus = td->urb->transfer_flags & URB_SHORT_NOT_OK ?
2373                 -EREMOTEIO : 0;
2374
2375         /* handle completion code */
2376         switch (trb_comp_code) {
2377         case COMP_SUCCESS:
2378                 /* Don't overwrite status if TD had an error, see xHCI 4.9.1 */
2379                 if (td->error_mid_td)
2380                         break;
2381                 if (remaining) {
2382                         frame->status = short_framestatus;
2383                         if (xhci->quirks & XHCI_TRUST_TX_LENGTH)
2384                                 sum_trbs_for_length = true;
2385                         break;
2386                 }
2387                 frame->status = 0;
2388                 break;
2389         case COMP_SHORT_PACKET:
2390                 frame->status = short_framestatus;
2391                 sum_trbs_for_length = true;
2392                 break;
2393         case COMP_BANDWIDTH_OVERRUN_ERROR:
2394                 frame->status = -ECOMM;
2395                 break;
2396         case COMP_BABBLE_DETECTED_ERROR:
2397                 sum_trbs_for_length = true;
2398                 fallthrough;
2399         case COMP_ISOCH_BUFFER_OVERRUN:
2400                 frame->status = -EOVERFLOW;
2401                 if (ep_trb != td->last_trb)
2402                         td->error_mid_td = true;
2403                 break;
2404         case COMP_INCOMPATIBLE_DEVICE_ERROR:
2405         case COMP_STALL_ERROR:
2406                 frame->status = -EPROTO;
2407                 break;
2408         case COMP_USB_TRANSACTION_ERROR:
2409                 frame->status = -EPROTO;
2410                 sum_trbs_for_length = true;
2411                 if (ep_trb != td->last_trb)
2412                         td->error_mid_td = true;
2413                 break;
2414         case COMP_STOPPED:
2415                 sum_trbs_for_length = true;
2416                 break;
2417         case COMP_STOPPED_SHORT_PACKET:
2418                 /* field normally containing residue now contains tranferred */
2419                 frame->status = short_framestatus;
2420                 requested = remaining;
2421                 break;
2422         case COMP_STOPPED_LENGTH_INVALID:
2423                 requested = 0;
2424                 remaining = 0;
2425                 break;
2426         default:
2427                 sum_trbs_for_length = true;
2428                 frame->status = -1;
2429                 break;
2430         }
2431
2432         if (td->urb_length_set)
2433                 goto finish_td;
2434
2435         if (sum_trbs_for_length)
2436                 frame->actual_length = sum_trb_lengths(xhci, ep->ring, ep_trb) +
2437                         ep_trb_len - remaining;
2438         else
2439                 frame->actual_length = requested;
2440
2441         td->urb->actual_length += frame->actual_length;
2442
2443 finish_td:
2444         /* Don't give back TD yet if we encountered an error mid TD */
2445         if (td->error_mid_td && ep_trb != td->last_trb) {
2446                 xhci_dbg(xhci, "Error mid isoc TD, wait for final completion event\n");
2447                 td->urb_length_set = true;
2448                 return 0;
2449         }
2450
2451         return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2452 }
2453
2454 static int skip_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td,
2455                         struct xhci_virt_ep *ep, int status)
2456 {
2457         struct urb_priv *urb_priv;
2458         struct usb_iso_packet_descriptor *frame;
2459         int idx;
2460
2461         urb_priv = td->urb->hcpriv;
2462         idx = urb_priv->num_tds_done;
2463         frame = &td->urb->iso_frame_desc[idx];
2464
2465         /* The transfer is partly done. */
2466         frame->status = -EXDEV;
2467
2468         /* calc actual length */
2469         frame->actual_length = 0;
2470
2471         /* Update ring dequeue pointer */
2472         ep->ring->dequeue = td->last_trb;
2473         ep->ring->deq_seg = td->last_trb_seg;
2474         inc_deq(xhci, ep->ring);
2475
2476         return xhci_td_cleanup(xhci, td, ep->ring, status);
2477 }
2478
2479 /*
2480  * Process bulk and interrupt tds, update urb status and actual_length.
2481  */
2482 static int process_bulk_intr_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2483                 struct xhci_ring *ep_ring, struct xhci_td *td,
2484                 union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2485 {
2486         struct xhci_slot_ctx *slot_ctx;
2487         u32 trb_comp_code;
2488         u32 remaining, requested, ep_trb_len;
2489
2490         slot_ctx = xhci_get_slot_ctx(xhci, ep->vdev->out_ctx);
2491         trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2492         remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2493         ep_trb_len = TRB_LEN(le32_to_cpu(ep_trb->generic.field[2]));
2494         requested = td->urb->transfer_buffer_length;
2495
2496         switch (trb_comp_code) {
2497         case COMP_SUCCESS:
2498                 ep->err_count = 0;
2499                 /* handle success with untransferred data as short packet */
2500                 if (ep_trb != td->last_trb || remaining) {
2501                         xhci_warn(xhci, "WARN Successful completion on short TX\n");
2502                         xhci_dbg(xhci, "ep %#x - asked for %d bytes, %d bytes untransferred\n",
2503                                  td->urb->ep->desc.bEndpointAddress,
2504                                  requested, remaining);
2505                 }
2506                 td->status = 0;
2507                 break;
2508         case COMP_SHORT_PACKET:
2509                 xhci_dbg(xhci, "ep %#x - asked for %d bytes, %d bytes untransferred\n",
2510                          td->urb->ep->desc.bEndpointAddress,
2511                          requested, remaining);
2512                 td->status = 0;
2513                 break;
2514         case COMP_STOPPED_SHORT_PACKET:
2515                 td->urb->actual_length = remaining;
2516                 goto finish_td;
2517         case COMP_STOPPED_LENGTH_INVALID:
2518                 /* stopped on ep trb with invalid length, exclude it */
2519                 ep_trb_len      = 0;
2520                 remaining       = 0;
2521                 break;
2522         case COMP_USB_TRANSACTION_ERROR:
2523                 if (xhci->quirks & XHCI_NO_SOFT_RETRY ||
2524                     (ep->err_count++ > MAX_SOFT_RETRY) ||
2525                     le32_to_cpu(slot_ctx->tt_info) & TT_SLOT)
2526                         break;
2527
2528                 td->status = 0;
2529
2530                 xhci_handle_halted_endpoint(xhci, ep, td, EP_SOFT_RESET);
2531                 return 0;
2532         default:
2533                 /* do nothing */
2534                 break;
2535         }
2536
2537         if (ep_trb == td->last_trb)
2538                 td->urb->actual_length = requested - remaining;
2539         else
2540                 td->urb->actual_length =
2541                         sum_trb_lengths(xhci, ep_ring, ep_trb) +
2542                         ep_trb_len - remaining;
2543 finish_td:
2544         if (remaining > requested) {
2545                 xhci_warn(xhci, "bad transfer trb length %d in event trb\n",
2546                           remaining);
2547                 td->urb->actual_length = 0;
2548         }
2549
2550         return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2551 }
2552
2553 /*
2554  * If this function returns an error condition, it means it got a Transfer
2555  * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address.
2556  * At this point, the host controller is probably hosed and should be reset.
2557  */
2558 static int handle_tx_event(struct xhci_hcd *xhci,
2559                            struct xhci_interrupter *ir,
2560                            struct xhci_transfer_event *event)
2561 {
2562         struct xhci_virt_ep *ep;
2563         struct xhci_ring *ep_ring;
2564         unsigned int slot_id;
2565         int ep_index;
2566         struct xhci_td *td = NULL;
2567         dma_addr_t ep_trb_dma;
2568         struct xhci_segment *ep_seg;
2569         union xhci_trb *ep_trb;
2570         int status = -EINPROGRESS;
2571         struct xhci_ep_ctx *ep_ctx;
2572         u32 trb_comp_code;
2573         int td_num = 0;
2574         bool handling_skipped_tds = false;
2575
2576         slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
2577         ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1;
2578         trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2579         ep_trb_dma = le64_to_cpu(event->buffer);
2580
2581         ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
2582         if (!ep) {
2583                 xhci_err(xhci, "ERROR Invalid Transfer event\n");
2584                 goto err_out;
2585         }
2586
2587         ep_ring = xhci_dma_to_transfer_ring(ep, ep_trb_dma);
2588         ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
2589
2590         if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) {
2591                 xhci_err(xhci,
2592                          "ERROR Transfer event for disabled endpoint slot %u ep %u\n",
2593                           slot_id, ep_index);
2594                 goto err_out;
2595         }
2596
2597         /* Some transfer events don't always point to a trb, see xhci 4.17.4 */
2598         if (!ep_ring) {
2599                 switch (trb_comp_code) {
2600                 case COMP_STALL_ERROR:
2601                 case COMP_USB_TRANSACTION_ERROR:
2602                 case COMP_INVALID_STREAM_TYPE_ERROR:
2603                 case COMP_INVALID_STREAM_ID_ERROR:
2604                         xhci_dbg(xhci, "Stream transaction error ep %u no id\n",
2605                                  ep_index);
2606                         if (ep->err_count++ > MAX_SOFT_RETRY)
2607                                 xhci_handle_halted_endpoint(xhci, ep, NULL,
2608                                                             EP_HARD_RESET);
2609                         else
2610                                 xhci_handle_halted_endpoint(xhci, ep, NULL,
2611                                                             EP_SOFT_RESET);
2612                         goto cleanup;
2613                 case COMP_RING_UNDERRUN:
2614                 case COMP_RING_OVERRUN:
2615                 case COMP_STOPPED_LENGTH_INVALID:
2616                         goto cleanup;
2617                 default:
2618                         xhci_err(xhci, "ERROR Transfer event for unknown stream ring slot %u ep %u\n",
2619                                  slot_id, ep_index);
2620                         goto err_out;
2621                 }
2622         }
2623
2624         /* Count current td numbers if ep->skip is set */
2625         if (ep->skip)
2626                 td_num += list_count_nodes(&ep_ring->td_list);
2627
2628         /* Look for common error cases */
2629         switch (trb_comp_code) {
2630         /* Skip codes that require special handling depending on
2631          * transfer type
2632          */
2633         case COMP_SUCCESS:
2634                 if (EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)) == 0)
2635                         break;
2636                 if (xhci->quirks & XHCI_TRUST_TX_LENGTH ||
2637                     ep_ring->last_td_was_short)
2638                         trb_comp_code = COMP_SHORT_PACKET;
2639                 else
2640                         xhci_warn_ratelimited(xhci,
2641                                               "WARN Successful completion on short TX for slot %u ep %u: needs XHCI_TRUST_TX_LENGTH quirk?\n",
2642                                               slot_id, ep_index);
2643                 break;
2644         case COMP_SHORT_PACKET:
2645                 break;
2646         /* Completion codes for endpoint stopped state */
2647         case COMP_STOPPED:
2648                 xhci_dbg(xhci, "Stopped on Transfer TRB for slot %u ep %u\n",
2649                          slot_id, ep_index);
2650                 break;
2651         case COMP_STOPPED_LENGTH_INVALID:
2652                 xhci_dbg(xhci,
2653                          "Stopped on No-op or Link TRB for slot %u ep %u\n",
2654                          slot_id, ep_index);
2655                 break;
2656         case COMP_STOPPED_SHORT_PACKET:
2657                 xhci_dbg(xhci,
2658                          "Stopped with short packet transfer detected for slot %u ep %u\n",
2659                          slot_id, ep_index);
2660                 break;
2661         /* Completion codes for endpoint halted state */
2662         case COMP_STALL_ERROR:
2663                 xhci_dbg(xhci, "Stalled endpoint for slot %u ep %u\n", slot_id,
2664                          ep_index);
2665                 status = -EPIPE;
2666                 break;
2667         case COMP_SPLIT_TRANSACTION_ERROR:
2668                 xhci_dbg(xhci, "Split transaction error for slot %u ep %u\n",
2669                          slot_id, ep_index);
2670                 status = -EPROTO;
2671                 break;
2672         case COMP_USB_TRANSACTION_ERROR:
2673                 xhci_dbg(xhci, "Transfer error for slot %u ep %u on endpoint\n",
2674                          slot_id, ep_index);
2675                 status = -EPROTO;
2676                 break;
2677         case COMP_BABBLE_DETECTED_ERROR:
2678                 xhci_dbg(xhci, "Babble error for slot %u ep %u on endpoint\n",
2679                          slot_id, ep_index);
2680                 status = -EOVERFLOW;
2681                 break;
2682         /* Completion codes for endpoint error state */
2683         case COMP_TRB_ERROR:
2684                 xhci_warn(xhci,
2685                           "WARN: TRB error for slot %u ep %u on endpoint\n",
2686                           slot_id, ep_index);
2687                 status = -EILSEQ;
2688                 break;
2689         /* completion codes not indicating endpoint state change */
2690         case COMP_DATA_BUFFER_ERROR:
2691                 xhci_warn(xhci,
2692                           "WARN: HC couldn't access mem fast enough for slot %u ep %u\n",
2693                           slot_id, ep_index);
2694                 status = -ENOSR;
2695                 break;
2696         case COMP_BANDWIDTH_OVERRUN_ERROR:
2697                 xhci_warn(xhci,
2698                           "WARN: bandwidth overrun event for slot %u ep %u on endpoint\n",
2699                           slot_id, ep_index);
2700                 break;
2701         case COMP_ISOCH_BUFFER_OVERRUN:
2702                 xhci_warn(xhci,
2703                           "WARN: buffer overrun event for slot %u ep %u on endpoint",
2704                           slot_id, ep_index);
2705                 break;
2706         case COMP_RING_UNDERRUN:
2707                 /*
2708                  * When the Isoch ring is empty, the xHC will generate
2709                  * a Ring Overrun Event for IN Isoch endpoint or Ring
2710                  * Underrun Event for OUT Isoch endpoint.
2711                  */
2712                 xhci_dbg(xhci, "underrun event on endpoint\n");
2713                 if (!list_empty(&ep_ring->td_list))
2714                         xhci_dbg(xhci, "Underrun Event for slot %d ep %d "
2715                                         "still with TDs queued?\n",
2716                                  TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2717                                  ep_index);
2718                 goto cleanup;
2719         case COMP_RING_OVERRUN:
2720                 xhci_dbg(xhci, "overrun event on endpoint\n");
2721                 if (!list_empty(&ep_ring->td_list))
2722                         xhci_dbg(xhci, "Overrun Event for slot %d ep %d "
2723                                         "still with TDs queued?\n",
2724                                  TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2725                                  ep_index);
2726                 goto cleanup;
2727         case COMP_MISSED_SERVICE_ERROR:
2728                 /*
2729                  * When encounter missed service error, one or more isoc tds
2730                  * may be missed by xHC.
2731                  * Set skip flag of the ep_ring; Complete the missed tds as
2732                  * short transfer when process the ep_ring next time.
2733                  */
2734                 ep->skip = true;
2735                 xhci_dbg(xhci,
2736                          "Miss service interval error for slot %u ep %u, set skip flag\n",
2737                          slot_id, ep_index);
2738                 goto cleanup;
2739         case COMP_NO_PING_RESPONSE_ERROR:
2740                 ep->skip = true;
2741                 xhci_dbg(xhci,
2742                          "No Ping response error for slot %u ep %u, Skip one Isoc TD\n",
2743                          slot_id, ep_index);
2744                 goto cleanup;
2745
2746         case COMP_INCOMPATIBLE_DEVICE_ERROR:
2747                 /* needs disable slot command to recover */
2748                 xhci_warn(xhci,
2749                           "WARN: detect an incompatible device for slot %u ep %u",
2750                           slot_id, ep_index);
2751                 status = -EPROTO;
2752                 break;
2753         default:
2754                 if (xhci_is_vendor_info_code(xhci, trb_comp_code)) {
2755                         status = 0;
2756                         break;
2757                 }
2758                 xhci_warn(xhci,
2759                           "ERROR Unknown event condition %u for slot %u ep %u , HC probably busted\n",
2760                           trb_comp_code, slot_id, ep_index);
2761                 goto cleanup;
2762         }
2763
2764         do {
2765                 /* This TRB should be in the TD at the head of this ring's
2766                  * TD list.
2767                  */
2768                 if (list_empty(&ep_ring->td_list)) {
2769                         /*
2770                          * Don't print wanings if it's due to a stopped endpoint
2771                          * generating an extra completion event if the device
2772                          * was suspended. Or, a event for the last TRB of a
2773                          * short TD we already got a short event for.
2774                          * The short TD is already removed from the TD list.
2775                          */
2776
2777                         if (!(trb_comp_code == COMP_STOPPED ||
2778                               trb_comp_code == COMP_STOPPED_LENGTH_INVALID ||
2779                               ep_ring->last_td_was_short)) {
2780                                 xhci_warn(xhci, "WARN Event TRB for slot %d ep %d with no TDs queued?\n",
2781                                                 TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2782                                                 ep_index);
2783                         }
2784                         if (ep->skip) {
2785                                 ep->skip = false;
2786                                 xhci_dbg(xhci, "td_list is empty while skip flag set. Clear skip flag for slot %u ep %u.\n",
2787                                          slot_id, ep_index);
2788                         }
2789                         if (trb_comp_code == COMP_STALL_ERROR ||
2790                             xhci_requires_manual_halt_cleanup(xhci, ep_ctx,
2791                                                               trb_comp_code)) {
2792                                 xhci_handle_halted_endpoint(xhci, ep, NULL,
2793                                                             EP_HARD_RESET);
2794                         }
2795                         goto cleanup;
2796                 }
2797
2798                 /* We've skipped all the TDs on the ep ring when ep->skip set */
2799                 if (ep->skip && td_num == 0) {
2800                         ep->skip = false;
2801                         xhci_dbg(xhci, "All tds on the ep_ring skipped. Clear skip flag for slot %u ep %u.\n",
2802                                  slot_id, ep_index);
2803                         goto cleanup;
2804                 }
2805
2806                 td = list_first_entry(&ep_ring->td_list, struct xhci_td,
2807                                       td_list);
2808                 if (ep->skip)
2809                         td_num--;
2810
2811                 /* Is this a TRB in the currently executing TD? */
2812                 ep_seg = trb_in_td(xhci, ep_ring->deq_seg, ep_ring->dequeue,
2813                                 td->last_trb, ep_trb_dma, false);
2814
2815                 /*
2816                  * Skip the Force Stopped Event. The event_trb(event_dma) of FSE
2817                  * is not in the current TD pointed by ep_ring->dequeue because
2818                  * that the hardware dequeue pointer still at the previous TRB
2819                  * of the current TD. The previous TRB maybe a Link TD or the
2820                  * last TRB of the previous TD. The command completion handle
2821                  * will take care the rest.
2822                  */
2823                 if (!ep_seg && (trb_comp_code == COMP_STOPPED ||
2824                            trb_comp_code == COMP_STOPPED_LENGTH_INVALID)) {
2825                         goto cleanup;
2826                 }
2827
2828                 if (!ep_seg) {
2829
2830                         if (ep->skip && usb_endpoint_xfer_isoc(&td->urb->ep->desc)) {
2831                                 skip_isoc_td(xhci, td, ep, status);
2832                                 goto cleanup;
2833                         }
2834
2835                         /*
2836                          * Some hosts give a spurious success event after a short
2837                          * transfer. Ignore it.
2838                          */
2839                         if ((xhci->quirks & XHCI_SPURIOUS_SUCCESS) &&
2840                             ep_ring->last_td_was_short) {
2841                                 ep_ring->last_td_was_short = false;
2842                                 goto cleanup;
2843                         }
2844
2845                         /*
2846                          * xhci 4.10.2 states isoc endpoints should continue
2847                          * processing the next TD if there was an error mid TD.
2848                          * So host like NEC don't generate an event for the last
2849                          * isoc TRB even if the IOC flag is set.
2850                          * xhci 4.9.1 states that if there are errors in mult-TRB
2851                          * TDs xHC should generate an error for that TRB, and if xHC
2852                          * proceeds to the next TD it should genete an event for
2853                          * any TRB with IOC flag on the way. Other host follow this.
2854                          * So this event might be for the next TD.
2855                          */
2856                         if (td->error_mid_td &&
2857                             !list_is_last(&td->td_list, &ep_ring->td_list)) {
2858                                 struct xhci_td *td_next = list_next_entry(td, td_list);
2859
2860                                 ep_seg = trb_in_td(xhci, td_next->start_seg, td_next->first_trb,
2861                                                    td_next->last_trb, ep_trb_dma, false);
2862                                 if (ep_seg) {
2863                                         /* give back previous TD, start handling new */
2864                                         xhci_dbg(xhci, "Missing TD completion event after mid TD error\n");
2865                                         ep_ring->dequeue = td->last_trb;
2866                                         ep_ring->deq_seg = td->last_trb_seg;
2867                                         inc_deq(xhci, ep_ring);
2868                                         xhci_td_cleanup(xhci, td, ep_ring, td->status);
2869                                         td = td_next;
2870                                 }
2871                         }
2872
2873                         if (!ep_seg) {
2874                                 /* HC is busted, give up! */
2875                                 xhci_err(xhci,
2876                                         "ERROR Transfer event TRB DMA ptr not "
2877                                         "part of current TD ep_index %d "
2878                                         "comp_code %u\n", ep_index,
2879                                         trb_comp_code);
2880                                 trb_in_td(xhci, ep_ring->deq_seg,
2881                                           ep_ring->dequeue, td->last_trb,
2882                                           ep_trb_dma, true);
2883                                 return -ESHUTDOWN;
2884                         }
2885                 }
2886                 if (trb_comp_code == COMP_SHORT_PACKET)
2887                         ep_ring->last_td_was_short = true;
2888                 else
2889                         ep_ring->last_td_was_short = false;
2890
2891                 if (ep->skip) {
2892                         xhci_dbg(xhci,
2893                                  "Found td. Clear skip flag for slot %u ep %u.\n",
2894                                  slot_id, ep_index);
2895                         ep->skip = false;
2896                 }
2897
2898                 ep_trb = &ep_seg->trbs[(ep_trb_dma - ep_seg->dma) /
2899                                                 sizeof(*ep_trb)];
2900
2901                 trace_xhci_handle_transfer(ep_ring,
2902                                 (struct xhci_generic_trb *) ep_trb);
2903
2904                 /*
2905                  * No-op TRB could trigger interrupts in a case where
2906                  * a URB was killed and a STALL_ERROR happens right
2907                  * after the endpoint ring stopped. Reset the halted
2908                  * endpoint. Otherwise, the endpoint remains stalled
2909                  * indefinitely.
2910                  */
2911
2912                 if (trb_is_noop(ep_trb)) {
2913                         if (trb_comp_code == COMP_STALL_ERROR ||
2914                             xhci_requires_manual_halt_cleanup(xhci, ep_ctx,
2915                                                               trb_comp_code))
2916                                 xhci_handle_halted_endpoint(xhci, ep, td,
2917                                                             EP_HARD_RESET);
2918                         goto cleanup;
2919                 }
2920
2921                 td->status = status;
2922
2923                 /* update the urb's actual_length and give back to the core */
2924                 if (usb_endpoint_xfer_control(&td->urb->ep->desc))
2925                         process_ctrl_td(xhci, ep, ep_ring, td, ep_trb, event);
2926                 else if (usb_endpoint_xfer_isoc(&td->urb->ep->desc))
2927                         process_isoc_td(xhci, ep, ep_ring, td, ep_trb, event);
2928                 else
2929                         process_bulk_intr_td(xhci, ep, ep_ring, td, ep_trb, event);
2930 cleanup:
2931                 handling_skipped_tds = ep->skip &&
2932                         trb_comp_code != COMP_MISSED_SERVICE_ERROR &&
2933                         trb_comp_code != COMP_NO_PING_RESPONSE_ERROR;
2934
2935         /*
2936          * If ep->skip is set, it means there are missed tds on the
2937          * endpoint ring need to take care of.
2938          * Process them as short transfer until reach the td pointed by
2939          * the event.
2940          */
2941         } while (handling_skipped_tds);
2942
2943         return 0;
2944
2945 err_out:
2946         xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n",
2947                  (unsigned long long) xhci_trb_virt_to_dma(
2948                          ir->event_ring->deq_seg,
2949                          ir->event_ring->dequeue),
2950                  lower_32_bits(le64_to_cpu(event->buffer)),
2951                  upper_32_bits(le64_to_cpu(event->buffer)),
2952                  le32_to_cpu(event->transfer_len),
2953                  le32_to_cpu(event->flags));
2954         return -ENODEV;
2955 }
2956
2957 /*
2958  * This function handles all OS-owned events on the event ring.  It may drop
2959  * xhci->lock between event processing (e.g. to pass up port status changes).
2960  * Returns >0 for "possibly more events to process" (caller should call again),
2961  * otherwise 0 if done.  In future, <0 returns should indicate error code.
2962  */
2963 static int xhci_handle_event(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
2964 {
2965         union xhci_trb *event;
2966         u32 trb_type;
2967
2968         /* Event ring hasn't been allocated yet. */
2969         if (!ir || !ir->event_ring || !ir->event_ring->dequeue) {
2970                 xhci_err(xhci, "ERROR interrupter not ready\n");
2971                 return -ENOMEM;
2972         }
2973
2974         event = ir->event_ring->dequeue;
2975         /* Does the HC or OS own the TRB? */
2976         if ((le32_to_cpu(event->event_cmd.flags) & TRB_CYCLE) !=
2977             ir->event_ring->cycle_state)
2978                 return 0;
2979
2980         trace_xhci_handle_event(ir->event_ring, &event->generic);
2981
2982         /*
2983          * Barrier between reading the TRB_CYCLE (valid) flag above and any
2984          * speculative reads of the event's flags/data below.
2985          */
2986         rmb();
2987         trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(event->event_cmd.flags));
2988         /* FIXME: Handle more event types. */
2989
2990         switch (trb_type) {
2991         case TRB_COMPLETION:
2992                 handle_cmd_completion(xhci, &event->event_cmd);
2993                 break;
2994         case TRB_PORT_STATUS:
2995                 handle_port_status(xhci, ir, event);
2996                 break;
2997         case TRB_TRANSFER:
2998                 handle_tx_event(xhci, ir, &event->trans_event);
2999                 break;
3000         case TRB_DEV_NOTE:
3001                 handle_device_notification(xhci, event);
3002                 break;
3003         default:
3004                 if (trb_type >= TRB_VENDOR_DEFINED_LOW)
3005                         handle_vendor_event(xhci, event, trb_type);
3006                 else
3007                         xhci_warn(xhci, "ERROR unknown event type %d\n", trb_type);
3008         }
3009         /* Any of the above functions may drop and re-acquire the lock, so check
3010          * to make sure a watchdog timer didn't mark the host as non-responsive.
3011          */
3012         if (xhci->xhc_state & XHCI_STATE_DYING) {
3013                 xhci_dbg(xhci, "xHCI host dying, returning from "
3014                                 "event handler.\n");
3015                 return 0;
3016         }
3017
3018         /* Update SW event ring dequeue pointer */
3019         inc_deq(xhci, ir->event_ring);
3020
3021         /* Are there more items on the event ring?  Caller will call us again to
3022          * check.
3023          */
3024         return 1;
3025 }
3026
3027 /*
3028  * Update Event Ring Dequeue Pointer:
3029  * - When all events have finished
3030  * - To avoid "Event Ring Full Error" condition
3031  */
3032 static void xhci_update_erst_dequeue(struct xhci_hcd *xhci,
3033                                      struct xhci_interrupter *ir,
3034                                      union xhci_trb *event_ring_deq,
3035                                      bool clear_ehb)
3036 {
3037         u64 temp_64;
3038         dma_addr_t deq;
3039
3040         temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
3041         /* If necessary, update the HW's version of the event ring deq ptr. */
3042         if (event_ring_deq != ir->event_ring->dequeue) {
3043                 deq = xhci_trb_virt_to_dma(ir->event_ring->deq_seg,
3044                                 ir->event_ring->dequeue);
3045                 if (deq == 0)
3046                         xhci_warn(xhci, "WARN something wrong with SW event ring dequeue ptr\n");
3047                 /*
3048                  * Per 4.9.4, Software writes to the ERDP register shall
3049                  * always advance the Event Ring Dequeue Pointer value.
3050                  */
3051                 if ((temp_64 & ERST_PTR_MASK) == (deq & ERST_PTR_MASK))
3052                         return;
3053
3054                 /* Update HC event ring dequeue pointer */
3055                 temp_64 = ir->event_ring->deq_seg->num & ERST_DESI_MASK;
3056                 temp_64 |= deq & ERST_PTR_MASK;
3057         }
3058
3059         /* Clear the event handler busy flag (RW1C) */
3060         if (clear_ehb)
3061                 temp_64 |= ERST_EHB;
3062         xhci_write_64(xhci, temp_64, &ir->ir_set->erst_dequeue);
3063 }
3064
3065 /*
3066  * xHCI spec says we can get an interrupt, and if the HC has an error condition,
3067  * we might get bad data out of the event ring.  Section 4.10.2.7 has a list of
3068  * indicators of an event TRB error, but we check the status *first* to be safe.
3069  */
3070 irqreturn_t xhci_irq(struct usb_hcd *hcd)
3071 {
3072         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3073         union xhci_trb *event_ring_deq;
3074         struct xhci_interrupter *ir;
3075         irqreturn_t ret = IRQ_NONE;
3076         u64 temp_64;
3077         u32 status;
3078         int event_loop = 0;
3079
3080         spin_lock(&xhci->lock);
3081         /* Check if the xHC generated the interrupt, or the irq is shared */
3082         status = readl(&xhci->op_regs->status);
3083         if (status == ~(u32)0) {
3084                 xhci_hc_died(xhci);
3085                 ret = IRQ_HANDLED;
3086                 goto out;
3087         }
3088
3089         if (!(status & STS_EINT))
3090                 goto out;
3091
3092         if (status & STS_HCE) {
3093                 xhci_warn(xhci, "WARNING: Host Controller Error\n");
3094                 goto out;
3095         }
3096
3097         if (status & STS_FATAL) {
3098                 xhci_warn(xhci, "WARNING: Host System Error\n");
3099                 xhci_halt(xhci);
3100                 ret = IRQ_HANDLED;
3101                 goto out;
3102         }
3103
3104         /*
3105          * Clear the op reg interrupt status first,
3106          * so we can receive interrupts from other MSI-X interrupters.
3107          * Write 1 to clear the interrupt status.
3108          */
3109         status |= STS_EINT;
3110         writel(status, &xhci->op_regs->status);
3111
3112         /* This is the handler of the primary interrupter */
3113         ir = xhci->interrupter;
3114         if (!hcd->msi_enabled) {
3115                 u32 irq_pending;
3116                 irq_pending = readl(&ir->ir_set->irq_pending);
3117                 irq_pending |= IMAN_IP;
3118                 writel(irq_pending, &ir->ir_set->irq_pending);
3119         }
3120
3121         if (xhci->xhc_state & XHCI_STATE_DYING ||
3122             xhci->xhc_state & XHCI_STATE_HALTED) {
3123                 xhci_dbg(xhci, "xHCI dying, ignoring interrupt. "
3124                                 "Shouldn't IRQs be disabled?\n");
3125                 /* Clear the event handler busy flag (RW1C);
3126                  * the event ring should be empty.
3127                  */
3128                 temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
3129                 xhci_write_64(xhci, temp_64 | ERST_EHB,
3130                                 &ir->ir_set->erst_dequeue);
3131                 ret = IRQ_HANDLED;
3132                 goto out;
3133         }
3134
3135         event_ring_deq = ir->event_ring->dequeue;
3136         /* FIXME this should be a delayed service routine
3137          * that clears the EHB.
3138          */
3139         while (xhci_handle_event(xhci, ir) > 0) {
3140                 if (event_loop++ < TRBS_PER_SEGMENT / 2)
3141                         continue;
3142                 xhci_update_erst_dequeue(xhci, ir, event_ring_deq, false);
3143                 event_ring_deq = ir->event_ring->dequeue;
3144
3145                 /* ring is half-full, force isoc trbs to interrupt more often */
3146                 if (xhci->isoc_bei_interval > AVOID_BEI_INTERVAL_MIN)
3147                         xhci->isoc_bei_interval = xhci->isoc_bei_interval / 2;
3148
3149                 event_loop = 0;
3150         }
3151
3152         xhci_update_erst_dequeue(xhci, ir, event_ring_deq, true);
3153         ret = IRQ_HANDLED;
3154
3155 out:
3156         spin_unlock(&xhci->lock);
3157
3158         return ret;
3159 }
3160
3161 irqreturn_t xhci_msi_irq(int irq, void *hcd)
3162 {
3163         return xhci_irq(hcd);
3164 }
3165 EXPORT_SYMBOL_GPL(xhci_msi_irq);
3166
3167 /****           Endpoint Ring Operations        ****/
3168
3169 /*
3170  * Generic function for queueing a TRB on a ring.
3171  * The caller must have checked to make sure there's room on the ring.
3172  *
3173  * @more_trbs_coming:   Will you enqueue more TRBs before calling
3174  *                      prepare_transfer()?
3175  */
3176 static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
3177                 bool more_trbs_coming,
3178                 u32 field1, u32 field2, u32 field3, u32 field4)
3179 {
3180         struct xhci_generic_trb *trb;
3181
3182         trb = &ring->enqueue->generic;
3183         trb->field[0] = cpu_to_le32(field1);
3184         trb->field[1] = cpu_to_le32(field2);
3185         trb->field[2] = cpu_to_le32(field3);
3186         /* make sure TRB is fully written before giving it to the controller */
3187         wmb();
3188         trb->field[3] = cpu_to_le32(field4);
3189
3190         trace_xhci_queue_trb(ring, trb);
3191
3192         inc_enq(xhci, ring, more_trbs_coming);
3193 }
3194
3195 /*
3196  * Does various checks on the endpoint ring, and makes it ready to queue num_trbs.
3197  * expand ring if it start to be full.
3198  */
3199 static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
3200                 u32 ep_state, unsigned int num_trbs, gfp_t mem_flags)
3201 {
3202         unsigned int link_trb_count = 0;
3203         unsigned int new_segs = 0;
3204
3205         /* Make sure the endpoint has been added to xHC schedule */
3206         switch (ep_state) {
3207         case EP_STATE_DISABLED:
3208                 /*
3209                  * USB core changed config/interfaces without notifying us,
3210                  * or hardware is reporting the wrong state.
3211                  */
3212                 xhci_warn(xhci, "WARN urb submitted to disabled ep\n");
3213                 return -ENOENT;
3214         case EP_STATE_ERROR:
3215                 xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n");
3216                 /* FIXME event handling code for error needs to clear it */
3217                 /* XXX not sure if this should be -ENOENT or not */
3218                 return -EINVAL;
3219         case EP_STATE_HALTED:
3220                 xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n");
3221                 break;
3222         case EP_STATE_STOPPED:
3223         case EP_STATE_RUNNING:
3224                 break;
3225         default:
3226                 xhci_err(xhci, "ERROR unknown endpoint state for ep\n");
3227                 /*
3228                  * FIXME issue Configure Endpoint command to try to get the HC
3229                  * back into a known state.
3230                  */
3231                 return -EINVAL;
3232         }
3233
3234         if (ep_ring != xhci->cmd_ring) {
3235                 new_segs = xhci_ring_expansion_needed(xhci, ep_ring, num_trbs);
3236         } else if (xhci_num_trbs_free(xhci, ep_ring) <= num_trbs) {
3237                 xhci_err(xhci, "Do not support expand command ring\n");
3238                 return -ENOMEM;
3239         }
3240
3241         if (new_segs) {
3242                 xhci_dbg_trace(xhci, trace_xhci_dbg_ring_expansion,
3243                                 "ERROR no room on ep ring, try ring expansion");
3244                 if (xhci_ring_expansion(xhci, ep_ring, new_segs, mem_flags)) {
3245                         xhci_err(xhci, "Ring expansion failed\n");
3246                         return -ENOMEM;
3247                 }
3248         }
3249
3250         while (trb_is_link(ep_ring->enqueue)) {
3251                 /* If we're not dealing with 0.95 hardware or isoc rings
3252                  * on AMD 0.96 host, clear the chain bit.
3253                  */
3254                 if (!xhci_link_trb_quirk(xhci) &&
3255                     !(ep_ring->type == TYPE_ISOC &&
3256                       (xhci->quirks & XHCI_AMD_0x96_HOST)))
3257                         ep_ring->enqueue->link.control &=
3258                                 cpu_to_le32(~TRB_CHAIN);
3259                 else
3260                         ep_ring->enqueue->link.control |=
3261                                 cpu_to_le32(TRB_CHAIN);
3262
3263                 wmb();
3264                 ep_ring->enqueue->link.control ^= cpu_to_le32(TRB_CYCLE);
3265
3266                 /* Toggle the cycle bit after the last ring segment. */
3267                 if (link_trb_toggles_cycle(ep_ring->enqueue))
3268                         ep_ring->cycle_state ^= 1;
3269
3270                 ep_ring->enq_seg = ep_ring->enq_seg->next;
3271                 ep_ring->enqueue = ep_ring->enq_seg->trbs;
3272
3273                 /* prevent infinite loop if all first trbs are link trbs */
3274                 if (link_trb_count++ > ep_ring->num_segs) {
3275                         xhci_warn(xhci, "Ring is an endless link TRB loop\n");
3276                         return -EINVAL;
3277                 }
3278         }
3279
3280         if (last_trb_on_seg(ep_ring->enq_seg, ep_ring->enqueue)) {
3281                 xhci_warn(xhci, "Missing link TRB at end of ring segment\n");
3282                 return -EINVAL;
3283         }
3284
3285         return 0;
3286 }
3287
3288 static int prepare_transfer(struct xhci_hcd *xhci,
3289                 struct xhci_virt_device *xdev,
3290                 unsigned int ep_index,
3291                 unsigned int stream_id,
3292                 unsigned int num_trbs,
3293                 struct urb *urb,
3294                 unsigned int td_index,
3295                 gfp_t mem_flags)
3296 {
3297         int ret;
3298         struct urb_priv *urb_priv;
3299         struct xhci_td  *td;
3300         struct xhci_ring *ep_ring;
3301         struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
3302
3303         ep_ring = xhci_triad_to_transfer_ring(xhci, xdev->slot_id, ep_index,
3304                                               stream_id);
3305         if (!ep_ring) {
3306                 xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n",
3307                                 stream_id);
3308                 return -EINVAL;
3309         }
3310
3311         ret = prepare_ring(xhci, ep_ring, GET_EP_CTX_STATE(ep_ctx),
3312                            num_trbs, mem_flags);
3313         if (ret)
3314                 return ret;
3315
3316         urb_priv = urb->hcpriv;
3317         td = &urb_priv->td[td_index];
3318
3319         INIT_LIST_HEAD(&td->td_list);
3320         INIT_LIST_HEAD(&td->cancelled_td_list);
3321
3322         if (td_index == 0) {
3323                 ret = usb_hcd_link_urb_to_ep(bus_to_hcd(urb->dev->bus), urb);
3324                 if (unlikely(ret))
3325                         return ret;
3326         }
3327
3328         td->urb = urb;
3329         /* Add this TD to the tail of the endpoint ring's TD list */
3330         list_add_tail(&td->td_list, &ep_ring->td_list);
3331         td->start_seg = ep_ring->enq_seg;
3332         td->first_trb = ep_ring->enqueue;
3333
3334         return 0;
3335 }
3336
3337 unsigned int count_trbs(u64 addr, u64 len)
3338 {
3339         unsigned int num_trbs;
3340
3341         num_trbs = DIV_ROUND_UP(len + (addr & (TRB_MAX_BUFF_SIZE - 1)),
3342                         TRB_MAX_BUFF_SIZE);
3343         if (num_trbs == 0)
3344                 num_trbs++;
3345
3346         return num_trbs;
3347 }
3348
3349 static inline unsigned int count_trbs_needed(struct urb *urb)
3350 {
3351         return count_trbs(urb->transfer_dma, urb->transfer_buffer_length);
3352 }
3353
3354 static unsigned int count_sg_trbs_needed(struct urb *urb)
3355 {
3356         struct scatterlist *sg;
3357         unsigned int i, len, full_len, num_trbs = 0;
3358
3359         full_len = urb->transfer_buffer_length;
3360
3361         for_each_sg(urb->sg, sg, urb->num_mapped_sgs, i) {
3362                 len = sg_dma_len(sg);
3363                 num_trbs += count_trbs(sg_dma_address(sg), len);
3364                 len = min_t(unsigned int, len, full_len);
3365                 full_len -= len;
3366                 if (full_len == 0)
3367                         break;
3368         }
3369
3370         return num_trbs;
3371 }
3372
3373 static unsigned int count_isoc_trbs_needed(struct urb *urb, int i)
3374 {
3375         u64 addr, len;
3376
3377         addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset);
3378         len = urb->iso_frame_desc[i].length;
3379
3380         return count_trbs(addr, len);
3381 }
3382
3383 static void check_trb_math(struct urb *urb, int running_total)
3384 {
3385         if (unlikely(running_total != urb->transfer_buffer_length))
3386                 dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, "
3387                                 "queued %#x (%d), asked for %#x (%d)\n",
3388                                 __func__,
3389                                 urb->ep->desc.bEndpointAddress,
3390                                 running_total, running_total,
3391                                 urb->transfer_buffer_length,
3392                                 urb->transfer_buffer_length);
3393 }
3394
3395 static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id,
3396                 unsigned int ep_index, unsigned int stream_id, int start_cycle,
3397                 struct xhci_generic_trb *start_trb)
3398 {
3399         /*
3400          * Pass all the TRBs to the hardware at once and make sure this write
3401          * isn't reordered.
3402          */
3403         wmb();
3404         if (start_cycle)
3405                 start_trb->field[3] |= cpu_to_le32(start_cycle);
3406         else
3407                 start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE);
3408         xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
3409 }
3410
3411 static void check_interval(struct xhci_hcd *xhci, struct urb *urb,
3412                                                 struct xhci_ep_ctx *ep_ctx)
3413 {
3414         int xhci_interval;
3415         int ep_interval;
3416
3417         xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info));
3418         ep_interval = urb->interval;
3419
3420         /* Convert to microframes */
3421         if (urb->dev->speed == USB_SPEED_LOW ||
3422                         urb->dev->speed == USB_SPEED_FULL)
3423                 ep_interval *= 8;
3424
3425         /* FIXME change this to a warning and a suggestion to use the new API
3426          * to set the polling interval (once the API is added).
3427          */
3428         if (xhci_interval != ep_interval) {
3429                 dev_dbg_ratelimited(&urb->dev->dev,
3430                                 "Driver uses different interval (%d microframe%s) than xHCI (%d microframe%s)\n",
3431                                 ep_interval, ep_interval == 1 ? "" : "s",
3432                                 xhci_interval, xhci_interval == 1 ? "" : "s");
3433                 urb->interval = xhci_interval;
3434                 /* Convert back to frames for LS/FS devices */
3435                 if (urb->dev->speed == USB_SPEED_LOW ||
3436                                 urb->dev->speed == USB_SPEED_FULL)
3437                         urb->interval /= 8;
3438         }
3439 }
3440
3441 /*
3442  * xHCI uses normal TRBs for both bulk and interrupt.  When the interrupt
3443  * endpoint is to be serviced, the xHC will consume (at most) one TD.  A TD
3444  * (comprised of sg list entries) can take several service intervals to
3445  * transmit.
3446  */
3447 int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3448                 struct urb *urb, int slot_id, unsigned int ep_index)
3449 {
3450         struct xhci_ep_ctx *ep_ctx;
3451
3452         ep_ctx = xhci_get_ep_ctx(xhci, xhci->devs[slot_id]->out_ctx, ep_index);
3453         check_interval(xhci, urb, ep_ctx);
3454
3455         return xhci_queue_bulk_tx(xhci, mem_flags, urb, slot_id, ep_index);
3456 }
3457
3458 /*
3459  * For xHCI 1.0 host controllers, TD size is the number of max packet sized
3460  * packets remaining in the TD (*not* including this TRB).
3461  *
3462  * Total TD packet count = total_packet_count =
3463  *     DIV_ROUND_UP(TD size in bytes / wMaxPacketSize)
3464  *
3465  * Packets transferred up to and including this TRB = packets_transferred =
3466  *     rounddown(total bytes transferred including this TRB / wMaxPacketSize)
3467  *
3468  * TD size = total_packet_count - packets_transferred
3469  *
3470  * For xHCI 0.96 and older, TD size field should be the remaining bytes
3471  * including this TRB, right shifted by 10
3472  *
3473  * For all hosts it must fit in bits 21:17, so it can't be bigger than 31.
3474  * This is taken care of in the TRB_TD_SIZE() macro
3475  *
3476  * The last TRB in a TD must have the TD size set to zero.
3477  */
3478 static u32 xhci_td_remainder(struct xhci_hcd *xhci, int transferred,
3479                               int trb_buff_len, unsigned int td_total_len,
3480                               struct urb *urb, bool more_trbs_coming)
3481 {
3482         u32 maxp, total_packet_count;
3483
3484         /* MTK xHCI 0.96 contains some features from 1.0 */
3485         if (xhci->hci_version < 0x100 && !(xhci->quirks & XHCI_MTK_HOST))
3486                 return ((td_total_len - transferred) >> 10);
3487
3488         /* One TRB with a zero-length data packet. */
3489         if (!more_trbs_coming || (transferred == 0 && trb_buff_len == 0) ||
3490             trb_buff_len == td_total_len)
3491                 return 0;
3492
3493         /* for MTK xHCI 0.96, TD size include this TRB, but not in 1.x */
3494         if ((xhci->quirks & XHCI_MTK_HOST) && (xhci->hci_version < 0x100))
3495                 trb_buff_len = 0;
3496
3497         maxp = usb_endpoint_maxp(&urb->ep->desc);
3498         total_packet_count = DIV_ROUND_UP(td_total_len, maxp);
3499
3500         /* Queueing functions don't count the current TRB into transferred */
3501         return (total_packet_count - ((transferred + trb_buff_len) / maxp));
3502 }
3503
3504
3505 static int xhci_align_td(struct xhci_hcd *xhci, struct urb *urb, u32 enqd_len,
3506                          u32 *trb_buff_len, struct xhci_segment *seg)
3507 {
3508         struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
3509         unsigned int unalign;
3510         unsigned int max_pkt;
3511         u32 new_buff_len;
3512         size_t len;
3513
3514         max_pkt = usb_endpoint_maxp(&urb->ep->desc);
3515         unalign = (enqd_len + *trb_buff_len) % max_pkt;
3516
3517         /* we got lucky, last normal TRB data on segment is packet aligned */
3518         if (unalign == 0)
3519                 return 0;
3520
3521         xhci_dbg(xhci, "Unaligned %d bytes, buff len %d\n",
3522                  unalign, *trb_buff_len);
3523
3524         /* is the last nornal TRB alignable by splitting it */
3525         if (*trb_buff_len > unalign) {
3526                 *trb_buff_len -= unalign;
3527                 xhci_dbg(xhci, "split align, new buff len %d\n", *trb_buff_len);
3528                 return 0;
3529         }
3530
3531         /*
3532          * We want enqd_len + trb_buff_len to sum up to a number aligned to
3533          * number which is divisible by the endpoint's wMaxPacketSize. IOW:
3534          * (size of currently enqueued TRBs + remainder) % wMaxPacketSize == 0.
3535          */
3536         new_buff_len = max_pkt - (enqd_len % max_pkt);
3537
3538         if (new_buff_len > (urb->transfer_buffer_length - enqd_len))
3539                 new_buff_len = (urb->transfer_buffer_length - enqd_len);
3540
3541         /* create a max max_pkt sized bounce buffer pointed to by last trb */
3542         if (usb_urb_dir_out(urb)) {
3543                 if (urb->num_sgs) {
3544                         len = sg_pcopy_to_buffer(urb->sg, urb->num_sgs,
3545                                                  seg->bounce_buf, new_buff_len, enqd_len);
3546                         if (len != new_buff_len)
3547                                 xhci_warn(xhci, "WARN Wrong bounce buffer write length: %zu != %d\n",
3548                                           len, new_buff_len);
3549                 } else {
3550                         memcpy(seg->bounce_buf, urb->transfer_buffer + enqd_len, new_buff_len);
3551                 }
3552
3553                 seg->bounce_dma = dma_map_single(dev, seg->bounce_buf,
3554                                                  max_pkt, DMA_TO_DEVICE);
3555         } else {
3556                 seg->bounce_dma = dma_map_single(dev, seg->bounce_buf,
3557                                                  max_pkt, DMA_FROM_DEVICE);
3558         }
3559
3560         if (dma_mapping_error(dev, seg->bounce_dma)) {
3561                 /* try without aligning. Some host controllers survive */
3562                 xhci_warn(xhci, "Failed mapping bounce buffer, not aligning\n");
3563                 return 0;
3564         }
3565         *trb_buff_len = new_buff_len;
3566         seg->bounce_len = new_buff_len;
3567         seg->bounce_offs = enqd_len;
3568
3569         xhci_dbg(xhci, "Bounce align, new buff len %d\n", *trb_buff_len);
3570
3571         return 1;
3572 }
3573
3574 /* This is very similar to what ehci-q.c qtd_fill() does */
3575 int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3576                 struct urb *urb, int slot_id, unsigned int ep_index)
3577 {
3578         struct xhci_ring *ring;
3579         struct urb_priv *urb_priv;
3580         struct xhci_td *td;
3581         struct xhci_generic_trb *start_trb;
3582         struct scatterlist *sg = NULL;
3583         bool more_trbs_coming = true;
3584         bool need_zero_pkt = false;
3585         bool first_trb = true;
3586         unsigned int num_trbs;
3587         unsigned int start_cycle, num_sgs = 0;
3588         unsigned int enqd_len, block_len, trb_buff_len, full_len;
3589         int sent_len, ret;
3590         u32 field, length_field, remainder;
3591         u64 addr, send_addr;
3592
3593         ring = xhci_urb_to_transfer_ring(xhci, urb);
3594         if (!ring)
3595                 return -EINVAL;
3596
3597         full_len = urb->transfer_buffer_length;
3598         /* If we have scatter/gather list, we use it. */
3599         if (urb->num_sgs && !(urb->transfer_flags & URB_DMA_MAP_SINGLE)) {
3600                 num_sgs = urb->num_mapped_sgs;
3601                 sg = urb->sg;
3602                 addr = (u64) sg_dma_address(sg);
3603                 block_len = sg_dma_len(sg);
3604                 num_trbs = count_sg_trbs_needed(urb);
3605         } else {
3606                 num_trbs = count_trbs_needed(urb);
3607                 addr = (u64) urb->transfer_dma;
3608                 block_len = full_len;
3609         }
3610         ret = prepare_transfer(xhci, xhci->devs[slot_id],
3611                         ep_index, urb->stream_id,
3612                         num_trbs, urb, 0, mem_flags);
3613         if (unlikely(ret < 0))
3614                 return ret;
3615
3616         urb_priv = urb->hcpriv;
3617
3618         /* Deal with URB_ZERO_PACKET - need one more td/trb */
3619         if (urb->transfer_flags & URB_ZERO_PACKET && urb_priv->num_tds > 1)
3620                 need_zero_pkt = true;
3621
3622         td = &urb_priv->td[0];
3623
3624         /*
3625          * Don't give the first TRB to the hardware (by toggling the cycle bit)
3626          * until we've finished creating all the other TRBs.  The ring's cycle
3627          * state may change as we enqueue the other TRBs, so save it too.
3628          */
3629         start_trb = &ring->enqueue->generic;
3630         start_cycle = ring->cycle_state;
3631         send_addr = addr;
3632
3633         /* Queue the TRBs, even if they are zero-length */
3634         for (enqd_len = 0; first_trb || enqd_len < full_len;
3635                         enqd_len += trb_buff_len) {
3636                 field = TRB_TYPE(TRB_NORMAL);
3637
3638                 /* TRB buffer should not cross 64KB boundaries */
3639                 trb_buff_len = TRB_BUFF_LEN_UP_TO_BOUNDARY(addr);
3640                 trb_buff_len = min_t(unsigned int, trb_buff_len, block_len);
3641
3642                 if (enqd_len + trb_buff_len > full_len)
3643                         trb_buff_len = full_len - enqd_len;
3644
3645                 /* Don't change the cycle bit of the first TRB until later */
3646                 if (first_trb) {
3647                         first_trb = false;
3648                         if (start_cycle == 0)
3649                                 field |= TRB_CYCLE;
3650                 } else
3651                         field |= ring->cycle_state;
3652
3653                 /* Chain all the TRBs together; clear the chain bit in the last
3654                  * TRB to indicate it's the last TRB in the chain.
3655                  */
3656                 if (enqd_len + trb_buff_len < full_len) {
3657                         field |= TRB_CHAIN;
3658                         if (trb_is_link(ring->enqueue + 1)) {
3659                                 if (xhci_align_td(xhci, urb, enqd_len,
3660                                                   &trb_buff_len,
3661                                                   ring->enq_seg)) {
3662                                         send_addr = ring->enq_seg->bounce_dma;
3663                                         /* assuming TD won't span 2 segs */
3664                                         td->bounce_seg = ring->enq_seg;
3665                                 }
3666                         }
3667                 }
3668                 if (enqd_len + trb_buff_len >= full_len) {
3669                         field &= ~TRB_CHAIN;
3670                         field |= TRB_IOC;
3671                         more_trbs_coming = false;
3672                         td->last_trb = ring->enqueue;
3673                         td->last_trb_seg = ring->enq_seg;
3674                         if (xhci_urb_suitable_for_idt(urb)) {
3675                                 memcpy(&send_addr, urb->transfer_buffer,
3676                                        trb_buff_len);
3677                                 le64_to_cpus(&send_addr);
3678                                 field |= TRB_IDT;
3679                         }
3680                 }
3681
3682                 /* Only set interrupt on short packet for IN endpoints */
3683                 if (usb_urb_dir_in(urb))
3684                         field |= TRB_ISP;
3685
3686                 /* Set the TRB length, TD size, and interrupter fields. */
3687                 remainder = xhci_td_remainder(xhci, enqd_len, trb_buff_len,
3688                                               full_len, urb, more_trbs_coming);
3689
3690                 length_field = TRB_LEN(trb_buff_len) |
3691                         TRB_TD_SIZE(remainder) |
3692                         TRB_INTR_TARGET(0);
3693
3694                 queue_trb(xhci, ring, more_trbs_coming | need_zero_pkt,
3695                                 lower_32_bits(send_addr),
3696                                 upper_32_bits(send_addr),
3697                                 length_field,
3698                                 field);
3699                 td->num_trbs++;
3700                 addr += trb_buff_len;
3701                 sent_len = trb_buff_len;
3702
3703                 while (sg && sent_len >= block_len) {
3704                         /* New sg entry */
3705                         --num_sgs;
3706                         sent_len -= block_len;
3707                         sg = sg_next(sg);
3708                         if (num_sgs != 0 && sg) {
3709                                 block_len = sg_dma_len(sg);
3710                                 addr = (u64) sg_dma_address(sg);
3711                                 addr += sent_len;
3712                         }
3713                 }
3714                 block_len -= sent_len;
3715                 send_addr = addr;
3716         }
3717
3718         if (need_zero_pkt) {
3719                 ret = prepare_transfer(xhci, xhci->devs[slot_id],
3720                                        ep_index, urb->stream_id,
3721                                        1, urb, 1, mem_flags);
3722                 urb_priv->td[1].last_trb = ring->enqueue;
3723                 urb_priv->td[1].last_trb_seg = ring->enq_seg;
3724                 field = TRB_TYPE(TRB_NORMAL) | ring->cycle_state | TRB_IOC;
3725                 queue_trb(xhci, ring, 0, 0, 0, TRB_INTR_TARGET(0), field);
3726                 urb_priv->td[1].num_trbs++;
3727         }
3728
3729         check_trb_math(urb, enqd_len);
3730         giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
3731                         start_cycle, start_trb);
3732         return 0;
3733 }
3734
3735 /* Caller must have locked xhci->lock */
3736 int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3737                 struct urb *urb, int slot_id, unsigned int ep_index)
3738 {
3739         struct xhci_ring *ep_ring;
3740         int num_trbs;
3741         int ret;
3742         struct usb_ctrlrequest *setup;
3743         struct xhci_generic_trb *start_trb;
3744         int start_cycle;
3745         u32 field;
3746         struct urb_priv *urb_priv;
3747         struct xhci_td *td;
3748
3749         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
3750         if (!ep_ring)
3751                 return -EINVAL;
3752
3753         /*
3754          * Need to copy setup packet into setup TRB, so we can't use the setup
3755          * DMA address.
3756          */
3757         if (!urb->setup_packet)
3758                 return -EINVAL;
3759
3760         /* 1 TRB for setup, 1 for status */
3761         num_trbs = 2;
3762         /*
3763          * Don't need to check if we need additional event data and normal TRBs,
3764          * since data in control transfers will never get bigger than 16MB
3765          * XXX: can we get a buffer that crosses 64KB boundaries?
3766          */
3767         if (urb->transfer_buffer_length > 0)
3768                 num_trbs++;
3769         ret = prepare_transfer(xhci, xhci->devs[slot_id],
3770                         ep_index, urb->stream_id,
3771                         num_trbs, urb, 0, mem_flags);
3772         if (ret < 0)
3773                 return ret;
3774
3775         urb_priv = urb->hcpriv;
3776         td = &urb_priv->td[0];
3777         td->num_trbs = num_trbs;
3778
3779         /*
3780          * Don't give the first TRB to the hardware (by toggling the cycle bit)
3781          * until we've finished creating all the other TRBs.  The ring's cycle
3782          * state may change as we enqueue the other TRBs, so save it too.
3783          */
3784         start_trb = &ep_ring->enqueue->generic;
3785         start_cycle = ep_ring->cycle_state;
3786
3787         /* Queue setup TRB - see section 6.4.1.2.1 */
3788         /* FIXME better way to translate setup_packet into two u32 fields? */
3789         setup = (struct usb_ctrlrequest *) urb->setup_packet;
3790         field = 0;
3791         field |= TRB_IDT | TRB_TYPE(TRB_SETUP);
3792         if (start_cycle == 0)
3793                 field |= 0x1;
3794
3795         /* xHCI 1.0/1.1 6.4.1.2.1: Transfer Type field */
3796         if ((xhci->hci_version >= 0x100) || (xhci->quirks & XHCI_MTK_HOST)) {
3797                 if (urb->transfer_buffer_length > 0) {
3798                         if (setup->bRequestType & USB_DIR_IN)
3799                                 field |= TRB_TX_TYPE(TRB_DATA_IN);
3800                         else
3801                                 field |= TRB_TX_TYPE(TRB_DATA_OUT);
3802                 }
3803         }
3804
3805         queue_trb(xhci, ep_ring, true,
3806                   setup->bRequestType | setup->bRequest << 8 | le16_to_cpu(setup->wValue) << 16,
3807                   le16_to_cpu(setup->wIndex) | le16_to_cpu(setup->wLength) << 16,
3808                   TRB_LEN(8) | TRB_INTR_TARGET(0),
3809                   /* Immediate data in pointer */
3810                   field);
3811
3812         /* If there's data, queue data TRBs */
3813         /* Only set interrupt on short packet for IN endpoints */
3814         if (usb_urb_dir_in(urb))
3815                 field = TRB_ISP | TRB_TYPE(TRB_DATA);
3816         else
3817                 field = TRB_TYPE(TRB_DATA);
3818
3819         if (urb->transfer_buffer_length > 0) {
3820                 u32 length_field, remainder;
3821                 u64 addr;
3822
3823                 if (xhci_urb_suitable_for_idt(urb)) {
3824                         memcpy(&addr, urb->transfer_buffer,
3825                                urb->transfer_buffer_length);
3826                         le64_to_cpus(&addr);
3827                         field |= TRB_IDT;
3828                 } else {
3829                         addr = (u64) urb->transfer_dma;
3830                 }
3831
3832                 remainder = xhci_td_remainder(xhci, 0,
3833                                 urb->transfer_buffer_length,
3834                                 urb->transfer_buffer_length,
3835                                 urb, 1);
3836                 length_field = TRB_LEN(urb->transfer_buffer_length) |
3837                                 TRB_TD_SIZE(remainder) |
3838                                 TRB_INTR_TARGET(0);
3839                 if (setup->bRequestType & USB_DIR_IN)
3840                         field |= TRB_DIR_IN;
3841                 queue_trb(xhci, ep_ring, true,
3842                                 lower_32_bits(addr),
3843                                 upper_32_bits(addr),
3844                                 length_field,
3845                                 field | ep_ring->cycle_state);
3846         }
3847
3848         /* Save the DMA address of the last TRB in the TD */
3849         td->last_trb = ep_ring->enqueue;
3850         td->last_trb_seg = ep_ring->enq_seg;
3851
3852         /* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */
3853         /* If the device sent data, the status stage is an OUT transfer */
3854         if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN)
3855                 field = 0;
3856         else
3857                 field = TRB_DIR_IN;
3858         queue_trb(xhci, ep_ring, false,
3859                         0,
3860                         0,
3861                         TRB_INTR_TARGET(0),
3862                         /* Event on completion */
3863                         field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state);
3864
3865         giveback_first_trb(xhci, slot_id, ep_index, 0,
3866                         start_cycle, start_trb);
3867         return 0;
3868 }
3869
3870 /*
3871  * The transfer burst count field of the isochronous TRB defines the number of
3872  * bursts that are required to move all packets in this TD.  Only SuperSpeed
3873  * devices can burst up to bMaxBurst number of packets per service interval.
3874  * This field is zero based, meaning a value of zero in the field means one
3875  * burst.  Basically, for everything but SuperSpeed devices, this field will be
3876  * zero.  Only xHCI 1.0 host controllers support this field.
3877  */
3878 static unsigned int xhci_get_burst_count(struct xhci_hcd *xhci,
3879                 struct urb *urb, unsigned int total_packet_count)
3880 {
3881         unsigned int max_burst;
3882
3883         if (xhci->hci_version < 0x100 || urb->dev->speed < USB_SPEED_SUPER)
3884                 return 0;
3885
3886         max_burst = urb->ep->ss_ep_comp.bMaxBurst;
3887         return DIV_ROUND_UP(total_packet_count, max_burst + 1) - 1;
3888 }
3889
3890 /*
3891  * Returns the number of packets in the last "burst" of packets.  This field is
3892  * valid for all speeds of devices.  USB 2.0 devices can only do one "burst", so
3893  * the last burst packet count is equal to the total number of packets in the
3894  * TD.  SuperSpeed endpoints can have up to 3 bursts.  All but the last burst
3895  * must contain (bMaxBurst + 1) number of packets, but the last burst can
3896  * contain 1 to (bMaxBurst + 1) packets.
3897  */
3898 static unsigned int xhci_get_last_burst_packet_count(struct xhci_hcd *xhci,
3899                 struct urb *urb, unsigned int total_packet_count)
3900 {
3901         unsigned int max_burst;
3902         unsigned int residue;
3903
3904         if (xhci->hci_version < 0x100)
3905                 return 0;
3906
3907         if (urb->dev->speed >= USB_SPEED_SUPER) {
3908                 /* bMaxBurst is zero based: 0 means 1 packet per burst */
3909                 max_burst = urb->ep->ss_ep_comp.bMaxBurst;
3910                 residue = total_packet_count % (max_burst + 1);
3911                 /* If residue is zero, the last burst contains (max_burst + 1)
3912                  * number of packets, but the TLBPC field is zero-based.
3913                  */
3914                 if (residue == 0)
3915                         return max_burst;
3916                 return residue - 1;
3917         }
3918         if (total_packet_count == 0)
3919                 return 0;
3920         return total_packet_count - 1;
3921 }
3922
3923 /*
3924  * Calculates Frame ID field of the isochronous TRB identifies the
3925  * target frame that the Interval associated with this Isochronous
3926  * Transfer Descriptor will start on. Refer to 4.11.2.5 in 1.1 spec.
3927  *
3928  * Returns actual frame id on success, negative value on error.
3929  */
3930 static int xhci_get_isoc_frame_id(struct xhci_hcd *xhci,
3931                 struct urb *urb, int index)
3932 {
3933         int start_frame, ist, ret = 0;
3934         int start_frame_id, end_frame_id, current_frame_id;
3935
3936         if (urb->dev->speed == USB_SPEED_LOW ||
3937                         urb->dev->speed == USB_SPEED_FULL)
3938                 start_frame = urb->start_frame + index * urb->interval;
3939         else
3940                 start_frame = (urb->start_frame + index * urb->interval) >> 3;
3941
3942         /* Isochronous Scheduling Threshold (IST, bits 0~3 in HCSPARAMS2):
3943          *
3944          * If bit [3] of IST is cleared to '0', software can add a TRB no
3945          * later than IST[2:0] Microframes before that TRB is scheduled to
3946          * be executed.
3947          * If bit [3] of IST is set to '1', software can add a TRB no later
3948          * than IST[2:0] Frames before that TRB is scheduled to be executed.
3949          */
3950         ist = HCS_IST(xhci->hcs_params2) & 0x7;
3951         if (HCS_IST(xhci->hcs_params2) & (1 << 3))
3952                 ist <<= 3;
3953
3954         /* Software shall not schedule an Isoch TD with a Frame ID value that
3955          * is less than the Start Frame ID or greater than the End Frame ID,
3956          * where:
3957          *
3958          * End Frame ID = (Current MFINDEX register value + 895 ms.) MOD 2048
3959          * Start Frame ID = (Current MFINDEX register value + IST + 1) MOD 2048
3960          *
3961          * Both the End Frame ID and Start Frame ID values are calculated
3962          * in microframes. When software determines the valid Frame ID value;
3963          * The End Frame ID value should be rounded down to the nearest Frame
3964          * boundary, and the Start Frame ID value should be rounded up to the
3965          * nearest Frame boundary.
3966          */
3967         current_frame_id = readl(&xhci->run_regs->microframe_index);
3968         start_frame_id = roundup(current_frame_id + ist + 1, 8);
3969         end_frame_id = rounddown(current_frame_id + 895 * 8, 8);
3970
3971         start_frame &= 0x7ff;
3972         start_frame_id = (start_frame_id >> 3) & 0x7ff;
3973         end_frame_id = (end_frame_id >> 3) & 0x7ff;
3974
3975         xhci_dbg(xhci, "%s: index %d, reg 0x%x start_frame_id 0x%x, end_frame_id 0x%x, start_frame 0x%x\n",
3976                  __func__, index, readl(&xhci->run_regs->microframe_index),
3977                  start_frame_id, end_frame_id, start_frame);
3978
3979         if (start_frame_id < end_frame_id) {
3980                 if (start_frame > end_frame_id ||
3981                                 start_frame < start_frame_id)
3982                         ret = -EINVAL;
3983         } else if (start_frame_id > end_frame_id) {
3984                 if ((start_frame > end_frame_id &&
3985                                 start_frame < start_frame_id))
3986                         ret = -EINVAL;
3987         } else {
3988                         ret = -EINVAL;
3989         }
3990
3991         if (index == 0) {
3992                 if (ret == -EINVAL || start_frame == start_frame_id) {
3993                         start_frame = start_frame_id + 1;
3994                         if (urb->dev->speed == USB_SPEED_LOW ||
3995                                         urb->dev->speed == USB_SPEED_FULL)
3996                                 urb->start_frame = start_frame;
3997                         else
3998                                 urb->start_frame = start_frame << 3;
3999                         ret = 0;
4000                 }
4001         }
4002
4003         if (ret) {
4004                 xhci_warn(xhci, "Frame ID %d (reg %d, index %d) beyond range (%d, %d)\n",
4005                                 start_frame, current_frame_id, index,
4006                                 start_frame_id, end_frame_id);
4007                 xhci_warn(xhci, "Ignore frame ID field, use SIA bit instead\n");
4008                 return ret;
4009         }
4010
4011         return start_frame;
4012 }
4013
4014 /* Check if we should generate event interrupt for a TD in an isoc URB */
4015 static bool trb_block_event_intr(struct xhci_hcd *xhci, int num_tds, int i)
4016 {
4017         if (xhci->hci_version < 0x100)
4018                 return false;
4019         /* always generate an event interrupt for the last TD */
4020         if (i == num_tds - 1)
4021                 return false;
4022         /*
4023          * If AVOID_BEI is set the host handles full event rings poorly,
4024          * generate an event at least every 8th TD to clear the event ring
4025          */
4026         if (i && xhci->quirks & XHCI_AVOID_BEI)
4027                 return !!(i % xhci->isoc_bei_interval);
4028
4029         return true;
4030 }
4031
4032 /* This is for isoc transfer */
4033 static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
4034                 struct urb *urb, int slot_id, unsigned int ep_index)
4035 {
4036         struct xhci_ring *ep_ring;
4037         struct urb_priv *urb_priv;
4038         struct xhci_td *td;
4039         int num_tds, trbs_per_td;
4040         struct xhci_generic_trb *start_trb;
4041         bool first_trb;
4042         int start_cycle;
4043         u32 field, length_field;
4044         int running_total, trb_buff_len, td_len, td_remain_len, ret;
4045         u64 start_addr, addr;
4046         int i, j;
4047         bool more_trbs_coming;
4048         struct xhci_virt_ep *xep;
4049         int frame_id;
4050
4051         xep = &xhci->devs[slot_id]->eps[ep_index];
4052         ep_ring = xhci->devs[slot_id]->eps[ep_index].ring;
4053
4054         num_tds = urb->number_of_packets;
4055         if (num_tds < 1) {
4056                 xhci_dbg(xhci, "Isoc URB with zero packets?\n");
4057                 return -EINVAL;
4058         }
4059         start_addr = (u64) urb->transfer_dma;
4060         start_trb = &ep_ring->enqueue->generic;
4061         start_cycle = ep_ring->cycle_state;
4062
4063         urb_priv = urb->hcpriv;
4064         /* Queue the TRBs for each TD, even if they are zero-length */
4065         for (i = 0; i < num_tds; i++) {
4066                 unsigned int total_pkt_count, max_pkt;
4067                 unsigned int burst_count, last_burst_pkt_count;
4068                 u32 sia_frame_id;
4069
4070                 first_trb = true;
4071                 running_total = 0;
4072                 addr = start_addr + urb->iso_frame_desc[i].offset;
4073                 td_len = urb->iso_frame_desc[i].length;
4074                 td_remain_len = td_len;
4075                 max_pkt = usb_endpoint_maxp(&urb->ep->desc);
4076                 total_pkt_count = DIV_ROUND_UP(td_len, max_pkt);
4077
4078                 /* A zero-length transfer still involves at least one packet. */
4079                 if (total_pkt_count == 0)
4080                         total_pkt_count++;
4081                 burst_count = xhci_get_burst_count(xhci, urb, total_pkt_count);
4082                 last_burst_pkt_count = xhci_get_last_burst_packet_count(xhci,
4083                                                         urb, total_pkt_count);
4084
4085                 trbs_per_td = count_isoc_trbs_needed(urb, i);
4086
4087                 ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index,
4088                                 urb->stream_id, trbs_per_td, urb, i, mem_flags);
4089                 if (ret < 0) {
4090                         if (i == 0)
4091                                 return ret;
4092                         goto cleanup;
4093                 }
4094                 td = &urb_priv->td[i];
4095                 td->num_trbs = trbs_per_td;
4096                 /* use SIA as default, if frame id is used overwrite it */
4097                 sia_frame_id = TRB_SIA;
4098                 if (!(urb->transfer_flags & URB_ISO_ASAP) &&
4099                     HCC_CFC(xhci->hcc_params)) {
4100                         frame_id = xhci_get_isoc_frame_id(xhci, urb, i);
4101                         if (frame_id >= 0)
4102                                 sia_frame_id = TRB_FRAME_ID(frame_id);
4103                 }
4104                 /*
4105                  * Set isoc specific data for the first TRB in a TD.
4106                  * Prevent HW from getting the TRBs by keeping the cycle state
4107                  * inverted in the first TDs isoc TRB.
4108                  */
4109                 field = TRB_TYPE(TRB_ISOC) |
4110                         TRB_TLBPC(last_burst_pkt_count) |
4111                         sia_frame_id |
4112                         (i ? ep_ring->cycle_state : !start_cycle);
4113
4114                 /* xhci 1.1 with ETE uses TD_Size field for TBC, old is Rsvdz */
4115                 if (!xep->use_extended_tbc)
4116                         field |= TRB_TBC(burst_count);
4117
4118                 /* fill the rest of the TRB fields, and remaining normal TRBs */
4119                 for (j = 0; j < trbs_per_td; j++) {
4120                         u32 remainder = 0;
4121
4122                         /* only first TRB is isoc, overwrite otherwise */
4123                         if (!first_trb)
4124                                 field = TRB_TYPE(TRB_NORMAL) |
4125                                         ep_ring->cycle_state;
4126
4127                         /* Only set interrupt on short packet for IN EPs */
4128                         if (usb_urb_dir_in(urb))
4129                                 field |= TRB_ISP;
4130
4131                         /* Set the chain bit for all except the last TRB  */
4132                         if (j < trbs_per_td - 1) {
4133                                 more_trbs_coming = true;
4134                                 field |= TRB_CHAIN;
4135                         } else {
4136                                 more_trbs_coming = false;
4137                                 td->last_trb = ep_ring->enqueue;
4138                                 td->last_trb_seg = ep_ring->enq_seg;
4139                                 field |= TRB_IOC;
4140                                 if (trb_block_event_intr(xhci, num_tds, i))
4141                                         field |= TRB_BEI;
4142                         }
4143                         /* Calculate TRB length */
4144                         trb_buff_len = TRB_BUFF_LEN_UP_TO_BOUNDARY(addr);
4145                         if (trb_buff_len > td_remain_len)
4146                                 trb_buff_len = td_remain_len;
4147
4148                         /* Set the TRB length, TD size, & interrupter fields. */
4149                         remainder = xhci_td_remainder(xhci, running_total,
4150                                                    trb_buff_len, td_len,
4151                                                    urb, more_trbs_coming);
4152
4153                         length_field = TRB_LEN(trb_buff_len) |
4154                                 TRB_INTR_TARGET(0);
4155
4156                         /* xhci 1.1 with ETE uses TD Size field for TBC */
4157                         if (first_trb && xep->use_extended_tbc)
4158                                 length_field |= TRB_TD_SIZE_TBC(burst_count);
4159                         else
4160                                 length_field |= TRB_TD_SIZE(remainder);
4161                         first_trb = false;
4162
4163                         queue_trb(xhci, ep_ring, more_trbs_coming,
4164                                 lower_32_bits(addr),
4165                                 upper_32_bits(addr),
4166                                 length_field,
4167                                 field);
4168                         running_total += trb_buff_len;
4169
4170                         addr += trb_buff_len;
4171                         td_remain_len -= trb_buff_len;
4172                 }
4173
4174                 /* Check TD length */
4175                 if (running_total != td_len) {
4176                         xhci_err(xhci, "ISOC TD length unmatch\n");
4177                         ret = -EINVAL;
4178                         goto cleanup;
4179                 }
4180         }
4181
4182         /* store the next frame id */
4183         if (HCC_CFC(xhci->hcc_params))
4184                 xep->next_frame_id = urb->start_frame + num_tds * urb->interval;
4185
4186         if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) {
4187                 if (xhci->quirks & XHCI_AMD_PLL_FIX)
4188                         usb_amd_quirk_pll_disable();
4189         }
4190         xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs++;
4191
4192         giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
4193                         start_cycle, start_trb);
4194         return 0;
4195 cleanup:
4196         /* Clean up a partially enqueued isoc transfer. */
4197
4198         for (i--; i >= 0; i--)
4199                 list_del_init(&urb_priv->td[i].td_list);
4200
4201         /* Use the first TD as a temporary variable to turn the TDs we've queued
4202          * into No-ops with a software-owned cycle bit. That way the hardware
4203          * won't accidentally start executing bogus TDs when we partially
4204          * overwrite them.  td->first_trb and td->start_seg are already set.
4205          */
4206         urb_priv->td[0].last_trb = ep_ring->enqueue;
4207         /* Every TRB except the first & last will have its cycle bit flipped. */
4208         td_to_noop(xhci, ep_ring, &urb_priv->td[0], true);
4209
4210         /* Reset the ring enqueue back to the first TRB and its cycle bit. */
4211         ep_ring->enqueue = urb_priv->td[0].first_trb;
4212         ep_ring->enq_seg = urb_priv->td[0].start_seg;
4213         ep_ring->cycle_state = start_cycle;
4214         usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb);
4215         return ret;
4216 }
4217
4218 /*
4219  * Check transfer ring to guarantee there is enough room for the urb.
4220  * Update ISO URB start_frame and interval.
4221  * Update interval as xhci_queue_intr_tx does. Use xhci frame_index to
4222  * update urb->start_frame if URB_ISO_ASAP is set in transfer_flags or
4223  * Contiguous Frame ID is not supported by HC.
4224  */
4225 int xhci_queue_isoc_tx_prepare(struct xhci_hcd *xhci, gfp_t mem_flags,
4226                 struct urb *urb, int slot_id, unsigned int ep_index)
4227 {
4228         struct xhci_virt_device *xdev;
4229         struct xhci_ring *ep_ring;
4230         struct xhci_ep_ctx *ep_ctx;
4231         int start_frame;
4232         int num_tds, num_trbs, i;
4233         int ret;
4234         struct xhci_virt_ep *xep;
4235         int ist;
4236
4237         xdev = xhci->devs[slot_id];
4238         xep = &xhci->devs[slot_id]->eps[ep_index];
4239         ep_ring = xdev->eps[ep_index].ring;
4240         ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
4241
4242         num_trbs = 0;
4243         num_tds = urb->number_of_packets;
4244         for (i = 0; i < num_tds; i++)
4245                 num_trbs += count_isoc_trbs_needed(urb, i);
4246
4247         /* Check the ring to guarantee there is enough room for the whole urb.
4248          * Do not insert any td of the urb to the ring if the check failed.
4249          */
4250         ret = prepare_ring(xhci, ep_ring, GET_EP_CTX_STATE(ep_ctx),
4251                            num_trbs, mem_flags);
4252         if (ret)
4253                 return ret;
4254
4255         /*
4256          * Check interval value. This should be done before we start to
4257          * calculate the start frame value.
4258          */
4259         check_interval(xhci, urb, ep_ctx);
4260
4261         /* Calculate the start frame and put it in urb->start_frame. */
4262         if (HCC_CFC(xhci->hcc_params) && !list_empty(&ep_ring->td_list)) {
4263                 if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_RUNNING) {
4264                         urb->start_frame = xep->next_frame_id;
4265                         goto skip_start_over;
4266                 }
4267         }
4268
4269         start_frame = readl(&xhci->run_regs->microframe_index);
4270         start_frame &= 0x3fff;
4271         /*
4272          * Round up to the next frame and consider the time before trb really
4273          * gets scheduled by hardare.
4274          */
4275         ist = HCS_IST(xhci->hcs_params2) & 0x7;
4276         if (HCS_IST(xhci->hcs_params2) & (1 << 3))
4277                 ist <<= 3;
4278         start_frame += ist + XHCI_CFC_DELAY;
4279         start_frame = roundup(start_frame, 8);
4280
4281         /*
4282          * Round up to the next ESIT (Endpoint Service Interval Time) if ESIT
4283          * is greate than 8 microframes.
4284          */
4285         if (urb->dev->speed == USB_SPEED_LOW ||
4286                         urb->dev->speed == USB_SPEED_FULL) {
4287                 start_frame = roundup(start_frame, urb->interval << 3);
4288                 urb->start_frame = start_frame >> 3;
4289         } else {
4290                 start_frame = roundup(start_frame, urb->interval);
4291                 urb->start_frame = start_frame;
4292         }
4293
4294 skip_start_over:
4295
4296         return xhci_queue_isoc_tx(xhci, mem_flags, urb, slot_id, ep_index);
4297 }
4298
4299 /****           Command Ring Operations         ****/
4300
4301 /* Generic function for queueing a command TRB on the command ring.
4302  * Check to make sure there's room on the command ring for one command TRB.
4303  * Also check that there's room reserved for commands that must not fail.
4304  * If this is a command that must not fail, meaning command_must_succeed = TRUE,
4305  * then only check for the number of reserved spots.
4306  * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB
4307  * because the command event handler may want to resubmit a failed command.
4308  */
4309 static int queue_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
4310                          u32 field1, u32 field2,
4311                          u32 field3, u32 field4, bool command_must_succeed)
4312 {
4313         int reserved_trbs = xhci->cmd_ring_reserved_trbs;
4314         int ret;
4315
4316         if ((xhci->xhc_state & XHCI_STATE_DYING) ||
4317                 (xhci->xhc_state & XHCI_STATE_HALTED)) {
4318                 xhci_dbg(xhci, "xHCI dying or halted, can't queue_command\n");
4319                 return -ESHUTDOWN;
4320         }
4321
4322         if (!command_must_succeed)
4323                 reserved_trbs++;
4324
4325         ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING,
4326                         reserved_trbs, GFP_ATOMIC);
4327         if (ret < 0) {
4328                 xhci_err(xhci, "ERR: No room for command on command ring\n");
4329                 if (command_must_succeed)
4330                         xhci_err(xhci, "ERR: Reserved TRB counting for "
4331                                         "unfailable commands failed.\n");
4332                 return ret;
4333         }
4334
4335         cmd->command_trb = xhci->cmd_ring->enqueue;
4336
4337         /* if there are no other commands queued we start the timeout timer */
4338         if (list_empty(&xhci->cmd_list)) {
4339                 xhci->current_cmd = cmd;
4340                 xhci_mod_cmd_timer(xhci, XHCI_CMD_DEFAULT_TIMEOUT);
4341         }
4342
4343         list_add_tail(&cmd->cmd_list, &xhci->cmd_list);
4344
4345         queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3,
4346                         field4 | xhci->cmd_ring->cycle_state);
4347         return 0;
4348 }
4349
4350 /* Queue a slot enable or disable request on the command ring */
4351 int xhci_queue_slot_control(struct xhci_hcd *xhci, struct xhci_command *cmd,
4352                 u32 trb_type, u32 slot_id)
4353 {
4354         return queue_command(xhci, cmd, 0, 0, 0,
4355                         TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false);
4356 }
4357
4358 /* Queue an address device command TRB */
4359 int xhci_queue_address_device(struct xhci_hcd *xhci, struct xhci_command *cmd,
4360                 dma_addr_t in_ctx_ptr, u32 slot_id, enum xhci_setup_dev setup)
4361 {
4362         return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4363                         upper_32_bits(in_ctx_ptr), 0,
4364                         TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id)
4365                         | (setup == SETUP_CONTEXT_ONLY ? TRB_BSR : 0), false);
4366 }
4367
4368 int xhci_queue_vendor_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
4369                 u32 field1, u32 field2, u32 field3, u32 field4)
4370 {
4371         return queue_command(xhci, cmd, field1, field2, field3, field4, false);
4372 }
4373
4374 /* Queue a reset device command TRB */
4375 int xhci_queue_reset_device(struct xhci_hcd *xhci, struct xhci_command *cmd,
4376                 u32 slot_id)
4377 {
4378         return queue_command(xhci, cmd, 0, 0, 0,
4379                         TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id),
4380                         false);
4381 }
4382
4383 /* Queue a configure endpoint command TRB */
4384 int xhci_queue_configure_endpoint(struct xhci_hcd *xhci,
4385                 struct xhci_command *cmd, dma_addr_t in_ctx_ptr,
4386                 u32 slot_id, bool command_must_succeed)
4387 {
4388         return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4389                         upper_32_bits(in_ctx_ptr), 0,
4390                         TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id),
4391                         command_must_succeed);
4392 }
4393
4394 /* Queue an evaluate context command TRB */
4395 int xhci_queue_evaluate_context(struct xhci_hcd *xhci, struct xhci_command *cmd,
4396                 dma_addr_t in_ctx_ptr, u32 slot_id, bool command_must_succeed)
4397 {
4398         return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4399                         upper_32_bits(in_ctx_ptr), 0,
4400                         TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id),
4401                         command_must_succeed);
4402 }
4403
4404 /*
4405  * Suspend is set to indicate "Stop Endpoint Command" is being issued to stop
4406  * activity on an endpoint that is about to be suspended.
4407  */
4408 int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, struct xhci_command *cmd,
4409                              int slot_id, unsigned int ep_index, int suspend)
4410 {
4411         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
4412         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
4413         u32 type = TRB_TYPE(TRB_STOP_RING);
4414         u32 trb_suspend = SUSPEND_PORT_FOR_TRB(suspend);
4415
4416         return queue_command(xhci, cmd, 0, 0, 0,
4417                         trb_slot_id | trb_ep_index | type | trb_suspend, false);
4418 }
4419
4420 int xhci_queue_reset_ep(struct xhci_hcd *xhci, struct xhci_command *cmd,
4421                         int slot_id, unsigned int ep_index,
4422                         enum xhci_ep_reset_type reset_type)
4423 {
4424         u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
4425         u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
4426         u32 type = TRB_TYPE(TRB_RESET_EP);
4427
4428         if (reset_type == EP_SOFT_RESET)
4429                 type |= TRB_TSP;
4430
4431         return queue_command(xhci, cmd, 0, 0, 0,
4432                         trb_slot_id | trb_ep_index | type, false);
4433 }