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