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