1 // SPDX-License-Identifier: GPL-2.0
3 * xHCI host controller driver
5 * Copyright (C) 2008 Intel Corp.
8 * Some code borrowed from the Linux EHCI driver.
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.
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.
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.
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
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.
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.
55 #include <linux/scatterlist.h>
56 #include <linux/slab.h>
57 #include <linux/dma-mapping.h>
59 #include "xhci-trace.h"
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);
66 * Returns zero if the TRB isn't in this segment, otherwise it returns the DMA
69 dma_addr_t xhci_trb_virt_to_dma(struct xhci_segment *seg,
72 unsigned long segment_offset;
74 if (!seg || !trb || trb < seg->trbs)
77 segment_offset = trb - seg->trbs;
78 if (segment_offset >= TRBS_PER_SEGMENT)
80 return seg->dma + (segment_offset * sizeof(*trb));
83 static bool trb_is_noop(union xhci_trb *trb)
85 return TRB_TYPE_NOOP_LE32(trb->generic.field[3]);
88 static bool trb_is_link(union xhci_trb *trb)
90 return TRB_TYPE_LINK_LE32(trb->link.control);
93 static bool last_trb_on_seg(struct xhci_segment *seg,
94 unsigned int trbs_per_seg, union xhci_trb *trb)
96 return trb == &seg->trbs[trbs_per_seg - 1];
99 static bool last_trb_on_ring(struct xhci_ring *ring,
100 struct xhci_segment *seg, union xhci_trb *trb)
102 return last_trb_on_seg(seg, ring->trbs_per_seg, trb) && (seg->next == ring->first_seg);
105 static bool link_trb_toggles_cycle(union xhci_trb *trb)
107 return le32_to_cpu(trb->link.control) & LINK_TOGGLE;
110 static bool last_td_in_urb(struct xhci_td *td)
112 struct urb_priv *urb_priv = td->urb->hcpriv;
114 return urb_priv->num_tds_done == urb_priv->num_tds;
117 static void inc_td_cnt(struct urb *urb)
119 struct urb_priv *urb_priv = urb->hcpriv;
121 urb_priv->num_tds_done++;
124 static void trb_to_noop(union xhci_trb *trb, u32 noop_type)
126 if (trb_is_link(trb)) {
127 /* unchain chained link TRBs */
128 trb->link.control &= cpu_to_le32(~TRB_CHAIN);
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));
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.
143 static void next_trb(struct xhci_hcd *xhci,
144 struct xhci_ring *ring,
145 struct xhci_segment **seg,
146 union xhci_trb **trb)
148 if (trb_is_link(*trb)) {
150 *trb = ((*seg)->trbs);
157 * See Cycle bit rules. SW is the consumer for the event ring only.
159 void inc_deq(struct xhci_hcd *xhci, struct xhci_ring *ring)
161 unsigned int link_trb_count = 0;
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,
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;
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,
181 xhci_warn(xhci, "Missing link TRB at end of segment\n");
184 ring->num_trbs_free++;
188 while (trb_is_link(ring->dequeue)) {
189 ring->deq_seg = ring->deq_seg->next;
190 ring->dequeue = ring->deq_seg->trbs;
192 if (link_trb_count++ > ring->num_segs) {
193 xhci_warn(xhci, "Ring is an endless link TRB loop\n");
198 trace_xhci_inc_deq(ring);
204 * See Cycle bit rules. SW is the consumer for the event ring only.
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).
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.
216 * @more_trbs_coming: Will you enqueue more TRBs before calling
217 * prepare_transfer()?
219 static void inc_enq(struct xhci_hcd *xhci, struct xhci_ring *ring,
220 bool more_trbs_coming)
223 union xhci_trb *next;
224 unsigned int link_trb_count = 0;
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--;
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");
236 next = ++(ring->enqueue);
238 /* Update the dequeue pointer further if that was a link TRB */
239 while (trb_is_link(next)) {
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
248 if (!chain && !more_trbs_coming)
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).
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);
261 /* Give this link TRB to the hardware */
263 next->link.control ^= cpu_to_le32(TRB_CYCLE);
265 /* Toggle the cycle bit after the last ring segment. */
266 if (link_trb_toggles_cycle(next))
267 ring->cycle_state ^= 1;
269 ring->enq_seg = ring->enq_seg->next;
270 ring->enqueue = ring->enq_seg->trbs;
271 next = ring->enqueue;
273 if (link_trb_count++ > ring->num_segs) {
274 xhci_warn(xhci, "%s: Ring link TRB loop\n", __func__);
279 trace_xhci_inc_enq(ring);
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.
286 static inline int room_on_ring(struct xhci_hcd *xhci, struct xhci_ring *ring,
287 unsigned int num_trbs)
289 int num_trbs_in_deq_seg;
291 if (ring->num_trbs_free < num_trbs)
294 if (ring->type != TYPE_COMMAND && ring->type != TYPE_EVENT) {
296 * If the ring has a single segment the dequeue segment
297 * never changes, so don't use it as measure of free space.
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)
309 /* Ring the host controller doorbell after placing a command on the ring */
310 void xhci_ring_cmd_db(struct xhci_hcd *xhci)
312 if (!(xhci->cmd_ring_state & CMD_RING_STATE_RUNNING))
315 xhci_dbg(xhci, "// Ding dong!\n");
317 trace_xhci_ring_host_doorbell(0, DB_VALUE_HOST);
319 writel(DB_VALUE_HOST, &xhci->dba->doorbell[0]);
320 /* Flush PCI posted writes */
321 readl(&xhci->dba->doorbell[0]);
324 static bool xhci_mod_cmd_timer(struct xhci_hcd *xhci, unsigned long delay)
326 return mod_delayed_work(system_wq, &xhci->cmd_timer, delay);
329 static struct xhci_command *xhci_next_queued_cmd(struct xhci_hcd *xhci)
331 return list_first_entry_or_null(&xhci->cmd_list, struct xhci_command,
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.
340 static void xhci_handle_stopped_cmd_ring(struct xhci_hcd *xhci,
341 struct xhci_command *cur_cmd)
343 struct xhci_command *i_cmd;
345 /* Turn all aborted commands in list to no-ops, then restart */
346 list_for_each_entry(i_cmd, &xhci->cmd_list, cmd_list) {
348 if (i_cmd->status != COMP_COMMAND_ABORTED)
351 i_cmd->status = COMP_COMMAND_RING_STOPPED;
353 xhci_dbg(xhci, "Turn aborted command %p to no-op\n",
356 trb_to_noop(i_cmd->command_trb, TRB_CMD_NOOP);
359 * caller waiting for completion is called when command
360 * completion event is received for these no-op commands
364 xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
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);
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)
378 struct xhci_segment *new_seg = xhci->cmd_ring->deq_seg;
379 union xhci_trb *new_deq = xhci->cmd_ring->dequeue;
383 xhci_dbg(xhci, "Abort command ring\n");
385 reinit_completion(&xhci->cmd_ring_stop_completion);
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.
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);
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);
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.
408 ret = xhci_handshake(&xhci->op_regs->cmd_ring,
409 CMD_RING_RUNNING, 0, 5 * 1000 * 1000);
411 xhci_err(xhci, "Abort failed to stop command ring: %d\n", ret);
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.
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);
427 xhci_dbg(xhci, "No stop event for abort, ring start fail?\n");
428 xhci_cleanup_command_queue(xhci);
430 xhci_handle_stopped_cmd_ring(xhci, xhci_next_queued_cmd(xhci));
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)
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;
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.
450 if ((ep_state & EP_STOP_CMD_PENDING) || (ep_state & SET_DEQ_PENDING) ||
451 (ep_state & EP_HALTED) || (ep_state & EP_CLEARING_TT))
454 trace_xhci_ring_ep_doorbell(slot_id, DB_VALUE(ep_index, stream_id));
456 writel(DB_VALUE(ep_index, stream_id), db_addr);
457 /* flush the write */
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)
466 unsigned int stream_id;
467 struct xhci_virt_ep *ep;
469 ep = &xhci->devs[slot_id]->eps[ep_index];
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);
478 for (stream_id = 1; stream_id < ep->stream_info->num_streams;
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,
487 void xhci_ring_doorbell_for_active_rings(struct xhci_hcd *xhci,
488 unsigned int slot_id,
489 unsigned int ep_index)
491 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
494 static struct xhci_virt_ep *xhci_get_virt_ep(struct xhci_hcd *xhci,
495 unsigned int slot_id,
496 unsigned int ep_index)
498 if (slot_id == 0 || slot_id >= MAX_HC_SLOTS) {
499 xhci_warn(xhci, "Invalid slot_id %u\n", slot_id);
502 if (ep_index >= EP_CTX_PER_DEV) {
503 xhci_warn(xhci, "Invalid endpoint index %u\n", ep_index);
506 if (!xhci->devs[slot_id]) {
507 xhci_warn(xhci, "No xhci virt device for slot_id %u\n", slot_id);
511 return &xhci->devs[slot_id]->eps[ep_index];
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)
518 /* common case, no streams */
519 if (!(ep->ep_state & EP_HAS_STREAMS))
522 if (!ep->stream_info)
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);
531 return ep->stream_info->stream_rings[stream_id];
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.
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)
542 struct xhci_virt_ep *ep;
544 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
548 return xhci_virt_ep_to_ring(xhci, ep, stream_id);
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.
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)
561 struct xhci_ep_ctx *ep_ctx;
562 struct xhci_stream_ctx *st_ctx;
563 struct xhci_virt_ep *ep;
565 ep = &vdev->eps[ep_index];
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);
571 ep_ctx = xhci_get_ep_ctx(xhci, vdev->out_ctx, ep_index);
572 return le64_to_cpu(ep_ctx->deq);
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)
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;
587 union xhci_trb *halted_trb;
591 bool cycle_found = false;
592 bool td_last_trb_found = false;
596 ep_ring = xhci_triad_to_transfer_ring(xhci, slot_id,
597 ep_index, stream_id);
599 xhci_warn(xhci, "WARN can't find new dequeue, invalid stream ID %u\n",
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
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");
618 xhci_warn(xhci, "Can't find new dequeue state, missing td\n");
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;
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.
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);
638 index = ((dma_addr_t)(hw_dequeue & ~0xf) - halted_seg->dma) /
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);
645 new_cycle = hw_dequeue & 0x1;
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
655 if (!cycle_found && xhci_trb_virt_to_dma(new_seg, new_deq)
656 == (dma_addr_t)(hw_dequeue & ~0xf)) {
658 if (td_last_trb_found)
661 if (new_deq == td->last_trb)
662 td_last_trb_found = true;
664 if (cycle_found && trb_is_link(new_deq) &&
665 link_trb_toggles_cycle(new_deq))
668 next_trb(xhci, ep_ring, &new_seg, &new_deq);
670 /* Search wrapped around, bail out */
671 if (new_deq == ep->ring->dequeue) {
672 xhci_err(xhci, "Error: Failed finding new dequeue state\n");
676 } while (!cycle_found || !td_last_trb_found);
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).
683 if (xhci->quirks & XHCI_AVOID_DQ_ON_LINK && trb_is_link(new_deq)) {
684 if (link_trb_toggles_cycle(new_deq))
686 next_trb(xhci, ep_ring, &new_seg, &new_deq);
689 /* Don't update the ring cycle state for the producer (us). */
690 addr = xhci_trb_virt_to_dma(new_seg, new_deq);
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);
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",
700 ep->ep_state &= ~SET_DEQ_PENDING;
703 /* This function gets called from contexts where it cannot sleep */
704 cmd = xhci_alloc_command(xhci, false, GFP_ATOMIC);
706 xhci_warn(xhci, "Can't alloc Set TR Deq cmd 0x%pad\n", &addr);
711 trb_sct = SCT_FOR_TRB(SCT_PRI_TR);
712 ret = queue_command(xhci, cmd,
713 lower_32_bits(addr) | trb_sct | new_cycle,
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);
718 xhci_free_command(xhci, cmd);
721 ep->queued_deq_seg = new_seg;
722 ep->queued_deq_ptr = new_deq;
724 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
725 "Set TR Deq ptr 0x%llx, cycle %u\n", addr, new_cycle);
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
732 ep->ep_state |= SET_DEQ_PENDING;
733 xhci_ring_cmd_db(xhci);
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.
741 static void td_to_noop(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
742 struct xhci_td *td, bool flip_cycle)
744 struct xhci_segment *seg = td->start_seg;
745 union xhci_trb *trb = td->first_trb;
748 trb_to_noop(trb, TRB_TR_NOOP);
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);
754 if (trb == td->last_trb)
757 next_trb(xhci, ep_ring, &seg, &trb);
761 static void xhci_stop_watchdog_timer_in_irq(struct xhci_hcd *xhci,
762 struct xhci_virt_ep *ep)
764 ep->ep_state &= ~EP_STOP_CMD_PENDING;
765 /* Can't del_timer_sync in interrupt */
766 del_timer(&ep->stop_cmd_timer);
770 * Must be called with xhci->lock held in interrupt context,
771 * releases and re-acquires xhci->lock
773 static void xhci_giveback_urb_in_irq(struct xhci_hcd *xhci,
774 struct xhci_td *cur_td, int status)
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);
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();
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);
793 static void xhci_unmap_td_bounce_buffer(struct xhci_hcd *xhci,
794 struct xhci_ring *ring, struct xhci_td *td)
796 struct device *dev = xhci_to_hcd(xhci)->self.controller;
797 struct xhci_segment *seg = td->bounce_seg;
798 struct urb *urb = td->urb;
801 if (!ring || !seg || !urb)
804 if (usb_urb_dir_out(urb)) {
805 dma_unmap_single(dev, seg->bounce_dma, ring->bounce_buf_len,
810 dma_unmap_single(dev, seg->bounce_dma, ring->bounce_buf_len,
812 /* for in tranfers we need to copy the data from bounce to sg */
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);
820 memcpy(urb->transfer_buffer + seg->bounce_offs, seg->bounce_buf,
824 seg->bounce_offs = 0;
827 static int xhci_td_cleanup(struct xhci_hcd *xhci, struct xhci_td *td,
828 struct xhci_ring *ep_ring, int status)
830 struct urb *urb = NULL;
832 /* Clean up the endpoint's TD list */
835 /* if a bounce buffer was used to align this td then unmap it */
836 xhci_unmap_td_bounce_buffer(xhci, ep_ring, td);
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.
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;
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);
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);
866 /* set isoc urb status to 0 just as EHCI, UHCI, and OHCI */
867 if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS)
869 xhci_giveback_urb_in_irq(xhci, td, status);
876 /* Complete the cancelled URBs we unlinked from td_list. */
877 static void xhci_giveback_invalidated_tds(struct xhci_virt_ep *ep)
879 struct xhci_ring *ring;
880 struct xhci_td *td, *tmp_td;
882 list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list,
885 ring = xhci_urb_to_transfer_ring(ep->xhci, td->urb);
887 if (td->cancel_status == TD_CLEARED) {
888 xhci_dbg(ep->xhci, "%s: Giveback cancelled URB %p TD\n",
890 xhci_td_cleanup(ep->xhci, td, ring, td->status);
892 xhci_dbg(ep->xhci, "%s: Keep cancelled URB %p TD as cancel_status is %d\n",
893 __func__, td->urb, td->cancel_status);
895 if (ep->xhci->xhc_state & XHCI_STATE_DYING)
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)
903 struct xhci_command *command;
906 command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
912 xhci_dbg(xhci, "%s-reset ep %u, slot %u\n",
913 (reset_type == EP_HARD_RESET) ? "Hard" : "Soft",
916 ret = xhci_queue_reset_ep(xhci, command, slot_id, ep_index, reset_type);
919 xhci_err(xhci, "ERROR queuing reset endpoint for slot %d ep_index %d, %d\n",
920 slot_id, ep_index, ret);
924 static int xhci_handle_halted_endpoint(struct xhci_hcd *xhci,
925 struct xhci_virt_ep *ep, unsigned int stream_id,
927 enum xhci_ep_reset_type reset_type)
929 unsigned int slot_id = ep->vdev->slot_id;
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
936 if (ep->vdev->flags & VDEV_PORT_ERROR)
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;
948 if (ep->ep_state & EP_HALTED) {
949 xhci_dbg(xhci, "Reset ep command for ep_index %d already pending\n",
954 err = xhci_reset_halted_ep(xhci, slot_id, ep->ep_index, reset_type);
958 ep->ep_state |= EP_HALTED;
960 xhci_ring_cmd_db(xhci);
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.
971 * only call this when ring is not in a running state
974 static int xhci_invalidate_cancelled_tds(struct xhci_virt_ep *ep)
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;
982 unsigned int slot_id = ep->vdev->slot_id;
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);
996 xhci_warn(xhci, "WARN Cancelled URB %p has invalid stream ID %u.\n",
997 td->urb, td->urb->stream_id);
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.
1006 hw_deq = xhci_get_hw_deq(xhci, ep->vdev, ep->ep_index,
1007 td->urb->stream_id);
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 */
1016 case TD_DIRTY: /* TD is cached, clear it */
1018 td->cancel_status = TD_CLEARING_CACHE;
1020 /* FIXME stream case, several stopped rings */
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);
1026 ring->num_trbs_free += td->num_trbs;
1030 td_to_noop(xhci, ring, td, false);
1031 td->cancel_status = TD_CLEARED;
1032 ring->num_trbs_free += td->num_trbs;
1036 /* If there's no need to move the dequeue pointer then we're done */
1040 err = xhci_move_dequeue_past_td(xhci, slot_id, ep->ep_index,
1041 cached_td->urb->stream_id,
1044 /* Failed to move past cached td, just set cached TDs to no-op */
1045 list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list, cancelled_td_list) {
1046 if (td->cancel_status != TD_CLEARING_CACHE)
1048 xhci_dbg(xhci, "Failed to clear cancelled cached URB %p, mark clear anyway\n",
1050 td_to_noop(xhci, ring, td, false);
1051 td->cancel_status = TD_CLEARED;
1058 * Returns the TD the endpoint ring halted on.
1059 * Only call for non-running rings without streams.
1061 static struct xhci_td *find_halted_td(struct xhci_virt_ep *ep)
1066 if (!list_empty(&ep->ring->td_list)) { /* Not streams compatible */
1067 hw_deq = xhci_get_hw_deq(ep->xhci, ep->vdev, ep->ep_index, 0);
1069 td = list_first_entry(&ep->ring->td_list, struct xhci_td, td_list);
1070 if (trb_in_td(ep->xhci, td->start_seg, td->first_trb,
1071 td->last_trb, hw_deq, false))
1078 * When we get a command completion for a Stop Endpoint Command, we need to
1079 * unlink any cancelled TDs from the ring. There are two ways to do that:
1081 * 1. If the HW was in the middle of processing the TD that needs to be
1082 * cancelled, then we must move the ring's dequeue pointer past the last TRB
1083 * in the TD with a Set Dequeue Pointer Command.
1084 * 2. Otherwise, we turn all the TRBs in the TD into No-op TRBs (with the chain
1085 * bit cleared) so that the HW will skip over them.
1087 static void xhci_handle_cmd_stop_ep(struct xhci_hcd *xhci, int slot_id,
1088 union xhci_trb *trb, u32 comp_code)
1090 unsigned int ep_index;
1091 struct xhci_virt_ep *ep;
1092 struct xhci_ep_ctx *ep_ctx;
1093 struct xhci_td *td = NULL;
1094 enum xhci_ep_reset_type reset_type;
1095 struct xhci_command *command;
1098 if (unlikely(TRB_TO_SUSPEND_PORT(le32_to_cpu(trb->generic.field[3])))) {
1099 if (!xhci->devs[slot_id])
1100 xhci_warn(xhci, "Stop endpoint command completion for disabled slot %u\n",
1105 ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1106 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1110 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1112 trace_xhci_handle_cmd_stop_ep(ep_ctx);
1114 if (comp_code == COMP_CONTEXT_STATE_ERROR) {
1116 * If stop endpoint command raced with a halting endpoint we need to
1117 * reset the host side endpoint first.
1118 * If the TD we halted on isn't cancelled the TD should be given back
1119 * with a proper error code, and the ring dequeue moved past the TD.
1120 * If streams case we can't find hw_deq, or the TD we halted on so do a
1123 * Proper error code is unknown here, it would be -EPIPE if device side
1124 * of enadpoit halted (aka STALL), and -EPROTO if not (transaction error)
1125 * We use -EPROTO, if device is stalled it should return a stall error on
1126 * next transfer, which then will return -EPIPE, and device side stall is
1127 * noted and cleared by class driver.
1129 switch (GET_EP_CTX_STATE(ep_ctx)) {
1130 case EP_STATE_HALTED:
1131 xhci_dbg(xhci, "Stop ep completion raced with stall, reset ep\n");
1132 if (ep->ep_state & EP_HAS_STREAMS) {
1133 reset_type = EP_SOFT_RESET;
1135 reset_type = EP_HARD_RESET;
1136 td = find_halted_td(ep);
1138 td->status = -EPROTO;
1140 /* reset ep, reset handler cleans up cancelled tds */
1141 err = xhci_handle_halted_endpoint(xhci, ep, 0, td,
1145 xhci_stop_watchdog_timer_in_irq(xhci, ep);
1147 case EP_STATE_RUNNING:
1148 /* Race, HW handled stop ep cmd before ep was running */
1149 xhci_dbg(xhci, "Stop ep completion ctx error, ep is running\n");
1151 command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
1153 xhci_stop_watchdog_timer_in_irq(xhci, ep);
1155 mod_timer(&ep->stop_cmd_timer,
1156 jiffies + XHCI_STOP_EP_CMD_TIMEOUT * HZ);
1157 xhci_queue_stop_endpoint(xhci, command, slot_id, ep_index, 0);
1158 xhci_ring_cmd_db(xhci);
1165 /* will queue a set TR deq if stopped on a cancelled, uncleared TD */
1166 xhci_invalidate_cancelled_tds(ep);
1167 xhci_stop_watchdog_timer_in_irq(xhci, ep);
1169 /* Otherwise ring the doorbell(s) to restart queued transfers */
1170 xhci_giveback_invalidated_tds(ep);
1171 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1174 static void xhci_kill_ring_urbs(struct xhci_hcd *xhci, struct xhci_ring *ring)
1176 struct xhci_td *cur_td;
1177 struct xhci_td *tmp;
1179 list_for_each_entry_safe(cur_td, tmp, &ring->td_list, td_list) {
1180 list_del_init(&cur_td->td_list);
1182 if (!list_empty(&cur_td->cancelled_td_list))
1183 list_del_init(&cur_td->cancelled_td_list);
1185 xhci_unmap_td_bounce_buffer(xhci, ring, cur_td);
1187 inc_td_cnt(cur_td->urb);
1188 if (last_td_in_urb(cur_td))
1189 xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN);
1193 static void xhci_kill_endpoint_urbs(struct xhci_hcd *xhci,
1194 int slot_id, int ep_index)
1196 struct xhci_td *cur_td;
1197 struct xhci_td *tmp;
1198 struct xhci_virt_ep *ep;
1199 struct xhci_ring *ring;
1201 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1205 if ((ep->ep_state & EP_HAS_STREAMS) ||
1206 (ep->ep_state & EP_GETTING_NO_STREAMS)) {
1209 for (stream_id = 1; stream_id < ep->stream_info->num_streams;
1211 ring = ep->stream_info->stream_rings[stream_id];
1215 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1216 "Killing URBs for slot ID %u, ep index %u, stream %u",
1217 slot_id, ep_index, stream_id);
1218 xhci_kill_ring_urbs(xhci, ring);
1224 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1225 "Killing URBs for slot ID %u, ep index %u",
1227 xhci_kill_ring_urbs(xhci, ring);
1230 list_for_each_entry_safe(cur_td, tmp, &ep->cancelled_td_list,
1231 cancelled_td_list) {
1232 list_del_init(&cur_td->cancelled_td_list);
1233 inc_td_cnt(cur_td->urb);
1235 if (last_td_in_urb(cur_td))
1236 xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN);
1241 * host controller died, register read returns 0xffffffff
1242 * Complete pending commands, mark them ABORTED.
1243 * URBs need to be given back as usb core might be waiting with device locks
1244 * held for the URBs to finish during device disconnect, blocking host remove.
1246 * Call with xhci->lock held.
1247 * lock is relased and re-acquired while giving back urb.
1249 void xhci_hc_died(struct xhci_hcd *xhci)
1253 if (xhci->xhc_state & XHCI_STATE_DYING)
1256 xhci_err(xhci, "xHCI host controller not responding, assume dead\n");
1257 xhci->xhc_state |= XHCI_STATE_DYING;
1259 xhci_cleanup_command_queue(xhci);
1261 /* return any pending urbs, remove may be waiting for them */
1262 for (i = 0; i <= HCS_MAX_SLOTS(xhci->hcs_params1); i++) {
1265 for (j = 0; j < 31; j++)
1266 xhci_kill_endpoint_urbs(xhci, i, j);
1269 /* inform usb core hc died if PCI remove isn't already handling it */
1270 if (!(xhci->xhc_state & XHCI_STATE_REMOVING))
1271 usb_hc_died(xhci_to_hcd(xhci));
1274 /* Watchdog timer function for when a stop endpoint command fails to complete.
1275 * In this case, we assume the host controller is broken or dying or dead. The
1276 * host may still be completing some other events, so we have to be careful to
1277 * let the event ring handler and the URB dequeueing/enqueueing functions know
1278 * through xhci->state.
1280 * The timer may also fire if the host takes a very long time to respond to the
1281 * command, and the stop endpoint command completion handler cannot delete the
1282 * timer before the timer function is called. Another endpoint cancellation may
1283 * sneak in before the timer function can grab the lock, and that may queue
1284 * another stop endpoint command and add the timer back. So we cannot use a
1285 * simple flag to say whether there is a pending stop endpoint command for a
1286 * particular endpoint.
1288 * Instead we use a combination of that flag and checking if a new timer is
1291 void xhci_stop_endpoint_command_watchdog(struct timer_list *t)
1293 struct xhci_virt_ep *ep = from_timer(ep, t, stop_cmd_timer);
1294 struct xhci_hcd *xhci = ep->xhci;
1295 unsigned long flags;
1297 char str[XHCI_MSG_MAX];
1299 spin_lock_irqsave(&xhci->lock, flags);
1301 /* bail out if cmd completed but raced with stop ep watchdog timer.*/
1302 if (!(ep->ep_state & EP_STOP_CMD_PENDING) ||
1303 timer_pending(&ep->stop_cmd_timer)) {
1304 spin_unlock_irqrestore(&xhci->lock, flags);
1305 xhci_dbg(xhci, "Stop EP timer raced with cmd completion, exit");
1308 usbsts = readl(&xhci->op_regs->status);
1310 xhci_warn(xhci, "xHCI host not responding to stop endpoint command.\n");
1311 xhci_warn(xhci, "USBSTS:%s\n", xhci_decode_usbsts(str, usbsts));
1313 ep->ep_state &= ~EP_STOP_CMD_PENDING;
1318 * handle a stop endpoint cmd timeout as if host died (-ENODEV).
1319 * In the future we could distinguish between -ENODEV and -ETIMEDOUT
1320 * and try to recover a -ETIMEDOUT with a host controller reset
1324 spin_unlock_irqrestore(&xhci->lock, flags);
1325 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1326 "xHCI host controller is dead.");
1329 static void update_ring_for_set_deq_completion(struct xhci_hcd *xhci,
1330 struct xhci_virt_device *dev,
1331 struct xhci_ring *ep_ring,
1332 unsigned int ep_index)
1334 union xhci_trb *dequeue_temp;
1336 dequeue_temp = ep_ring->dequeue;
1338 /* If we get two back-to-back stalls, and the first stalled transfer
1339 * ends just before a link TRB, the dequeue pointer will be left on
1340 * the link TRB by the code in the while loop. So we have to update
1341 * the dequeue pointer one segment further, or we'll jump off
1342 * the segment into la-la-land.
1344 if (trb_is_link(ep_ring->dequeue)) {
1345 ep_ring->deq_seg = ep_ring->deq_seg->next;
1346 ep_ring->dequeue = ep_ring->deq_seg->trbs;
1349 while (ep_ring->dequeue != dev->eps[ep_index].queued_deq_ptr) {
1351 if (trb_is_link(ep_ring->dequeue)) {
1352 if (ep_ring->dequeue ==
1353 dev->eps[ep_index].queued_deq_ptr)
1355 ep_ring->deq_seg = ep_ring->deq_seg->next;
1356 ep_ring->dequeue = ep_ring->deq_seg->trbs;
1358 if (ep_ring->dequeue == dequeue_temp) {
1359 xhci_dbg(xhci, "Unable to find new dequeue pointer\n");
1366 * When we get a completion for a Set Transfer Ring Dequeue Pointer command,
1367 * we need to clear the set deq pending flag in the endpoint ring state, so that
1368 * the TD queueing code can ring the doorbell again. We also need to ring the
1369 * endpoint doorbell to restart the ring, but only if there aren't more
1370 * cancellations pending.
1372 static void xhci_handle_cmd_set_deq(struct xhci_hcd *xhci, int slot_id,
1373 union xhci_trb *trb, u32 cmd_comp_code)
1375 unsigned int ep_index;
1376 unsigned int stream_id;
1377 struct xhci_ring *ep_ring;
1378 struct xhci_virt_ep *ep;
1379 struct xhci_ep_ctx *ep_ctx;
1380 struct xhci_slot_ctx *slot_ctx;
1381 struct xhci_td *td, *tmp_td;
1383 ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1384 stream_id = TRB_TO_STREAM_ID(le32_to_cpu(trb->generic.field[2]));
1385 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1389 ep_ring = xhci_virt_ep_to_ring(xhci, ep, stream_id);
1391 xhci_warn(xhci, "WARN Set TR deq ptr command for freed stream ID %u\n",
1393 /* XXX: Harmless??? */
1397 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1398 slot_ctx = xhci_get_slot_ctx(xhci, ep->vdev->out_ctx);
1399 trace_xhci_handle_cmd_set_deq(slot_ctx);
1400 trace_xhci_handle_cmd_set_deq_ep(ep_ctx);
1402 if (cmd_comp_code != COMP_SUCCESS) {
1403 unsigned int ep_state;
1404 unsigned int slot_state;
1406 switch (cmd_comp_code) {
1407 case COMP_TRB_ERROR:
1408 xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because of stream ID configuration\n");
1410 case COMP_CONTEXT_STATE_ERROR:
1411 xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due to incorrect slot or ep state.\n");
1412 ep_state = GET_EP_CTX_STATE(ep_ctx);
1413 slot_state = le32_to_cpu(slot_ctx->dev_state);
1414 slot_state = GET_SLOT_STATE(slot_state);
1415 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1416 "Slot state = %u, EP state = %u",
1417 slot_state, ep_state);
1419 case COMP_SLOT_NOT_ENABLED_ERROR:
1420 xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because slot %u was not enabled.\n",
1424 xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown completion code of %u.\n",
1428 /* OK what do we do now? The endpoint state is hosed, and we
1429 * should never get to this point if the synchronization between
1430 * queueing, and endpoint state are correct. This might happen
1431 * if the device gets disconnected after we've finished
1432 * cancelling URBs, which might not be an error...
1436 /* 4.6.10 deq ptr is written to the stream ctx for streams */
1437 if (ep->ep_state & EP_HAS_STREAMS) {
1438 struct xhci_stream_ctx *ctx =
1439 &ep->stream_info->stream_ctx_array[stream_id];
1440 deq = le64_to_cpu(ctx->stream_ring) & SCTX_DEQ_MASK;
1442 deq = le64_to_cpu(ep_ctx->deq) & ~EP_CTX_CYCLE_MASK;
1444 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1445 "Successful Set TR Deq Ptr cmd, deq = @%08llx", deq);
1446 if (xhci_trb_virt_to_dma(ep->queued_deq_seg,
1447 ep->queued_deq_ptr) == deq) {
1448 /* Update the ring's dequeue segment and dequeue pointer
1449 * to reflect the new position.
1451 update_ring_for_set_deq_completion(xhci, ep->vdev,
1454 xhci_warn(xhci, "Mismatch between completed Set TR Deq Ptr command & xHCI internal state.\n");
1455 xhci_warn(xhci, "ep deq seg = %p, deq ptr = %p\n",
1456 ep->queued_deq_seg, ep->queued_deq_ptr);
1459 /* HW cached TDs cleared from cache, give them back */
1460 list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list,
1461 cancelled_td_list) {
1462 ep_ring = xhci_urb_to_transfer_ring(ep->xhci, td->urb);
1463 if (td->cancel_status == TD_CLEARING_CACHE) {
1464 td->cancel_status = TD_CLEARED;
1465 xhci_dbg(ep->xhci, "%s: Giveback cancelled URB %p TD\n",
1467 xhci_td_cleanup(ep->xhci, td, ep_ring, td->status);
1469 xhci_dbg(ep->xhci, "%s: Keep cancelled URB %p TD as cancel_status is %d\n",
1470 __func__, td->urb, td->cancel_status);
1474 ep->ep_state &= ~SET_DEQ_PENDING;
1475 ep->queued_deq_seg = NULL;
1476 ep->queued_deq_ptr = NULL;
1477 /* Restart any rings with pending URBs */
1478 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1481 static void xhci_handle_cmd_reset_ep(struct xhci_hcd *xhci, int slot_id,
1482 union xhci_trb *trb, u32 cmd_comp_code)
1484 struct xhci_virt_ep *ep;
1485 struct xhci_ep_ctx *ep_ctx;
1486 unsigned int ep_index;
1488 ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1489 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1493 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1494 trace_xhci_handle_cmd_reset_ep(ep_ctx);
1496 /* This command will only fail if the endpoint wasn't halted,
1497 * but we don't care.
1499 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
1500 "Ignoring reset ep completion code of %u", cmd_comp_code);
1502 /* Cleanup cancelled TDs as ep is stopped. May queue a Set TR Deq cmd */
1503 xhci_invalidate_cancelled_tds(ep);
1505 if (xhci->quirks & XHCI_RESET_EP_QUIRK)
1506 xhci_dbg(xhci, "Note: Removed workaround to queue config ep for this hw");
1507 /* Clear our internal halted state */
1508 ep->ep_state &= ~EP_HALTED;
1510 xhci_giveback_invalidated_tds(ep);
1512 /* if this was a soft reset, then restart */
1513 if ((le32_to_cpu(trb->generic.field[3])) & TRB_TSP)
1514 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1517 static void xhci_handle_cmd_enable_slot(struct xhci_hcd *xhci, int slot_id,
1518 struct xhci_command *command, u32 cmd_comp_code)
1520 if (cmd_comp_code == COMP_SUCCESS)
1521 command->slot_id = slot_id;
1523 command->slot_id = 0;
1526 static void xhci_handle_cmd_disable_slot(struct xhci_hcd *xhci, int slot_id)
1528 struct xhci_virt_device *virt_dev;
1529 struct xhci_slot_ctx *slot_ctx;
1531 virt_dev = xhci->devs[slot_id];
1535 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
1536 trace_xhci_handle_cmd_disable_slot(slot_ctx);
1538 if (xhci->quirks & XHCI_EP_LIMIT_QUIRK)
1539 /* Delete default control endpoint resources */
1540 xhci_free_device_endpoint_resources(xhci, virt_dev, true);
1543 static void xhci_handle_cmd_config_ep(struct xhci_hcd *xhci, int slot_id,
1546 struct xhci_virt_device *virt_dev;
1547 struct xhci_input_control_ctx *ctrl_ctx;
1548 struct xhci_ep_ctx *ep_ctx;
1549 unsigned int ep_index;
1550 unsigned int ep_state;
1551 u32 add_flags, drop_flags;
1554 * Configure endpoint commands can come from the USB core
1555 * configuration or alt setting changes, or because the HW
1556 * needed an extra configure endpoint command after a reset
1557 * endpoint command or streams were being configured.
1558 * If the command was for a halted endpoint, the xHCI driver
1559 * is not waiting on the configure endpoint command.
1561 virt_dev = xhci->devs[slot_id];
1564 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1566 xhci_warn(xhci, "Could not get input context, bad type.\n");
1570 add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1571 drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1572 /* Input ctx add_flags are the endpoint index plus one */
1573 ep_index = xhci_last_valid_endpoint(add_flags) - 1;
1575 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->out_ctx, ep_index);
1576 trace_xhci_handle_cmd_config_ep(ep_ctx);
1578 /* A usb_set_interface() call directly after clearing a halted
1579 * condition may race on this quirky hardware. Not worth
1580 * worrying about, since this is prototype hardware. Not sure
1581 * if this will work for streams, but streams support was
1582 * untested on this prototype.
1584 if (xhci->quirks & XHCI_RESET_EP_QUIRK &&
1585 ep_index != (unsigned int) -1 &&
1586 add_flags - SLOT_FLAG == drop_flags) {
1587 ep_state = virt_dev->eps[ep_index].ep_state;
1588 if (!(ep_state & EP_HALTED))
1590 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1591 "Completed config ep cmd - "
1592 "last ep index = %d, state = %d",
1593 ep_index, ep_state);
1594 /* Clear internal halted state and restart ring(s) */
1595 virt_dev->eps[ep_index].ep_state &= ~EP_HALTED;
1596 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1602 static void xhci_handle_cmd_addr_dev(struct xhci_hcd *xhci, int slot_id)
1604 struct xhci_virt_device *vdev;
1605 struct xhci_slot_ctx *slot_ctx;
1607 vdev = xhci->devs[slot_id];
1610 slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
1611 trace_xhci_handle_cmd_addr_dev(slot_ctx);
1614 static void xhci_handle_cmd_reset_dev(struct xhci_hcd *xhci, int slot_id)
1616 struct xhci_virt_device *vdev;
1617 struct xhci_slot_ctx *slot_ctx;
1619 vdev = xhci->devs[slot_id];
1621 xhci_warn(xhci, "Reset device command completion for disabled slot %u\n",
1625 slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
1626 trace_xhci_handle_cmd_reset_dev(slot_ctx);
1628 xhci_dbg(xhci, "Completed reset device command.\n");
1631 static void xhci_handle_cmd_nec_get_fw(struct xhci_hcd *xhci,
1632 struct xhci_event_cmd *event)
1634 if (!(xhci->quirks & XHCI_NEC_HOST)) {
1635 xhci_warn(xhci, "WARN NEC_GET_FW command on non-NEC host\n");
1638 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1639 "NEC firmware version %2x.%02x",
1640 NEC_FW_MAJOR(le32_to_cpu(event->status)),
1641 NEC_FW_MINOR(le32_to_cpu(event->status)));
1644 static void xhci_complete_del_and_free_cmd(struct xhci_command *cmd, u32 status)
1646 list_del(&cmd->cmd_list);
1648 if (cmd->completion) {
1649 cmd->status = status;
1650 complete(cmd->completion);
1656 void xhci_cleanup_command_queue(struct xhci_hcd *xhci)
1658 struct xhci_command *cur_cmd, *tmp_cmd;
1659 xhci->current_cmd = NULL;
1660 list_for_each_entry_safe(cur_cmd, tmp_cmd, &xhci->cmd_list, cmd_list)
1661 xhci_complete_del_and_free_cmd(cur_cmd, COMP_COMMAND_ABORTED);
1664 void xhci_handle_command_timeout(struct work_struct *work)
1666 struct xhci_hcd *xhci;
1667 unsigned long flags;
1670 xhci = container_of(to_delayed_work(work), struct xhci_hcd, cmd_timer);
1672 spin_lock_irqsave(&xhci->lock, flags);
1675 * If timeout work is pending, or current_cmd is NULL, it means we
1676 * raced with command completion. Command is handled so just return.
1678 if (!xhci->current_cmd || delayed_work_pending(&xhci->cmd_timer)) {
1679 spin_unlock_irqrestore(&xhci->lock, flags);
1682 /* mark this command to be cancelled */
1683 xhci->current_cmd->status = COMP_COMMAND_ABORTED;
1685 /* Make sure command ring is running before aborting it */
1686 hw_ring_state = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
1687 if (hw_ring_state == ~(u64)0) {
1689 goto time_out_completed;
1692 if ((xhci->cmd_ring_state & CMD_RING_STATE_RUNNING) &&
1693 (hw_ring_state & CMD_RING_RUNNING)) {
1694 /* Prevent new doorbell, and start command abort */
1695 xhci->cmd_ring_state = CMD_RING_STATE_ABORTED;
1696 xhci_dbg(xhci, "Command timeout\n");
1697 xhci_abort_cmd_ring(xhci, flags);
1698 goto time_out_completed;
1701 /* host removed. Bail out */
1702 if (xhci->xhc_state & XHCI_STATE_REMOVING) {
1703 xhci_dbg(xhci, "host removed, ring start fail?\n");
1704 xhci_cleanup_command_queue(xhci);
1706 goto time_out_completed;
1709 /* command timeout on stopped ring, ring can't be aborted */
1710 xhci_dbg(xhci, "Command timeout on stopped ring\n");
1711 xhci_handle_stopped_cmd_ring(xhci, xhci->current_cmd);
1714 spin_unlock_irqrestore(&xhci->lock, flags);
1718 static void handle_cmd_completion(struct xhci_hcd *xhci,
1719 struct xhci_event_cmd *event)
1721 unsigned int slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
1723 dma_addr_t cmd_dequeue_dma;
1725 union xhci_trb *cmd_trb;
1726 struct xhci_command *cmd;
1729 if (slot_id >= MAX_HC_SLOTS) {
1730 xhci_warn(xhci, "Invalid slot_id %u\n", slot_id);
1734 cmd_dma = le64_to_cpu(event->cmd_trb);
1735 cmd_trb = xhci->cmd_ring->dequeue;
1737 trace_xhci_handle_command(xhci->cmd_ring, &cmd_trb->generic);
1739 cmd_dequeue_dma = xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
1742 * Check whether the completion event is for our internal kept
1745 if (!cmd_dequeue_dma || cmd_dma != (u64)cmd_dequeue_dma) {
1747 "ERROR mismatched command completion event\n");
1751 cmd = list_first_entry(&xhci->cmd_list, struct xhci_command, cmd_list);
1753 cancel_delayed_work(&xhci->cmd_timer);
1755 cmd_comp_code = GET_COMP_CODE(le32_to_cpu(event->status));
1757 /* If CMD ring stopped we own the trbs between enqueue and dequeue */
1758 if (cmd_comp_code == COMP_COMMAND_RING_STOPPED) {
1759 complete_all(&xhci->cmd_ring_stop_completion);
1763 if (cmd->command_trb != xhci->cmd_ring->dequeue) {
1765 "Command completion event does not match command\n");
1770 * Host aborted the command ring, check if the current command was
1771 * supposed to be aborted, otherwise continue normally.
1772 * The command ring is stopped now, but the xHC will issue a Command
1773 * Ring Stopped event which will cause us to restart it.
1775 if (cmd_comp_code == COMP_COMMAND_ABORTED) {
1776 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
1777 if (cmd->status == COMP_COMMAND_ABORTED) {
1778 if (xhci->current_cmd == cmd)
1779 xhci->current_cmd = NULL;
1784 cmd_type = TRB_FIELD_TO_TYPE(le32_to_cpu(cmd_trb->generic.field[3]));
1786 case TRB_ENABLE_SLOT:
1787 xhci_handle_cmd_enable_slot(xhci, slot_id, cmd, cmd_comp_code);
1789 case TRB_DISABLE_SLOT:
1790 xhci_handle_cmd_disable_slot(xhci, slot_id);
1793 if (!cmd->completion)
1794 xhci_handle_cmd_config_ep(xhci, slot_id, cmd_comp_code);
1796 case TRB_EVAL_CONTEXT:
1799 xhci_handle_cmd_addr_dev(xhci, slot_id);
1802 WARN_ON(slot_id != TRB_TO_SLOT_ID(
1803 le32_to_cpu(cmd_trb->generic.field[3])));
1804 if (!cmd->completion)
1805 xhci_handle_cmd_stop_ep(xhci, slot_id, cmd_trb,
1809 WARN_ON(slot_id != TRB_TO_SLOT_ID(
1810 le32_to_cpu(cmd_trb->generic.field[3])));
1811 xhci_handle_cmd_set_deq(xhci, slot_id, cmd_trb, cmd_comp_code);
1814 /* Is this an aborted command turned to NO-OP? */
1815 if (cmd->status == COMP_COMMAND_RING_STOPPED)
1816 cmd_comp_code = COMP_COMMAND_RING_STOPPED;
1819 WARN_ON(slot_id != TRB_TO_SLOT_ID(
1820 le32_to_cpu(cmd_trb->generic.field[3])));
1821 xhci_handle_cmd_reset_ep(xhci, slot_id, cmd_trb, cmd_comp_code);
1824 /* SLOT_ID field in reset device cmd completion event TRB is 0.
1825 * Use the SLOT_ID from the command TRB instead (xhci 4.6.11)
1827 slot_id = TRB_TO_SLOT_ID(
1828 le32_to_cpu(cmd_trb->generic.field[3]));
1829 xhci_handle_cmd_reset_dev(xhci, slot_id);
1831 case TRB_NEC_GET_FW:
1832 xhci_handle_cmd_nec_get_fw(xhci, event);
1835 /* Skip over unknown commands on the event ring */
1836 xhci_info(xhci, "INFO unknown command type %d\n", cmd_type);
1840 /* restart timer if this wasn't the last command */
1841 if (!list_is_singular(&xhci->cmd_list)) {
1842 xhci->current_cmd = list_first_entry(&cmd->cmd_list,
1843 struct xhci_command, cmd_list);
1844 xhci_mod_cmd_timer(xhci, XHCI_CMD_DEFAULT_TIMEOUT);
1845 } else if (xhci->current_cmd == cmd) {
1846 xhci->current_cmd = NULL;
1850 xhci_complete_del_and_free_cmd(cmd, cmd_comp_code);
1852 inc_deq(xhci, xhci->cmd_ring);
1855 static void handle_vendor_event(struct xhci_hcd *xhci,
1856 union xhci_trb *event, u32 trb_type)
1858 xhci_dbg(xhci, "Vendor specific event TRB type = %u\n", trb_type);
1859 if (trb_type == TRB_NEC_CMD_COMP && (xhci->quirks & XHCI_NEC_HOST))
1860 handle_cmd_completion(xhci, &event->event_cmd);
1863 static void handle_device_notification(struct xhci_hcd *xhci,
1864 union xhci_trb *event)
1867 struct usb_device *udev;
1869 slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->generic.field[3]));
1870 if (!xhci->devs[slot_id]) {
1871 xhci_warn(xhci, "Device Notification event for "
1872 "unused slot %u\n", slot_id);
1876 xhci_dbg(xhci, "Device Wake Notification event for slot ID %u\n",
1878 udev = xhci->devs[slot_id]->udev;
1879 if (udev && udev->parent)
1880 usb_wakeup_notification(udev->parent, udev->portnum);
1884 * Quirk hanlder for errata seen on Cavium ThunderX2 processor XHCI
1886 * As per ThunderX2errata-129 USB 2 device may come up as USB 1
1887 * If a connection to a USB 1 device is followed by another connection
1888 * to a USB 2 device.
1890 * Reset the PHY after the USB device is disconnected if device speed
1891 * is less than HCD_USB3.
1892 * Retry the reset sequence max of 4 times checking the PLL lock status.
1895 static void xhci_cavium_reset_phy_quirk(struct xhci_hcd *xhci)
1897 struct usb_hcd *hcd = xhci_to_hcd(xhci);
1899 u32 retry_count = 4;
1902 /* Assert PHY reset */
1903 writel(0x6F, hcd->regs + 0x1048);
1905 /* De-assert the PHY reset */
1906 writel(0x7F, hcd->regs + 0x1048);
1908 pll_lock_check = readl(hcd->regs + 0x1070);
1909 } while (!(pll_lock_check & 0x1) && --retry_count);
1912 static void handle_port_status(struct xhci_hcd *xhci,
1913 union xhci_trb *event)
1915 struct usb_hcd *hcd;
1917 u32 portsc, cmd_reg;
1920 unsigned int hcd_portnum;
1921 struct xhci_bus_state *bus_state;
1922 bool bogus_port_status = false;
1923 struct xhci_port *port;
1925 /* Port status change events always have a successful completion code */
1926 if (GET_COMP_CODE(le32_to_cpu(event->generic.field[2])) != COMP_SUCCESS)
1928 "WARN: xHC returned failed port status event\n");
1930 port_id = GET_PORT_ID(le32_to_cpu(event->generic.field[0]));
1931 max_ports = HCS_MAX_PORTS(xhci->hcs_params1);
1933 if ((port_id <= 0) || (port_id > max_ports)) {
1934 xhci_warn(xhci, "Port change event with invalid port ID %d\n",
1936 inc_deq(xhci, xhci->event_ring);
1940 port = &xhci->hw_ports[port_id - 1];
1941 if (!port || !port->rhub || port->hcd_portnum == DUPLICATE_ENTRY) {
1942 xhci_warn(xhci, "Port change event, no port for port ID %u\n",
1944 bogus_port_status = true;
1948 /* We might get interrupts after shared_hcd is removed */
1949 if (port->rhub == &xhci->usb3_rhub && xhci->shared_hcd == NULL) {
1950 xhci_dbg(xhci, "ignore port event for removed USB3 hcd\n");
1951 bogus_port_status = true;
1955 hcd = port->rhub->hcd;
1956 bus_state = &port->rhub->bus_state;
1957 hcd_portnum = port->hcd_portnum;
1958 portsc = readl(port->addr);
1960 xhci_dbg(xhci, "Port change event, %d-%d, id %d, portsc: 0x%x\n",
1961 hcd->self.busnum, hcd_portnum + 1, port_id, portsc);
1963 trace_xhci_handle_port_status(hcd_portnum, portsc);
1965 if (hcd->state == HC_STATE_SUSPENDED) {
1966 xhci_dbg(xhci, "resume root hub\n");
1967 usb_hcd_resume_root_hub(hcd);
1970 if (hcd->speed >= HCD_USB3 &&
1971 (portsc & PORT_PLS_MASK) == XDEV_INACTIVE) {
1972 slot_id = xhci_find_slot_id_by_port(hcd, xhci, hcd_portnum + 1);
1973 if (slot_id && xhci->devs[slot_id])
1974 xhci->devs[slot_id]->flags |= VDEV_PORT_ERROR;
1977 if ((portsc & PORT_PLC) && (portsc & PORT_PLS_MASK) == XDEV_RESUME) {
1978 xhci_dbg(xhci, "port resume event for port %d\n", port_id);
1980 cmd_reg = readl(&xhci->op_regs->command);
1981 if (!(cmd_reg & CMD_RUN)) {
1982 xhci_warn(xhci, "xHC is not running.\n");
1986 if (DEV_SUPERSPEED_ANY(portsc)) {
1987 xhci_dbg(xhci, "remote wake SS port %d\n", port_id);
1988 /* Set a flag to say the port signaled remote wakeup,
1989 * so we can tell the difference between the end of
1990 * device and host initiated resume.
1992 bus_state->port_remote_wakeup |= 1 << hcd_portnum;
1993 xhci_test_and_clear_bit(xhci, port, PORT_PLC);
1994 usb_hcd_start_port_resume(&hcd->self, hcd_portnum);
1995 xhci_set_link_state(xhci, port, XDEV_U0);
1996 /* Need to wait until the next link state change
1997 * indicates the device is actually in U0.
1999 bogus_port_status = true;
2001 } else if (!test_bit(hcd_portnum, &bus_state->resuming_ports)) {
2002 xhci_dbg(xhci, "resume HS port %d\n", port_id);
2003 bus_state->resume_done[hcd_portnum] = jiffies +
2004 msecs_to_jiffies(USB_RESUME_TIMEOUT);
2005 set_bit(hcd_portnum, &bus_state->resuming_ports);
2006 /* Do the rest in GetPortStatus after resume time delay.
2007 * Avoid polling roothub status before that so that a
2008 * usb device auto-resume latency around ~40ms.
2010 set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2011 mod_timer(&hcd->rh_timer,
2012 bus_state->resume_done[hcd_portnum]);
2013 usb_hcd_start_port_resume(&hcd->self, hcd_portnum);
2014 bogus_port_status = true;
2018 if ((portsc & PORT_PLC) &&
2019 DEV_SUPERSPEED_ANY(portsc) &&
2020 ((portsc & PORT_PLS_MASK) == XDEV_U0 ||
2021 (portsc & PORT_PLS_MASK) == XDEV_U1 ||
2022 (portsc & PORT_PLS_MASK) == XDEV_U2)) {
2023 xhci_dbg(xhci, "resume SS port %d finished\n", port_id);
2024 complete(&bus_state->u3exit_done[hcd_portnum]);
2025 /* We've just brought the device into U0/1/2 through either the
2026 * Resume state after a device remote wakeup, or through the
2027 * U3Exit state after a host-initiated resume. If it's a device
2028 * initiated remote wake, don't pass up the link state change,
2029 * so the roothub behavior is consistent with external
2030 * USB 3.0 hub behavior.
2032 slot_id = xhci_find_slot_id_by_port(hcd, xhci, hcd_portnum + 1);
2033 if (slot_id && xhci->devs[slot_id])
2034 xhci_ring_device(xhci, slot_id);
2035 if (bus_state->port_remote_wakeup & (1 << hcd_portnum)) {
2036 xhci_test_and_clear_bit(xhci, port, PORT_PLC);
2037 usb_wakeup_notification(hcd->self.root_hub,
2039 bogus_port_status = true;
2045 * Check to see if xhci-hub.c is waiting on RExit to U0 transition (or
2046 * RExit to a disconnect state). If so, let the the driver know it's
2047 * out of the RExit state.
2049 if (!DEV_SUPERSPEED_ANY(portsc) && hcd->speed < HCD_USB3 &&
2050 test_and_clear_bit(hcd_portnum,
2051 &bus_state->rexit_ports)) {
2052 complete(&bus_state->rexit_done[hcd_portnum]);
2053 bogus_port_status = true;
2057 if (hcd->speed < HCD_USB3) {
2058 xhci_test_and_clear_bit(xhci, port, PORT_PLC);
2059 if ((xhci->quirks & XHCI_RESET_PLL_ON_DISCONNECT) &&
2060 (portsc & PORT_CSC) && !(portsc & PORT_CONNECT))
2061 xhci_cavium_reset_phy_quirk(xhci);
2065 /* Update event ring dequeue pointer before dropping the lock */
2066 inc_deq(xhci, xhci->event_ring);
2068 /* Don't make the USB core poll the roothub if we got a bad port status
2069 * change event. Besides, at that point we can't tell which roothub
2070 * (USB 2.0 or USB 3.0) to kick.
2072 if (bogus_port_status)
2076 * xHCI port-status-change events occur when the "or" of all the
2077 * status-change bits in the portsc register changes from 0 to 1.
2078 * New status changes won't cause an event if any other change
2079 * bits are still set. When an event occurs, switch over to
2080 * polling to avoid losing status changes.
2082 xhci_dbg(xhci, "%s: starting usb%d port polling.\n",
2083 __func__, hcd->self.busnum);
2084 set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2085 spin_unlock(&xhci->lock);
2086 /* Pass this up to the core */
2087 usb_hcd_poll_rh_status(hcd);
2088 spin_lock(&xhci->lock);
2092 * This TD is defined by the TRBs starting at start_trb in start_seg and ending
2093 * at end_trb, which may be in another segment. If the suspect DMA address is a
2094 * TRB in this TD, this function returns that TRB's segment. Otherwise it
2097 struct xhci_segment *trb_in_td(struct xhci_hcd *xhci,
2098 struct xhci_segment *start_seg,
2099 union xhci_trb *start_trb,
2100 union xhci_trb *end_trb,
2101 dma_addr_t suspect_dma,
2104 dma_addr_t start_dma;
2105 dma_addr_t end_seg_dma;
2106 dma_addr_t end_trb_dma;
2107 struct xhci_segment *cur_seg;
2109 start_dma = xhci_trb_virt_to_dma(start_seg, start_trb);
2110 cur_seg = start_seg;
2115 /* We may get an event for a Link TRB in the middle of a TD */
2116 end_seg_dma = xhci_trb_virt_to_dma(cur_seg,
2117 &cur_seg->trbs[TRBS_PER_SEGMENT - 1]);
2118 /* If the end TRB isn't in this segment, this is set to 0 */
2119 end_trb_dma = xhci_trb_virt_to_dma(cur_seg, end_trb);
2123 "Looking for event-dma %016llx trb-start %016llx trb-end %016llx seg-start %016llx seg-end %016llx\n",
2124 (unsigned long long)suspect_dma,
2125 (unsigned long long)start_dma,
2126 (unsigned long long)end_trb_dma,
2127 (unsigned long long)cur_seg->dma,
2128 (unsigned long long)end_seg_dma);
2130 if (end_trb_dma > 0) {
2131 /* The end TRB is in this segment, so suspect should be here */
2132 if (start_dma <= end_trb_dma) {
2133 if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma)
2136 /* Case for one segment with
2137 * a TD wrapped around to the top
2139 if ((suspect_dma >= start_dma &&
2140 suspect_dma <= end_seg_dma) ||
2141 (suspect_dma >= cur_seg->dma &&
2142 suspect_dma <= end_trb_dma))
2147 /* Might still be somewhere in this segment */
2148 if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma)
2151 cur_seg = cur_seg->next;
2152 start_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[0]);
2153 } while (cur_seg != start_seg);
2158 static void xhci_clear_hub_tt_buffer(struct xhci_hcd *xhci, struct xhci_td *td,
2159 struct xhci_virt_ep *ep)
2162 * As part of low/full-speed endpoint-halt processing
2163 * we must clear the TT buffer (USB 2.0 specification 11.17.5).
2165 if (td->urb->dev->tt && !usb_pipeint(td->urb->pipe) &&
2166 (td->urb->dev->tt->hub != xhci_to_hcd(xhci)->self.root_hub) &&
2167 !(ep->ep_state & EP_CLEARING_TT)) {
2168 ep->ep_state |= EP_CLEARING_TT;
2169 td->urb->ep->hcpriv = td->urb->dev;
2170 if (usb_hub_clear_tt_buffer(td->urb))
2171 ep->ep_state &= ~EP_CLEARING_TT;
2175 /* Check if an error has halted the endpoint ring. The class driver will
2176 * cleanup the halt for a non-default control endpoint if we indicate a stall.
2177 * However, a babble and other errors also halt the endpoint ring, and the class
2178 * driver won't clear the halt in that case, so we need to issue a Set Transfer
2179 * Ring Dequeue Pointer command manually.
2181 static int xhci_requires_manual_halt_cleanup(struct xhci_hcd *xhci,
2182 struct xhci_ep_ctx *ep_ctx,
2183 unsigned int trb_comp_code)
2185 /* TRB completion codes that may require a manual halt cleanup */
2186 if (trb_comp_code == COMP_USB_TRANSACTION_ERROR ||
2187 trb_comp_code == COMP_BABBLE_DETECTED_ERROR ||
2188 trb_comp_code == COMP_SPLIT_TRANSACTION_ERROR)
2189 /* The 0.95 spec says a babbling control endpoint
2190 * is not halted. The 0.96 spec says it is. Some HW
2191 * claims to be 0.95 compliant, but it halts the control
2192 * endpoint anyway. Check if a babble halted the
2195 if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_HALTED)
2201 int xhci_is_vendor_info_code(struct xhci_hcd *xhci, unsigned int trb_comp_code)
2203 if (trb_comp_code >= 224 && trb_comp_code <= 255) {
2204 /* Vendor defined "informational" completion code,
2205 * treat as not-an-error.
2207 xhci_dbg(xhci, "Vendor defined info completion code %u\n",
2209 xhci_dbg(xhci, "Treating code as success.\n");
2215 static int finish_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2216 struct xhci_ring *ep_ring, struct xhci_td *td,
2219 struct xhci_ep_ctx *ep_ctx;
2221 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep->ep_index);
2223 switch (trb_comp_code) {
2224 case COMP_STOPPED_LENGTH_INVALID:
2225 case COMP_STOPPED_SHORT_PACKET:
2228 * The "Stop Endpoint" completion will take care of any
2229 * stopped TDs. A stopped TD may be restarted, so don't update
2230 * the ring dequeue pointer or take this TD off any lists yet.
2233 case COMP_USB_TRANSACTION_ERROR:
2234 case COMP_BABBLE_DETECTED_ERROR:
2235 case COMP_SPLIT_TRANSACTION_ERROR:
2237 * If endpoint context state is not halted we might be
2238 * racing with a reset endpoint command issued by a unsuccessful
2239 * stop endpoint completion (context error). In that case the
2240 * td should be on the cancelled list, and EP_HALTED flag set.
2242 * Or then it's not halted due to the 0.95 spec stating that a
2243 * babbling control endpoint should not halt. The 0.96 spec
2244 * again says it should. Some HW claims to be 0.95 compliant,
2245 * but it halts the control endpoint anyway.
2247 if (GET_EP_CTX_STATE(ep_ctx) != EP_STATE_HALTED) {
2249 * If EP_HALTED is set and TD is on the cancelled list
2250 * the TD and dequeue pointer will be handled by reset
2251 * ep command completion
2253 if ((ep->ep_state & EP_HALTED) &&
2254 !list_empty(&td->cancelled_td_list)) {
2255 xhci_dbg(xhci, "Already resolving halted ep for 0x%llx\n",
2256 (unsigned long long)xhci_trb_virt_to_dma(
2257 td->start_seg, td->first_trb));
2260 /* endpoint not halted, don't reset it */
2263 /* Almost same procedure as for STALL_ERROR below */
2264 xhci_clear_hub_tt_buffer(xhci, td, ep);
2265 xhci_handle_halted_endpoint(xhci, ep, ep_ring->stream_id, td,
2268 case COMP_STALL_ERROR:
2270 * xhci internal endpoint state will go to a "halt" state for
2271 * any stall, including default control pipe protocol stall.
2272 * To clear the host side halt we need to issue a reset endpoint
2273 * command, followed by a set dequeue command to move past the
2275 * Class drivers clear the device side halt from a functional
2276 * stall later. Hub TT buffer should only be cleared for FS/LS
2277 * devices behind HS hubs for functional stalls.
2279 if (ep->ep_index != 0)
2280 xhci_clear_hub_tt_buffer(xhci, td, ep);
2282 xhci_handle_halted_endpoint(xhci, ep, ep_ring->stream_id, td,
2285 return 0; /* xhci_handle_halted_endpoint marked td cancelled */
2290 /* Update ring dequeue pointer */
2291 ep_ring->dequeue = td->last_trb;
2292 ep_ring->deq_seg = td->last_trb_seg;
2293 ep_ring->num_trbs_free += td->num_trbs - 1;
2294 inc_deq(xhci, ep_ring);
2296 return xhci_td_cleanup(xhci, td, ep_ring, td->status);
2299 /* sum trb lengths from ring dequeue up to stop_trb, _excluding_ stop_trb */
2300 static int sum_trb_lengths(struct xhci_hcd *xhci, struct xhci_ring *ring,
2301 union xhci_trb *stop_trb)
2304 union xhci_trb *trb = ring->dequeue;
2305 struct xhci_segment *seg = ring->deq_seg;
2307 for (sum = 0; trb != stop_trb; next_trb(xhci, ring, &seg, &trb)) {
2308 if (!trb_is_noop(trb) && !trb_is_link(trb))
2309 sum += TRB_LEN(le32_to_cpu(trb->generic.field[2]));
2315 * Process control tds, update urb status and actual_length.
2317 static int process_ctrl_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2318 struct xhci_ring *ep_ring, struct xhci_td *td,
2319 union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2321 struct xhci_ep_ctx *ep_ctx;
2323 u32 remaining, requested;
2326 trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(ep_trb->generic.field[3]));
2327 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep->ep_index);
2328 trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2329 requested = td->urb->transfer_buffer_length;
2330 remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2332 switch (trb_comp_code) {
2334 if (trb_type != TRB_STATUS) {
2335 xhci_warn(xhci, "WARN: Success on ctrl %s TRB without IOC set?\n",
2336 (trb_type == TRB_DATA) ? "data" : "setup");
2337 td->status = -ESHUTDOWN;
2342 case COMP_SHORT_PACKET:
2345 case COMP_STOPPED_SHORT_PACKET:
2346 if (trb_type == TRB_DATA || trb_type == TRB_NORMAL)
2347 td->urb->actual_length = remaining;
2349 xhci_warn(xhci, "WARN: Stopped Short Packet on ctrl setup or status TRB\n");
2354 td->urb->actual_length = 0;
2358 td->urb->actual_length = requested - remaining;
2361 td->urb->actual_length = requested;
2364 xhci_warn(xhci, "WARN: unexpected TRB Type %d\n",
2368 case COMP_STOPPED_LENGTH_INVALID:
2371 if (!xhci_requires_manual_halt_cleanup(xhci,
2372 ep_ctx, trb_comp_code))
2374 xhci_dbg(xhci, "TRB error %u, halted endpoint index = %u\n",
2375 trb_comp_code, ep->ep_index);
2377 case COMP_STALL_ERROR:
2378 /* Did we transfer part of the data (middle) phase? */
2379 if (trb_type == TRB_DATA || trb_type == TRB_NORMAL)
2380 td->urb->actual_length = requested - remaining;
2381 else if (!td->urb_length_set)
2382 td->urb->actual_length = 0;
2386 /* stopped at setup stage, no data transferred */
2387 if (trb_type == TRB_SETUP)
2391 * if on data stage then update the actual_length of the URB and flag it
2392 * as set, so it won't be overwritten in the event for the last TRB.
2394 if (trb_type == TRB_DATA ||
2395 trb_type == TRB_NORMAL) {
2396 td->urb_length_set = true;
2397 td->urb->actual_length = requested - remaining;
2398 xhci_dbg(xhci, "Waiting for status stage event\n");
2402 /* at status stage */
2403 if (!td->urb_length_set)
2404 td->urb->actual_length = requested;
2407 return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2411 * Process isochronous tds, update urb packet status and actual_length.
2413 static int process_isoc_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2414 struct xhci_ring *ep_ring, struct xhci_td *td,
2415 union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2417 struct urb_priv *urb_priv;
2419 struct usb_iso_packet_descriptor *frame;
2421 bool sum_trbs_for_length = false;
2422 u32 remaining, requested, ep_trb_len;
2423 int short_framestatus;
2425 trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2426 urb_priv = td->urb->hcpriv;
2427 idx = urb_priv->num_tds_done;
2428 frame = &td->urb->iso_frame_desc[idx];
2429 requested = frame->length;
2430 remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2431 ep_trb_len = TRB_LEN(le32_to_cpu(ep_trb->generic.field[2]));
2432 short_framestatus = td->urb->transfer_flags & URB_SHORT_NOT_OK ?
2435 /* handle completion code */
2436 switch (trb_comp_code) {
2439 frame->status = short_framestatus;
2440 if (xhci->quirks & XHCI_TRUST_TX_LENGTH)
2441 sum_trbs_for_length = true;
2446 case COMP_SHORT_PACKET:
2447 frame->status = short_framestatus;
2448 sum_trbs_for_length = true;
2450 case COMP_BANDWIDTH_OVERRUN_ERROR:
2451 frame->status = -ECOMM;
2453 case COMP_ISOCH_BUFFER_OVERRUN:
2454 case COMP_BABBLE_DETECTED_ERROR:
2455 frame->status = -EOVERFLOW;
2457 case COMP_INCOMPATIBLE_DEVICE_ERROR:
2458 case COMP_STALL_ERROR:
2459 frame->status = -EPROTO;
2461 case COMP_USB_TRANSACTION_ERROR:
2462 frame->status = -EPROTO;
2463 if (ep_trb != td->last_trb)
2467 sum_trbs_for_length = true;
2469 case COMP_STOPPED_SHORT_PACKET:
2470 /* field normally containing residue now contains tranferred */
2471 frame->status = short_framestatus;
2472 requested = remaining;
2474 case COMP_STOPPED_LENGTH_INVALID:
2479 sum_trbs_for_length = true;
2484 if (sum_trbs_for_length)
2485 frame->actual_length = sum_trb_lengths(xhci, ep->ring, ep_trb) +
2486 ep_trb_len - remaining;
2488 frame->actual_length = requested;
2490 td->urb->actual_length += frame->actual_length;
2492 return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2495 static int skip_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td,
2496 struct xhci_virt_ep *ep, int status)
2498 struct urb_priv *urb_priv;
2499 struct usb_iso_packet_descriptor *frame;
2502 urb_priv = td->urb->hcpriv;
2503 idx = urb_priv->num_tds_done;
2504 frame = &td->urb->iso_frame_desc[idx];
2506 /* The transfer is partly done. */
2507 frame->status = -EXDEV;
2509 /* calc actual length */
2510 frame->actual_length = 0;
2512 /* Update ring dequeue pointer */
2513 ep->ring->dequeue = td->last_trb;
2514 ep->ring->deq_seg = td->last_trb_seg;
2515 ep->ring->num_trbs_free += td->num_trbs - 1;
2516 inc_deq(xhci, ep->ring);
2518 return xhci_td_cleanup(xhci, td, ep->ring, status);
2522 * Process bulk and interrupt tds, update urb status and actual_length.
2524 static int process_bulk_intr_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2525 struct xhci_ring *ep_ring, struct xhci_td *td,
2526 union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2528 struct xhci_slot_ctx *slot_ctx;
2530 u32 remaining, requested, ep_trb_len;
2532 slot_ctx = xhci_get_slot_ctx(xhci, ep->vdev->out_ctx);
2533 trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2534 remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2535 ep_trb_len = TRB_LEN(le32_to_cpu(ep_trb->generic.field[2]));
2536 requested = td->urb->transfer_buffer_length;
2538 switch (trb_comp_code) {
2541 /* handle success with untransferred data as short packet */
2542 if (ep_trb != td->last_trb || remaining) {
2543 xhci_warn(xhci, "WARN Successful completion on short TX\n");
2544 xhci_dbg(xhci, "ep %#x - asked for %d bytes, %d bytes untransferred\n",
2545 td->urb->ep->desc.bEndpointAddress,
2546 requested, remaining);
2550 case COMP_SHORT_PACKET:
2551 xhci_dbg(xhci, "ep %#x - asked for %d bytes, %d bytes untransferred\n",
2552 td->urb->ep->desc.bEndpointAddress,
2553 requested, remaining);
2556 case COMP_STOPPED_SHORT_PACKET:
2557 td->urb->actual_length = remaining;
2559 case COMP_STOPPED_LENGTH_INVALID:
2560 /* stopped on ep trb with invalid length, exclude it */
2564 case COMP_USB_TRANSACTION_ERROR:
2565 if (xhci->quirks & XHCI_NO_SOFT_RETRY ||
2566 (ep->err_count++ > MAX_SOFT_RETRY) ||
2567 le32_to_cpu(slot_ctx->tt_info) & TT_SLOT)
2572 xhci_handle_halted_endpoint(xhci, ep, ep_ring->stream_id, td,
2580 if (ep_trb == td->last_trb)
2581 td->urb->actual_length = requested - remaining;
2583 td->urb->actual_length =
2584 sum_trb_lengths(xhci, ep_ring, ep_trb) +
2585 ep_trb_len - remaining;
2587 if (remaining > requested) {
2588 xhci_warn(xhci, "bad transfer trb length %d in event trb\n",
2590 td->urb->actual_length = 0;
2593 return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2597 * If this function returns an error condition, it means it got a Transfer
2598 * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address.
2599 * At this point, the host controller is probably hosed and should be reset.
2601 static int handle_tx_event(struct xhci_hcd *xhci,
2602 struct xhci_transfer_event *event)
2604 struct xhci_virt_ep *ep;
2605 struct xhci_ring *ep_ring;
2606 unsigned int slot_id;
2608 struct xhci_td *td = NULL;
2609 dma_addr_t ep_trb_dma;
2610 struct xhci_segment *ep_seg;
2611 union xhci_trb *ep_trb;
2612 int status = -EINPROGRESS;
2613 struct xhci_ep_ctx *ep_ctx;
2614 struct list_head *tmp;
2617 bool handling_skipped_tds = false;
2619 slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
2620 ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1;
2621 trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2622 ep_trb_dma = le64_to_cpu(event->buffer);
2624 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
2626 xhci_err(xhci, "ERROR Invalid Transfer event\n");
2630 ep_ring = xhci_dma_to_transfer_ring(ep, ep_trb_dma);
2631 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
2633 if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) {
2635 "ERROR Transfer event for disabled endpoint slot %u ep %u\n",
2640 /* Some transfer events don't always point to a trb, see xhci 4.17.4 */
2642 switch (trb_comp_code) {
2643 case COMP_STALL_ERROR:
2644 case COMP_USB_TRANSACTION_ERROR:
2645 case COMP_INVALID_STREAM_TYPE_ERROR:
2646 case COMP_INVALID_STREAM_ID_ERROR:
2647 xhci_dbg(xhci, "Stream transaction error ep %u no id\n",
2649 if (ep->err_count++ > MAX_SOFT_RETRY)
2650 xhci_handle_halted_endpoint(xhci, ep, 0, NULL,
2653 xhci_handle_halted_endpoint(xhci, ep, 0, NULL,
2656 case COMP_RING_UNDERRUN:
2657 case COMP_RING_OVERRUN:
2658 case COMP_STOPPED_LENGTH_INVALID:
2661 xhci_err(xhci, "ERROR Transfer event for unknown stream ring slot %u ep %u\n",
2667 /* Count current td numbers if ep->skip is set */
2669 list_for_each(tmp, &ep_ring->td_list)
2673 /* Look for common error cases */
2674 switch (trb_comp_code) {
2675 /* Skip codes that require special handling depending on
2679 if (EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)) == 0)
2681 if (xhci->quirks & XHCI_TRUST_TX_LENGTH ||
2682 ep_ring->last_td_was_short)
2683 trb_comp_code = COMP_SHORT_PACKET;
2685 xhci_warn_ratelimited(xhci,
2686 "WARN Successful completion on short TX for slot %u ep %u: needs XHCI_TRUST_TX_LENGTH quirk?\n",
2689 case COMP_SHORT_PACKET:
2691 /* Completion codes for endpoint stopped state */
2693 xhci_dbg(xhci, "Stopped on Transfer TRB for slot %u ep %u\n",
2696 case COMP_STOPPED_LENGTH_INVALID:
2698 "Stopped on No-op or Link TRB for slot %u ep %u\n",
2701 case COMP_STOPPED_SHORT_PACKET:
2703 "Stopped with short packet transfer detected for slot %u ep %u\n",
2706 /* Completion codes for endpoint halted state */
2707 case COMP_STALL_ERROR:
2708 xhci_dbg(xhci, "Stalled endpoint for slot %u ep %u\n", slot_id,
2712 case COMP_SPLIT_TRANSACTION_ERROR:
2713 xhci_dbg(xhci, "Split transaction error for slot %u ep %u\n",
2717 case COMP_USB_TRANSACTION_ERROR:
2718 xhci_dbg(xhci, "Transfer error for slot %u ep %u on endpoint\n",
2722 case COMP_BABBLE_DETECTED_ERROR:
2723 xhci_dbg(xhci, "Babble error for slot %u ep %u on endpoint\n",
2725 status = -EOVERFLOW;
2727 /* Completion codes for endpoint error state */
2728 case COMP_TRB_ERROR:
2730 "WARN: TRB error for slot %u ep %u on endpoint\n",
2734 /* completion codes not indicating endpoint state change */
2735 case COMP_DATA_BUFFER_ERROR:
2737 "WARN: HC couldn't access mem fast enough for slot %u ep %u\n",
2741 case COMP_BANDWIDTH_OVERRUN_ERROR:
2743 "WARN: bandwidth overrun event for slot %u ep %u on endpoint\n",
2746 case COMP_ISOCH_BUFFER_OVERRUN:
2748 "WARN: buffer overrun event for slot %u ep %u on endpoint",
2751 case COMP_RING_UNDERRUN:
2753 * When the Isoch ring is empty, the xHC will generate
2754 * a Ring Overrun Event for IN Isoch endpoint or Ring
2755 * Underrun Event for OUT Isoch endpoint.
2757 xhci_dbg(xhci, "underrun event on endpoint\n");
2758 if (!list_empty(&ep_ring->td_list))
2759 xhci_dbg(xhci, "Underrun Event for slot %d ep %d "
2760 "still with TDs queued?\n",
2761 TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2764 case COMP_RING_OVERRUN:
2765 xhci_dbg(xhci, "overrun event on endpoint\n");
2766 if (!list_empty(&ep_ring->td_list))
2767 xhci_dbg(xhci, "Overrun Event for slot %d ep %d "
2768 "still with TDs queued?\n",
2769 TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2772 case COMP_MISSED_SERVICE_ERROR:
2774 * When encounter missed service error, one or more isoc tds
2775 * may be missed by xHC.
2776 * Set skip flag of the ep_ring; Complete the missed tds as
2777 * short transfer when process the ep_ring next time.
2781 "Miss service interval error for slot %u ep %u, set skip flag\n",
2784 case COMP_NO_PING_RESPONSE_ERROR:
2787 "No Ping response error for slot %u ep %u, Skip one Isoc TD\n",
2791 case COMP_INCOMPATIBLE_DEVICE_ERROR:
2792 /* needs disable slot command to recover */
2794 "WARN: detect an incompatible device for slot %u ep %u",
2799 if (xhci_is_vendor_info_code(xhci, trb_comp_code)) {
2804 "ERROR Unknown event condition %u for slot %u ep %u , HC probably busted\n",
2805 trb_comp_code, slot_id, ep_index);
2810 /* This TRB should be in the TD at the head of this ring's
2813 if (list_empty(&ep_ring->td_list)) {
2815 * Don't print wanings if it's due to a stopped endpoint
2816 * generating an extra completion event if the device
2817 * was suspended. Or, a event for the last TRB of a
2818 * short TD we already got a short event for.
2819 * The short TD is already removed from the TD list.
2822 if (!(trb_comp_code == COMP_STOPPED ||
2823 trb_comp_code == COMP_STOPPED_LENGTH_INVALID ||
2824 ep_ring->last_td_was_short)) {
2825 xhci_warn(xhci, "WARN Event TRB for slot %d ep %d with no TDs queued?\n",
2826 TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2831 xhci_dbg(xhci, "td_list is empty while skip flag set. Clear skip flag for slot %u ep %u.\n",
2834 if (trb_comp_code == COMP_STALL_ERROR ||
2835 xhci_requires_manual_halt_cleanup(xhci, ep_ctx,
2837 xhci_handle_halted_endpoint(xhci, ep,
2845 /* We've skipped all the TDs on the ep ring when ep->skip set */
2846 if (ep->skip && td_num == 0) {
2848 xhci_dbg(xhci, "All tds on the ep_ring skipped. Clear skip flag for slot %u ep %u.\n",
2853 td = list_first_entry(&ep_ring->td_list, struct xhci_td,
2858 /* Is this a TRB in the currently executing TD? */
2859 ep_seg = trb_in_td(xhci, ep_ring->deq_seg, ep_ring->dequeue,
2860 td->last_trb, ep_trb_dma, false);
2863 * Skip the Force Stopped Event. The event_trb(event_dma) of FSE
2864 * is not in the current TD pointed by ep_ring->dequeue because
2865 * that the hardware dequeue pointer still at the previous TRB
2866 * of the current TD. The previous TRB maybe a Link TD or the
2867 * last TRB of the previous TD. The command completion handle
2868 * will take care the rest.
2870 if (!ep_seg && (trb_comp_code == COMP_STOPPED ||
2871 trb_comp_code == COMP_STOPPED_LENGTH_INVALID)) {
2877 !usb_endpoint_xfer_isoc(&td->urb->ep->desc)) {
2878 /* Some host controllers give a spurious
2879 * successful event after a short transfer.
2882 if ((xhci->quirks & XHCI_SPURIOUS_SUCCESS) &&
2883 ep_ring->last_td_was_short) {
2884 ep_ring->last_td_was_short = false;
2887 /* HC is busted, give up! */
2889 "ERROR Transfer event TRB DMA ptr not "
2890 "part of current TD ep_index %d "
2891 "comp_code %u\n", ep_index,
2893 trb_in_td(xhci, ep_ring->deq_seg,
2894 ep_ring->dequeue, td->last_trb,
2899 skip_isoc_td(xhci, td, ep, status);
2902 if (trb_comp_code == COMP_SHORT_PACKET)
2903 ep_ring->last_td_was_short = true;
2905 ep_ring->last_td_was_short = false;
2909 "Found td. Clear skip flag for slot %u ep %u.\n",
2914 ep_trb = &ep_seg->trbs[(ep_trb_dma - ep_seg->dma) /
2917 trace_xhci_handle_transfer(ep_ring,
2918 (struct xhci_generic_trb *) ep_trb);
2921 * No-op TRB could trigger interrupts in a case where
2922 * a URB was killed and a STALL_ERROR happens right
2923 * after the endpoint ring stopped. Reset the halted
2924 * endpoint. Otherwise, the endpoint remains stalled
2928 if (trb_is_noop(ep_trb)) {
2929 if (trb_comp_code == COMP_STALL_ERROR ||
2930 xhci_requires_manual_halt_cleanup(xhci, ep_ctx,
2932 xhci_handle_halted_endpoint(xhci, ep,
2938 td->status = status;
2940 /* update the urb's actual_length and give back to the core */
2941 if (usb_endpoint_xfer_control(&td->urb->ep->desc))
2942 process_ctrl_td(xhci, ep, ep_ring, td, ep_trb, event);
2943 else if (usb_endpoint_xfer_isoc(&td->urb->ep->desc))
2944 process_isoc_td(xhci, ep, ep_ring, td, ep_trb, event);
2946 process_bulk_intr_td(xhci, ep, ep_ring, td, ep_trb, event);
2948 handling_skipped_tds = ep->skip &&
2949 trb_comp_code != COMP_MISSED_SERVICE_ERROR &&
2950 trb_comp_code != COMP_NO_PING_RESPONSE_ERROR;
2953 * Do not update event ring dequeue pointer if we're in a loop
2954 * processing missed tds.
2956 if (!handling_skipped_tds)
2957 inc_deq(xhci, xhci->event_ring);
2960 * If ep->skip is set, it means there are missed tds on the
2961 * endpoint ring need to take care of.
2962 * Process them as short transfer until reach the td pointed by
2965 } while (handling_skipped_tds);
2970 xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n",
2971 (unsigned long long) xhci_trb_virt_to_dma(
2972 xhci->event_ring->deq_seg,
2973 xhci->event_ring->dequeue),
2974 lower_32_bits(le64_to_cpu(event->buffer)),
2975 upper_32_bits(le64_to_cpu(event->buffer)),
2976 le32_to_cpu(event->transfer_len),
2977 le32_to_cpu(event->flags));
2982 * This function handles all OS-owned events on the event ring. It may drop
2983 * xhci->lock between event processing (e.g. to pass up port status changes).
2984 * Returns >0 for "possibly more events to process" (caller should call again),
2985 * otherwise 0 if done. In future, <0 returns should indicate error code.
2987 static int xhci_handle_event(struct xhci_hcd *xhci)
2989 union xhci_trb *event;
2990 int update_ptrs = 1;
2994 /* Event ring hasn't been allocated yet. */
2995 if (!xhci->event_ring || !xhci->event_ring->dequeue) {
2996 xhci_err(xhci, "ERROR event ring not ready\n");
3000 event = xhci->event_ring->dequeue;
3001 /* Does the HC or OS own the TRB? */
3002 if ((le32_to_cpu(event->event_cmd.flags) & TRB_CYCLE) !=
3003 xhci->event_ring->cycle_state)
3006 trace_xhci_handle_event(xhci->event_ring, &event->generic);
3009 * Barrier between reading the TRB_CYCLE (valid) flag above and any
3010 * speculative reads of the event's flags/data below.
3013 trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(event->event_cmd.flags));
3014 /* FIXME: Handle more event types. */
3017 case TRB_COMPLETION:
3018 handle_cmd_completion(xhci, &event->event_cmd);
3020 case TRB_PORT_STATUS:
3021 handle_port_status(xhci, event);
3025 ret = handle_tx_event(xhci, &event->trans_event);
3030 handle_device_notification(xhci, event);
3033 if (trb_type >= TRB_VENDOR_DEFINED_LOW)
3034 handle_vendor_event(xhci, event, trb_type);
3036 xhci_warn(xhci, "ERROR unknown event type %d\n", trb_type);
3038 /* Any of the above functions may drop and re-acquire the lock, so check
3039 * to make sure a watchdog timer didn't mark the host as non-responsive.
3041 if (xhci->xhc_state & XHCI_STATE_DYING) {
3042 xhci_dbg(xhci, "xHCI host dying, returning from "
3043 "event handler.\n");
3048 /* Update SW event ring dequeue pointer */
3049 inc_deq(xhci, xhci->event_ring);
3051 /* Are there more items on the event ring? Caller will call us again to
3058 * Update Event Ring Dequeue Pointer:
3059 * - When all events have finished
3060 * - To avoid "Event Ring Full Error" condition
3062 static void xhci_update_erst_dequeue(struct xhci_hcd *xhci,
3063 union xhci_trb *event_ring_deq)
3068 temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
3069 /* If necessary, update the HW's version of the event ring deq ptr. */
3070 if (event_ring_deq != xhci->event_ring->dequeue) {
3071 deq = xhci_trb_virt_to_dma(xhci->event_ring->deq_seg,
3072 xhci->event_ring->dequeue);
3074 xhci_warn(xhci, "WARN something wrong with SW event ring dequeue ptr\n");
3076 * Per 4.9.4, Software writes to the ERDP register shall
3077 * always advance the Event Ring Dequeue Pointer value.
3079 if ((temp_64 & (u64) ~ERST_PTR_MASK) ==
3080 ((u64) deq & (u64) ~ERST_PTR_MASK))
3083 /* Update HC event ring dequeue pointer */
3084 temp_64 &= ERST_PTR_MASK;
3085 temp_64 |= ((u64) deq & (u64) ~ERST_PTR_MASK);
3088 /* Clear the event handler busy flag (RW1C) */
3089 temp_64 |= ERST_EHB;
3090 xhci_write_64(xhci, temp_64, &xhci->ir_set->erst_dequeue);
3094 * xHCI spec says we can get an interrupt, and if the HC has an error condition,
3095 * we might get bad data out of the event ring. Section 4.10.2.7 has a list of
3096 * indicators of an event TRB error, but we check the status *first* to be safe.
3098 irqreturn_t xhci_irq(struct usb_hcd *hcd)
3100 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3101 union xhci_trb *event_ring_deq;
3102 irqreturn_t ret = IRQ_NONE;
3107 spin_lock(&xhci->lock);
3108 /* Check if the xHC generated the interrupt, or the irq is shared */
3109 status = readl(&xhci->op_regs->status);
3110 if (status == ~(u32)0) {
3116 if (!(status & STS_EINT))
3119 if (status & STS_FATAL) {
3120 xhci_warn(xhci, "WARNING: Host System Error\n");
3127 * Clear the op reg interrupt status first,
3128 * so we can receive interrupts from other MSI-X interrupters.
3129 * Write 1 to clear the interrupt status.
3132 writel(status, &xhci->op_regs->status);
3134 if (!hcd->msi_enabled) {
3136 irq_pending = readl(&xhci->ir_set->irq_pending);
3137 irq_pending |= IMAN_IP;
3138 writel(irq_pending, &xhci->ir_set->irq_pending);
3141 if (xhci->xhc_state & XHCI_STATE_DYING ||
3142 xhci->xhc_state & XHCI_STATE_HALTED) {
3143 xhci_dbg(xhci, "xHCI dying, ignoring interrupt. "
3144 "Shouldn't IRQs be disabled?\n");
3145 /* Clear the event handler busy flag (RW1C);
3146 * the event ring should be empty.
3148 temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
3149 xhci_write_64(xhci, temp_64 | ERST_EHB,
3150 &xhci->ir_set->erst_dequeue);
3155 event_ring_deq = xhci->event_ring->dequeue;
3156 /* FIXME this should be a delayed service routine
3157 * that clears the EHB.
3159 while (xhci_handle_event(xhci) > 0) {
3160 if (event_loop++ < xhci->event_ring->trbs_per_seg / 2)
3162 xhci_update_erst_dequeue(xhci, event_ring_deq);
3163 event_ring_deq = xhci->event_ring->dequeue;
3165 /* ring is half-full, force isoc trbs to interrupt more often */
3166 if (xhci->isoc_bei_interval > AVOID_BEI_INTERVAL_MIN)
3167 xhci->isoc_bei_interval = xhci->isoc_bei_interval / 2;
3172 xhci_update_erst_dequeue(xhci, event_ring_deq);
3176 spin_unlock(&xhci->lock);
3181 irqreturn_t xhci_msi_irq(int irq, void *hcd)
3183 return xhci_irq(hcd);
3186 /**** Endpoint Ring Operations ****/
3189 * Generic function for queueing a TRB on a ring.
3190 * The caller must have checked to make sure there's room on the ring.
3192 * @more_trbs_coming: Will you enqueue more TRBs before calling
3193 * prepare_transfer()?
3195 static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
3196 bool more_trbs_coming,
3197 u32 field1, u32 field2, u32 field3, u32 field4)
3199 struct xhci_generic_trb *trb;
3201 trb = &ring->enqueue->generic;
3202 trb->field[0] = cpu_to_le32(field1);
3203 trb->field[1] = cpu_to_le32(field2);
3204 trb->field[2] = cpu_to_le32(field3);
3205 /* make sure TRB is fully written before giving it to the controller */
3207 trb->field[3] = cpu_to_le32(field4);
3209 trace_xhci_queue_trb(ring, trb);
3211 inc_enq(xhci, ring, more_trbs_coming);
3215 * Does various checks on the endpoint ring, and makes it ready to queue num_trbs.
3216 * FIXME allocate segments if the ring is full.
3218 static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
3219 u32 ep_state, unsigned int num_trbs, gfp_t mem_flags)
3221 unsigned int num_trbs_needed;
3222 unsigned int link_trb_count = 0;
3224 /* Make sure the endpoint has been added to xHC schedule */
3226 case EP_STATE_DISABLED:
3228 * USB core changed config/interfaces without notifying us,
3229 * or hardware is reporting the wrong state.
3231 xhci_warn(xhci, "WARN urb submitted to disabled ep\n");
3233 case EP_STATE_ERROR:
3234 xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n");
3235 /* FIXME event handling code for error needs to clear it */
3236 /* XXX not sure if this should be -ENOENT or not */
3238 case EP_STATE_HALTED:
3239 xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n");
3241 case EP_STATE_STOPPED:
3242 case EP_STATE_RUNNING:
3245 xhci_err(xhci, "ERROR unknown endpoint state for ep\n");
3247 * FIXME issue Configure Endpoint command to try to get the HC
3248 * back into a known state.
3254 if (room_on_ring(xhci, ep_ring, num_trbs))
3257 if (ep_ring == xhci->cmd_ring) {
3258 xhci_err(xhci, "Do not support expand command ring\n");
3262 xhci_dbg_trace(xhci, trace_xhci_dbg_ring_expansion,
3263 "ERROR no room on ep ring, try ring expansion");
3264 num_trbs_needed = num_trbs - ep_ring->num_trbs_free;
3265 if (xhci_ring_expansion(xhci, ep_ring, num_trbs_needed,
3267 xhci_err(xhci, "Ring expansion failed\n");
3272 while (trb_is_link(ep_ring->enqueue)) {
3273 /* If we're not dealing with 0.95 hardware or isoc rings
3274 * on AMD 0.96 host, clear the chain bit.
3276 if (!xhci_link_trb_quirk(xhci) &&
3277 !(ep_ring->type == TYPE_ISOC &&
3278 (xhci->quirks & XHCI_AMD_0x96_HOST)))
3279 ep_ring->enqueue->link.control &=
3280 cpu_to_le32(~TRB_CHAIN);
3282 ep_ring->enqueue->link.control |=
3283 cpu_to_le32(TRB_CHAIN);
3286 ep_ring->enqueue->link.control ^= cpu_to_le32(TRB_CYCLE);
3288 /* Toggle the cycle bit after the last ring segment. */
3289 if (link_trb_toggles_cycle(ep_ring->enqueue))
3290 ep_ring->cycle_state ^= 1;
3292 ep_ring->enq_seg = ep_ring->enq_seg->next;
3293 ep_ring->enqueue = ep_ring->enq_seg->trbs;
3295 /* prevent infinite loop if all first trbs are link trbs */
3296 if (link_trb_count++ > ep_ring->num_segs) {
3297 xhci_warn(xhci, "Ring is an endless link TRB loop\n");
3302 if (last_trb_on_seg(ep_ring->enq_seg, ep_ring->trbs_per_seg,
3303 ep_ring->enqueue)) {
3304 xhci_warn(xhci, "Missing link TRB at end of ring segment\n");
3311 static int prepare_transfer(struct xhci_hcd *xhci,
3312 struct xhci_virt_device *xdev,
3313 unsigned int ep_index,
3314 unsigned int stream_id,
3315 unsigned int num_trbs,
3317 unsigned int td_index,
3321 struct urb_priv *urb_priv;
3323 struct xhci_ring *ep_ring;
3324 struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
3326 ep_ring = xhci_triad_to_transfer_ring(xhci, xdev->slot_id, ep_index,
3329 xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n",
3334 ret = prepare_ring(xhci, ep_ring, GET_EP_CTX_STATE(ep_ctx),
3335 num_trbs, mem_flags);
3339 urb_priv = urb->hcpriv;
3340 td = &urb_priv->td[td_index];
3342 INIT_LIST_HEAD(&td->td_list);
3343 INIT_LIST_HEAD(&td->cancelled_td_list);
3345 if (td_index == 0) {
3346 ret = usb_hcd_link_urb_to_ep(bus_to_hcd(urb->dev->bus), urb);
3352 /* Add this TD to the tail of the endpoint ring's TD list */
3353 list_add_tail(&td->td_list, &ep_ring->td_list);
3354 td->start_seg = ep_ring->enq_seg;
3355 td->first_trb = ep_ring->enqueue;
3360 unsigned int count_trbs(u64 addr, u64 len)
3362 unsigned int num_trbs;
3364 num_trbs = DIV_ROUND_UP(len + (addr & (TRB_MAX_BUFF_SIZE - 1)),
3372 static inline unsigned int count_trbs_needed(struct urb *urb)
3374 return count_trbs(urb->transfer_dma, urb->transfer_buffer_length);
3377 static unsigned int count_sg_trbs_needed(struct urb *urb)
3379 struct scatterlist *sg;
3380 unsigned int i, len, full_len, num_trbs = 0;
3382 full_len = urb->transfer_buffer_length;
3384 for_each_sg(urb->sg, sg, urb->num_mapped_sgs, i) {
3385 len = sg_dma_len(sg);
3386 num_trbs += count_trbs(sg_dma_address(sg), len);
3387 len = min_t(unsigned int, len, full_len);
3396 static unsigned int count_isoc_trbs_needed(struct urb *urb, int i)
3400 addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset);
3401 len = urb->iso_frame_desc[i].length;
3403 return count_trbs(addr, len);
3406 static void check_trb_math(struct urb *urb, int running_total)
3408 if (unlikely(running_total != urb->transfer_buffer_length))
3409 dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, "
3410 "queued %#x (%d), asked for %#x (%d)\n",
3412 urb->ep->desc.bEndpointAddress,
3413 running_total, running_total,
3414 urb->transfer_buffer_length,
3415 urb->transfer_buffer_length);
3418 static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id,
3419 unsigned int ep_index, unsigned int stream_id, int start_cycle,
3420 struct xhci_generic_trb *start_trb)
3423 * Pass all the TRBs to the hardware at once and make sure this write
3428 start_trb->field[3] |= cpu_to_le32(start_cycle);
3430 start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE);
3431 xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
3434 static void check_interval(struct xhci_hcd *xhci, struct urb *urb,
3435 struct xhci_ep_ctx *ep_ctx)
3440 xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info));
3441 ep_interval = urb->interval;
3443 /* Convert to microframes */
3444 if (urb->dev->speed == USB_SPEED_LOW ||
3445 urb->dev->speed == USB_SPEED_FULL)
3448 /* FIXME change this to a warning and a suggestion to use the new API
3449 * to set the polling interval (once the API is added).
3451 if (xhci_interval != ep_interval) {
3452 dev_dbg_ratelimited(&urb->dev->dev,
3453 "Driver uses different interval (%d microframe%s) than xHCI (%d microframe%s)\n",
3454 ep_interval, ep_interval == 1 ? "" : "s",
3455 xhci_interval, xhci_interval == 1 ? "" : "s");
3456 urb->interval = xhci_interval;
3457 /* Convert back to frames for LS/FS devices */
3458 if (urb->dev->speed == USB_SPEED_LOW ||
3459 urb->dev->speed == USB_SPEED_FULL)
3465 * xHCI uses normal TRBs for both bulk and interrupt. When the interrupt
3466 * endpoint is to be serviced, the xHC will consume (at most) one TD. A TD
3467 * (comprised of sg list entries) can take several service intervals to
3470 int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3471 struct urb *urb, int slot_id, unsigned int ep_index)
3473 struct xhci_ep_ctx *ep_ctx;
3475 ep_ctx = xhci_get_ep_ctx(xhci, xhci->devs[slot_id]->out_ctx, ep_index);
3476 check_interval(xhci, urb, ep_ctx);
3478 return xhci_queue_bulk_tx(xhci, mem_flags, urb, slot_id, ep_index);
3482 * For xHCI 1.0 host controllers, TD size is the number of max packet sized
3483 * packets remaining in the TD (*not* including this TRB).
3485 * Total TD packet count = total_packet_count =
3486 * DIV_ROUND_UP(TD size in bytes / wMaxPacketSize)
3488 * Packets transferred up to and including this TRB = packets_transferred =
3489 * rounddown(total bytes transferred including this TRB / wMaxPacketSize)
3491 * TD size = total_packet_count - packets_transferred
3493 * For xHCI 0.96 and older, TD size field should be the remaining bytes
3494 * including this TRB, right shifted by 10
3496 * For all hosts it must fit in bits 21:17, so it can't be bigger than 31.
3497 * This is taken care of in the TRB_TD_SIZE() macro
3499 * The last TRB in a TD must have the TD size set to zero.
3501 static u32 xhci_td_remainder(struct xhci_hcd *xhci, int transferred,
3502 int trb_buff_len, unsigned int td_total_len,
3503 struct urb *urb, bool more_trbs_coming)
3505 u32 maxp, total_packet_count;
3507 /* MTK xHCI 0.96 contains some features from 1.0 */
3508 if (xhci->hci_version < 0x100 && !(xhci->quirks & XHCI_MTK_HOST))
3509 return ((td_total_len - transferred) >> 10);
3511 /* One TRB with a zero-length data packet. */
3512 if (!more_trbs_coming || (transferred == 0 && trb_buff_len == 0) ||
3513 trb_buff_len == td_total_len)
3516 /* for MTK xHCI 0.96, TD size include this TRB, but not in 1.x */
3517 if ((xhci->quirks & XHCI_MTK_HOST) && (xhci->hci_version < 0x100))
3520 maxp = usb_endpoint_maxp(&urb->ep->desc);
3521 total_packet_count = DIV_ROUND_UP(td_total_len, maxp);
3523 /* Queueing functions don't count the current TRB into transferred */
3524 return (total_packet_count - ((transferred + trb_buff_len) / maxp));
3528 static int xhci_align_td(struct xhci_hcd *xhci, struct urb *urb, u32 enqd_len,
3529 u32 *trb_buff_len, struct xhci_segment *seg)
3531 struct device *dev = xhci_to_hcd(xhci)->self.controller;
3532 unsigned int unalign;
3533 unsigned int max_pkt;
3537 max_pkt = usb_endpoint_maxp(&urb->ep->desc);
3538 unalign = (enqd_len + *trb_buff_len) % max_pkt;
3540 /* we got lucky, last normal TRB data on segment is packet aligned */
3544 xhci_dbg(xhci, "Unaligned %d bytes, buff len %d\n",
3545 unalign, *trb_buff_len);
3547 /* is the last nornal TRB alignable by splitting it */
3548 if (*trb_buff_len > unalign) {
3549 *trb_buff_len -= unalign;
3550 xhci_dbg(xhci, "split align, new buff len %d\n", *trb_buff_len);
3555 * We want enqd_len + trb_buff_len to sum up to a number aligned to
3556 * number which is divisible by the endpoint's wMaxPacketSize. IOW:
3557 * (size of currently enqueued TRBs + remainder) % wMaxPacketSize == 0.
3559 new_buff_len = max_pkt - (enqd_len % max_pkt);
3561 if (new_buff_len > (urb->transfer_buffer_length - enqd_len))
3562 new_buff_len = (urb->transfer_buffer_length - enqd_len);
3564 /* create a max max_pkt sized bounce buffer pointed to by last trb */
3565 if (usb_urb_dir_out(urb)) {
3567 len = sg_pcopy_to_buffer(urb->sg, urb->num_sgs,
3568 seg->bounce_buf, new_buff_len, enqd_len);
3569 if (len != new_buff_len)
3570 xhci_warn(xhci, "WARN Wrong bounce buffer write length: %zu != %d\n",
3573 memcpy(seg->bounce_buf, urb->transfer_buffer + enqd_len, new_buff_len);
3576 seg->bounce_dma = dma_map_single(dev, seg->bounce_buf,
3577 max_pkt, DMA_TO_DEVICE);
3579 seg->bounce_dma = dma_map_single(dev, seg->bounce_buf,
3580 max_pkt, DMA_FROM_DEVICE);
3583 if (dma_mapping_error(dev, seg->bounce_dma)) {
3584 /* try without aligning. Some host controllers survive */
3585 xhci_warn(xhci, "Failed mapping bounce buffer, not aligning\n");
3588 *trb_buff_len = new_buff_len;
3589 seg->bounce_len = new_buff_len;
3590 seg->bounce_offs = enqd_len;
3592 xhci_dbg(xhci, "Bounce align, new buff len %d\n", *trb_buff_len);
3597 static void xhci_vl805_hub_tt_quirk(struct xhci_hcd *xhci, struct urb *urb,
3598 struct xhci_ring *ring)
3600 struct list_head *tmp;
3601 struct usb_device *udev = urb->dev;
3602 unsigned int timeout = 0;
3603 unsigned int single_td = 0;
3606 * Adding a TD to an Idle ring for a FS nonperiodic endpoint
3607 * that is behind the internal hub's TT will run the risk of causing a
3608 * downstream port babble if submitted late in uFrame 7.
3609 * Wait until we've moved on into at least uFrame 0
3610 * (MFINDEX references the next SOF to be transmitted).
3612 * Rings for IN endpoints in the Running state also risk causing
3613 * babble if the returned data is large, but there's not much we can do
3616 if (udev->route & 0xffff0 || udev->speed != USB_SPEED_FULL)
3619 list_for_each(tmp, &ring->td_list) {
3621 if (single_td == 2) {
3627 while (timeout < 20 &&
3628 (readl(&xhci->run_regs->microframe_index) & 0x7) == 0) {
3633 xhci_warn(xhci, "MFINDEX didn't advance - %u.%u dodged\n",
3634 readl(&xhci->run_regs->microframe_index) >> 3,
3635 readl(&xhci->run_regs->microframe_index) & 7);
3639 /* This is very similar to what ehci-q.c qtd_fill() does */
3640 int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3641 struct urb *urb, int slot_id, unsigned int ep_index)
3643 struct xhci_ring *ring;
3644 struct urb_priv *urb_priv;
3646 struct xhci_generic_trb *start_trb;
3647 struct scatterlist *sg = NULL;
3648 bool more_trbs_coming = true;
3649 bool need_zero_pkt = false;
3650 bool first_trb = true;
3651 unsigned int num_trbs;
3652 unsigned int start_cycle, num_sgs = 0;
3653 unsigned int enqd_len, block_len, trb_buff_len, full_len;
3654 int sent_len, ret, vli_bulk_quirk = 0;
3655 u32 field, length_field, remainder, maxpacket;
3656 u64 addr, send_addr;
3658 ring = xhci_urb_to_transfer_ring(xhci, urb);
3662 maxpacket = usb_endpoint_maxp(&urb->ep->desc);
3663 full_len = urb->transfer_buffer_length;
3664 /* If we have scatter/gather list, we use it. */
3665 if (urb->num_sgs && !(urb->transfer_flags & URB_DMA_MAP_SINGLE)) {
3666 num_sgs = urb->num_mapped_sgs;
3668 addr = (u64) sg_dma_address(sg);
3669 block_len = sg_dma_len(sg);
3670 num_trbs = count_sg_trbs_needed(urb);
3672 num_trbs = count_trbs_needed(urb);
3673 addr = (u64) urb->transfer_dma;
3674 block_len = full_len;
3676 ret = prepare_transfer(xhci, xhci->devs[slot_id],
3677 ep_index, urb->stream_id,
3678 num_trbs, urb, 0, mem_flags);
3679 if (unlikely(ret < 0))
3682 urb_priv = urb->hcpriv;
3684 /* Deal with URB_ZERO_PACKET - need one more td/trb */
3685 if (urb->transfer_flags & URB_ZERO_PACKET && urb_priv->num_tds > 1)
3686 need_zero_pkt = true;
3688 td = &urb_priv->td[0];
3691 * Don't give the first TRB to the hardware (by toggling the cycle bit)
3692 * until we've finished creating all the other TRBs. The ring's cycle
3693 * state may change as we enqueue the other TRBs, so save it too.
3695 start_trb = &ring->enqueue->generic;
3696 start_cycle = ring->cycle_state;
3699 if (xhci->quirks & XHCI_VLI_SS_BULK_OUT_BUG &&
3700 usb_endpoint_is_bulk_out(&urb->ep->desc)
3701 && urb->dev->speed >= USB_SPEED_SUPER) {
3705 /* Queue the TRBs, even if they are zero-length */
3706 for (enqd_len = 0; first_trb || enqd_len < full_len;
3707 enqd_len += trb_buff_len) {
3708 field = TRB_TYPE(TRB_NORMAL);
3710 /* TRB buffer should not cross 64KB boundaries */
3711 trb_buff_len = TRB_BUFF_LEN_UP_TO_BOUNDARY(addr);
3712 trb_buff_len = min_t(unsigned int, trb_buff_len, block_len);
3714 if (enqd_len + trb_buff_len > full_len)
3715 trb_buff_len = full_len - enqd_len;
3717 if (vli_bulk_quirk && trb_buff_len > maxpacket) {
3718 /* SS bulk wMaxPacket is 1024B */
3719 remainder = trb_buff_len & (maxpacket - 1);
3720 trb_buff_len -= remainder;
3722 /* Don't change the cycle bit of the first TRB until later */
3725 if (start_cycle == 0)
3728 field |= ring->cycle_state;
3730 /* Chain all the TRBs together; clear the chain bit in the last
3731 * TRB to indicate it's the last TRB in the chain.
3733 if (enqd_len + trb_buff_len < full_len) {
3735 if (trb_is_link(ring->enqueue + 1)) {
3736 if (xhci_align_td(xhci, urb, enqd_len,
3739 send_addr = ring->enq_seg->bounce_dma;
3740 /* assuming TD won't span 2 segs */
3741 td->bounce_seg = ring->enq_seg;
3745 if (enqd_len + trb_buff_len >= full_len) {
3746 field &= ~TRB_CHAIN;
3748 more_trbs_coming = false;
3749 td->last_trb = ring->enqueue;
3750 td->last_trb_seg = ring->enq_seg;
3751 if (xhci_urb_suitable_for_idt(urb)) {
3752 memcpy(&send_addr, urb->transfer_buffer,
3754 le64_to_cpus(&send_addr);
3759 /* Only set interrupt on short packet for IN endpoints */
3760 if (usb_urb_dir_in(urb))
3763 /* Set the TRB length, TD size, and interrupter fields. */
3764 remainder = xhci_td_remainder(xhci, enqd_len, trb_buff_len,
3765 full_len, urb, more_trbs_coming);
3767 length_field = TRB_LEN(trb_buff_len) |
3768 TRB_TD_SIZE(remainder) |
3771 queue_trb(xhci, ring, more_trbs_coming | need_zero_pkt,
3772 lower_32_bits(send_addr),
3773 upper_32_bits(send_addr),
3777 addr += trb_buff_len;
3778 sent_len = trb_buff_len;
3780 while (sg && sent_len >= block_len) {
3783 sent_len -= block_len;
3785 if (num_sgs != 0 && sg) {
3786 block_len = sg_dma_len(sg);
3787 addr = (u64) sg_dma_address(sg);
3791 block_len -= sent_len;
3795 if (need_zero_pkt) {
3796 ret = prepare_transfer(xhci, xhci->devs[slot_id],
3797 ep_index, urb->stream_id,
3798 1, urb, 1, mem_flags);
3799 urb_priv->td[1].last_trb = ring->enqueue;
3800 urb_priv->td[1].last_trb_seg = ring->enq_seg;
3801 field = TRB_TYPE(TRB_NORMAL) | ring->cycle_state | TRB_IOC;
3802 queue_trb(xhci, ring, 0, 0, 0, TRB_INTR_TARGET(0), field);
3803 urb_priv->td[1].num_trbs++;
3806 check_trb_math(urb, enqd_len);
3807 if (xhci->quirks & XHCI_VLI_HUB_TT_QUIRK)
3808 xhci_vl805_hub_tt_quirk(xhci, urb, ring);
3809 giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
3810 start_cycle, start_trb);
3814 /* Caller must have locked xhci->lock */
3815 int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3816 struct urb *urb, int slot_id, unsigned int ep_index)
3818 struct xhci_ring *ep_ring;
3821 struct usb_ctrlrequest *setup;
3822 struct xhci_generic_trb *start_trb;
3825 struct urb_priv *urb_priv;
3828 ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
3833 * Need to copy setup packet into setup TRB, so we can't use the setup
3836 if (!urb->setup_packet)
3839 /* 1 TRB for setup, 1 for status */
3842 * Don't need to check if we need additional event data and normal TRBs,
3843 * since data in control transfers will never get bigger than 16MB
3844 * XXX: can we get a buffer that crosses 64KB boundaries?
3846 if (urb->transfer_buffer_length > 0)
3848 ret = prepare_transfer(xhci, xhci->devs[slot_id],
3849 ep_index, urb->stream_id,
3850 num_trbs, urb, 0, mem_flags);
3854 urb_priv = urb->hcpriv;
3855 td = &urb_priv->td[0];
3856 td->num_trbs = num_trbs;
3859 * Don't give the first TRB to the hardware (by toggling the cycle bit)
3860 * until we've finished creating all the other TRBs. The ring's cycle
3861 * state may change as we enqueue the other TRBs, so save it too.
3863 start_trb = &ep_ring->enqueue->generic;
3864 start_cycle = ep_ring->cycle_state;
3866 /* Queue setup TRB - see section 6.4.1.2.1 */
3867 /* FIXME better way to translate setup_packet into two u32 fields? */
3868 setup = (struct usb_ctrlrequest *) urb->setup_packet;
3870 field |= TRB_IDT | TRB_TYPE(TRB_SETUP);
3871 if (start_cycle == 0)
3874 /* xHCI 1.0/1.1 6.4.1.2.1: Transfer Type field */
3875 if ((xhci->hci_version >= 0x100) || (xhci->quirks & XHCI_MTK_HOST)) {
3876 if (urb->transfer_buffer_length > 0) {
3877 if (setup->bRequestType & USB_DIR_IN)
3878 field |= TRB_TX_TYPE(TRB_DATA_IN);
3880 field |= TRB_TX_TYPE(TRB_DATA_OUT);
3884 queue_trb(xhci, ep_ring, true,
3885 setup->bRequestType | setup->bRequest << 8 | le16_to_cpu(setup->wValue) << 16,
3886 le16_to_cpu(setup->wIndex) | le16_to_cpu(setup->wLength) << 16,
3887 TRB_LEN(8) | TRB_INTR_TARGET(0),
3888 /* Immediate data in pointer */
3891 /* If there's data, queue data TRBs */
3892 /* Only set interrupt on short packet for IN endpoints */
3893 if (usb_urb_dir_in(urb))
3894 field = TRB_ISP | TRB_TYPE(TRB_DATA);
3896 field = TRB_TYPE(TRB_DATA);
3898 if (urb->transfer_buffer_length > 0) {
3899 u32 length_field, remainder;
3902 if (xhci_urb_suitable_for_idt(urb)) {
3903 memcpy(&addr, urb->transfer_buffer,
3904 urb->transfer_buffer_length);
3905 le64_to_cpus(&addr);
3908 addr = (u64) urb->transfer_dma;
3911 remainder = xhci_td_remainder(xhci, 0,
3912 urb->transfer_buffer_length,
3913 urb->transfer_buffer_length,
3915 length_field = TRB_LEN(urb->transfer_buffer_length) |
3916 TRB_TD_SIZE(remainder) |
3918 if (setup->bRequestType & USB_DIR_IN)
3919 field |= TRB_DIR_IN;
3920 queue_trb(xhci, ep_ring, true,
3921 lower_32_bits(addr),
3922 upper_32_bits(addr),
3924 field | ep_ring->cycle_state);
3927 /* Save the DMA address of the last TRB in the TD */
3928 td->last_trb = ep_ring->enqueue;
3929 td->last_trb_seg = ep_ring->enq_seg;
3931 /* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */
3932 /* If the device sent data, the status stage is an OUT transfer */
3933 if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN)
3937 queue_trb(xhci, ep_ring, false,
3941 /* Event on completion */
3942 field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state);
3944 if (xhci->quirks & XHCI_VLI_HUB_TT_QUIRK)
3945 xhci_vl805_hub_tt_quirk(xhci, urb, ep_ring);
3946 giveback_first_trb(xhci, slot_id, ep_index, 0,
3947 start_cycle, start_trb);
3952 * The transfer burst count field of the isochronous TRB defines the number of
3953 * bursts that are required to move all packets in this TD. Only SuperSpeed
3954 * devices can burst up to bMaxBurst number of packets per service interval.
3955 * This field is zero based, meaning a value of zero in the field means one
3956 * burst. Basically, for everything but SuperSpeed devices, this field will be
3957 * zero. Only xHCI 1.0 host controllers support this field.
3959 static unsigned int xhci_get_burst_count(struct xhci_hcd *xhci,
3960 struct urb *urb, unsigned int total_packet_count)
3962 unsigned int max_burst;
3964 if (xhci->hci_version < 0x100 || urb->dev->speed < USB_SPEED_SUPER)
3967 max_burst = urb->ep->ss_ep_comp.bMaxBurst;
3968 return DIV_ROUND_UP(total_packet_count, max_burst + 1) - 1;
3972 * Returns the number of packets in the last "burst" of packets. This field is
3973 * valid for all speeds of devices. USB 2.0 devices can only do one "burst", so
3974 * the last burst packet count is equal to the total number of packets in the
3975 * TD. SuperSpeed endpoints can have up to 3 bursts. All but the last burst
3976 * must contain (bMaxBurst + 1) number of packets, but the last burst can
3977 * contain 1 to (bMaxBurst + 1) packets.
3979 static unsigned int xhci_get_last_burst_packet_count(struct xhci_hcd *xhci,
3980 struct urb *urb, unsigned int total_packet_count)
3982 unsigned int max_burst;
3983 unsigned int residue;
3985 if (xhci->hci_version < 0x100)
3988 if (urb->dev->speed >= USB_SPEED_SUPER) {
3989 /* bMaxBurst is zero based: 0 means 1 packet per burst */
3990 max_burst = urb->ep->ss_ep_comp.bMaxBurst;
3991 residue = total_packet_count % (max_burst + 1);
3992 /* If residue is zero, the last burst contains (max_burst + 1)
3993 * number of packets, but the TLBPC field is zero-based.
3999 if (total_packet_count == 0)
4001 return total_packet_count - 1;
4005 * Calculates Frame ID field of the isochronous TRB identifies the
4006 * target frame that the Interval associated with this Isochronous
4007 * Transfer Descriptor will start on. Refer to 4.11.2.5 in 1.1 spec.
4009 * Returns actual frame id on success, negative value on error.
4011 static int xhci_get_isoc_frame_id(struct xhci_hcd *xhci,
4012 struct urb *urb, int index)
4014 int start_frame, ist, ret = 0;
4015 int start_frame_id, end_frame_id, current_frame_id;
4017 if (urb->dev->speed == USB_SPEED_LOW ||
4018 urb->dev->speed == USB_SPEED_FULL)
4019 start_frame = urb->start_frame + index * urb->interval;
4021 start_frame = (urb->start_frame + index * urb->interval) >> 3;
4023 /* Isochronous Scheduling Threshold (IST, bits 0~3 in HCSPARAMS2):
4025 * If bit [3] of IST is cleared to '0', software can add a TRB no
4026 * later than IST[2:0] Microframes before that TRB is scheduled to
4028 * If bit [3] of IST is set to '1', software can add a TRB no later
4029 * than IST[2:0] Frames before that TRB is scheduled to be executed.
4031 ist = HCS_IST(xhci->hcs_params2) & 0x7;
4032 if (HCS_IST(xhci->hcs_params2) & (1 << 3))
4035 /* Software shall not schedule an Isoch TD with a Frame ID value that
4036 * is less than the Start Frame ID or greater than the End Frame ID,
4039 * End Frame ID = (Current MFINDEX register value + 895 ms.) MOD 2048
4040 * Start Frame ID = (Current MFINDEX register value + IST + 1) MOD 2048
4042 * Both the End Frame ID and Start Frame ID values are calculated
4043 * in microframes. When software determines the valid Frame ID value;
4044 * The End Frame ID value should be rounded down to the nearest Frame
4045 * boundary, and the Start Frame ID value should be rounded up to the
4046 * nearest Frame boundary.
4048 current_frame_id = readl(&xhci->run_regs->microframe_index);
4049 start_frame_id = roundup(current_frame_id + ist + 1, 8);
4050 end_frame_id = rounddown(current_frame_id + 895 * 8, 8);
4052 start_frame &= 0x7ff;
4053 start_frame_id = (start_frame_id >> 3) & 0x7ff;
4054 end_frame_id = (end_frame_id >> 3) & 0x7ff;
4056 xhci_dbg(xhci, "%s: index %d, reg 0x%x start_frame_id 0x%x, end_frame_id 0x%x, start_frame 0x%x\n",
4057 __func__, index, readl(&xhci->run_regs->microframe_index),
4058 start_frame_id, end_frame_id, start_frame);
4060 if (start_frame_id < end_frame_id) {
4061 if (start_frame > end_frame_id ||
4062 start_frame < start_frame_id)
4064 } else if (start_frame_id > end_frame_id) {
4065 if ((start_frame > end_frame_id &&
4066 start_frame < start_frame_id))
4073 if (ret == -EINVAL || start_frame == start_frame_id) {
4074 start_frame = start_frame_id + 1;
4075 if (urb->dev->speed == USB_SPEED_LOW ||
4076 urb->dev->speed == USB_SPEED_FULL)
4077 urb->start_frame = start_frame;
4079 urb->start_frame = start_frame << 3;
4085 xhci_warn(xhci, "Frame ID %d (reg %d, index %d) beyond range (%d, %d)\n",
4086 start_frame, current_frame_id, index,
4087 start_frame_id, end_frame_id);
4088 xhci_warn(xhci, "Ignore frame ID field, use SIA bit instead\n");
4095 /* Check if we should generate event interrupt for a TD in an isoc URB */
4096 static bool trb_block_event_intr(struct xhci_hcd *xhci, int num_tds, int i)
4098 if (xhci->hci_version < 0x100)
4100 /* always generate an event interrupt for the last TD */
4101 if (i == num_tds - 1)
4104 * If AVOID_BEI is set the host handles full event rings poorly,
4105 * generate an event at least every 8th TD to clear the event ring
4107 if (i && xhci->quirks & XHCI_AVOID_BEI)
4108 return !!(i % xhci->isoc_bei_interval);
4113 /* This is for isoc transfer */
4114 static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
4115 struct urb *urb, int slot_id, unsigned int ep_index)
4117 struct xhci_ring *ep_ring;
4118 struct urb_priv *urb_priv;
4120 int num_tds, trbs_per_td;
4121 struct xhci_generic_trb *start_trb;
4124 u32 field, length_field;
4125 int running_total, trb_buff_len, td_len, td_remain_len, ret;
4126 u64 start_addr, addr;
4128 bool more_trbs_coming;
4129 struct xhci_virt_ep *xep;
4132 xep = &xhci->devs[slot_id]->eps[ep_index];
4133 ep_ring = xhci->devs[slot_id]->eps[ep_index].ring;
4135 num_tds = urb->number_of_packets;
4137 xhci_dbg(xhci, "Isoc URB with zero packets?\n");
4140 start_addr = (u64) urb->transfer_dma;
4141 start_trb = &ep_ring->enqueue->generic;
4142 start_cycle = ep_ring->cycle_state;
4144 urb_priv = urb->hcpriv;
4145 /* Queue the TRBs for each TD, even if they are zero-length */
4146 for (i = 0; i < num_tds; i++) {
4147 unsigned int total_pkt_count, max_pkt;
4148 unsigned int burst_count, last_burst_pkt_count;
4153 addr = start_addr + urb->iso_frame_desc[i].offset;
4154 td_len = urb->iso_frame_desc[i].length;
4155 td_remain_len = td_len;
4156 max_pkt = usb_endpoint_maxp(&urb->ep->desc);
4157 total_pkt_count = DIV_ROUND_UP(td_len, max_pkt);
4159 /* A zero-length transfer still involves at least one packet. */
4160 if (total_pkt_count == 0)
4162 burst_count = xhci_get_burst_count(xhci, urb, total_pkt_count);
4163 last_burst_pkt_count = xhci_get_last_burst_packet_count(xhci,
4164 urb, total_pkt_count);
4166 trbs_per_td = count_isoc_trbs_needed(urb, i);
4168 ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index,
4169 urb->stream_id, trbs_per_td, urb, i, mem_flags);
4175 td = &urb_priv->td[i];
4176 td->num_trbs = trbs_per_td;
4177 /* use SIA as default, if frame id is used overwrite it */
4178 sia_frame_id = TRB_SIA;
4179 if (!(urb->transfer_flags & URB_ISO_ASAP) &&
4180 HCC_CFC(xhci->hcc_params)) {
4181 frame_id = xhci_get_isoc_frame_id(xhci, urb, i);
4183 sia_frame_id = TRB_FRAME_ID(frame_id);
4186 * Set isoc specific data for the first TRB in a TD.
4187 * Prevent HW from getting the TRBs by keeping the cycle state
4188 * inverted in the first TDs isoc TRB.
4190 field = TRB_TYPE(TRB_ISOC) |
4191 TRB_TLBPC(last_burst_pkt_count) |
4193 (i ? ep_ring->cycle_state : !start_cycle);
4195 /* xhci 1.1 with ETE uses TD_Size field for TBC, old is Rsvdz */
4196 if (!xep->use_extended_tbc)
4197 field |= TRB_TBC(burst_count);
4199 /* fill the rest of the TRB fields, and remaining normal TRBs */
4200 for (j = 0; j < trbs_per_td; j++) {
4203 /* only first TRB is isoc, overwrite otherwise */
4205 field = TRB_TYPE(TRB_NORMAL) |
4206 ep_ring->cycle_state;
4208 /* Only set interrupt on short packet for IN EPs */
4209 if (usb_urb_dir_in(urb))
4212 /* Set the chain bit for all except the last TRB */
4213 if (j < trbs_per_td - 1) {
4214 more_trbs_coming = true;
4217 more_trbs_coming = false;
4218 td->last_trb = ep_ring->enqueue;
4219 td->last_trb_seg = ep_ring->enq_seg;
4221 if (trb_block_event_intr(xhci, num_tds, i))
4224 /* Calculate TRB length */
4225 trb_buff_len = TRB_BUFF_LEN_UP_TO_BOUNDARY(addr);
4226 if (trb_buff_len > td_remain_len)
4227 trb_buff_len = td_remain_len;
4229 /* Set the TRB length, TD size, & interrupter fields. */
4230 remainder = xhci_td_remainder(xhci, running_total,
4231 trb_buff_len, td_len,
4232 urb, more_trbs_coming);
4234 length_field = TRB_LEN(trb_buff_len) |
4237 /* xhci 1.1 with ETE uses TD Size field for TBC */
4238 if (first_trb && xep->use_extended_tbc)
4239 length_field |= TRB_TD_SIZE_TBC(burst_count);
4241 length_field |= TRB_TD_SIZE(remainder);
4244 queue_trb(xhci, ep_ring, more_trbs_coming,
4245 lower_32_bits(addr),
4246 upper_32_bits(addr),
4249 running_total += trb_buff_len;
4251 addr += trb_buff_len;
4252 td_remain_len -= trb_buff_len;
4255 /* Check TD length */
4256 if (running_total != td_len) {
4257 xhci_err(xhci, "ISOC TD length unmatch\n");
4263 /* store the next frame id */
4264 if (HCC_CFC(xhci->hcc_params))
4265 xep->next_frame_id = urb->start_frame + num_tds * urb->interval;
4267 if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) {
4268 if (xhci->quirks & XHCI_AMD_PLL_FIX)
4269 usb_amd_quirk_pll_disable();
4271 xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs++;
4273 giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
4274 start_cycle, start_trb);
4277 /* Clean up a partially enqueued isoc transfer. */
4279 for (i--; i >= 0; i--)
4280 list_del_init(&urb_priv->td[i].td_list);
4282 /* Use the first TD as a temporary variable to turn the TDs we've queued
4283 * into No-ops with a software-owned cycle bit. That way the hardware
4284 * won't accidentally start executing bogus TDs when we partially
4285 * overwrite them. td->first_trb and td->start_seg are already set.
4287 urb_priv->td[0].last_trb = ep_ring->enqueue;
4288 /* Every TRB except the first & last will have its cycle bit flipped. */
4289 td_to_noop(xhci, ep_ring, &urb_priv->td[0], true);
4291 /* Reset the ring enqueue back to the first TRB and its cycle bit. */
4292 ep_ring->enqueue = urb_priv->td[0].first_trb;
4293 ep_ring->enq_seg = urb_priv->td[0].start_seg;
4294 ep_ring->cycle_state = start_cycle;
4295 ep_ring->num_trbs_free = ep_ring->num_trbs_free_temp;
4296 usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb);
4301 * Check transfer ring to guarantee there is enough room for the urb.
4302 * Update ISO URB start_frame and interval.
4303 * Update interval as xhci_queue_intr_tx does. Use xhci frame_index to
4304 * update urb->start_frame if URB_ISO_ASAP is set in transfer_flags or
4305 * Contiguous Frame ID is not supported by HC.
4307 int xhci_queue_isoc_tx_prepare(struct xhci_hcd *xhci, gfp_t mem_flags,
4308 struct urb *urb, int slot_id, unsigned int ep_index)
4310 struct xhci_virt_device *xdev;
4311 struct xhci_ring *ep_ring;
4312 struct xhci_ep_ctx *ep_ctx;
4314 int num_tds, num_trbs, i;
4316 struct xhci_virt_ep *xep;
4319 xdev = xhci->devs[slot_id];
4320 xep = &xhci->devs[slot_id]->eps[ep_index];
4321 ep_ring = xdev->eps[ep_index].ring;
4322 ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
4325 num_tds = urb->number_of_packets;
4326 for (i = 0; i < num_tds; i++)
4327 num_trbs += count_isoc_trbs_needed(urb, i);
4329 /* Check the ring to guarantee there is enough room for the whole urb.
4330 * Do not insert any td of the urb to the ring if the check failed.
4332 ret = prepare_ring(xhci, ep_ring, GET_EP_CTX_STATE(ep_ctx),
4333 num_trbs, mem_flags);
4338 * Check interval value. This should be done before we start to
4339 * calculate the start frame value.
4341 check_interval(xhci, urb, ep_ctx);
4343 /* Calculate the start frame and put it in urb->start_frame. */
4344 if (HCC_CFC(xhci->hcc_params) && !list_empty(&ep_ring->td_list)) {
4345 if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_RUNNING) {
4346 urb->start_frame = xep->next_frame_id;
4347 goto skip_start_over;
4351 start_frame = readl(&xhci->run_regs->microframe_index);
4352 start_frame &= 0x3fff;
4354 * Round up to the next frame and consider the time before trb really
4355 * gets scheduled by hardare.
4357 ist = HCS_IST(xhci->hcs_params2) & 0x7;
4358 if (HCS_IST(xhci->hcs_params2) & (1 << 3))
4360 start_frame += ist + XHCI_CFC_DELAY;
4361 start_frame = roundup(start_frame, 8);
4364 * Round up to the next ESIT (Endpoint Service Interval Time) if ESIT
4365 * is greate than 8 microframes.
4367 if (urb->dev->speed == USB_SPEED_LOW ||
4368 urb->dev->speed == USB_SPEED_FULL) {
4369 start_frame = roundup(start_frame, urb->interval << 3);
4370 urb->start_frame = start_frame >> 3;
4372 start_frame = roundup(start_frame, urb->interval);
4373 urb->start_frame = start_frame;
4377 ep_ring->num_trbs_free_temp = ep_ring->num_trbs_free;
4379 return xhci_queue_isoc_tx(xhci, mem_flags, urb, slot_id, ep_index);
4382 /**** Command Ring Operations ****/
4384 /* Generic function for queueing a command TRB on the command ring.
4385 * Check to make sure there's room on the command ring for one command TRB.
4386 * Also check that there's room reserved for commands that must not fail.
4387 * If this is a command that must not fail, meaning command_must_succeed = TRUE,
4388 * then only check for the number of reserved spots.
4389 * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB
4390 * because the command event handler may want to resubmit a failed command.
4392 static int queue_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
4393 u32 field1, u32 field2,
4394 u32 field3, u32 field4, bool command_must_succeed)
4396 int reserved_trbs = xhci->cmd_ring_reserved_trbs;
4399 if ((xhci->xhc_state & XHCI_STATE_DYING) ||
4400 (xhci->xhc_state & XHCI_STATE_HALTED)) {
4401 xhci_dbg(xhci, "xHCI dying or halted, can't queue_command\n");
4405 if (!command_must_succeed)
4408 ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING,
4409 reserved_trbs, GFP_ATOMIC);
4411 xhci_err(xhci, "ERR: No room for command on command ring\n");
4412 if (command_must_succeed)
4413 xhci_err(xhci, "ERR: Reserved TRB counting for "
4414 "unfailable commands failed.\n");
4418 cmd->command_trb = xhci->cmd_ring->enqueue;
4420 /* if there are no other commands queued we start the timeout timer */
4421 if (list_empty(&xhci->cmd_list)) {
4422 xhci->current_cmd = cmd;
4423 xhci_mod_cmd_timer(xhci, XHCI_CMD_DEFAULT_TIMEOUT);
4426 list_add_tail(&cmd->cmd_list, &xhci->cmd_list);
4428 queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3,
4429 field4 | xhci->cmd_ring->cycle_state);
4433 /* Queue a slot enable or disable request on the command ring */
4434 int xhci_queue_slot_control(struct xhci_hcd *xhci, struct xhci_command *cmd,
4435 u32 trb_type, u32 slot_id)
4437 return queue_command(xhci, cmd, 0, 0, 0,
4438 TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false);
4441 /* Queue an address device command TRB */
4442 int xhci_queue_address_device(struct xhci_hcd *xhci, struct xhci_command *cmd,
4443 dma_addr_t in_ctx_ptr, u32 slot_id, enum xhci_setup_dev setup)
4445 return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4446 upper_32_bits(in_ctx_ptr), 0,
4447 TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id)
4448 | (setup == SETUP_CONTEXT_ONLY ? TRB_BSR : 0), false);
4451 int xhci_queue_vendor_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
4452 u32 field1, u32 field2, u32 field3, u32 field4)
4454 return queue_command(xhci, cmd, field1, field2, field3, field4, false);
4457 /* Queue a reset device command TRB */
4458 int xhci_queue_reset_device(struct xhci_hcd *xhci, struct xhci_command *cmd,
4461 return queue_command(xhci, cmd, 0, 0, 0,
4462 TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id),
4466 /* Queue a configure endpoint command TRB */
4467 int xhci_queue_configure_endpoint(struct xhci_hcd *xhci,
4468 struct xhci_command *cmd, dma_addr_t in_ctx_ptr,
4469 u32 slot_id, bool command_must_succeed)
4471 return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4472 upper_32_bits(in_ctx_ptr), 0,
4473 TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id),
4474 command_must_succeed);
4477 /* Queue an evaluate context command TRB */
4478 int xhci_queue_evaluate_context(struct xhci_hcd *xhci, struct xhci_command *cmd,
4479 dma_addr_t in_ctx_ptr, u32 slot_id, bool command_must_succeed)
4481 return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4482 upper_32_bits(in_ctx_ptr), 0,
4483 TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id),
4484 command_must_succeed);
4488 * Suspend is set to indicate "Stop Endpoint Command" is being issued to stop
4489 * activity on an endpoint that is about to be suspended.
4491 int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, struct xhci_command *cmd,
4492 int slot_id, unsigned int ep_index, int suspend)
4494 u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
4495 u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
4496 u32 type = TRB_TYPE(TRB_STOP_RING);
4497 u32 trb_suspend = SUSPEND_PORT_FOR_TRB(suspend);
4499 return queue_command(xhci, cmd, 0, 0, 0,
4500 trb_slot_id | trb_ep_index | type | trb_suspend, false);
4503 int xhci_queue_reset_ep(struct xhci_hcd *xhci, struct xhci_command *cmd,
4504 int slot_id, unsigned int ep_index,
4505 enum xhci_ep_reset_type reset_type)
4507 u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
4508 u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
4509 u32 type = TRB_TYPE(TRB_RESET_EP);
4511 if (reset_type == EP_SOFT_RESET)
4514 return queue_command(xhci, cmd, 0, 0, 0,
4515 trb_slot_id | trb_ep_index | type, false);