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