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