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, union xhci_trb *trb)
95 return trb == &seg->trbs[TRBS_PER_SEGMENT - 1];
98 static bool last_trb_on_ring(struct xhci_ring *ring,
99 struct xhci_segment *seg, union xhci_trb *trb)
101 return last_trb_on_seg(seg, trb) && (seg->next == ring->first_seg);
104 static bool link_trb_toggles_cycle(union xhci_trb *trb)
106 return le32_to_cpu(trb->link.control) & LINK_TOGGLE;
109 static bool last_td_in_urb(struct xhci_td *td)
111 struct urb_priv *urb_priv = td->urb->hcpriv;
113 return urb_priv->num_tds_done == urb_priv->num_tds;
116 static bool unhandled_event_trb(struct xhci_ring *ring)
118 return ((le32_to_cpu(ring->dequeue->event_cmd.flags) & TRB_CYCLE) ==
122 static void inc_td_cnt(struct urb *urb)
124 struct urb_priv *urb_priv = urb->hcpriv;
126 urb_priv->num_tds_done++;
129 static void trb_to_noop(union xhci_trb *trb, u32 noop_type)
131 if (trb_is_link(trb)) {
132 /* unchain chained link TRBs */
133 trb->link.control &= cpu_to_le32(~TRB_CHAIN);
135 trb->generic.field[0] = 0;
136 trb->generic.field[1] = 0;
137 trb->generic.field[2] = 0;
138 /* Preserve only the cycle bit of this TRB */
139 trb->generic.field[3] &= cpu_to_le32(TRB_CYCLE);
140 trb->generic.field[3] |= cpu_to_le32(TRB_TYPE(noop_type));
144 /* Updates trb to point to the next TRB in the ring, and updates seg if the next
145 * TRB is in a new segment. This does not skip over link TRBs, and it does not
146 * effect the ring dequeue or enqueue pointers.
148 static void next_trb(struct xhci_hcd *xhci,
149 struct xhci_ring *ring,
150 struct xhci_segment **seg,
151 union xhci_trb **trb)
153 if (trb_is_link(*trb) || last_trb_on_seg(*seg, *trb)) {
155 *trb = ((*seg)->trbs);
162 * See Cycle bit rules. SW is the consumer for the event ring only.
164 void inc_deq(struct xhci_hcd *xhci, struct xhci_ring *ring)
166 unsigned int link_trb_count = 0;
168 /* event ring doesn't have link trbs, check for last trb */
169 if (ring->type == TYPE_EVENT) {
170 if (!last_trb_on_seg(ring->deq_seg, ring->dequeue)) {
174 if (last_trb_on_ring(ring, ring->deq_seg, ring->dequeue))
175 ring->cycle_state ^= 1;
176 ring->deq_seg = ring->deq_seg->next;
177 ring->dequeue = ring->deq_seg->trbs;
181 /* All other rings have link trbs */
182 if (!trb_is_link(ring->dequeue)) {
183 if (last_trb_on_seg(ring->deq_seg, ring->dequeue))
184 xhci_warn(xhci, "Missing link TRB at end of segment\n");
189 while (trb_is_link(ring->dequeue)) {
190 ring->deq_seg = ring->deq_seg->next;
191 ring->dequeue = ring->deq_seg->trbs;
193 if (link_trb_count++ > ring->num_segs) {
194 xhci_warn(xhci, "Ring is an endless link TRB loop\n");
199 trace_xhci_inc_deq(ring);
205 * See Cycle bit rules. SW is the consumer for the event ring only.
207 * If we've just enqueued a TRB that is in the middle of a TD (meaning the
208 * chain bit is set), then set the chain bit in all the following link TRBs.
209 * If we've enqueued the last TRB in a TD, make sure the following link TRBs
210 * have their chain bit cleared (so that each Link TRB is a separate TD).
212 * Section 6.4.4.1 of the 0.95 spec says link TRBs cannot have the chain bit
213 * set, but other sections talk about dealing with the chain bit set. This was
214 * fixed in the 0.96 specification errata, but we have to assume that all 0.95
215 * xHCI hardware can't handle the chain bit being cleared on a link TRB.
217 * @more_trbs_coming: Will you enqueue more TRBs before calling
218 * prepare_transfer()?
220 static void inc_enq(struct xhci_hcd *xhci, struct xhci_ring *ring,
221 bool more_trbs_coming)
224 union xhci_trb *next;
225 unsigned int link_trb_count = 0;
227 chain = le32_to_cpu(ring->enqueue->generic.field[3]) & TRB_CHAIN;
229 if (last_trb_on_seg(ring->enq_seg, ring->enqueue)) {
230 xhci_err(xhci, "Tried to move enqueue past ring segment\n");
234 next = ++(ring->enqueue);
236 /* Update the dequeue pointer further if that was a link TRB */
237 while (trb_is_link(next)) {
240 * If the caller doesn't plan on enqueueing more TDs before
241 * ringing the doorbell, then we don't want to give the link TRB
242 * to the hardware just yet. We'll give the link TRB back in
243 * prepare_ring() just before we enqueue the TD at the top of
246 if (!chain && !more_trbs_coming)
249 /* If we're not dealing with 0.95 hardware or isoc rings on
250 * AMD 0.96 host, carry over the chain bit of the previous TRB
251 * (which may mean the chain bit is cleared).
253 if (!xhci_link_chain_quirk(xhci, ring->type)) {
254 next->link.control &= cpu_to_le32(~TRB_CHAIN);
255 next->link.control |= cpu_to_le32(chain);
257 /* Give this link TRB to the hardware */
259 next->link.control ^= cpu_to_le32(TRB_CYCLE);
261 /* Toggle the cycle bit after the last ring segment. */
262 if (link_trb_toggles_cycle(next))
263 ring->cycle_state ^= 1;
265 ring->enq_seg = ring->enq_seg->next;
266 ring->enqueue = ring->enq_seg->trbs;
267 next = ring->enqueue;
269 if (link_trb_count++ > ring->num_segs) {
270 xhci_warn(xhci, "%s: Ring link TRB loop\n", __func__);
275 trace_xhci_inc_enq(ring);
279 * Return number of free normal TRBs from enqueue to dequeue pointer on ring.
280 * Not counting an assumed link TRB at end of each TRBS_PER_SEGMENT sized segment.
281 * Only for transfer and command rings where driver is the producer, not for
284 static unsigned int xhci_num_trbs_free(struct xhci_ring *ring)
286 struct xhci_segment *enq_seg = ring->enq_seg;
287 union xhci_trb *enq = ring->enqueue;
288 union xhci_trb *last_on_seg;
289 unsigned int free = 0;
292 /* Ring might be empty even if enq != deq if enq is left on a link trb */
293 if (trb_is_link(enq)) {
294 enq_seg = enq_seg->next;
298 /* Empty ring, common case, don't walk the segments */
299 if (enq == ring->dequeue)
300 return ring->num_segs * (TRBS_PER_SEGMENT - 1);
303 if (ring->deq_seg == enq_seg && ring->dequeue >= enq)
304 return free + (ring->dequeue - enq);
305 last_on_seg = &enq_seg->trbs[TRBS_PER_SEGMENT - 1];
306 free += last_on_seg - enq;
307 enq_seg = enq_seg->next;
309 } while (i++ < ring->num_segs);
315 * Check to see if there's room to enqueue num_trbs on the ring and make sure
316 * enqueue pointer will not advance into dequeue segment. See rules above.
317 * return number of new segments needed to ensure this.
320 static unsigned int xhci_ring_expansion_needed(struct xhci_hcd *xhci, struct xhci_ring *ring,
321 unsigned int num_trbs)
323 struct xhci_segment *seg;
328 enq_used = ring->enqueue - ring->enq_seg->trbs;
330 /* how many trbs will be queued past the enqueue segment? */
331 trbs_past_seg = enq_used + num_trbs - (TRBS_PER_SEGMENT - 1);
334 * Consider expanding the ring already if num_trbs fills the current
335 * segment (i.e. trbs_past_seg == 0), not only when num_trbs goes into
336 * the next segment. Avoids confusing full ring with special empty ring
339 if (trbs_past_seg < 0)
342 /* Empty ring special case, enqueue stuck on link trb while dequeue advanced */
343 if (trb_is_link(ring->enqueue) && ring->enq_seg->next->trbs == ring->dequeue)
346 new_segs = 1 + (trbs_past_seg / (TRBS_PER_SEGMENT - 1));
349 while (new_segs > 0) {
351 if (seg == ring->deq_seg) {
352 xhci_dbg(xhci, "Adding %d trbs requires expanding ring by %d segments\n",
362 /* Ring the host controller doorbell after placing a command on the ring */
363 void xhci_ring_cmd_db(struct xhci_hcd *xhci)
365 if (!(xhci->cmd_ring_state & CMD_RING_STATE_RUNNING))
368 xhci_dbg(xhci, "// Ding dong!\n");
370 trace_xhci_ring_host_doorbell(0, DB_VALUE_HOST);
372 writel(DB_VALUE_HOST, &xhci->dba->doorbell[0]);
373 /* Flush PCI posted writes */
374 readl(&xhci->dba->doorbell[0]);
377 static bool xhci_mod_cmd_timer(struct xhci_hcd *xhci)
379 return mod_delayed_work(system_wq, &xhci->cmd_timer,
380 msecs_to_jiffies(xhci->current_cmd->timeout_ms));
383 static struct xhci_command *xhci_next_queued_cmd(struct xhci_hcd *xhci)
385 return list_first_entry_or_null(&xhci->cmd_list, struct xhci_command,
390 * Turn all commands on command ring with status set to "aborted" to no-op trbs.
391 * If there are other commands waiting then restart the ring and kick the timer.
392 * This must be called with command ring stopped and xhci->lock held.
394 static void xhci_handle_stopped_cmd_ring(struct xhci_hcd *xhci,
395 struct xhci_command *cur_cmd)
397 struct xhci_command *i_cmd;
399 /* Turn all aborted commands in list to no-ops, then restart */
400 list_for_each_entry(i_cmd, &xhci->cmd_list, cmd_list) {
402 if (i_cmd->status != COMP_COMMAND_ABORTED)
405 i_cmd->status = COMP_COMMAND_RING_STOPPED;
407 xhci_dbg(xhci, "Turn aborted command %p to no-op\n",
410 trb_to_noop(i_cmd->command_trb, TRB_CMD_NOOP);
413 * caller waiting for completion is called when command
414 * completion event is received for these no-op commands
418 xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
420 /* ring command ring doorbell to restart the command ring */
421 if ((xhci->cmd_ring->dequeue != xhci->cmd_ring->enqueue) &&
422 !(xhci->xhc_state & XHCI_STATE_DYING)) {
423 xhci->current_cmd = cur_cmd;
424 xhci_mod_cmd_timer(xhci);
425 xhci_ring_cmd_db(xhci);
429 /* Must be called with xhci->lock held, releases and aquires lock back */
430 static int xhci_abort_cmd_ring(struct xhci_hcd *xhci, unsigned long flags)
432 struct xhci_segment *new_seg = xhci->cmd_ring->deq_seg;
433 union xhci_trb *new_deq = xhci->cmd_ring->dequeue;
437 xhci_dbg(xhci, "Abort command ring\n");
439 reinit_completion(&xhci->cmd_ring_stop_completion);
442 * The control bits like command stop, abort are located in lower
443 * dword of the command ring control register.
444 * Some controllers require all 64 bits to be written to abort the ring.
445 * Make sure the upper dword is valid, pointing to the next command,
446 * avoiding corrupting the command ring pointer in case the command ring
447 * is stopped by the time the upper dword is written.
449 next_trb(xhci, NULL, &new_seg, &new_deq);
450 if (trb_is_link(new_deq))
451 next_trb(xhci, NULL, &new_seg, &new_deq);
453 crcr = xhci_trb_virt_to_dma(new_seg, new_deq);
454 xhci_write_64(xhci, crcr | CMD_RING_ABORT, &xhci->op_regs->cmd_ring);
456 /* Section 4.6.1.2 of xHCI 1.0 spec says software should also time the
457 * completion of the Command Abort operation. If CRR is not negated in 5
458 * seconds then driver handles it as if host died (-ENODEV).
459 * In the future we should distinguish between -ENODEV and -ETIMEDOUT
460 * and try to recover a -ETIMEDOUT with a host controller reset.
462 ret = xhci_handshake_check_state(xhci, &xhci->op_regs->cmd_ring,
463 CMD_RING_RUNNING, 0, 5 * 1000 * 1000,
464 XHCI_STATE_REMOVING);
466 xhci_err(xhci, "Abort failed to stop command ring: %d\n", ret);
472 * Writing the CMD_RING_ABORT bit should cause a cmd completion event,
473 * however on some host hw the CMD_RING_RUNNING bit is correctly cleared
474 * but the completion event in never sent. Wait 2 secs (arbitrary
475 * number) to handle those cases after negation of CMD_RING_RUNNING.
477 spin_unlock_irqrestore(&xhci->lock, flags);
478 ret = wait_for_completion_timeout(&xhci->cmd_ring_stop_completion,
479 msecs_to_jiffies(2000));
480 spin_lock_irqsave(&xhci->lock, flags);
482 xhci_dbg(xhci, "No stop event for abort, ring start fail?\n");
483 xhci_cleanup_command_queue(xhci);
485 xhci_handle_stopped_cmd_ring(xhci, xhci_next_queued_cmd(xhci));
490 void xhci_ring_ep_doorbell(struct xhci_hcd *xhci,
491 unsigned int slot_id,
492 unsigned int ep_index,
493 unsigned int stream_id)
495 __le32 __iomem *db_addr = &xhci->dba->doorbell[slot_id];
496 struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index];
497 unsigned int ep_state = ep->ep_state;
499 /* Don't ring the doorbell for this endpoint if there are pending
500 * cancellations because we don't want to interrupt processing.
501 * We don't want to restart any stream rings if there's a set dequeue
502 * pointer command pending because the device can choose to start any
503 * stream once the endpoint is on the HW schedule.
505 if ((ep_state & EP_STOP_CMD_PENDING) || (ep_state & SET_DEQ_PENDING) ||
506 (ep_state & EP_HALTED) || (ep_state & EP_CLEARING_TT))
509 trace_xhci_ring_ep_doorbell(slot_id, DB_VALUE(ep_index, stream_id));
511 writel(DB_VALUE(ep_index, stream_id), db_addr);
512 /* flush the write */
516 /* Ring the doorbell for any rings with pending URBs */
517 static void ring_doorbell_for_active_rings(struct xhci_hcd *xhci,
518 unsigned int slot_id,
519 unsigned int ep_index)
521 unsigned int stream_id;
522 struct xhci_virt_ep *ep;
524 ep = &xhci->devs[slot_id]->eps[ep_index];
526 /* A ring has pending URBs if its TD list is not empty */
527 if (!(ep->ep_state & EP_HAS_STREAMS)) {
528 if (ep->ring && !(list_empty(&ep->ring->td_list)))
529 xhci_ring_ep_doorbell(xhci, slot_id, ep_index, 0);
533 for (stream_id = 1; stream_id < ep->stream_info->num_streams;
535 struct xhci_stream_info *stream_info = ep->stream_info;
536 if (!list_empty(&stream_info->stream_rings[stream_id]->td_list))
537 xhci_ring_ep_doorbell(xhci, slot_id, ep_index,
542 void xhci_ring_doorbell_for_active_rings(struct xhci_hcd *xhci,
543 unsigned int slot_id,
544 unsigned int ep_index)
546 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
549 static struct xhci_virt_ep *xhci_get_virt_ep(struct xhci_hcd *xhci,
550 unsigned int slot_id,
551 unsigned int ep_index)
553 if (slot_id == 0 || slot_id >= MAX_HC_SLOTS) {
554 xhci_warn(xhci, "Invalid slot_id %u\n", slot_id);
557 if (ep_index >= EP_CTX_PER_DEV) {
558 xhci_warn(xhci, "Invalid endpoint index %u\n", ep_index);
561 if (!xhci->devs[slot_id]) {
562 xhci_warn(xhci, "No xhci virt device for slot_id %u\n", slot_id);
566 return &xhci->devs[slot_id]->eps[ep_index];
569 static struct xhci_ring *xhci_virt_ep_to_ring(struct xhci_hcd *xhci,
570 struct xhci_virt_ep *ep,
571 unsigned int stream_id)
573 /* common case, no streams */
574 if (!(ep->ep_state & EP_HAS_STREAMS))
577 if (!ep->stream_info)
580 if (stream_id == 0 || stream_id >= ep->stream_info->num_streams) {
581 xhci_warn(xhci, "Invalid stream_id %u request for slot_id %u ep_index %u\n",
582 stream_id, ep->vdev->slot_id, ep->ep_index);
586 return ep->stream_info->stream_rings[stream_id];
589 /* Get the right ring for the given slot_id, ep_index and stream_id.
590 * If the endpoint supports streams, boundary check the URB's stream ID.
591 * If the endpoint doesn't support streams, return the singular endpoint ring.
593 struct xhci_ring *xhci_triad_to_transfer_ring(struct xhci_hcd *xhci,
594 unsigned int slot_id, unsigned int ep_index,
595 unsigned int stream_id)
597 struct xhci_virt_ep *ep;
599 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
603 return xhci_virt_ep_to_ring(xhci, ep, stream_id);
608 * Get the hw dequeue pointer xHC stopped on, either directly from the
609 * endpoint context, or if streams are in use from the stream context.
610 * The returned hw_dequeue contains the lowest four bits with cycle state
611 * and possbile stream context type.
613 static u64 xhci_get_hw_deq(struct xhci_hcd *xhci, struct xhci_virt_device *vdev,
614 unsigned int ep_index, unsigned int stream_id)
616 struct xhci_ep_ctx *ep_ctx;
617 struct xhci_stream_ctx *st_ctx;
618 struct xhci_virt_ep *ep;
620 ep = &vdev->eps[ep_index];
622 if (ep->ep_state & EP_HAS_STREAMS) {
623 st_ctx = &ep->stream_info->stream_ctx_array[stream_id];
624 return le64_to_cpu(st_ctx->stream_ring);
626 ep_ctx = xhci_get_ep_ctx(xhci, vdev->out_ctx, ep_index);
627 return le64_to_cpu(ep_ctx->deq);
630 static int xhci_move_dequeue_past_td(struct xhci_hcd *xhci,
631 unsigned int slot_id, unsigned int ep_index,
632 unsigned int stream_id, struct xhci_td *td)
634 struct xhci_virt_device *dev = xhci->devs[slot_id];
635 struct xhci_virt_ep *ep = &dev->eps[ep_index];
636 struct xhci_ring *ep_ring;
637 struct xhci_command *cmd;
638 struct xhci_segment *new_seg;
639 union xhci_trb *new_deq;
643 bool cycle_found = false;
644 bool td_last_trb_found = false;
648 ep_ring = xhci_triad_to_transfer_ring(xhci, slot_id,
649 ep_index, stream_id);
651 xhci_warn(xhci, "WARN can't find new dequeue, invalid stream ID %u\n",
656 hw_dequeue = xhci_get_hw_deq(xhci, dev, ep_index, stream_id);
657 new_seg = ep_ring->deq_seg;
658 new_deq = ep_ring->dequeue;
659 new_cycle = hw_dequeue & 0x1;
662 * We want to find the pointer, segment and cycle state of the new trb
663 * (the one after current TD's last_trb). We know the cycle state at
664 * hw_dequeue, so walk the ring until both hw_dequeue and last_trb are
668 if (!cycle_found && xhci_trb_virt_to_dma(new_seg, new_deq)
669 == (dma_addr_t)(hw_dequeue & ~0xf)) {
671 if (td_last_trb_found)
674 if (new_deq == td->last_trb)
675 td_last_trb_found = true;
677 if (cycle_found && trb_is_link(new_deq) &&
678 link_trb_toggles_cycle(new_deq))
681 next_trb(xhci, ep_ring, &new_seg, &new_deq);
683 /* Search wrapped around, bail out */
684 if (new_deq == ep->ring->dequeue) {
685 xhci_err(xhci, "Error: Failed finding new dequeue state\n");
689 } while (!cycle_found || !td_last_trb_found);
691 /* Don't update the ring cycle state for the producer (us). */
692 addr = xhci_trb_virt_to_dma(new_seg, new_deq);
694 xhci_warn(xhci, "Can't find dma of new dequeue ptr\n");
695 xhci_warn(xhci, "deq seg = %p, deq ptr = %p\n", new_seg, new_deq);
699 if ((ep->ep_state & SET_DEQ_PENDING)) {
700 xhci_warn(xhci, "Set TR Deq already pending, don't submit for 0x%pad\n",
705 /* This function gets called from contexts where it cannot sleep */
706 cmd = xhci_alloc_command(xhci, false, GFP_ATOMIC);
708 xhci_warn(xhci, "Can't alloc Set TR Deq cmd 0x%pad\n", &addr);
713 trb_sct = SCT_FOR_TRB(SCT_PRI_TR);
714 ret = queue_command(xhci, cmd,
715 lower_32_bits(addr) | trb_sct | new_cycle,
717 STREAM_ID_FOR_TRB(stream_id), SLOT_ID_FOR_TRB(slot_id) |
718 EP_INDEX_FOR_TRB(ep_index) | TRB_TYPE(TRB_SET_DEQ), false);
720 xhci_free_command(xhci, cmd);
723 ep->queued_deq_seg = new_seg;
724 ep->queued_deq_ptr = new_deq;
726 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
727 "Set TR Deq ptr 0x%llx, cycle %u\n", addr, new_cycle);
729 /* Stop the TD queueing code from ringing the doorbell until
730 * this command completes. The HC won't set the dequeue pointer
731 * if the ring is running, and ringing the doorbell starts the
734 ep->ep_state |= SET_DEQ_PENDING;
735 xhci_ring_cmd_db(xhci);
739 /* flip_cycle means flip the cycle bit of all but the first and last TRB.
740 * (The last TRB actually points to the ring enqueue pointer, which is not part
741 * of this TD.) This is used to remove partially enqueued isoc TDs from a ring.
743 static void td_to_noop(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
744 struct xhci_td *td, bool flip_cycle)
746 struct xhci_segment *seg = td->start_seg;
747 union xhci_trb *trb = td->first_trb;
750 trb_to_noop(trb, TRB_TR_NOOP);
752 /* flip cycle if asked to */
753 if (flip_cycle && trb != td->first_trb && trb != td->last_trb)
754 trb->generic.field[3] ^= cpu_to_le32(TRB_CYCLE);
756 if (trb == td->last_trb)
759 next_trb(xhci, ep_ring, &seg, &trb);
763 static void xhci_giveback_urb_in_irq(struct xhci_hcd *xhci,
764 struct xhci_td *cur_td, int status)
766 struct urb *urb = cur_td->urb;
767 struct urb_priv *urb_priv = urb->hcpriv;
768 struct usb_hcd *hcd = bus_to_hcd(urb->dev->bus);
770 if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
771 xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs--;
772 if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) {
773 if (xhci->quirks & XHCI_AMD_PLL_FIX)
774 usb_amd_quirk_pll_enable();
777 xhci_urb_free_priv(urb_priv);
778 usb_hcd_unlink_urb_from_ep(hcd, urb);
779 trace_xhci_urb_giveback(urb);
780 usb_hcd_giveback_urb(hcd, urb, status);
783 static void xhci_unmap_td_bounce_buffer(struct xhci_hcd *xhci,
784 struct xhci_ring *ring, struct xhci_td *td)
786 struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
787 struct xhci_segment *seg = td->bounce_seg;
788 struct urb *urb = td->urb;
791 if (!ring || !seg || !urb)
794 if (usb_urb_dir_out(urb)) {
795 dma_unmap_single(dev, seg->bounce_dma, ring->bounce_buf_len,
800 dma_unmap_single(dev, seg->bounce_dma, ring->bounce_buf_len,
802 /* for in tranfers we need to copy the data from bounce to sg */
804 len = sg_pcopy_from_buffer(urb->sg, urb->num_sgs, seg->bounce_buf,
805 seg->bounce_len, seg->bounce_offs);
806 if (len != seg->bounce_len)
807 xhci_warn(xhci, "WARN Wrong bounce buffer read length: %zu != %d\n",
808 len, seg->bounce_len);
810 memcpy(urb->transfer_buffer + seg->bounce_offs, seg->bounce_buf,
814 seg->bounce_offs = 0;
817 static int xhci_td_cleanup(struct xhci_hcd *xhci, struct xhci_td *td,
818 struct xhci_ring *ep_ring, int status)
820 struct urb *urb = NULL;
822 /* Clean up the endpoint's TD list */
825 /* if a bounce buffer was used to align this td then unmap it */
826 xhci_unmap_td_bounce_buffer(xhci, ep_ring, td);
828 /* Do one last check of the actual transfer length.
829 * If the host controller said we transferred more data than the buffer
830 * length, urb->actual_length will be a very big number (since it's
831 * unsigned). Play it safe and say we didn't transfer anything.
833 if (urb->actual_length > urb->transfer_buffer_length) {
834 xhci_warn(xhci, "URB req %u and actual %u transfer length mismatch\n",
835 urb->transfer_buffer_length, urb->actual_length);
836 urb->actual_length = 0;
839 /* TD might be removed from td_list if we are giving back a cancelled URB */
840 if (!list_empty(&td->td_list))
841 list_del_init(&td->td_list);
842 /* Giving back a cancelled URB, or if a slated TD completed anyway */
843 if (!list_empty(&td->cancelled_td_list))
844 list_del_init(&td->cancelled_td_list);
847 /* Giveback the urb when all the tds are completed */
848 if (last_td_in_urb(td)) {
849 if ((urb->actual_length != urb->transfer_buffer_length &&
850 (urb->transfer_flags & URB_SHORT_NOT_OK)) ||
851 (status != 0 && !usb_endpoint_xfer_isoc(&urb->ep->desc)))
852 xhci_dbg(xhci, "Giveback URB %p, len = %d, expected = %d, status = %d\n",
853 urb, urb->actual_length,
854 urb->transfer_buffer_length, status);
856 /* set isoc urb status to 0 just as EHCI, UHCI, and OHCI */
857 if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS)
859 xhci_giveback_urb_in_irq(xhci, td, status);
866 /* Complete the cancelled URBs we unlinked from td_list. */
867 static void xhci_giveback_invalidated_tds(struct xhci_virt_ep *ep)
869 struct xhci_ring *ring;
870 struct xhci_td *td, *tmp_td;
872 list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list,
875 ring = xhci_urb_to_transfer_ring(ep->xhci, td->urb);
877 if (td->cancel_status == TD_CLEARED) {
878 xhci_dbg(ep->xhci, "%s: Giveback cancelled URB %p TD\n",
880 xhci_td_cleanup(ep->xhci, td, ring, td->status);
882 xhci_dbg(ep->xhci, "%s: Keep cancelled URB %p TD as cancel_status is %d\n",
883 __func__, td->urb, td->cancel_status);
885 if (ep->xhci->xhc_state & XHCI_STATE_DYING)
890 static int xhci_reset_halted_ep(struct xhci_hcd *xhci, unsigned int slot_id,
891 unsigned int ep_index, enum xhci_ep_reset_type reset_type)
893 struct xhci_command *command;
896 command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
902 xhci_dbg(xhci, "%s-reset ep %u, slot %u\n",
903 (reset_type == EP_HARD_RESET) ? "Hard" : "Soft",
906 ret = xhci_queue_reset_ep(xhci, command, slot_id, ep_index, reset_type);
909 xhci_err(xhci, "ERROR queuing reset endpoint for slot %d ep_index %d, %d\n",
910 slot_id, ep_index, ret);
914 static int xhci_handle_halted_endpoint(struct xhci_hcd *xhci,
915 struct xhci_virt_ep *ep,
917 enum xhci_ep_reset_type reset_type)
919 unsigned int slot_id = ep->vdev->slot_id;
923 * Avoid resetting endpoint if link is inactive. Can cause host hang.
924 * Device will be reset soon to recover the link so don't do anything
926 if (ep->vdev->flags & VDEV_PORT_ERROR)
929 /* add td to cancelled list and let reset ep handler take care of it */
930 if (reset_type == EP_HARD_RESET) {
931 ep->ep_state |= EP_HARD_CLEAR_TOGGLE;
932 if (td && list_empty(&td->cancelled_td_list)) {
933 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
934 td->cancel_status = TD_HALTED;
938 if (ep->ep_state & EP_HALTED) {
939 xhci_dbg(xhci, "Reset ep command for ep_index %d already pending\n",
944 err = xhci_reset_halted_ep(xhci, slot_id, ep->ep_index, reset_type);
948 ep->ep_state |= EP_HALTED;
950 xhci_ring_cmd_db(xhci);
956 * Fix up the ep ring first, so HW stops executing cancelled TDs.
957 * We have the xHCI lock, so nothing can modify this list until we drop it.
958 * We're also in the event handler, so we can't get re-interrupted if another
959 * Stop Endpoint command completes.
961 * only call this when ring is not in a running state
964 static int xhci_invalidate_cancelled_tds(struct xhci_virt_ep *ep)
966 struct xhci_hcd *xhci;
967 struct xhci_td *td = NULL;
968 struct xhci_td *tmp_td = NULL;
969 struct xhci_td *cached_td = NULL;
970 struct xhci_ring *ring;
972 unsigned int slot_id = ep->vdev->slot_id;
977 list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list, cancelled_td_list) {
978 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
979 "Removing canceled TD starting at 0x%llx (dma) in stream %u URB %p",
980 (unsigned long long)xhci_trb_virt_to_dma(
981 td->start_seg, td->first_trb),
982 td->urb->stream_id, td->urb);
983 list_del_init(&td->td_list);
984 ring = xhci_urb_to_transfer_ring(xhci, td->urb);
986 xhci_warn(xhci, "WARN Cancelled URB %p has invalid stream ID %u.\n",
987 td->urb, td->urb->stream_id);
991 * If a ring stopped on the TD we need to cancel then we have to
992 * move the xHC endpoint ring dequeue pointer past this TD.
993 * Rings halted due to STALL may show hw_deq is past the stalled
994 * TD, but still require a set TR Deq command to flush xHC cache.
996 hw_deq = xhci_get_hw_deq(xhci, ep->vdev, ep->ep_index,
1000 if (td->cancel_status == TD_HALTED || trb_in_td(xhci, td, hw_deq, false)) {
1001 switch (td->cancel_status) {
1002 case TD_CLEARED: /* TD is already no-op */
1003 case TD_CLEARING_CACHE: /* set TR deq command already queued */
1005 case TD_DIRTY: /* TD is cached, clear it */
1007 case TD_CLEARING_CACHE_DEFERRED:
1009 if (cached_td->urb->stream_id != td->urb->stream_id) {
1010 /* Multiple streams case, defer move dq */
1012 "Move dq deferred: stream %u URB %p\n",
1013 td->urb->stream_id, td->urb);
1014 td->cancel_status = TD_CLEARING_CACHE_DEFERRED;
1018 /* Should never happen, but clear the TD if it does */
1020 "Found multiple active URBs %p and %p in stream %u?\n",
1021 td->urb, cached_td->urb,
1022 td->urb->stream_id);
1023 td_to_noop(xhci, ring, cached_td, false);
1024 cached_td->cancel_status = TD_CLEARED;
1027 td->cancel_status = TD_CLEARING_CACHE;
1032 td_to_noop(xhci, ring, td, false);
1033 td->cancel_status = TD_CLEARED;
1037 /* If there's no need to move the dequeue pointer then we're done */
1041 err = xhci_move_dequeue_past_td(xhci, slot_id, ep->ep_index,
1042 cached_td->urb->stream_id,
1045 /* Failed to move past cached td, just set cached TDs to no-op */
1046 list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list, cancelled_td_list) {
1048 * Deferred TDs need to have the deq pointer set after the above command
1049 * completes, so if that failed we just give up on all of them (and
1050 * complain loudly since this could cause issues due to caching).
1052 if (td->cancel_status != TD_CLEARING_CACHE &&
1053 td->cancel_status != TD_CLEARING_CACHE_DEFERRED)
1055 xhci_warn(xhci, "Failed to clear cancelled cached URB %p, mark clear anyway\n",
1057 td_to_noop(xhci, ring, td, false);
1058 td->cancel_status = TD_CLEARED;
1065 * Returns the TD the endpoint ring halted on.
1066 * Only call for non-running rings without streams.
1068 static struct xhci_td *find_halted_td(struct xhci_virt_ep *ep)
1073 if (!list_empty(&ep->ring->td_list)) { /* Not streams compatible */
1074 hw_deq = xhci_get_hw_deq(ep->xhci, ep->vdev, ep->ep_index, 0);
1076 td = list_first_entry(&ep->ring->td_list, struct xhci_td, td_list);
1077 if (trb_in_td(ep->xhci, td, hw_deq, false))
1084 * When we get a command completion for a Stop Endpoint Command, we need to
1085 * unlink any cancelled TDs from the ring. There are two ways to do that:
1087 * 1. If the HW was in the middle of processing the TD that needs to be
1088 * cancelled, then we must move the ring's dequeue pointer past the last TRB
1089 * in the TD with a Set Dequeue Pointer Command.
1090 * 2. Otherwise, we turn all the TRBs in the TD into No-op TRBs (with the chain
1091 * bit cleared) so that the HW will skip over them.
1093 static void xhci_handle_cmd_stop_ep(struct xhci_hcd *xhci, int slot_id,
1094 union xhci_trb *trb, u32 comp_code)
1096 unsigned int ep_index;
1097 struct xhci_virt_ep *ep;
1098 struct xhci_ep_ctx *ep_ctx;
1099 struct xhci_td *td = NULL;
1100 enum xhci_ep_reset_type reset_type;
1101 struct xhci_command *command;
1104 if (unlikely(TRB_TO_SUSPEND_PORT(le32_to_cpu(trb->generic.field[3])))) {
1105 if (!xhci->devs[slot_id])
1106 xhci_warn(xhci, "Stop endpoint command completion for disabled slot %u\n",
1111 ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1112 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1116 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1118 trace_xhci_handle_cmd_stop_ep(ep_ctx);
1120 if (comp_code == COMP_CONTEXT_STATE_ERROR) {
1122 * If stop endpoint command raced with a halting endpoint we need to
1123 * reset the host side endpoint first.
1124 * If the TD we halted on isn't cancelled the TD should be given back
1125 * with a proper error code, and the ring dequeue moved past the TD.
1126 * If streams case we can't find hw_deq, or the TD we halted on so do a
1129 * Proper error code is unknown here, it would be -EPIPE if device side
1130 * of enadpoit halted (aka STALL), and -EPROTO if not (transaction error)
1131 * We use -EPROTO, if device is stalled it should return a stall error on
1132 * next transfer, which then will return -EPIPE, and device side stall is
1133 * noted and cleared by class driver.
1135 switch (GET_EP_CTX_STATE(ep_ctx)) {
1136 case EP_STATE_HALTED:
1137 xhci_dbg(xhci, "Stop ep completion raced with stall, reset ep\n");
1138 if (ep->ep_state & EP_HAS_STREAMS) {
1139 reset_type = EP_SOFT_RESET;
1141 reset_type = EP_HARD_RESET;
1142 td = find_halted_td(ep);
1144 td->status = -EPROTO;
1146 /* reset ep, reset handler cleans up cancelled tds */
1147 err = xhci_handle_halted_endpoint(xhci, ep, td, reset_type);
1150 ep->ep_state &= ~EP_STOP_CMD_PENDING;
1152 case EP_STATE_STOPPED:
1154 * NEC uPD720200 sometimes sets this state and fails with
1155 * Context Error while continuing to process TRBs.
1156 * Be conservative and trust EP_CTX_STATE on other chips.
1158 if (!(xhci->quirks & XHCI_NEC_HOST))
1161 case EP_STATE_RUNNING:
1162 /* Race, HW handled stop ep cmd before ep was running */
1163 xhci_dbg(xhci, "Stop ep completion ctx error, ep is running\n");
1165 command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
1167 ep->ep_state &= ~EP_STOP_CMD_PENDING;
1170 xhci_queue_stop_endpoint(xhci, command, slot_id, ep_index, 0);
1171 xhci_ring_cmd_db(xhci);
1179 /* will queue a set TR deq if stopped on a cancelled, uncleared TD */
1180 xhci_invalidate_cancelled_tds(ep);
1181 ep->ep_state &= ~EP_STOP_CMD_PENDING;
1183 /* Otherwise ring the doorbell(s) to restart queued transfers */
1184 xhci_giveback_invalidated_tds(ep);
1185 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1188 static void xhci_kill_ring_urbs(struct xhci_hcd *xhci, struct xhci_ring *ring)
1190 struct xhci_td *cur_td;
1191 struct xhci_td *tmp;
1193 list_for_each_entry_safe(cur_td, tmp, &ring->td_list, td_list) {
1194 list_del_init(&cur_td->td_list);
1196 if (!list_empty(&cur_td->cancelled_td_list))
1197 list_del_init(&cur_td->cancelled_td_list);
1199 xhci_unmap_td_bounce_buffer(xhci, ring, cur_td);
1201 inc_td_cnt(cur_td->urb);
1202 if (last_td_in_urb(cur_td))
1203 xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN);
1207 static void xhci_kill_endpoint_urbs(struct xhci_hcd *xhci,
1208 int slot_id, int ep_index)
1210 struct xhci_td *cur_td;
1211 struct xhci_td *tmp;
1212 struct xhci_virt_ep *ep;
1213 struct xhci_ring *ring;
1215 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1219 if ((ep->ep_state & EP_HAS_STREAMS) ||
1220 (ep->ep_state & EP_GETTING_NO_STREAMS)) {
1223 for (stream_id = 1; stream_id < ep->stream_info->num_streams;
1225 ring = ep->stream_info->stream_rings[stream_id];
1229 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1230 "Killing URBs for slot ID %u, ep index %u, stream %u",
1231 slot_id, ep_index, stream_id);
1232 xhci_kill_ring_urbs(xhci, ring);
1238 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1239 "Killing URBs for slot ID %u, ep index %u",
1241 xhci_kill_ring_urbs(xhci, ring);
1244 list_for_each_entry_safe(cur_td, tmp, &ep->cancelled_td_list,
1245 cancelled_td_list) {
1246 list_del_init(&cur_td->cancelled_td_list);
1247 inc_td_cnt(cur_td->urb);
1249 if (last_td_in_urb(cur_td))
1250 xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN);
1255 * host controller died, register read returns 0xffffffff
1256 * Complete pending commands, mark them ABORTED.
1257 * URBs need to be given back as usb core might be waiting with device locks
1258 * held for the URBs to finish during device disconnect, blocking host remove.
1260 * Call with xhci->lock held.
1261 * lock is relased and re-acquired while giving back urb.
1263 void xhci_hc_died(struct xhci_hcd *xhci)
1267 if (xhci->xhc_state & XHCI_STATE_DYING)
1270 xhci_err(xhci, "xHCI host controller not responding, assume dead\n");
1271 xhci->xhc_state |= XHCI_STATE_DYING;
1273 xhci_cleanup_command_queue(xhci);
1275 /* return any pending urbs, remove may be waiting for them */
1276 for (i = 0; i <= HCS_MAX_SLOTS(xhci->hcs_params1); i++) {
1279 for (j = 0; j < 31; j++)
1280 xhci_kill_endpoint_urbs(xhci, i, j);
1283 /* inform usb core hc died if PCI remove isn't already handling it */
1284 if (!(xhci->xhc_state & XHCI_STATE_REMOVING))
1285 usb_hc_died(xhci_to_hcd(xhci));
1288 static void update_ring_for_set_deq_completion(struct xhci_hcd *xhci,
1289 struct xhci_virt_device *dev,
1290 struct xhci_ring *ep_ring,
1291 unsigned int ep_index)
1293 union xhci_trb *dequeue_temp;
1295 dequeue_temp = ep_ring->dequeue;
1297 /* If we get two back-to-back stalls, and the first stalled transfer
1298 * ends just before a link TRB, the dequeue pointer will be left on
1299 * the link TRB by the code in the while loop. So we have to update
1300 * the dequeue pointer one segment further, or we'll jump off
1301 * the segment into la-la-land.
1303 if (trb_is_link(ep_ring->dequeue)) {
1304 ep_ring->deq_seg = ep_ring->deq_seg->next;
1305 ep_ring->dequeue = ep_ring->deq_seg->trbs;
1308 while (ep_ring->dequeue != dev->eps[ep_index].queued_deq_ptr) {
1309 /* We have more usable TRBs */
1311 if (trb_is_link(ep_ring->dequeue)) {
1312 if (ep_ring->dequeue ==
1313 dev->eps[ep_index].queued_deq_ptr)
1315 ep_ring->deq_seg = ep_ring->deq_seg->next;
1316 ep_ring->dequeue = ep_ring->deq_seg->trbs;
1318 if (ep_ring->dequeue == dequeue_temp) {
1319 xhci_dbg(xhci, "Unable to find new dequeue pointer\n");
1326 * When we get a completion for a Set Transfer Ring Dequeue Pointer command,
1327 * we need to clear the set deq pending flag in the endpoint ring state, so that
1328 * the TD queueing code can ring the doorbell again. We also need to ring the
1329 * endpoint doorbell to restart the ring, but only if there aren't more
1330 * cancellations pending.
1332 static void xhci_handle_cmd_set_deq(struct xhci_hcd *xhci, int slot_id,
1333 union xhci_trb *trb, u32 cmd_comp_code)
1335 unsigned int ep_index;
1336 unsigned int stream_id;
1337 struct xhci_ring *ep_ring;
1338 struct xhci_virt_ep *ep;
1339 struct xhci_ep_ctx *ep_ctx;
1340 struct xhci_slot_ctx *slot_ctx;
1341 struct xhci_td *td, *tmp_td;
1342 bool deferred = false;
1344 ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1345 stream_id = TRB_TO_STREAM_ID(le32_to_cpu(trb->generic.field[2]));
1346 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1350 ep_ring = xhci_virt_ep_to_ring(xhci, ep, stream_id);
1352 xhci_warn(xhci, "WARN Set TR deq ptr command for freed stream ID %u\n",
1354 /* XXX: Harmless??? */
1358 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1359 slot_ctx = xhci_get_slot_ctx(xhci, ep->vdev->out_ctx);
1360 trace_xhci_handle_cmd_set_deq(slot_ctx);
1361 trace_xhci_handle_cmd_set_deq_ep(ep_ctx);
1363 if (cmd_comp_code != COMP_SUCCESS) {
1364 unsigned int ep_state;
1365 unsigned int slot_state;
1367 switch (cmd_comp_code) {
1368 case COMP_TRB_ERROR:
1369 xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because of stream ID configuration\n");
1371 case COMP_CONTEXT_STATE_ERROR:
1372 xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due to incorrect slot or ep state.\n");
1373 ep_state = GET_EP_CTX_STATE(ep_ctx);
1374 slot_state = le32_to_cpu(slot_ctx->dev_state);
1375 slot_state = GET_SLOT_STATE(slot_state);
1376 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1377 "Slot state = %u, EP state = %u",
1378 slot_state, ep_state);
1380 case COMP_SLOT_NOT_ENABLED_ERROR:
1381 xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because slot %u was not enabled.\n",
1385 xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown completion code of %u.\n",
1389 /* OK what do we do now? The endpoint state is hosed, and we
1390 * should never get to this point if the synchronization between
1391 * queueing, and endpoint state are correct. This might happen
1392 * if the device gets disconnected after we've finished
1393 * cancelling URBs, which might not be an error...
1397 /* 4.6.10 deq ptr is written to the stream ctx for streams */
1398 if (ep->ep_state & EP_HAS_STREAMS) {
1399 struct xhci_stream_ctx *ctx =
1400 &ep->stream_info->stream_ctx_array[stream_id];
1401 deq = le64_to_cpu(ctx->stream_ring) & SCTX_DEQ_MASK;
1403 deq = le64_to_cpu(ep_ctx->deq) & ~EP_CTX_CYCLE_MASK;
1405 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1406 "Successful Set TR Deq Ptr cmd, deq = @%08llx", deq);
1407 if (xhci_trb_virt_to_dma(ep->queued_deq_seg,
1408 ep->queued_deq_ptr) == deq) {
1409 /* Update the ring's dequeue segment and dequeue pointer
1410 * to reflect the new position.
1412 update_ring_for_set_deq_completion(xhci, ep->vdev,
1415 xhci_warn(xhci, "Mismatch between completed Set TR Deq Ptr command & xHCI internal state.\n");
1416 xhci_warn(xhci, "ep deq seg = %p, deq ptr = %p\n",
1417 ep->queued_deq_seg, ep->queued_deq_ptr);
1420 /* HW cached TDs cleared from cache, give them back */
1421 list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list,
1422 cancelled_td_list) {
1423 ep_ring = xhci_urb_to_transfer_ring(ep->xhci, td->urb);
1424 if (td->cancel_status == TD_CLEARING_CACHE) {
1425 td->cancel_status = TD_CLEARED;
1426 xhci_dbg(ep->xhci, "%s: Giveback cancelled URB %p TD\n",
1428 xhci_td_cleanup(ep->xhci, td, ep_ring, td->status);
1429 } else if (td->cancel_status == TD_CLEARING_CACHE_DEFERRED) {
1432 xhci_dbg(ep->xhci, "%s: Keep cancelled URB %p TD as cancel_status is %d\n",
1433 __func__, td->urb, td->cancel_status);
1437 ep->ep_state &= ~SET_DEQ_PENDING;
1438 ep->queued_deq_seg = NULL;
1439 ep->queued_deq_ptr = NULL;
1442 /* We have more streams to clear */
1443 xhci_dbg(ep->xhci, "%s: Pending TDs to clear, continuing with invalidation\n",
1445 xhci_invalidate_cancelled_tds(ep);
1447 /* Restart any rings with pending URBs */
1448 xhci_dbg(ep->xhci, "%s: All TDs cleared, ring doorbell\n", __func__);
1449 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1453 static void xhci_handle_cmd_reset_ep(struct xhci_hcd *xhci, int slot_id,
1454 union xhci_trb *trb, u32 cmd_comp_code)
1456 struct xhci_virt_ep *ep;
1457 struct xhci_ep_ctx *ep_ctx;
1458 unsigned int ep_index;
1460 ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1461 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1465 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1466 trace_xhci_handle_cmd_reset_ep(ep_ctx);
1468 /* This command will only fail if the endpoint wasn't halted,
1469 * but we don't care.
1471 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
1472 "Ignoring reset ep completion code of %u", cmd_comp_code);
1474 /* Cleanup cancelled TDs as ep is stopped. May queue a Set TR Deq cmd */
1475 xhci_invalidate_cancelled_tds(ep);
1477 /* Clear our internal halted state */
1478 ep->ep_state &= ~EP_HALTED;
1480 xhci_giveback_invalidated_tds(ep);
1482 /* if this was a soft reset, then restart */
1483 if ((le32_to_cpu(trb->generic.field[3])) & TRB_TSP)
1484 ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1487 static void xhci_handle_cmd_enable_slot(int slot_id, struct xhci_command *command,
1490 if (cmd_comp_code == COMP_SUCCESS)
1491 command->slot_id = slot_id;
1493 command->slot_id = 0;
1496 static void xhci_handle_cmd_disable_slot(struct xhci_hcd *xhci, int slot_id)
1498 struct xhci_virt_device *virt_dev;
1499 struct xhci_slot_ctx *slot_ctx;
1501 virt_dev = xhci->devs[slot_id];
1505 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
1506 trace_xhci_handle_cmd_disable_slot(slot_ctx);
1508 if (xhci->quirks & XHCI_EP_LIMIT_QUIRK)
1509 /* Delete default control endpoint resources */
1510 xhci_free_device_endpoint_resources(xhci, virt_dev, true);
1513 static void xhci_handle_cmd_config_ep(struct xhci_hcd *xhci, int slot_id)
1515 struct xhci_virt_device *virt_dev;
1516 struct xhci_input_control_ctx *ctrl_ctx;
1517 struct xhci_ep_ctx *ep_ctx;
1518 unsigned int ep_index;
1522 * Configure endpoint commands can come from the USB core configuration
1523 * or alt setting changes, or when streams were being configured.
1526 virt_dev = xhci->devs[slot_id];
1529 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1531 xhci_warn(xhci, "Could not get input context, bad type.\n");
1535 add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1537 /* Input ctx add_flags are the endpoint index plus one */
1538 ep_index = xhci_last_valid_endpoint(add_flags) - 1;
1540 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->out_ctx, ep_index);
1541 trace_xhci_handle_cmd_config_ep(ep_ctx);
1546 static void xhci_handle_cmd_addr_dev(struct xhci_hcd *xhci, int slot_id)
1548 struct xhci_virt_device *vdev;
1549 struct xhci_slot_ctx *slot_ctx;
1551 vdev = xhci->devs[slot_id];
1554 slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
1555 trace_xhci_handle_cmd_addr_dev(slot_ctx);
1558 static void xhci_handle_cmd_reset_dev(struct xhci_hcd *xhci, int slot_id)
1560 struct xhci_virt_device *vdev;
1561 struct xhci_slot_ctx *slot_ctx;
1563 vdev = xhci->devs[slot_id];
1565 xhci_warn(xhci, "Reset device command completion for disabled slot %u\n",
1569 slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
1570 trace_xhci_handle_cmd_reset_dev(slot_ctx);
1572 xhci_dbg(xhci, "Completed reset device command.\n");
1575 static void xhci_handle_cmd_nec_get_fw(struct xhci_hcd *xhci,
1576 struct xhci_event_cmd *event)
1578 if (!(xhci->quirks & XHCI_NEC_HOST)) {
1579 xhci_warn(xhci, "WARN NEC_GET_FW command on non-NEC host\n");
1582 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1583 "NEC firmware version %2x.%02x",
1584 NEC_FW_MAJOR(le32_to_cpu(event->status)),
1585 NEC_FW_MINOR(le32_to_cpu(event->status)));
1588 static void xhci_complete_del_and_free_cmd(struct xhci_command *cmd, u32 status)
1590 list_del(&cmd->cmd_list);
1592 if (cmd->completion) {
1593 cmd->status = status;
1594 complete(cmd->completion);
1600 void xhci_cleanup_command_queue(struct xhci_hcd *xhci)
1602 struct xhci_command *cur_cmd, *tmp_cmd;
1603 xhci->current_cmd = NULL;
1604 list_for_each_entry_safe(cur_cmd, tmp_cmd, &xhci->cmd_list, cmd_list)
1605 xhci_complete_del_and_free_cmd(cur_cmd, COMP_COMMAND_ABORTED);
1608 void xhci_handle_command_timeout(struct work_struct *work)
1610 struct xhci_hcd *xhci;
1611 unsigned long flags;
1612 char str[XHCI_MSG_MAX];
1617 xhci = container_of(to_delayed_work(work), struct xhci_hcd, cmd_timer);
1619 spin_lock_irqsave(&xhci->lock, flags);
1622 * If timeout work is pending, or current_cmd is NULL, it means we
1623 * raced with command completion. Command is handled so just return.
1625 if (!xhci->current_cmd || delayed_work_pending(&xhci->cmd_timer)) {
1626 spin_unlock_irqrestore(&xhci->lock, flags);
1630 cmd_field3 = le32_to_cpu(xhci->current_cmd->command_trb->generic.field[3]);
1631 usbsts = readl(&xhci->op_regs->status);
1632 xhci_dbg(xhci, "Command timeout, USBSTS:%s\n", xhci_decode_usbsts(str, usbsts));
1634 /* Bail out and tear down xhci if a stop endpoint command failed */
1635 if (TRB_FIELD_TO_TYPE(cmd_field3) == TRB_STOP_RING) {
1636 struct xhci_virt_ep *ep;
1638 xhci_warn(xhci, "xHCI host not responding to stop endpoint command\n");
1640 ep = xhci_get_virt_ep(xhci, TRB_TO_SLOT_ID(cmd_field3),
1641 TRB_TO_EP_INDEX(cmd_field3));
1643 ep->ep_state &= ~EP_STOP_CMD_PENDING;
1647 goto time_out_completed;
1650 /* mark this command to be cancelled */
1651 xhci->current_cmd->status = COMP_COMMAND_ABORTED;
1653 /* Make sure command ring is running before aborting it */
1654 hw_ring_state = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
1655 if (hw_ring_state == ~(u64)0) {
1657 goto time_out_completed;
1660 if ((xhci->cmd_ring_state & CMD_RING_STATE_RUNNING) &&
1661 (hw_ring_state & CMD_RING_RUNNING)) {
1662 /* Prevent new doorbell, and start command abort */
1663 xhci->cmd_ring_state = CMD_RING_STATE_ABORTED;
1664 xhci_dbg(xhci, "Command timeout\n");
1665 xhci_abort_cmd_ring(xhci, flags);
1666 goto time_out_completed;
1669 /* host removed. Bail out */
1670 if (xhci->xhc_state & XHCI_STATE_REMOVING) {
1671 xhci_dbg(xhci, "host removed, ring start fail?\n");
1672 xhci_cleanup_command_queue(xhci);
1674 goto time_out_completed;
1677 /* command timeout on stopped ring, ring can't be aborted */
1678 xhci_dbg(xhci, "Command timeout on stopped ring\n");
1679 xhci_handle_stopped_cmd_ring(xhci, xhci->current_cmd);
1682 spin_unlock_irqrestore(&xhci->lock, flags);
1686 static void handle_cmd_completion(struct xhci_hcd *xhci,
1687 struct xhci_event_cmd *event)
1689 unsigned int slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
1691 dma_addr_t cmd_dequeue_dma;
1693 union xhci_trb *cmd_trb;
1694 struct xhci_command *cmd;
1697 if (slot_id >= MAX_HC_SLOTS) {
1698 xhci_warn(xhci, "Invalid slot_id %u\n", slot_id);
1702 cmd_dma = le64_to_cpu(event->cmd_trb);
1703 cmd_trb = xhci->cmd_ring->dequeue;
1705 trace_xhci_handle_command(xhci->cmd_ring, &cmd_trb->generic);
1707 cmd_dequeue_dma = xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
1710 * Check whether the completion event is for our internal kept
1713 if (!cmd_dequeue_dma || cmd_dma != (u64)cmd_dequeue_dma) {
1715 "ERROR mismatched command completion event\n");
1719 cmd = list_first_entry(&xhci->cmd_list, struct xhci_command, cmd_list);
1721 cancel_delayed_work(&xhci->cmd_timer);
1723 cmd_comp_code = GET_COMP_CODE(le32_to_cpu(event->status));
1725 /* If CMD ring stopped we own the trbs between enqueue and dequeue */
1726 if (cmd_comp_code == COMP_COMMAND_RING_STOPPED) {
1727 complete_all(&xhci->cmd_ring_stop_completion);
1731 if (cmd->command_trb != xhci->cmd_ring->dequeue) {
1733 "Command completion event does not match command\n");
1738 * Host aborted the command ring, check if the current command was
1739 * supposed to be aborted, otherwise continue normally.
1740 * The command ring is stopped now, but the xHC will issue a Command
1741 * Ring Stopped event which will cause us to restart it.
1743 if (cmd_comp_code == COMP_COMMAND_ABORTED) {
1744 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
1745 if (cmd->status == COMP_COMMAND_ABORTED) {
1746 if (xhci->current_cmd == cmd)
1747 xhci->current_cmd = NULL;
1752 cmd_type = TRB_FIELD_TO_TYPE(le32_to_cpu(cmd_trb->generic.field[3]));
1754 case TRB_ENABLE_SLOT:
1755 xhci_handle_cmd_enable_slot(slot_id, cmd, cmd_comp_code);
1757 case TRB_DISABLE_SLOT:
1758 xhci_handle_cmd_disable_slot(xhci, slot_id);
1761 if (!cmd->completion)
1762 xhci_handle_cmd_config_ep(xhci, slot_id);
1764 case TRB_EVAL_CONTEXT:
1767 xhci_handle_cmd_addr_dev(xhci, slot_id);
1770 WARN_ON(slot_id != TRB_TO_SLOT_ID(
1771 le32_to_cpu(cmd_trb->generic.field[3])));
1772 if (!cmd->completion)
1773 xhci_handle_cmd_stop_ep(xhci, slot_id, cmd_trb,
1777 WARN_ON(slot_id != TRB_TO_SLOT_ID(
1778 le32_to_cpu(cmd_trb->generic.field[3])));
1779 xhci_handle_cmd_set_deq(xhci, slot_id, cmd_trb, cmd_comp_code);
1782 /* Is this an aborted command turned to NO-OP? */
1783 if (cmd->status == COMP_COMMAND_RING_STOPPED)
1784 cmd_comp_code = COMP_COMMAND_RING_STOPPED;
1787 WARN_ON(slot_id != TRB_TO_SLOT_ID(
1788 le32_to_cpu(cmd_trb->generic.field[3])));
1789 xhci_handle_cmd_reset_ep(xhci, slot_id, cmd_trb, cmd_comp_code);
1792 /* SLOT_ID field in reset device cmd completion event TRB is 0.
1793 * Use the SLOT_ID from the command TRB instead (xhci 4.6.11)
1795 slot_id = TRB_TO_SLOT_ID(
1796 le32_to_cpu(cmd_trb->generic.field[3]));
1797 xhci_handle_cmd_reset_dev(xhci, slot_id);
1799 case TRB_NEC_GET_FW:
1800 xhci_handle_cmd_nec_get_fw(xhci, event);
1803 /* Skip over unknown commands on the event ring */
1804 xhci_info(xhci, "INFO unknown command type %d\n", cmd_type);
1808 /* restart timer if this wasn't the last command */
1809 if (!list_is_singular(&xhci->cmd_list)) {
1810 xhci->current_cmd = list_first_entry(&cmd->cmd_list,
1811 struct xhci_command, cmd_list);
1812 xhci_mod_cmd_timer(xhci);
1813 } else if (xhci->current_cmd == cmd) {
1814 xhci->current_cmd = NULL;
1818 xhci_complete_del_and_free_cmd(cmd, cmd_comp_code);
1820 inc_deq(xhci, xhci->cmd_ring);
1823 static void handle_vendor_event(struct xhci_hcd *xhci,
1824 union xhci_trb *event, u32 trb_type)
1826 xhci_dbg(xhci, "Vendor specific event TRB type = %u\n", trb_type);
1827 if (trb_type == TRB_NEC_CMD_COMP && (xhci->quirks & XHCI_NEC_HOST))
1828 handle_cmd_completion(xhci, &event->event_cmd);
1831 static void handle_device_notification(struct xhci_hcd *xhci,
1832 union xhci_trb *event)
1835 struct usb_device *udev;
1837 slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->generic.field[3]));
1838 if (!xhci->devs[slot_id]) {
1839 xhci_warn(xhci, "Device Notification event for "
1840 "unused slot %u\n", slot_id);
1844 xhci_dbg(xhci, "Device Wake Notification event for slot ID %u\n",
1846 udev = xhci->devs[slot_id]->udev;
1847 if (udev && udev->parent)
1848 usb_wakeup_notification(udev->parent, udev->portnum);
1852 * Quirk hanlder for errata seen on Cavium ThunderX2 processor XHCI
1854 * As per ThunderX2errata-129 USB 2 device may come up as USB 1
1855 * If a connection to a USB 1 device is followed by another connection
1856 * to a USB 2 device.
1858 * Reset the PHY after the USB device is disconnected if device speed
1859 * is less than HCD_USB3.
1860 * Retry the reset sequence max of 4 times checking the PLL lock status.
1863 static void xhci_cavium_reset_phy_quirk(struct xhci_hcd *xhci)
1865 struct usb_hcd *hcd = xhci_to_hcd(xhci);
1867 u32 retry_count = 4;
1870 /* Assert PHY reset */
1871 writel(0x6F, hcd->regs + 0x1048);
1873 /* De-assert the PHY reset */
1874 writel(0x7F, hcd->regs + 0x1048);
1876 pll_lock_check = readl(hcd->regs + 0x1070);
1877 } while (!(pll_lock_check & 0x1) && --retry_count);
1880 static void handle_port_status(struct xhci_hcd *xhci, union xhci_trb *event)
1882 struct usb_hcd *hcd;
1884 u32 portsc, cmd_reg;
1886 unsigned int hcd_portnum;
1887 struct xhci_bus_state *bus_state;
1888 bool bogus_port_status = false;
1889 struct xhci_port *port;
1891 /* Port status change events always have a successful completion code */
1892 if (GET_COMP_CODE(le32_to_cpu(event->generic.field[2])) != COMP_SUCCESS)
1894 "WARN: xHC returned failed port status event\n");
1896 port_id = GET_PORT_ID(le32_to_cpu(event->generic.field[0]));
1897 max_ports = HCS_MAX_PORTS(xhci->hcs_params1);
1899 if ((port_id <= 0) || (port_id > max_ports)) {
1900 xhci_warn(xhci, "Port change event with invalid port ID %d\n",
1905 port = &xhci->hw_ports[port_id - 1];
1906 if (!port || !port->rhub || port->hcd_portnum == DUPLICATE_ENTRY) {
1907 xhci_warn(xhci, "Port change event, no port for port ID %u\n",
1909 bogus_port_status = true;
1913 /* We might get interrupts after shared_hcd is removed */
1914 if (port->rhub == &xhci->usb3_rhub && xhci->shared_hcd == NULL) {
1915 xhci_dbg(xhci, "ignore port event for removed USB3 hcd\n");
1916 bogus_port_status = true;
1920 hcd = port->rhub->hcd;
1921 bus_state = &port->rhub->bus_state;
1922 hcd_portnum = port->hcd_portnum;
1923 portsc = readl(port->addr);
1925 xhci_dbg(xhci, "Port change event, %d-%d, id %d, portsc: 0x%x\n",
1926 hcd->self.busnum, hcd_portnum + 1, port_id, portsc);
1928 trace_xhci_handle_port_status(port, portsc);
1930 if (hcd->state == HC_STATE_SUSPENDED) {
1931 xhci_dbg(xhci, "resume root hub\n");
1932 usb_hcd_resume_root_hub(hcd);
1935 if (hcd->speed >= HCD_USB3 &&
1936 (portsc & PORT_PLS_MASK) == XDEV_INACTIVE) {
1937 if (port->slot_id && xhci->devs[port->slot_id])
1938 xhci->devs[port->slot_id]->flags |= VDEV_PORT_ERROR;
1941 if ((portsc & PORT_PLC) && (portsc & PORT_PLS_MASK) == XDEV_RESUME) {
1942 xhci_dbg(xhci, "port resume event for port %d\n", port_id);
1944 cmd_reg = readl(&xhci->op_regs->command);
1945 if (!(cmd_reg & CMD_RUN)) {
1946 xhci_warn(xhci, "xHC is not running.\n");
1950 if (DEV_SUPERSPEED_ANY(portsc)) {
1951 xhci_dbg(xhci, "remote wake SS port %d\n", port_id);
1952 /* Set a flag to say the port signaled remote wakeup,
1953 * so we can tell the difference between the end of
1954 * device and host initiated resume.
1956 bus_state->port_remote_wakeup |= 1 << hcd_portnum;
1957 xhci_test_and_clear_bit(xhci, port, PORT_PLC);
1958 usb_hcd_start_port_resume(&hcd->self, hcd_portnum);
1959 xhci_set_link_state(xhci, port, XDEV_U0);
1960 /* Need to wait until the next link state change
1961 * indicates the device is actually in U0.
1963 bogus_port_status = true;
1965 } else if (!test_bit(hcd_portnum, &bus_state->resuming_ports)) {
1966 xhci_dbg(xhci, "resume HS port %d\n", port_id);
1967 port->resume_timestamp = jiffies +
1968 msecs_to_jiffies(USB_RESUME_TIMEOUT);
1969 set_bit(hcd_portnum, &bus_state->resuming_ports);
1970 /* Do the rest in GetPortStatus after resume time delay.
1971 * Avoid polling roothub status before that so that a
1972 * usb device auto-resume latency around ~40ms.
1974 set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1975 mod_timer(&hcd->rh_timer,
1976 port->resume_timestamp);
1977 usb_hcd_start_port_resume(&hcd->self, hcd_portnum);
1978 bogus_port_status = true;
1982 if ((portsc & PORT_PLC) &&
1983 DEV_SUPERSPEED_ANY(portsc) &&
1984 ((portsc & PORT_PLS_MASK) == XDEV_U0 ||
1985 (portsc & PORT_PLS_MASK) == XDEV_U1 ||
1986 (portsc & PORT_PLS_MASK) == XDEV_U2)) {
1987 xhci_dbg(xhci, "resume SS port %d finished\n", port_id);
1988 complete(&port->u3exit_done);
1989 /* We've just brought the device into U0/1/2 through either the
1990 * Resume state after a device remote wakeup, or through the
1991 * U3Exit state after a host-initiated resume. If it's a device
1992 * initiated remote wake, don't pass up the link state change,
1993 * so the roothub behavior is consistent with external
1994 * USB 3.0 hub behavior.
1996 if (port->slot_id && xhci->devs[port->slot_id])
1997 xhci_ring_device(xhci, port->slot_id);
1998 if (bus_state->port_remote_wakeup & (1 << hcd_portnum)) {
1999 xhci_test_and_clear_bit(xhci, port, PORT_PLC);
2000 usb_wakeup_notification(hcd->self.root_hub,
2002 bogus_port_status = true;
2008 * Check to see if xhci-hub.c is waiting on RExit to U0 transition (or
2009 * RExit to a disconnect state). If so, let the driver know it's
2010 * out of the RExit state.
2012 if (hcd->speed < HCD_USB3 && port->rexit_active) {
2013 complete(&port->rexit_done);
2014 port->rexit_active = false;
2015 bogus_port_status = true;
2019 if (hcd->speed < HCD_USB3) {
2020 xhci_test_and_clear_bit(xhci, port, PORT_PLC);
2021 if ((xhci->quirks & XHCI_RESET_PLL_ON_DISCONNECT) &&
2022 (portsc & PORT_CSC) && !(portsc & PORT_CONNECT))
2023 xhci_cavium_reset_phy_quirk(xhci);
2028 /* Don't make the USB core poll the roothub if we got a bad port status
2029 * change event. Besides, at that point we can't tell which roothub
2030 * (USB 2.0 or USB 3.0) to kick.
2032 if (bogus_port_status)
2036 * xHCI port-status-change events occur when the "or" of all the
2037 * status-change bits in the portsc register changes from 0 to 1.
2038 * New status changes won't cause an event if any other change
2039 * bits are still set. When an event occurs, switch over to
2040 * polling to avoid losing status changes.
2042 xhci_dbg(xhci, "%s: starting usb%d port polling.\n",
2043 __func__, hcd->self.busnum);
2044 set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2045 spin_unlock(&xhci->lock);
2046 /* Pass this up to the core */
2047 usb_hcd_poll_rh_status(hcd);
2048 spin_lock(&xhci->lock);
2052 * If the suspect DMA address is a TRB in this TD, this function returns that
2053 * TRB's segment. Otherwise it returns 0.
2055 struct xhci_segment *trb_in_td(struct xhci_hcd *xhci, struct xhci_td *td, dma_addr_t suspect_dma,
2058 dma_addr_t start_dma;
2059 dma_addr_t end_seg_dma;
2060 dma_addr_t end_trb_dma;
2061 struct xhci_segment *cur_seg;
2063 start_dma = xhci_trb_virt_to_dma(td->start_seg, td->first_trb);
2064 cur_seg = td->start_seg;
2069 /* We may get an event for a Link TRB in the middle of a TD */
2070 end_seg_dma = xhci_trb_virt_to_dma(cur_seg,
2071 &cur_seg->trbs[TRBS_PER_SEGMENT - 1]);
2072 /* If the end TRB isn't in this segment, this is set to 0 */
2073 end_trb_dma = xhci_trb_virt_to_dma(cur_seg, td->last_trb);
2077 "Looking for event-dma %016llx trb-start %016llx trb-end %016llx seg-start %016llx seg-end %016llx\n",
2078 (unsigned long long)suspect_dma,
2079 (unsigned long long)start_dma,
2080 (unsigned long long)end_trb_dma,
2081 (unsigned long long)cur_seg->dma,
2082 (unsigned long long)end_seg_dma);
2084 if (end_trb_dma > 0) {
2085 /* The end TRB is in this segment, so suspect should be here */
2086 if (start_dma <= end_trb_dma) {
2087 if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma)
2090 /* Case for one segment with
2091 * a TD wrapped around to the top
2093 if ((suspect_dma >= start_dma &&
2094 suspect_dma <= end_seg_dma) ||
2095 (suspect_dma >= cur_seg->dma &&
2096 suspect_dma <= end_trb_dma))
2101 /* Might still be somewhere in this segment */
2102 if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma)
2105 cur_seg = cur_seg->next;
2106 start_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[0]);
2107 } while (cur_seg != td->start_seg);
2112 static void xhci_clear_hub_tt_buffer(struct xhci_hcd *xhci, struct xhci_td *td,
2113 struct xhci_virt_ep *ep)
2116 * As part of low/full-speed endpoint-halt processing
2117 * we must clear the TT buffer (USB 2.0 specification 11.17.5).
2119 if (td->urb->dev->tt && !usb_pipeint(td->urb->pipe) &&
2120 (td->urb->dev->tt->hub != xhci_to_hcd(xhci)->self.root_hub) &&
2121 !(ep->ep_state & EP_CLEARING_TT)) {
2122 ep->ep_state |= EP_CLEARING_TT;
2123 td->urb->ep->hcpriv = td->urb->dev;
2124 if (usb_hub_clear_tt_buffer(td->urb))
2125 ep->ep_state &= ~EP_CLEARING_TT;
2130 * Check if xhci internal endpoint state has gone to a "halt" state due to an
2131 * error or stall, including default control pipe protocol stall.
2132 * The internal halt needs to be cleared with a reset endpoint command.
2134 * External device side is also halted in functional stall cases. Class driver
2135 * will clear the device halt with a CLEAR_FEATURE(ENDPOINT_HALT) request later.
2137 static bool xhci_halted_host_endpoint(struct xhci_ep_ctx *ep_ctx, unsigned int comp_code)
2139 /* Stall halts both internal and device side endpoint */
2140 if (comp_code == COMP_STALL_ERROR)
2143 /* TRB completion codes that may require internal halt cleanup */
2144 if (comp_code == COMP_USB_TRANSACTION_ERROR ||
2145 comp_code == COMP_BABBLE_DETECTED_ERROR ||
2146 comp_code == COMP_SPLIT_TRANSACTION_ERROR)
2148 * The 0.95 spec says a babbling control endpoint is not halted.
2149 * The 0.96 spec says it is. Some HW claims to be 0.95
2150 * compliant, but it halts the control endpoint anyway.
2151 * Check endpoint context if endpoint is halted.
2153 if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_HALTED)
2159 int xhci_is_vendor_info_code(struct xhci_hcd *xhci, unsigned int trb_comp_code)
2161 if (trb_comp_code >= 224 && trb_comp_code <= 255) {
2162 /* Vendor defined "informational" completion code,
2163 * treat as not-an-error.
2165 xhci_dbg(xhci, "Vendor defined info completion code %u\n",
2167 xhci_dbg(xhci, "Treating code as success.\n");
2173 static int finish_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2174 struct xhci_ring *ep_ring, struct xhci_td *td,
2177 struct xhci_ep_ctx *ep_ctx;
2179 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep->ep_index);
2181 switch (trb_comp_code) {
2182 case COMP_STOPPED_LENGTH_INVALID:
2183 case COMP_STOPPED_SHORT_PACKET:
2186 * The "Stop Endpoint" completion will take care of any
2187 * stopped TDs. A stopped TD may be restarted, so don't update
2188 * the ring dequeue pointer or take this TD off any lists yet.
2191 case COMP_USB_TRANSACTION_ERROR:
2192 case COMP_BABBLE_DETECTED_ERROR:
2193 case COMP_SPLIT_TRANSACTION_ERROR:
2195 * If endpoint context state is not halted we might be
2196 * racing with a reset endpoint command issued by a unsuccessful
2197 * stop endpoint completion (context error). In that case the
2198 * td should be on the cancelled list, and EP_HALTED flag set.
2200 * Or then it's not halted due to the 0.95 spec stating that a
2201 * babbling control endpoint should not halt. The 0.96 spec
2202 * again says it should. Some HW claims to be 0.95 compliant,
2203 * but it halts the control endpoint anyway.
2205 if (GET_EP_CTX_STATE(ep_ctx) != EP_STATE_HALTED) {
2207 * If EP_HALTED is set and TD is on the cancelled list
2208 * the TD and dequeue pointer will be handled by reset
2209 * ep command completion
2211 if ((ep->ep_state & EP_HALTED) &&
2212 !list_empty(&td->cancelled_td_list)) {
2213 xhci_dbg(xhci, "Already resolving halted ep for 0x%llx\n",
2214 (unsigned long long)xhci_trb_virt_to_dma(
2215 td->start_seg, td->first_trb));
2218 /* endpoint not halted, don't reset it */
2221 /* Almost same procedure as for STALL_ERROR below */
2222 xhci_clear_hub_tt_buffer(xhci, td, ep);
2223 xhci_handle_halted_endpoint(xhci, ep, td, EP_HARD_RESET);
2225 case COMP_STALL_ERROR:
2227 * xhci internal endpoint state will go to a "halt" state for
2228 * any stall, including default control pipe protocol stall.
2229 * To clear the host side halt we need to issue a reset endpoint
2230 * command, followed by a set dequeue command to move past the
2232 * Class drivers clear the device side halt from a functional
2233 * stall later. Hub TT buffer should only be cleared for FS/LS
2234 * devices behind HS hubs for functional stalls.
2236 if (ep->ep_index != 0)
2237 xhci_clear_hub_tt_buffer(xhci, td, ep);
2239 xhci_handle_halted_endpoint(xhci, ep, td, EP_HARD_RESET);
2241 return 0; /* xhci_handle_halted_endpoint marked td cancelled */
2246 /* Update ring dequeue pointer */
2247 ep_ring->dequeue = td->last_trb;
2248 ep_ring->deq_seg = td->last_trb_seg;
2249 inc_deq(xhci, ep_ring);
2251 return xhci_td_cleanup(xhci, td, ep_ring, td->status);
2254 /* sum trb lengths from ring dequeue up to stop_trb, _excluding_ stop_trb */
2255 static int sum_trb_lengths(struct xhci_hcd *xhci, struct xhci_ring *ring,
2256 union xhci_trb *stop_trb)
2259 union xhci_trb *trb = ring->dequeue;
2260 struct xhci_segment *seg = ring->deq_seg;
2262 for (sum = 0; trb != stop_trb; next_trb(xhci, ring, &seg, &trb)) {
2263 if (!trb_is_noop(trb) && !trb_is_link(trb))
2264 sum += TRB_LEN(le32_to_cpu(trb->generic.field[2]));
2270 * Process control tds, update urb status and actual_length.
2272 static int process_ctrl_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2273 struct xhci_ring *ep_ring, struct xhci_td *td,
2274 union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2276 struct xhci_ep_ctx *ep_ctx;
2278 u32 remaining, requested;
2281 trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(ep_trb->generic.field[3]));
2282 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep->ep_index);
2283 trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2284 requested = td->urb->transfer_buffer_length;
2285 remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2287 switch (trb_comp_code) {
2289 if (trb_type != TRB_STATUS) {
2290 xhci_warn(xhci, "WARN: Success on ctrl %s TRB without IOC set?\n",
2291 (trb_type == TRB_DATA) ? "data" : "setup");
2292 td->status = -ESHUTDOWN;
2297 case COMP_SHORT_PACKET:
2300 case COMP_STOPPED_SHORT_PACKET:
2301 if (trb_type == TRB_DATA || trb_type == TRB_NORMAL)
2302 td->urb->actual_length = remaining;
2304 xhci_warn(xhci, "WARN: Stopped Short Packet on ctrl setup or status TRB\n");
2309 td->urb->actual_length = 0;
2313 td->urb->actual_length = requested - remaining;
2316 td->urb->actual_length = requested;
2319 xhci_warn(xhci, "WARN: unexpected TRB Type %d\n",
2323 case COMP_STOPPED_LENGTH_INVALID:
2326 if (!xhci_halted_host_endpoint(ep_ctx, trb_comp_code))
2328 xhci_dbg(xhci, "TRB error %u, halted endpoint index = %u\n",
2329 trb_comp_code, ep->ep_index);
2331 case COMP_STALL_ERROR:
2332 /* Did we transfer part of the data (middle) phase? */
2333 if (trb_type == TRB_DATA || trb_type == TRB_NORMAL)
2334 td->urb->actual_length = requested - remaining;
2335 else if (!td->urb_length_set)
2336 td->urb->actual_length = 0;
2340 /* stopped at setup stage, no data transferred */
2341 if (trb_type == TRB_SETUP)
2345 * if on data stage then update the actual_length of the URB and flag it
2346 * as set, so it won't be overwritten in the event for the last TRB.
2348 if (trb_type == TRB_DATA ||
2349 trb_type == TRB_NORMAL) {
2350 td->urb_length_set = true;
2351 td->urb->actual_length = requested - remaining;
2352 xhci_dbg(xhci, "Waiting for status stage event\n");
2356 /* at status stage */
2357 if (!td->urb_length_set)
2358 td->urb->actual_length = requested;
2361 return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2365 * Process isochronous tds, update urb packet status and actual_length.
2367 static int process_isoc_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2368 struct xhci_ring *ep_ring, struct xhci_td *td,
2369 union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2371 struct urb_priv *urb_priv;
2373 struct usb_iso_packet_descriptor *frame;
2375 bool sum_trbs_for_length = false;
2376 u32 remaining, requested, ep_trb_len;
2377 int short_framestatus;
2379 trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2380 urb_priv = td->urb->hcpriv;
2381 idx = urb_priv->num_tds_done;
2382 frame = &td->urb->iso_frame_desc[idx];
2383 requested = frame->length;
2384 remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2385 ep_trb_len = TRB_LEN(le32_to_cpu(ep_trb->generic.field[2]));
2386 short_framestatus = td->urb->transfer_flags & URB_SHORT_NOT_OK ?
2389 /* handle completion code */
2390 switch (trb_comp_code) {
2392 /* Don't overwrite status if TD had an error, see xHCI 4.9.1 */
2393 if (td->error_mid_td)
2396 frame->status = short_framestatus;
2397 sum_trbs_for_length = true;
2402 case COMP_SHORT_PACKET:
2403 frame->status = short_framestatus;
2404 sum_trbs_for_length = true;
2406 case COMP_BANDWIDTH_OVERRUN_ERROR:
2407 frame->status = -ECOMM;
2409 case COMP_BABBLE_DETECTED_ERROR:
2410 sum_trbs_for_length = true;
2412 case COMP_ISOCH_BUFFER_OVERRUN:
2413 frame->status = -EOVERFLOW;
2414 if (ep_trb != td->last_trb)
2415 td->error_mid_td = true;
2417 case COMP_INCOMPATIBLE_DEVICE_ERROR:
2418 case COMP_STALL_ERROR:
2419 frame->status = -EPROTO;
2421 case COMP_USB_TRANSACTION_ERROR:
2422 frame->status = -EPROTO;
2423 sum_trbs_for_length = true;
2424 if (ep_trb != td->last_trb)
2425 td->error_mid_td = true;
2428 sum_trbs_for_length = true;
2430 case COMP_STOPPED_SHORT_PACKET:
2431 /* field normally containing residue now contains tranferred */
2432 frame->status = short_framestatus;
2433 requested = remaining;
2435 case COMP_STOPPED_LENGTH_INVALID:
2436 /* exclude stopped trb with invalid length from length sum */
2437 sum_trbs_for_length = true;
2442 sum_trbs_for_length = true;
2447 if (td->urb_length_set)
2450 if (sum_trbs_for_length)
2451 frame->actual_length = sum_trb_lengths(xhci, ep->ring, ep_trb) +
2452 ep_trb_len - remaining;
2454 frame->actual_length = requested;
2456 td->urb->actual_length += frame->actual_length;
2459 /* Don't give back TD yet if we encountered an error mid TD */
2460 if (td->error_mid_td && ep_trb != td->last_trb) {
2461 xhci_dbg(xhci, "Error mid isoc TD, wait for final completion event\n");
2462 td->urb_length_set = true;
2466 return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2469 static int skip_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td,
2470 struct xhci_virt_ep *ep, int status)
2472 struct urb_priv *urb_priv;
2473 struct usb_iso_packet_descriptor *frame;
2476 urb_priv = td->urb->hcpriv;
2477 idx = urb_priv->num_tds_done;
2478 frame = &td->urb->iso_frame_desc[idx];
2480 /* The transfer is partly done. */
2481 frame->status = -EXDEV;
2483 /* calc actual length */
2484 frame->actual_length = 0;
2486 /* Update ring dequeue pointer */
2487 ep->ring->dequeue = td->last_trb;
2488 ep->ring->deq_seg = td->last_trb_seg;
2489 inc_deq(xhci, ep->ring);
2491 return xhci_td_cleanup(xhci, td, ep->ring, status);
2495 * Process bulk and interrupt tds, update urb status and actual_length.
2497 static int process_bulk_intr_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2498 struct xhci_ring *ep_ring, struct xhci_td *td,
2499 union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2501 struct xhci_slot_ctx *slot_ctx;
2503 u32 remaining, requested, ep_trb_len;
2505 slot_ctx = xhci_get_slot_ctx(xhci, ep->vdev->out_ctx);
2506 trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2507 remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2508 ep_trb_len = TRB_LEN(le32_to_cpu(ep_trb->generic.field[2]));
2509 requested = td->urb->transfer_buffer_length;
2511 switch (trb_comp_code) {
2514 /* handle success with untransferred data as short packet */
2515 if (ep_trb != td->last_trb || remaining) {
2516 xhci_warn(xhci, "WARN Successful completion on short TX\n");
2517 xhci_dbg(xhci, "ep %#x - asked for %d bytes, %d bytes untransferred\n",
2518 td->urb->ep->desc.bEndpointAddress,
2519 requested, remaining);
2523 case COMP_SHORT_PACKET:
2524 xhci_dbg(xhci, "ep %#x - asked for %d bytes, %d bytes untransferred\n",
2525 td->urb->ep->desc.bEndpointAddress,
2526 requested, remaining);
2529 case COMP_STOPPED_SHORT_PACKET:
2530 td->urb->actual_length = remaining;
2532 case COMP_STOPPED_LENGTH_INVALID:
2533 /* stopped on ep trb with invalid length, exclude it */
2534 td->urb->actual_length = sum_trb_lengths(xhci, ep_ring, ep_trb);
2536 case COMP_USB_TRANSACTION_ERROR:
2537 if (xhci->quirks & XHCI_NO_SOFT_RETRY ||
2538 (ep->err_count++ > MAX_SOFT_RETRY) ||
2539 le32_to_cpu(slot_ctx->tt_info) & TT_SLOT)
2544 xhci_handle_halted_endpoint(xhci, ep, td, EP_SOFT_RESET);
2551 if (ep_trb == td->last_trb)
2552 td->urb->actual_length = requested - remaining;
2554 td->urb->actual_length =
2555 sum_trb_lengths(xhci, ep_ring, ep_trb) +
2556 ep_trb_len - remaining;
2558 if (remaining > requested) {
2559 xhci_warn(xhci, "bad transfer trb length %d in event trb\n",
2561 td->urb->actual_length = 0;
2564 return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2567 /* Transfer events which don't point to a transfer TRB, see xhci 4.17.4 */
2568 static int handle_transferless_tx_event(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2571 switch (trb_comp_code) {
2572 case COMP_STALL_ERROR:
2573 case COMP_USB_TRANSACTION_ERROR:
2574 case COMP_INVALID_STREAM_TYPE_ERROR:
2575 case COMP_INVALID_STREAM_ID_ERROR:
2576 xhci_dbg(xhci, "Stream transaction error ep %u no id\n", ep->ep_index);
2577 if (ep->err_count++ > MAX_SOFT_RETRY)
2578 xhci_handle_halted_endpoint(xhci, ep, NULL, EP_HARD_RESET);
2580 xhci_handle_halted_endpoint(xhci, ep, NULL, EP_SOFT_RESET);
2582 case COMP_RING_UNDERRUN:
2583 case COMP_RING_OVERRUN:
2584 case COMP_STOPPED_LENGTH_INVALID:
2587 xhci_err(xhci, "Transfer event %u for unknown stream ring slot %u ep %u\n",
2588 trb_comp_code, ep->vdev->slot_id, ep->ep_index);
2595 * If this function returns an error condition, it means it got a Transfer
2596 * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address.
2597 * At this point, the host controller is probably hosed and should be reset.
2599 static int handle_tx_event(struct xhci_hcd *xhci,
2600 struct xhci_interrupter *ir,
2601 struct xhci_transfer_event *event)
2603 struct xhci_virt_ep *ep;
2604 struct xhci_ring *ep_ring;
2605 unsigned int slot_id;
2607 struct xhci_td *td = NULL;
2608 dma_addr_t ep_trb_dma;
2609 struct xhci_segment *ep_seg;
2610 union xhci_trb *ep_trb;
2611 int status = -EINPROGRESS;
2612 struct xhci_ep_ctx *ep_ctx;
2615 slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
2616 ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1;
2617 trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2618 ep_trb_dma = le64_to_cpu(event->buffer);
2620 ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
2622 xhci_err(xhci, "ERROR Invalid Transfer event\n");
2626 ep_ring = xhci_dma_to_transfer_ring(ep, ep_trb_dma);
2627 ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
2629 if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) {
2631 "ERROR Transfer event for disabled endpoint slot %u ep %u\n",
2637 return handle_transferless_tx_event(xhci, ep, trb_comp_code);
2639 /* Look for common error cases */
2640 switch (trb_comp_code) {
2641 /* Skip codes that require special handling depending on
2645 if (EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)) != 0) {
2646 trb_comp_code = COMP_SHORT_PACKET;
2647 xhci_dbg(xhci, "Successful completion on short TX for slot %u ep %u with last td short %d\n",
2648 slot_id, ep_index, ep_ring->last_td_was_short);
2651 case COMP_SHORT_PACKET:
2653 /* Completion codes for endpoint stopped state */
2655 xhci_dbg(xhci, "Stopped on Transfer TRB for slot %u ep %u\n",
2658 case COMP_STOPPED_LENGTH_INVALID:
2660 "Stopped on No-op or Link TRB for slot %u ep %u\n",
2663 case COMP_STOPPED_SHORT_PACKET:
2665 "Stopped with short packet transfer detected for slot %u ep %u\n",
2668 /* Completion codes for endpoint halted state */
2669 case COMP_STALL_ERROR:
2670 xhci_dbg(xhci, "Stalled endpoint for slot %u ep %u\n", slot_id,
2674 case COMP_SPLIT_TRANSACTION_ERROR:
2675 xhci_dbg(xhci, "Split transaction error for slot %u ep %u\n",
2679 case COMP_USB_TRANSACTION_ERROR:
2680 xhci_dbg(xhci, "Transfer error for slot %u ep %u on endpoint\n",
2684 case COMP_BABBLE_DETECTED_ERROR:
2685 xhci_dbg(xhci, "Babble error for slot %u ep %u on endpoint\n",
2687 status = -EOVERFLOW;
2689 /* Completion codes for endpoint error state */
2690 case COMP_TRB_ERROR:
2692 "WARN: TRB error for slot %u ep %u on endpoint\n",
2696 /* completion codes not indicating endpoint state change */
2697 case COMP_DATA_BUFFER_ERROR:
2699 "WARN: HC couldn't access mem fast enough for slot %u ep %u\n",
2703 case COMP_BANDWIDTH_OVERRUN_ERROR:
2705 "WARN: bandwidth overrun event for slot %u ep %u on endpoint\n",
2708 case COMP_ISOCH_BUFFER_OVERRUN:
2710 "WARN: buffer overrun event for slot %u ep %u on endpoint",
2713 case COMP_RING_UNDERRUN:
2715 * When the Isoch ring is empty, the xHC will generate
2716 * a Ring Overrun Event for IN Isoch endpoint or Ring
2717 * Underrun Event for OUT Isoch endpoint.
2719 xhci_dbg(xhci, "Underrun event on slot %u ep %u\n", slot_id, ep_index);
2723 case COMP_RING_OVERRUN:
2724 xhci_dbg(xhci, "Overrun event on slot %u ep %u\n", slot_id, ep_index);
2728 case COMP_MISSED_SERVICE_ERROR:
2730 * When encounter missed service error, one or more isoc tds
2731 * may be missed by xHC.
2732 * Set skip flag of the ep_ring; Complete the missed tds as
2733 * short transfer when process the ep_ring next time.
2737 "Miss service interval error for slot %u ep %u, set skip flag\n",
2740 case COMP_NO_PING_RESPONSE_ERROR:
2743 "No Ping response error for slot %u ep %u, Skip one Isoc TD\n",
2747 case COMP_INCOMPATIBLE_DEVICE_ERROR:
2748 /* needs disable slot command to recover */
2750 "WARN: detect an incompatible device for slot %u ep %u",
2755 if (xhci_is_vendor_info_code(xhci, trb_comp_code)) {
2760 "ERROR Unknown event condition %u for slot %u ep %u , HC probably busted\n",
2761 trb_comp_code, slot_id, ep_index);
2768 /* This TRB should be in the TD at the head of this ring's
2771 if (list_empty(&ep_ring->td_list)) {
2773 * Don't print wanings if it's due to a stopped endpoint
2774 * generating an extra completion event if the device
2775 * was suspended. Or, a event for the last TRB of a
2776 * short TD we already got a short event for.
2777 * The short TD is already removed from the TD list.
2780 if (!(trb_comp_code == COMP_STOPPED ||
2781 trb_comp_code == COMP_STOPPED_LENGTH_INVALID ||
2782 ep_ring->last_td_was_short)) {
2783 xhci_warn(xhci, "WARN Event TRB for slot %u ep %d with no TDs queued?\n",
2788 xhci_dbg(xhci, "td_list is empty while skip flag set. Clear skip flag for slot %u ep %u.\n",
2793 goto check_endpoint_halted;
2796 td = list_first_entry(&ep_ring->td_list, struct xhci_td,
2799 /* Is this a TRB in the currently executing TD? */
2800 ep_seg = trb_in_td(xhci, td, ep_trb_dma, false);
2804 if (ep->skip && usb_endpoint_xfer_isoc(&td->urb->ep->desc)) {
2805 skip_isoc_td(xhci, td, ep, status);
2810 * Skip the Force Stopped Event. The 'ep_trb' of FSE is not in the current
2811 * TD pointed by 'ep_ring->dequeue' because that the hardware dequeue
2812 * pointer still at the previous TRB of the current TD. The previous TRB
2813 * maybe a Link TD or the last TRB of the previous TD. The command
2814 * completion handle will take care the rest.
2816 if (trb_comp_code == COMP_STOPPED ||
2817 trb_comp_code == COMP_STOPPED_LENGTH_INVALID) {
2822 * Some hosts give a spurious success event after a short
2823 * transfer. Ignore it.
2825 if ((xhci->quirks & XHCI_SPURIOUS_SUCCESS) &&
2826 ep_ring->last_td_was_short) {
2827 ep_ring->last_td_was_short = false;
2832 * xhci 4.10.2 states isoc endpoints should continue
2833 * processing the next TD if there was an error mid TD.
2834 * So host like NEC don't generate an event for the last
2835 * isoc TRB even if the IOC flag is set.
2836 * xhci 4.9.1 states that if there are errors in mult-TRB
2837 * TDs xHC should generate an error for that TRB, and if xHC
2838 * proceeds to the next TD it should genete an event for
2839 * any TRB with IOC flag on the way. Other host follow this.
2840 * So this event might be for the next TD.
2842 if (td->error_mid_td &&
2843 !list_is_last(&td->td_list, &ep_ring->td_list)) {
2844 struct xhci_td *td_next = list_next_entry(td, td_list);
2846 ep_seg = trb_in_td(xhci, td_next, ep_trb_dma, false);
2848 /* give back previous TD, start handling new */
2849 xhci_dbg(xhci, "Missing TD completion event after mid TD error\n");
2850 ep_ring->dequeue = td->last_trb;
2851 ep_ring->deq_seg = td->last_trb_seg;
2852 inc_deq(xhci, ep_ring);
2853 xhci_td_cleanup(xhci, td, ep_ring, td->status);
2859 /* HC is busted, give up! */
2861 "ERROR Transfer event TRB DMA ptr not "
2862 "part of current TD ep_index %d "
2863 "comp_code %u\n", ep_index,
2865 trb_in_td(xhci, td, ep_trb_dma, true);
2873 "Found td. Clear skip flag for slot %u ep %u.\n",
2879 * If ep->skip is set, it means there are missed tds on the
2880 * endpoint ring need to take care of.
2881 * Process them as short transfer until reach the td pointed by
2886 if (trb_comp_code == COMP_SHORT_PACKET)
2887 ep_ring->last_td_was_short = true;
2889 ep_ring->last_td_was_short = false;
2891 ep_trb = &ep_seg->trbs[(ep_trb_dma - ep_seg->dma) / sizeof(*ep_trb)];
2892 trace_xhci_handle_transfer(ep_ring, (struct xhci_generic_trb *) ep_trb);
2895 * No-op TRB could trigger interrupts in a case where a URB was killed
2896 * and a STALL_ERROR happens right after the endpoint ring stopped.
2897 * Reset the halted endpoint. Otherwise, the endpoint remains stalled
2901 if (trb_is_noop(ep_trb))
2902 goto check_endpoint_halted;
2904 td->status = status;
2906 /* update the urb's actual_length and give back to the core */
2907 if (usb_endpoint_xfer_control(&td->urb->ep->desc))
2908 process_ctrl_td(xhci, ep, ep_ring, td, ep_trb, event);
2909 else if (usb_endpoint_xfer_isoc(&td->urb->ep->desc))
2910 process_isoc_td(xhci, ep, ep_ring, td, ep_trb, event);
2912 process_bulk_intr_td(xhci, ep, ep_ring, td, ep_trb, event);
2915 check_endpoint_halted:
2916 if (xhci_halted_host_endpoint(ep_ctx, trb_comp_code))
2917 xhci_handle_halted_endpoint(xhci, ep, td, EP_HARD_RESET);
2922 xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n",
2923 (unsigned long long) xhci_trb_virt_to_dma(
2924 ir->event_ring->deq_seg,
2925 ir->event_ring->dequeue),
2926 lower_32_bits(le64_to_cpu(event->buffer)),
2927 upper_32_bits(le64_to_cpu(event->buffer)),
2928 le32_to_cpu(event->transfer_len),
2929 le32_to_cpu(event->flags));
2934 * This function handles one OS-owned event on the event ring. It may drop
2935 * xhci->lock between event processing (e.g. to pass up port status changes).
2937 static int xhci_handle_event_trb(struct xhci_hcd *xhci, struct xhci_interrupter *ir,
2938 union xhci_trb *event)
2942 trace_xhci_handle_event(ir->event_ring, &event->generic);
2945 * Barrier between reading the TRB_CYCLE (valid) flag before, and any
2946 * speculative reads of the event's flags/data below.
2949 trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(event->event_cmd.flags));
2950 /* FIXME: Handle more event types. */
2953 case TRB_COMPLETION:
2954 handle_cmd_completion(xhci, &event->event_cmd);
2956 case TRB_PORT_STATUS:
2957 handle_port_status(xhci, event);
2960 handle_tx_event(xhci, ir, &event->trans_event);
2963 handle_device_notification(xhci, event);
2966 if (trb_type >= TRB_VENDOR_DEFINED_LOW)
2967 handle_vendor_event(xhci, event, trb_type);
2969 xhci_warn(xhci, "ERROR unknown event type %d\n", trb_type);
2971 /* Any of the above functions may drop and re-acquire the lock, so check
2972 * to make sure a watchdog timer didn't mark the host as non-responsive.
2974 if (xhci->xhc_state & XHCI_STATE_DYING) {
2975 xhci_dbg(xhci, "xHCI host dying, returning from event handler.\n");
2983 * Update Event Ring Dequeue Pointer:
2984 * - When all events have finished
2985 * - To avoid "Event Ring Full Error" condition
2987 static void xhci_update_erst_dequeue(struct xhci_hcd *xhci,
2988 struct xhci_interrupter *ir,
2994 temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
2995 deq = xhci_trb_virt_to_dma(ir->event_ring->deq_seg,
2996 ir->event_ring->dequeue);
2998 xhci_warn(xhci, "WARN something wrong with SW event ring dequeue ptr\n");
3000 * Per 4.9.4, Software writes to the ERDP register shall always advance
3001 * the Event Ring Dequeue Pointer value.
3003 if ((temp_64 & ERST_PTR_MASK) == (deq & ERST_PTR_MASK) && !clear_ehb)
3006 /* Update HC event ring dequeue pointer */
3007 temp_64 = ir->event_ring->deq_seg->num & ERST_DESI_MASK;
3008 temp_64 |= deq & ERST_PTR_MASK;
3010 /* Clear the event handler busy flag (RW1C) */
3012 temp_64 |= ERST_EHB;
3013 xhci_write_64(xhci, temp_64, &ir->ir_set->erst_dequeue);
3016 /* Clear the interrupt pending bit for a specific interrupter. */
3017 static void xhci_clear_interrupt_pending(struct xhci_interrupter *ir)
3019 if (!ir->ip_autoclear) {
3022 irq_pending = readl(&ir->ir_set->irq_pending);
3023 irq_pending |= IMAN_IP;
3024 writel(irq_pending, &ir->ir_set->irq_pending);
3029 * Handle all OS-owned events on an interrupter event ring. It may drop
3030 * and reaquire xhci->lock between event processing.
3032 static int xhci_handle_events(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
3038 xhci_clear_interrupt_pending(ir);
3040 /* Event ring hasn't been allocated yet. */
3041 if (!ir->event_ring || !ir->event_ring->dequeue) {
3042 xhci_err(xhci, "ERROR interrupter event ring not ready\n");
3046 if (xhci->xhc_state & XHCI_STATE_DYING ||
3047 xhci->xhc_state & XHCI_STATE_HALTED) {
3048 xhci_dbg(xhci, "xHCI dying, ignoring interrupt. Shouldn't IRQs be disabled?\n");
3050 /* Clear the event handler busy flag (RW1C) */
3051 temp = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
3052 xhci_write_64(xhci, temp | ERST_EHB, &ir->ir_set->erst_dequeue);
3056 /* Process all OS owned event TRBs on this event ring */
3057 while (unhandled_event_trb(ir->event_ring)) {
3058 err = xhci_handle_event_trb(xhci, ir, ir->event_ring->dequeue);
3061 * If half a segment of events have been handled in one go then
3062 * update ERDP, and force isoc trbs to interrupt more often
3064 if (event_loop++ > TRBS_PER_SEGMENT / 2) {
3065 xhci_update_erst_dequeue(xhci, ir, false);
3067 if (ir->isoc_bei_interval > AVOID_BEI_INTERVAL_MIN)
3068 ir->isoc_bei_interval = ir->isoc_bei_interval / 2;
3073 /* Update SW event ring dequeue pointer */
3074 inc_deq(xhci, ir->event_ring);
3080 xhci_update_erst_dequeue(xhci, ir, true);
3086 * xHCI spec says we can get an interrupt, and if the HC has an error condition,
3087 * we might get bad data out of the event ring. Section 4.10.2.7 has a list of
3088 * indicators of an event TRB error, but we check the status *first* to be safe.
3090 irqreturn_t xhci_irq(struct usb_hcd *hcd)
3092 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3093 irqreturn_t ret = IRQ_HANDLED;
3096 spin_lock(&xhci->lock);
3097 /* Check if the xHC generated the interrupt, or the irq is shared */
3098 status = readl(&xhci->op_regs->status);
3099 if (status == ~(u32)0) {
3104 if (!(status & STS_EINT)) {
3109 if (status & STS_HCE) {
3110 xhci_warn(xhci, "WARNING: Host Controller Error\n");
3114 if (status & STS_FATAL) {
3115 xhci_warn(xhci, "WARNING: Host System Error\n");
3121 * Clear the op reg interrupt status first,
3122 * so we can receive interrupts from other MSI-X interrupters.
3123 * Write 1 to clear the interrupt status.
3126 writel(status, &xhci->op_regs->status);
3128 /* This is the handler of the primary interrupter */
3129 xhci_handle_events(xhci, xhci->interrupters[0]);
3131 spin_unlock(&xhci->lock);
3136 irqreturn_t xhci_msi_irq(int irq, void *hcd)
3138 return xhci_irq(hcd);
3140 EXPORT_SYMBOL_GPL(xhci_msi_irq);
3142 /**** Endpoint Ring Operations ****/
3145 * Generic function for queueing a TRB on a ring.
3146 * The caller must have checked to make sure there's room on the ring.
3148 * @more_trbs_coming: Will you enqueue more TRBs before calling
3149 * prepare_transfer()?
3151 static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
3152 bool more_trbs_coming,
3153 u32 field1, u32 field2, u32 field3, u32 field4)
3155 struct xhci_generic_trb *trb;
3157 trb = &ring->enqueue->generic;
3158 trb->field[0] = cpu_to_le32(field1);
3159 trb->field[1] = cpu_to_le32(field2);
3160 trb->field[2] = cpu_to_le32(field3);
3161 /* make sure TRB is fully written before giving it to the controller */
3163 trb->field[3] = cpu_to_le32(field4);
3165 trace_xhci_queue_trb(ring, trb);
3167 inc_enq(xhci, ring, more_trbs_coming);
3171 * Does various checks on the endpoint ring, and makes it ready to queue num_trbs.
3172 * expand ring if it start to be full.
3174 static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
3175 u32 ep_state, unsigned int num_trbs, gfp_t mem_flags)
3177 unsigned int link_trb_count = 0;
3178 unsigned int new_segs = 0;
3180 /* Make sure the endpoint has been added to xHC schedule */
3182 case EP_STATE_DISABLED:
3184 * USB core changed config/interfaces without notifying us,
3185 * or hardware is reporting the wrong state.
3187 xhci_warn(xhci, "WARN urb submitted to disabled ep\n");
3189 case EP_STATE_ERROR:
3190 xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n");
3191 /* FIXME event handling code for error needs to clear it */
3192 /* XXX not sure if this should be -ENOENT or not */
3194 case EP_STATE_HALTED:
3195 xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n");
3197 case EP_STATE_STOPPED:
3198 case EP_STATE_RUNNING:
3201 xhci_err(xhci, "ERROR unknown endpoint state for ep\n");
3203 * FIXME issue Configure Endpoint command to try to get the HC
3204 * back into a known state.
3209 if (ep_ring != xhci->cmd_ring) {
3210 new_segs = xhci_ring_expansion_needed(xhci, ep_ring, num_trbs);
3211 } else if (xhci_num_trbs_free(ep_ring) <= num_trbs) {
3212 xhci_err(xhci, "Do not support expand command ring\n");
3217 xhci_dbg_trace(xhci, trace_xhci_dbg_ring_expansion,
3218 "ERROR no room on ep ring, try ring expansion");
3219 if (xhci_ring_expansion(xhci, ep_ring, new_segs, mem_flags)) {
3220 xhci_err(xhci, "Ring expansion failed\n");
3225 while (trb_is_link(ep_ring->enqueue)) {
3226 /* If we're not dealing with 0.95 hardware or isoc rings
3227 * on AMD 0.96 host, clear the chain bit.
3229 if (!xhci_link_chain_quirk(xhci, ep_ring->type))
3230 ep_ring->enqueue->link.control &=
3231 cpu_to_le32(~TRB_CHAIN);
3233 ep_ring->enqueue->link.control |=
3234 cpu_to_le32(TRB_CHAIN);
3237 ep_ring->enqueue->link.control ^= cpu_to_le32(TRB_CYCLE);
3239 /* Toggle the cycle bit after the last ring segment. */
3240 if (link_trb_toggles_cycle(ep_ring->enqueue))
3241 ep_ring->cycle_state ^= 1;
3243 ep_ring->enq_seg = ep_ring->enq_seg->next;
3244 ep_ring->enqueue = ep_ring->enq_seg->trbs;
3246 /* prevent infinite loop if all first trbs are link trbs */
3247 if (link_trb_count++ > ep_ring->num_segs) {
3248 xhci_warn(xhci, "Ring is an endless link TRB loop\n");
3253 if (last_trb_on_seg(ep_ring->enq_seg, ep_ring->enqueue)) {
3254 xhci_warn(xhci, "Missing link TRB at end of ring segment\n");
3261 static int prepare_transfer(struct xhci_hcd *xhci,
3262 struct xhci_virt_device *xdev,
3263 unsigned int ep_index,
3264 unsigned int stream_id,
3265 unsigned int num_trbs,
3267 unsigned int td_index,
3271 struct urb_priv *urb_priv;
3273 struct xhci_ring *ep_ring;
3274 struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
3276 ep_ring = xhci_triad_to_transfer_ring(xhci, xdev->slot_id, ep_index,
3279 xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n",
3284 ret = prepare_ring(xhci, ep_ring, GET_EP_CTX_STATE(ep_ctx),
3285 num_trbs, mem_flags);
3289 urb_priv = urb->hcpriv;
3290 td = &urb_priv->td[td_index];
3292 INIT_LIST_HEAD(&td->td_list);
3293 INIT_LIST_HEAD(&td->cancelled_td_list);
3295 if (td_index == 0) {
3296 ret = usb_hcd_link_urb_to_ep(bus_to_hcd(urb->dev->bus), urb);
3302 /* Add this TD to the tail of the endpoint ring's TD list */
3303 list_add_tail(&td->td_list, &ep_ring->td_list);
3304 td->start_seg = ep_ring->enq_seg;
3305 td->first_trb = ep_ring->enqueue;
3310 unsigned int count_trbs(u64 addr, u64 len)
3312 unsigned int num_trbs;
3314 num_trbs = DIV_ROUND_UP(len + (addr & (TRB_MAX_BUFF_SIZE - 1)),
3322 static inline unsigned int count_trbs_needed(struct urb *urb)
3324 return count_trbs(urb->transfer_dma, urb->transfer_buffer_length);
3327 static unsigned int count_sg_trbs_needed(struct urb *urb)
3329 struct scatterlist *sg;
3330 unsigned int i, len, full_len, num_trbs = 0;
3332 full_len = urb->transfer_buffer_length;
3334 for_each_sg(urb->sg, sg, urb->num_mapped_sgs, i) {
3335 len = sg_dma_len(sg);
3336 num_trbs += count_trbs(sg_dma_address(sg), len);
3337 len = min_t(unsigned int, len, full_len);
3346 static unsigned int count_isoc_trbs_needed(struct urb *urb, int i)
3350 addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset);
3351 len = urb->iso_frame_desc[i].length;
3353 return count_trbs(addr, len);
3356 static void check_trb_math(struct urb *urb, int running_total)
3358 if (unlikely(running_total != urb->transfer_buffer_length))
3359 dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, "
3360 "queued %#x (%d), asked for %#x (%d)\n",
3362 urb->ep->desc.bEndpointAddress,
3363 running_total, running_total,
3364 urb->transfer_buffer_length,
3365 urb->transfer_buffer_length);
3368 static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id,
3369 unsigned int ep_index, unsigned int stream_id, int start_cycle,
3370 struct xhci_generic_trb *start_trb)
3373 * Pass all the TRBs to the hardware at once and make sure this write
3378 start_trb->field[3] |= cpu_to_le32(start_cycle);
3380 start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE);
3381 xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
3384 static void check_interval(struct urb *urb, struct xhci_ep_ctx *ep_ctx)
3389 xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info));
3390 ep_interval = urb->interval;
3392 /* Convert to microframes */
3393 if (urb->dev->speed == USB_SPEED_LOW ||
3394 urb->dev->speed == USB_SPEED_FULL)
3397 /* FIXME change this to a warning and a suggestion to use the new API
3398 * to set the polling interval (once the API is added).
3400 if (xhci_interval != ep_interval) {
3401 dev_dbg_ratelimited(&urb->dev->dev,
3402 "Driver uses different interval (%d microframe%s) than xHCI (%d microframe%s)\n",
3403 ep_interval, ep_interval == 1 ? "" : "s",
3404 xhci_interval, xhci_interval == 1 ? "" : "s");
3405 urb->interval = xhci_interval;
3406 /* Convert back to frames for LS/FS devices */
3407 if (urb->dev->speed == USB_SPEED_LOW ||
3408 urb->dev->speed == USB_SPEED_FULL)
3414 * xHCI uses normal TRBs for both bulk and interrupt. When the interrupt
3415 * endpoint is to be serviced, the xHC will consume (at most) one TD. A TD
3416 * (comprised of sg list entries) can take several service intervals to
3419 int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3420 struct urb *urb, int slot_id, unsigned int ep_index)
3422 struct xhci_ep_ctx *ep_ctx;
3424 ep_ctx = xhci_get_ep_ctx(xhci, xhci->devs[slot_id]->out_ctx, ep_index);
3425 check_interval(urb, ep_ctx);
3427 return xhci_queue_bulk_tx(xhci, mem_flags, urb, slot_id, ep_index);
3431 * For xHCI 1.0 host controllers, TD size is the number of max packet sized
3432 * packets remaining in the TD (*not* including this TRB).
3434 * Total TD packet count = total_packet_count =
3435 * DIV_ROUND_UP(TD size in bytes / wMaxPacketSize)
3437 * Packets transferred up to and including this TRB = packets_transferred =
3438 * rounddown(total bytes transferred including this TRB / wMaxPacketSize)
3440 * TD size = total_packet_count - packets_transferred
3442 * For xHCI 0.96 and older, TD size field should be the remaining bytes
3443 * including this TRB, right shifted by 10
3445 * For all hosts it must fit in bits 21:17, so it can't be bigger than 31.
3446 * This is taken care of in the TRB_TD_SIZE() macro
3448 * The last TRB in a TD must have the TD size set to zero.
3450 static u32 xhci_td_remainder(struct xhci_hcd *xhci, int transferred,
3451 int trb_buff_len, unsigned int td_total_len,
3452 struct urb *urb, bool more_trbs_coming)
3454 u32 maxp, total_packet_count;
3456 /* MTK xHCI 0.96 contains some features from 1.0 */
3457 if (xhci->hci_version < 0x100 && !(xhci->quirks & XHCI_MTK_HOST))
3458 return ((td_total_len - transferred) >> 10);
3460 /* One TRB with a zero-length data packet. */
3461 if (!more_trbs_coming || (transferred == 0 && trb_buff_len == 0) ||
3462 trb_buff_len == td_total_len)
3465 /* for MTK xHCI 0.96, TD size include this TRB, but not in 1.x */
3466 if ((xhci->quirks & XHCI_MTK_HOST) && (xhci->hci_version < 0x100))
3469 maxp = usb_endpoint_maxp(&urb->ep->desc);
3470 total_packet_count = DIV_ROUND_UP(td_total_len, maxp);
3472 /* Queueing functions don't count the current TRB into transferred */
3473 return (total_packet_count - ((transferred + trb_buff_len) / maxp));
3477 static int xhci_align_td(struct xhci_hcd *xhci, struct urb *urb, u32 enqd_len,
3478 u32 *trb_buff_len, struct xhci_segment *seg)
3480 struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
3481 unsigned int unalign;
3482 unsigned int max_pkt;
3486 max_pkt = usb_endpoint_maxp(&urb->ep->desc);
3487 unalign = (enqd_len + *trb_buff_len) % max_pkt;
3489 /* we got lucky, last normal TRB data on segment is packet aligned */
3493 xhci_dbg(xhci, "Unaligned %d bytes, buff len %d\n",
3494 unalign, *trb_buff_len);
3496 /* is the last nornal TRB alignable by splitting it */
3497 if (*trb_buff_len > unalign) {
3498 *trb_buff_len -= unalign;
3499 xhci_dbg(xhci, "split align, new buff len %d\n", *trb_buff_len);
3504 * We want enqd_len + trb_buff_len to sum up to a number aligned to
3505 * number which is divisible by the endpoint's wMaxPacketSize. IOW:
3506 * (size of currently enqueued TRBs + remainder) % wMaxPacketSize == 0.
3508 new_buff_len = max_pkt - (enqd_len % max_pkt);
3510 if (new_buff_len > (urb->transfer_buffer_length - enqd_len))
3511 new_buff_len = (urb->transfer_buffer_length - enqd_len);
3513 /* create a max max_pkt sized bounce buffer pointed to by last trb */
3514 if (usb_urb_dir_out(urb)) {
3516 len = sg_pcopy_to_buffer(urb->sg, urb->num_sgs,
3517 seg->bounce_buf, new_buff_len, enqd_len);
3518 if (len != new_buff_len)
3519 xhci_warn(xhci, "WARN Wrong bounce buffer write length: %zu != %d\n",
3522 memcpy(seg->bounce_buf, urb->transfer_buffer + enqd_len, new_buff_len);
3525 seg->bounce_dma = dma_map_single(dev, seg->bounce_buf,
3526 max_pkt, DMA_TO_DEVICE);
3528 seg->bounce_dma = dma_map_single(dev, seg->bounce_buf,
3529 max_pkt, DMA_FROM_DEVICE);
3532 if (dma_mapping_error(dev, seg->bounce_dma)) {
3533 /* try without aligning. Some host controllers survive */
3534 xhci_warn(xhci, "Failed mapping bounce buffer, not aligning\n");
3537 *trb_buff_len = new_buff_len;
3538 seg->bounce_len = new_buff_len;
3539 seg->bounce_offs = enqd_len;
3541 xhci_dbg(xhci, "Bounce align, new buff len %d\n", *trb_buff_len);
3546 /* This is very similar to what ehci-q.c qtd_fill() does */
3547 int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3548 struct urb *urb, int slot_id, unsigned int ep_index)
3550 struct xhci_ring *ring;
3551 struct urb_priv *urb_priv;
3553 struct xhci_generic_trb *start_trb;
3554 struct scatterlist *sg = NULL;
3555 bool more_trbs_coming = true;
3556 bool need_zero_pkt = false;
3557 bool first_trb = true;
3558 unsigned int num_trbs;
3559 unsigned int start_cycle, num_sgs = 0;
3560 unsigned int enqd_len, block_len, trb_buff_len, full_len;
3562 u32 field, length_field, remainder;
3563 u64 addr, send_addr;
3565 ring = xhci_urb_to_transfer_ring(xhci, urb);
3569 full_len = urb->transfer_buffer_length;
3570 /* If we have scatter/gather list, we use it. */
3571 if (urb->num_sgs && !(urb->transfer_flags & URB_DMA_MAP_SINGLE)) {
3572 num_sgs = urb->num_mapped_sgs;
3574 addr = (u64) sg_dma_address(sg);
3575 block_len = sg_dma_len(sg);
3576 num_trbs = count_sg_trbs_needed(urb);
3578 num_trbs = count_trbs_needed(urb);
3579 addr = (u64) urb->transfer_dma;
3580 block_len = full_len;
3582 ret = prepare_transfer(xhci, xhci->devs[slot_id],
3583 ep_index, urb->stream_id,
3584 num_trbs, urb, 0, mem_flags);
3585 if (unlikely(ret < 0))
3588 urb_priv = urb->hcpriv;
3590 /* Deal with URB_ZERO_PACKET - need one more td/trb */
3591 if (urb->transfer_flags & URB_ZERO_PACKET && urb_priv->num_tds > 1)
3592 need_zero_pkt = true;
3594 td = &urb_priv->td[0];
3597 * Don't give the first TRB to the hardware (by toggling the cycle bit)
3598 * until we've finished creating all the other TRBs. The ring's cycle
3599 * state may change as we enqueue the other TRBs, so save it too.
3601 start_trb = &ring->enqueue->generic;
3602 start_cycle = ring->cycle_state;
3605 /* Queue the TRBs, even if they are zero-length */
3606 for (enqd_len = 0; first_trb || enqd_len < full_len;
3607 enqd_len += trb_buff_len) {
3608 field = TRB_TYPE(TRB_NORMAL);
3610 /* TRB buffer should not cross 64KB boundaries */
3611 trb_buff_len = TRB_BUFF_LEN_UP_TO_BOUNDARY(addr);
3612 trb_buff_len = min_t(unsigned int, trb_buff_len, block_len);
3614 if (enqd_len + trb_buff_len > full_len)
3615 trb_buff_len = full_len - enqd_len;
3617 /* Don't change the cycle bit of the first TRB until later */
3620 if (start_cycle == 0)
3623 field |= ring->cycle_state;
3625 /* Chain all the TRBs together; clear the chain bit in the last
3626 * TRB to indicate it's the last TRB in the chain.
3628 if (enqd_len + trb_buff_len < full_len) {
3630 if (trb_is_link(ring->enqueue + 1)) {
3631 if (xhci_align_td(xhci, urb, enqd_len,
3634 send_addr = ring->enq_seg->bounce_dma;
3635 /* assuming TD won't span 2 segs */
3636 td->bounce_seg = ring->enq_seg;
3640 if (enqd_len + trb_buff_len >= full_len) {
3641 field &= ~TRB_CHAIN;
3643 more_trbs_coming = false;
3644 td->last_trb = ring->enqueue;
3645 td->last_trb_seg = ring->enq_seg;
3646 if (xhci_urb_suitable_for_idt(urb)) {
3647 memcpy(&send_addr, urb->transfer_buffer,
3649 le64_to_cpus(&send_addr);
3654 /* Only set interrupt on short packet for IN endpoints */
3655 if (usb_urb_dir_in(urb))
3658 /* Set the TRB length, TD size, and interrupter fields. */
3659 remainder = xhci_td_remainder(xhci, enqd_len, trb_buff_len,
3660 full_len, urb, more_trbs_coming);
3662 length_field = TRB_LEN(trb_buff_len) |
3663 TRB_TD_SIZE(remainder) |
3666 queue_trb(xhci, ring, more_trbs_coming | need_zero_pkt,
3667 lower_32_bits(send_addr),
3668 upper_32_bits(send_addr),
3671 addr += trb_buff_len;
3672 sent_len = trb_buff_len;
3674 while (sg && sent_len >= block_len) {
3677 sent_len -= block_len;
3679 if (num_sgs != 0 && sg) {
3680 block_len = sg_dma_len(sg);
3681 addr = (u64) sg_dma_address(sg);
3685 block_len -= sent_len;
3689 if (need_zero_pkt) {
3690 ret = prepare_transfer(xhci, xhci->devs[slot_id],
3691 ep_index, urb->stream_id,
3692 1, urb, 1, mem_flags);
3693 urb_priv->td[1].last_trb = ring->enqueue;
3694 urb_priv->td[1].last_trb_seg = ring->enq_seg;
3695 field = TRB_TYPE(TRB_NORMAL) | ring->cycle_state | TRB_IOC;
3696 queue_trb(xhci, ring, 0, 0, 0, TRB_INTR_TARGET(0), field);
3699 check_trb_math(urb, enqd_len);
3700 giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
3701 start_cycle, start_trb);
3705 /* Caller must have locked xhci->lock */
3706 int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3707 struct urb *urb, int slot_id, unsigned int ep_index)
3709 struct xhci_ring *ep_ring;
3712 struct usb_ctrlrequest *setup;
3713 struct xhci_generic_trb *start_trb;
3716 struct urb_priv *urb_priv;
3719 ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
3724 * Need to copy setup packet into setup TRB, so we can't use the setup
3727 if (!urb->setup_packet)
3730 /* 1 TRB for setup, 1 for status */
3733 * Don't need to check if we need additional event data and normal TRBs,
3734 * since data in control transfers will never get bigger than 16MB
3735 * XXX: can we get a buffer that crosses 64KB boundaries?
3737 if (urb->transfer_buffer_length > 0)
3739 ret = prepare_transfer(xhci, xhci->devs[slot_id],
3740 ep_index, urb->stream_id,
3741 num_trbs, urb, 0, mem_flags);
3745 urb_priv = urb->hcpriv;
3746 td = &urb_priv->td[0];
3749 * Don't give the first TRB to the hardware (by toggling the cycle bit)
3750 * until we've finished creating all the other TRBs. The ring's cycle
3751 * state may change as we enqueue the other TRBs, so save it too.
3753 start_trb = &ep_ring->enqueue->generic;
3754 start_cycle = ep_ring->cycle_state;
3756 /* Queue setup TRB - see section 6.4.1.2.1 */
3757 /* FIXME better way to translate setup_packet into two u32 fields? */
3758 setup = (struct usb_ctrlrequest *) urb->setup_packet;
3760 field |= TRB_IDT | TRB_TYPE(TRB_SETUP);
3761 if (start_cycle == 0)
3764 /* xHCI 1.0/1.1 6.4.1.2.1: Transfer Type field */
3765 if ((xhci->hci_version >= 0x100) || (xhci->quirks & XHCI_MTK_HOST)) {
3766 if (urb->transfer_buffer_length > 0) {
3767 if (setup->bRequestType & USB_DIR_IN)
3768 field |= TRB_TX_TYPE(TRB_DATA_IN);
3770 field |= TRB_TX_TYPE(TRB_DATA_OUT);
3774 queue_trb(xhci, ep_ring, true,
3775 setup->bRequestType | setup->bRequest << 8 | le16_to_cpu(setup->wValue) << 16,
3776 le16_to_cpu(setup->wIndex) | le16_to_cpu(setup->wLength) << 16,
3777 TRB_LEN(8) | TRB_INTR_TARGET(0),
3778 /* Immediate data in pointer */
3781 /* If there's data, queue data TRBs */
3782 /* Only set interrupt on short packet for IN endpoints */
3783 if (usb_urb_dir_in(urb))
3784 field = TRB_ISP | TRB_TYPE(TRB_DATA);
3786 field = TRB_TYPE(TRB_DATA);
3788 if (urb->transfer_buffer_length > 0) {
3789 u32 length_field, remainder;
3792 if (xhci_urb_suitable_for_idt(urb)) {
3793 memcpy(&addr, urb->transfer_buffer,
3794 urb->transfer_buffer_length);
3795 le64_to_cpus(&addr);
3798 addr = (u64) urb->transfer_dma;
3801 remainder = xhci_td_remainder(xhci, 0,
3802 urb->transfer_buffer_length,
3803 urb->transfer_buffer_length,
3805 length_field = TRB_LEN(urb->transfer_buffer_length) |
3806 TRB_TD_SIZE(remainder) |
3808 if (setup->bRequestType & USB_DIR_IN)
3809 field |= TRB_DIR_IN;
3810 queue_trb(xhci, ep_ring, true,
3811 lower_32_bits(addr),
3812 upper_32_bits(addr),
3814 field | ep_ring->cycle_state);
3817 /* Save the DMA address of the last TRB in the TD */
3818 td->last_trb = ep_ring->enqueue;
3819 td->last_trb_seg = ep_ring->enq_seg;
3821 /* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */
3822 /* If the device sent data, the status stage is an OUT transfer */
3823 if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN)
3827 queue_trb(xhci, ep_ring, false,
3831 /* Event on completion */
3832 field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state);
3834 giveback_first_trb(xhci, slot_id, ep_index, 0,
3835 start_cycle, start_trb);
3840 * The transfer burst count field of the isochronous TRB defines the number of
3841 * bursts that are required to move all packets in this TD. Only SuperSpeed
3842 * devices can burst up to bMaxBurst number of packets per service interval.
3843 * This field is zero based, meaning a value of zero in the field means one
3844 * burst. Basically, for everything but SuperSpeed devices, this field will be
3845 * zero. Only xHCI 1.0 host controllers support this field.
3847 static unsigned int xhci_get_burst_count(struct xhci_hcd *xhci,
3848 struct urb *urb, unsigned int total_packet_count)
3850 unsigned int max_burst;
3852 if (xhci->hci_version < 0x100 || urb->dev->speed < USB_SPEED_SUPER)
3855 max_burst = urb->ep->ss_ep_comp.bMaxBurst;
3856 return DIV_ROUND_UP(total_packet_count, max_burst + 1) - 1;
3860 * Returns the number of packets in the last "burst" of packets. This field is
3861 * valid for all speeds of devices. USB 2.0 devices can only do one "burst", so
3862 * the last burst packet count is equal to the total number of packets in the
3863 * TD. SuperSpeed endpoints can have up to 3 bursts. All but the last burst
3864 * must contain (bMaxBurst + 1) number of packets, but the last burst can
3865 * contain 1 to (bMaxBurst + 1) packets.
3867 static unsigned int xhci_get_last_burst_packet_count(struct xhci_hcd *xhci,
3868 struct urb *urb, unsigned int total_packet_count)
3870 unsigned int max_burst;
3871 unsigned int residue;
3873 if (xhci->hci_version < 0x100)
3876 if (urb->dev->speed >= USB_SPEED_SUPER) {
3877 /* bMaxBurst is zero based: 0 means 1 packet per burst */
3878 max_burst = urb->ep->ss_ep_comp.bMaxBurst;
3879 residue = total_packet_count % (max_burst + 1);
3880 /* If residue is zero, the last burst contains (max_burst + 1)
3881 * number of packets, but the TLBPC field is zero-based.
3887 if (total_packet_count == 0)
3889 return total_packet_count - 1;
3893 * Calculates Frame ID field of the isochronous TRB identifies the
3894 * target frame that the Interval associated with this Isochronous
3895 * Transfer Descriptor will start on. Refer to 4.11.2.5 in 1.1 spec.
3897 * Returns actual frame id on success, negative value on error.
3899 static int xhci_get_isoc_frame_id(struct xhci_hcd *xhci,
3900 struct urb *urb, int index)
3902 int start_frame, ist, ret = 0;
3903 int start_frame_id, end_frame_id, current_frame_id;
3905 if (urb->dev->speed == USB_SPEED_LOW ||
3906 urb->dev->speed == USB_SPEED_FULL)
3907 start_frame = urb->start_frame + index * urb->interval;
3909 start_frame = (urb->start_frame + index * urb->interval) >> 3;
3911 /* Isochronous Scheduling Threshold (IST, bits 0~3 in HCSPARAMS2):
3913 * If bit [3] of IST is cleared to '0', software can add a TRB no
3914 * later than IST[2:0] Microframes before that TRB is scheduled to
3916 * If bit [3] of IST is set to '1', software can add a TRB no later
3917 * than IST[2:0] Frames before that TRB is scheduled to be executed.
3919 ist = HCS_IST(xhci->hcs_params2) & 0x7;
3920 if (HCS_IST(xhci->hcs_params2) & (1 << 3))
3923 /* Software shall not schedule an Isoch TD with a Frame ID value that
3924 * is less than the Start Frame ID or greater than the End Frame ID,
3927 * End Frame ID = (Current MFINDEX register value + 895 ms.) MOD 2048
3928 * Start Frame ID = (Current MFINDEX register value + IST + 1) MOD 2048
3930 * Both the End Frame ID and Start Frame ID values are calculated
3931 * in microframes. When software determines the valid Frame ID value;
3932 * The End Frame ID value should be rounded down to the nearest Frame
3933 * boundary, and the Start Frame ID value should be rounded up to the
3934 * nearest Frame boundary.
3936 current_frame_id = readl(&xhci->run_regs->microframe_index);
3937 start_frame_id = roundup(current_frame_id + ist + 1, 8);
3938 end_frame_id = rounddown(current_frame_id + 895 * 8, 8);
3940 start_frame &= 0x7ff;
3941 start_frame_id = (start_frame_id >> 3) & 0x7ff;
3942 end_frame_id = (end_frame_id >> 3) & 0x7ff;
3944 xhci_dbg(xhci, "%s: index %d, reg 0x%x start_frame_id 0x%x, end_frame_id 0x%x, start_frame 0x%x\n",
3945 __func__, index, readl(&xhci->run_regs->microframe_index),
3946 start_frame_id, end_frame_id, start_frame);
3948 if (start_frame_id < end_frame_id) {
3949 if (start_frame > end_frame_id ||
3950 start_frame < start_frame_id)
3952 } else if (start_frame_id > end_frame_id) {
3953 if ((start_frame > end_frame_id &&
3954 start_frame < start_frame_id))
3961 if (ret == -EINVAL || start_frame == start_frame_id) {
3962 start_frame = start_frame_id + 1;
3963 if (urb->dev->speed == USB_SPEED_LOW ||
3964 urb->dev->speed == USB_SPEED_FULL)
3965 urb->start_frame = start_frame;
3967 urb->start_frame = start_frame << 3;
3973 xhci_warn(xhci, "Frame ID %d (reg %d, index %d) beyond range (%d, %d)\n",
3974 start_frame, current_frame_id, index,
3975 start_frame_id, end_frame_id);
3976 xhci_warn(xhci, "Ignore frame ID field, use SIA bit instead\n");
3983 /* Check if we should generate event interrupt for a TD in an isoc URB */
3984 static bool trb_block_event_intr(struct xhci_hcd *xhci, int num_tds, int i,
3985 struct xhci_interrupter *ir)
3987 if (xhci->hci_version < 0x100)
3989 /* always generate an event interrupt for the last TD */
3990 if (i == num_tds - 1)
3993 * If AVOID_BEI is set the host handles full event rings poorly,
3994 * generate an event at least every 8th TD to clear the event ring
3996 if (i && ir->isoc_bei_interval && xhci->quirks & XHCI_AVOID_BEI)
3997 return !!(i % ir->isoc_bei_interval);
4002 /* This is for isoc transfer */
4003 static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
4004 struct urb *urb, int slot_id, unsigned int ep_index)
4006 struct xhci_interrupter *ir;
4007 struct xhci_ring *ep_ring;
4008 struct urb_priv *urb_priv;
4010 int num_tds, trbs_per_td;
4011 struct xhci_generic_trb *start_trb;
4014 u32 field, length_field;
4015 int running_total, trb_buff_len, td_len, td_remain_len, ret;
4016 u64 start_addr, addr;
4018 bool more_trbs_coming;
4019 struct xhci_virt_ep *xep;
4022 xep = &xhci->devs[slot_id]->eps[ep_index];
4023 ep_ring = xhci->devs[slot_id]->eps[ep_index].ring;
4024 ir = xhci->interrupters[0];
4026 num_tds = urb->number_of_packets;
4028 xhci_dbg(xhci, "Isoc URB with zero packets?\n");
4031 start_addr = (u64) urb->transfer_dma;
4032 start_trb = &ep_ring->enqueue->generic;
4033 start_cycle = ep_ring->cycle_state;
4035 urb_priv = urb->hcpriv;
4036 /* Queue the TRBs for each TD, even if they are zero-length */
4037 for (i = 0; i < num_tds; i++) {
4038 unsigned int total_pkt_count, max_pkt;
4039 unsigned int burst_count, last_burst_pkt_count;
4044 addr = start_addr + urb->iso_frame_desc[i].offset;
4045 td_len = urb->iso_frame_desc[i].length;
4046 td_remain_len = td_len;
4047 max_pkt = usb_endpoint_maxp(&urb->ep->desc);
4048 total_pkt_count = DIV_ROUND_UP(td_len, max_pkt);
4050 /* A zero-length transfer still involves at least one packet. */
4051 if (total_pkt_count == 0)
4053 burst_count = xhci_get_burst_count(xhci, urb, total_pkt_count);
4054 last_burst_pkt_count = xhci_get_last_burst_packet_count(xhci,
4055 urb, total_pkt_count);
4057 trbs_per_td = count_isoc_trbs_needed(urb, i);
4059 ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index,
4060 urb->stream_id, trbs_per_td, urb, i, mem_flags);
4066 td = &urb_priv->td[i];
4067 /* use SIA as default, if frame id is used overwrite it */
4068 sia_frame_id = TRB_SIA;
4069 if (!(urb->transfer_flags & URB_ISO_ASAP) &&
4070 HCC_CFC(xhci->hcc_params)) {
4071 frame_id = xhci_get_isoc_frame_id(xhci, urb, i);
4073 sia_frame_id = TRB_FRAME_ID(frame_id);
4076 * Set isoc specific data for the first TRB in a TD.
4077 * Prevent HW from getting the TRBs by keeping the cycle state
4078 * inverted in the first TDs isoc TRB.
4080 field = TRB_TYPE(TRB_ISOC) |
4081 TRB_TLBPC(last_burst_pkt_count) |
4083 (i ? ep_ring->cycle_state : !start_cycle);
4085 /* xhci 1.1 with ETE uses TD_Size field for TBC, old is Rsvdz */
4086 if (!xep->use_extended_tbc)
4087 field |= TRB_TBC(burst_count);
4089 /* fill the rest of the TRB fields, and remaining normal TRBs */
4090 for (j = 0; j < trbs_per_td; j++) {
4093 /* only first TRB is isoc, overwrite otherwise */
4095 field = TRB_TYPE(TRB_NORMAL) |
4096 ep_ring->cycle_state;
4098 /* Only set interrupt on short packet for IN EPs */
4099 if (usb_urb_dir_in(urb))
4102 /* Set the chain bit for all except the last TRB */
4103 if (j < trbs_per_td - 1) {
4104 more_trbs_coming = true;
4107 more_trbs_coming = false;
4108 td->last_trb = ep_ring->enqueue;
4109 td->last_trb_seg = ep_ring->enq_seg;
4111 if (trb_block_event_intr(xhci, num_tds, i, ir))
4114 /* Calculate TRB length */
4115 trb_buff_len = TRB_BUFF_LEN_UP_TO_BOUNDARY(addr);
4116 if (trb_buff_len > td_remain_len)
4117 trb_buff_len = td_remain_len;
4119 /* Set the TRB length, TD size, & interrupter fields. */
4120 remainder = xhci_td_remainder(xhci, running_total,
4121 trb_buff_len, td_len,
4122 urb, more_trbs_coming);
4124 length_field = TRB_LEN(trb_buff_len) |
4127 /* xhci 1.1 with ETE uses TD Size field for TBC */
4128 if (first_trb && xep->use_extended_tbc)
4129 length_field |= TRB_TD_SIZE_TBC(burst_count);
4131 length_field |= TRB_TD_SIZE(remainder);
4134 queue_trb(xhci, ep_ring, more_trbs_coming,
4135 lower_32_bits(addr),
4136 upper_32_bits(addr),
4139 running_total += trb_buff_len;
4141 addr += trb_buff_len;
4142 td_remain_len -= trb_buff_len;
4145 /* Check TD length */
4146 if (running_total != td_len) {
4147 xhci_err(xhci, "ISOC TD length unmatch\n");
4153 /* store the next frame id */
4154 if (HCC_CFC(xhci->hcc_params))
4155 xep->next_frame_id = urb->start_frame + num_tds * urb->interval;
4157 if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) {
4158 if (xhci->quirks & XHCI_AMD_PLL_FIX)
4159 usb_amd_quirk_pll_disable();
4161 xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs++;
4163 giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
4164 start_cycle, start_trb);
4167 /* Clean up a partially enqueued isoc transfer. */
4169 for (i--; i >= 0; i--)
4170 list_del_init(&urb_priv->td[i].td_list);
4172 /* Use the first TD as a temporary variable to turn the TDs we've queued
4173 * into No-ops with a software-owned cycle bit. That way the hardware
4174 * won't accidentally start executing bogus TDs when we partially
4175 * overwrite them. td->first_trb and td->start_seg are already set.
4177 urb_priv->td[0].last_trb = ep_ring->enqueue;
4178 /* Every TRB except the first & last will have its cycle bit flipped. */
4179 td_to_noop(xhci, ep_ring, &urb_priv->td[0], true);
4181 /* Reset the ring enqueue back to the first TRB and its cycle bit. */
4182 ep_ring->enqueue = urb_priv->td[0].first_trb;
4183 ep_ring->enq_seg = urb_priv->td[0].start_seg;
4184 ep_ring->cycle_state = start_cycle;
4185 usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb);
4190 * Check transfer ring to guarantee there is enough room for the urb.
4191 * Update ISO URB start_frame and interval.
4192 * Update interval as xhci_queue_intr_tx does. Use xhci frame_index to
4193 * update urb->start_frame if URB_ISO_ASAP is set in transfer_flags or
4194 * Contiguous Frame ID is not supported by HC.
4196 int xhci_queue_isoc_tx_prepare(struct xhci_hcd *xhci, gfp_t mem_flags,
4197 struct urb *urb, int slot_id, unsigned int ep_index)
4199 struct xhci_virt_device *xdev;
4200 struct xhci_ring *ep_ring;
4201 struct xhci_ep_ctx *ep_ctx;
4203 int num_tds, num_trbs, i;
4205 struct xhci_virt_ep *xep;
4208 xdev = xhci->devs[slot_id];
4209 xep = &xhci->devs[slot_id]->eps[ep_index];
4210 ep_ring = xdev->eps[ep_index].ring;
4211 ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
4214 num_tds = urb->number_of_packets;
4215 for (i = 0; i < num_tds; i++)
4216 num_trbs += count_isoc_trbs_needed(urb, i);
4218 /* Check the ring to guarantee there is enough room for the whole urb.
4219 * Do not insert any td of the urb to the ring if the check failed.
4221 ret = prepare_ring(xhci, ep_ring, GET_EP_CTX_STATE(ep_ctx),
4222 num_trbs, mem_flags);
4227 * Check interval value. This should be done before we start to
4228 * calculate the start frame value.
4230 check_interval(urb, ep_ctx);
4232 /* Calculate the start frame and put it in urb->start_frame. */
4233 if (HCC_CFC(xhci->hcc_params) && !list_empty(&ep_ring->td_list)) {
4234 if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_RUNNING) {
4235 urb->start_frame = xep->next_frame_id;
4236 goto skip_start_over;
4240 start_frame = readl(&xhci->run_regs->microframe_index);
4241 start_frame &= 0x3fff;
4243 * Round up to the next frame and consider the time before trb really
4244 * gets scheduled by hardare.
4246 ist = HCS_IST(xhci->hcs_params2) & 0x7;
4247 if (HCS_IST(xhci->hcs_params2) & (1 << 3))
4249 start_frame += ist + XHCI_CFC_DELAY;
4250 start_frame = roundup(start_frame, 8);
4253 * Round up to the next ESIT (Endpoint Service Interval Time) if ESIT
4254 * is greate than 8 microframes.
4256 if (urb->dev->speed == USB_SPEED_LOW ||
4257 urb->dev->speed == USB_SPEED_FULL) {
4258 start_frame = roundup(start_frame, urb->interval << 3);
4259 urb->start_frame = start_frame >> 3;
4261 start_frame = roundup(start_frame, urb->interval);
4262 urb->start_frame = start_frame;
4267 return xhci_queue_isoc_tx(xhci, mem_flags, urb, slot_id, ep_index);
4270 /**** Command Ring Operations ****/
4272 /* Generic function for queueing a command TRB on the command ring.
4273 * Check to make sure there's room on the command ring for one command TRB.
4274 * Also check that there's room reserved for commands that must not fail.
4275 * If this is a command that must not fail, meaning command_must_succeed = TRUE,
4276 * then only check for the number of reserved spots.
4277 * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB
4278 * because the command event handler may want to resubmit a failed command.
4280 static int queue_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
4281 u32 field1, u32 field2,
4282 u32 field3, u32 field4, bool command_must_succeed)
4284 int reserved_trbs = xhci->cmd_ring_reserved_trbs;
4287 if ((xhci->xhc_state & XHCI_STATE_DYING) ||
4288 (xhci->xhc_state & XHCI_STATE_HALTED)) {
4289 xhci_dbg(xhci, "xHCI dying or halted, can't queue_command\n");
4293 if (!command_must_succeed)
4296 ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING,
4297 reserved_trbs, GFP_ATOMIC);
4299 xhci_err(xhci, "ERR: No room for command on command ring\n");
4300 if (command_must_succeed)
4301 xhci_err(xhci, "ERR: Reserved TRB counting for "
4302 "unfailable commands failed.\n");
4306 cmd->command_trb = xhci->cmd_ring->enqueue;
4308 /* if there are no other commands queued we start the timeout timer */
4309 if (list_empty(&xhci->cmd_list)) {
4310 xhci->current_cmd = cmd;
4311 xhci_mod_cmd_timer(xhci);
4314 list_add_tail(&cmd->cmd_list, &xhci->cmd_list);
4316 queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3,
4317 field4 | xhci->cmd_ring->cycle_state);
4321 /* Queue a slot enable or disable request on the command ring */
4322 int xhci_queue_slot_control(struct xhci_hcd *xhci, struct xhci_command *cmd,
4323 u32 trb_type, u32 slot_id)
4325 return queue_command(xhci, cmd, 0, 0, 0,
4326 TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false);
4329 /* Queue an address device command TRB */
4330 int xhci_queue_address_device(struct xhci_hcd *xhci, struct xhci_command *cmd,
4331 dma_addr_t in_ctx_ptr, u32 slot_id, enum xhci_setup_dev setup)
4333 return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4334 upper_32_bits(in_ctx_ptr), 0,
4335 TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id)
4336 | (setup == SETUP_CONTEXT_ONLY ? TRB_BSR : 0), false);
4339 int xhci_queue_vendor_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
4340 u32 field1, u32 field2, u32 field3, u32 field4)
4342 return queue_command(xhci, cmd, field1, field2, field3, field4, false);
4345 /* Queue a reset device command TRB */
4346 int xhci_queue_reset_device(struct xhci_hcd *xhci, struct xhci_command *cmd,
4349 return queue_command(xhci, cmd, 0, 0, 0,
4350 TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id),
4354 /* Queue a configure endpoint command TRB */
4355 int xhci_queue_configure_endpoint(struct xhci_hcd *xhci,
4356 struct xhci_command *cmd, dma_addr_t in_ctx_ptr,
4357 u32 slot_id, bool command_must_succeed)
4359 return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4360 upper_32_bits(in_ctx_ptr), 0,
4361 TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id),
4362 command_must_succeed);
4365 /* Queue an evaluate context command TRB */
4366 int xhci_queue_evaluate_context(struct xhci_hcd *xhci, struct xhci_command *cmd,
4367 dma_addr_t in_ctx_ptr, u32 slot_id, bool command_must_succeed)
4369 return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4370 upper_32_bits(in_ctx_ptr), 0,
4371 TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id),
4372 command_must_succeed);
4376 * Suspend is set to indicate "Stop Endpoint Command" is being issued to stop
4377 * activity on an endpoint that is about to be suspended.
4379 int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, struct xhci_command *cmd,
4380 int slot_id, unsigned int ep_index, int suspend)
4382 u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
4383 u32 trb_ep_index = EP_INDEX_FOR_TRB(ep_index);
4384 u32 type = TRB_TYPE(TRB_STOP_RING);
4385 u32 trb_suspend = SUSPEND_PORT_FOR_TRB(suspend);
4387 return queue_command(xhci, cmd, 0, 0, 0,
4388 trb_slot_id | trb_ep_index | type | trb_suspend, false);
4391 int xhci_queue_reset_ep(struct xhci_hcd *xhci, struct xhci_command *cmd,
4392 int slot_id, unsigned int ep_index,
4393 enum xhci_ep_reset_type reset_type)
4395 u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
4396 u32 trb_ep_index = EP_INDEX_FOR_TRB(ep_index);
4397 u32 type = TRB_TYPE(TRB_RESET_EP);
4399 if (reset_type == EP_SOFT_RESET)
4402 return queue_command(xhci, cmd, 0, 0, 0,
4403 trb_slot_id | trb_ep_index | type, false);