xref: /openbmc/linux/drivers/usb/host/xhci-ring.c (revision 479965a2)
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.controller;
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 {
3001 	u64 temp_64;
3002 	dma_addr_t deq;
3003 
3004 	temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
3005 	/* If necessary, update the HW's version of the event ring deq ptr. */
3006 	if (event_ring_deq != ir->event_ring->dequeue) {
3007 		deq = xhci_trb_virt_to_dma(ir->event_ring->deq_seg,
3008 				ir->event_ring->dequeue);
3009 		if (deq == 0)
3010 			xhci_warn(xhci, "WARN something wrong with SW event ring dequeue ptr\n");
3011 		/*
3012 		 * Per 4.9.4, Software writes to the ERDP register shall
3013 		 * always advance the Event Ring Dequeue Pointer value.
3014 		 */
3015 		if ((temp_64 & (u64) ~ERST_PTR_MASK) ==
3016 				((u64) deq & (u64) ~ERST_PTR_MASK))
3017 			return;
3018 
3019 		/* Update HC event ring dequeue pointer */
3020 		temp_64 &= ERST_PTR_MASK;
3021 		temp_64 |= ((u64) deq & (u64) ~ERST_PTR_MASK);
3022 	}
3023 
3024 	/* Clear the event handler busy flag (RW1C) */
3025 	temp_64 |= ERST_EHB;
3026 	xhci_write_64(xhci, temp_64, &ir->ir_set->erst_dequeue);
3027 }
3028 
3029 /*
3030  * xHCI spec says we can get an interrupt, and if the HC has an error condition,
3031  * we might get bad data out of the event ring.  Section 4.10.2.7 has a list of
3032  * indicators of an event TRB error, but we check the status *first* to be safe.
3033  */
3034 irqreturn_t xhci_irq(struct usb_hcd *hcd)
3035 {
3036 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3037 	union xhci_trb *event_ring_deq;
3038 	struct xhci_interrupter *ir;
3039 	irqreturn_t ret = IRQ_NONE;
3040 	u64 temp_64;
3041 	u32 status;
3042 	int event_loop = 0;
3043 
3044 	spin_lock(&xhci->lock);
3045 	/* Check if the xHC generated the interrupt, or the irq is shared */
3046 	status = readl(&xhci->op_regs->status);
3047 	if (status == ~(u32)0) {
3048 		xhci_hc_died(xhci);
3049 		ret = IRQ_HANDLED;
3050 		goto out;
3051 	}
3052 
3053 	if (!(status & STS_EINT))
3054 		goto out;
3055 
3056 	if (status & STS_HCE) {
3057 		xhci_warn(xhci, "WARNING: Host Controller Error\n");
3058 		goto out;
3059 	}
3060 
3061 	if (status & STS_FATAL) {
3062 		xhci_warn(xhci, "WARNING: Host System Error\n");
3063 		xhci_halt(xhci);
3064 		ret = IRQ_HANDLED;
3065 		goto out;
3066 	}
3067 
3068 	/*
3069 	 * Clear the op reg interrupt status first,
3070 	 * so we can receive interrupts from other MSI-X interrupters.
3071 	 * Write 1 to clear the interrupt status.
3072 	 */
3073 	status |= STS_EINT;
3074 	writel(status, &xhci->op_regs->status);
3075 
3076 	/* This is the handler of the primary interrupter */
3077 	ir = xhci->interrupter;
3078 	if (!hcd->msi_enabled) {
3079 		u32 irq_pending;
3080 		irq_pending = readl(&ir->ir_set->irq_pending);
3081 		irq_pending |= IMAN_IP;
3082 		writel(irq_pending, &ir->ir_set->irq_pending);
3083 	}
3084 
3085 	if (xhci->xhc_state & XHCI_STATE_DYING ||
3086 	    xhci->xhc_state & XHCI_STATE_HALTED) {
3087 		xhci_dbg(xhci, "xHCI dying, ignoring interrupt. "
3088 				"Shouldn't IRQs be disabled?\n");
3089 		/* Clear the event handler busy flag (RW1C);
3090 		 * the event ring should be empty.
3091 		 */
3092 		temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
3093 		xhci_write_64(xhci, temp_64 | ERST_EHB,
3094 				&ir->ir_set->erst_dequeue);
3095 		ret = IRQ_HANDLED;
3096 		goto out;
3097 	}
3098 
3099 	event_ring_deq = ir->event_ring->dequeue;
3100 	/* FIXME this should be a delayed service routine
3101 	 * that clears the EHB.
3102 	 */
3103 	while (xhci_handle_event(xhci, ir) > 0) {
3104 		if (event_loop++ < TRBS_PER_SEGMENT / 2)
3105 			continue;
3106 		xhci_update_erst_dequeue(xhci, ir, event_ring_deq);
3107 		event_ring_deq = ir->event_ring->dequeue;
3108 
3109 		/* ring is half-full, force isoc trbs to interrupt more often */
3110 		if (xhci->isoc_bei_interval > AVOID_BEI_INTERVAL_MIN)
3111 			xhci->isoc_bei_interval = xhci->isoc_bei_interval / 2;
3112 
3113 		event_loop = 0;
3114 	}
3115 
3116 	xhci_update_erst_dequeue(xhci, ir, event_ring_deq);
3117 	ret = IRQ_HANDLED;
3118 
3119 out:
3120 	spin_unlock(&xhci->lock);
3121 
3122 	return ret;
3123 }
3124 
3125 irqreturn_t xhci_msi_irq(int irq, void *hcd)
3126 {
3127 	return xhci_irq(hcd);
3128 }
3129 EXPORT_SYMBOL_GPL(xhci_msi_irq);
3130 
3131 /****		Endpoint Ring Operations	****/
3132 
3133 /*
3134  * Generic function for queueing a TRB on a ring.
3135  * The caller must have checked to make sure there's room on the ring.
3136  *
3137  * @more_trbs_coming:	Will you enqueue more TRBs before calling
3138  *			prepare_transfer()?
3139  */
3140 static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
3141 		bool more_trbs_coming,
3142 		u32 field1, u32 field2, u32 field3, u32 field4)
3143 {
3144 	struct xhci_generic_trb *trb;
3145 
3146 	trb = &ring->enqueue->generic;
3147 	trb->field[0] = cpu_to_le32(field1);
3148 	trb->field[1] = cpu_to_le32(field2);
3149 	trb->field[2] = cpu_to_le32(field3);
3150 	/* make sure TRB is fully written before giving it to the controller */
3151 	wmb();
3152 	trb->field[3] = cpu_to_le32(field4);
3153 
3154 	trace_xhci_queue_trb(ring, trb);
3155 
3156 	inc_enq(xhci, ring, more_trbs_coming);
3157 }
3158 
3159 /*
3160  * Does various checks on the endpoint ring, and makes it ready to queue num_trbs.
3161  * expand ring if it start to be full.
3162  */
3163 static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
3164 		u32 ep_state, unsigned int num_trbs, gfp_t mem_flags)
3165 {
3166 	unsigned int link_trb_count = 0;
3167 	unsigned int new_segs = 0;
3168 
3169 	/* Make sure the endpoint has been added to xHC schedule */
3170 	switch (ep_state) {
3171 	case EP_STATE_DISABLED:
3172 		/*
3173 		 * USB core changed config/interfaces without notifying us,
3174 		 * or hardware is reporting the wrong state.
3175 		 */
3176 		xhci_warn(xhci, "WARN urb submitted to disabled ep\n");
3177 		return -ENOENT;
3178 	case EP_STATE_ERROR:
3179 		xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n");
3180 		/* FIXME event handling code for error needs to clear it */
3181 		/* XXX not sure if this should be -ENOENT or not */
3182 		return -EINVAL;
3183 	case EP_STATE_HALTED:
3184 		xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n");
3185 		break;
3186 	case EP_STATE_STOPPED:
3187 	case EP_STATE_RUNNING:
3188 		break;
3189 	default:
3190 		xhci_err(xhci, "ERROR unknown endpoint state for ep\n");
3191 		/*
3192 		 * FIXME issue Configure Endpoint command to try to get the HC
3193 		 * back into a known state.
3194 		 */
3195 		return -EINVAL;
3196 	}
3197 
3198 	if (ep_ring != xhci->cmd_ring) {
3199 		new_segs = xhci_ring_expansion_needed(xhci, ep_ring, num_trbs);
3200 	} else if (xhci_num_trbs_free(xhci, ep_ring) <= num_trbs) {
3201 		xhci_err(xhci, "Do not support expand command ring\n");
3202 		return -ENOMEM;
3203 	}
3204 
3205 	if (new_segs) {
3206 		xhci_dbg_trace(xhci, trace_xhci_dbg_ring_expansion,
3207 				"ERROR no room on ep ring, try ring expansion");
3208 		if (xhci_ring_expansion(xhci, ep_ring, new_segs, mem_flags)) {
3209 			xhci_err(xhci, "Ring expansion failed\n");
3210 			return -ENOMEM;
3211 		}
3212 	}
3213 
3214 	while (trb_is_link(ep_ring->enqueue)) {
3215 		/* If we're not dealing with 0.95 hardware or isoc rings
3216 		 * on AMD 0.96 host, clear the chain bit.
3217 		 */
3218 		if (!xhci_link_trb_quirk(xhci) &&
3219 		    !(ep_ring->type == TYPE_ISOC &&
3220 		      (xhci->quirks & XHCI_AMD_0x96_HOST)))
3221 			ep_ring->enqueue->link.control &=
3222 				cpu_to_le32(~TRB_CHAIN);
3223 		else
3224 			ep_ring->enqueue->link.control |=
3225 				cpu_to_le32(TRB_CHAIN);
3226 
3227 		wmb();
3228 		ep_ring->enqueue->link.control ^= cpu_to_le32(TRB_CYCLE);
3229 
3230 		/* Toggle the cycle bit after the last ring segment. */
3231 		if (link_trb_toggles_cycle(ep_ring->enqueue))
3232 			ep_ring->cycle_state ^= 1;
3233 
3234 		ep_ring->enq_seg = ep_ring->enq_seg->next;
3235 		ep_ring->enqueue = ep_ring->enq_seg->trbs;
3236 
3237 		/* prevent infinite loop if all first trbs are link trbs */
3238 		if (link_trb_count++ > ep_ring->num_segs) {
3239 			xhci_warn(xhci, "Ring is an endless link TRB loop\n");
3240 			return -EINVAL;
3241 		}
3242 	}
3243 
3244 	if (last_trb_on_seg(ep_ring->enq_seg, ep_ring->enqueue)) {
3245 		xhci_warn(xhci, "Missing link TRB at end of ring segment\n");
3246 		return -EINVAL;
3247 	}
3248 
3249 	return 0;
3250 }
3251 
3252 static int prepare_transfer(struct xhci_hcd *xhci,
3253 		struct xhci_virt_device *xdev,
3254 		unsigned int ep_index,
3255 		unsigned int stream_id,
3256 		unsigned int num_trbs,
3257 		struct urb *urb,
3258 		unsigned int td_index,
3259 		gfp_t mem_flags)
3260 {
3261 	int ret;
3262 	struct urb_priv *urb_priv;
3263 	struct xhci_td	*td;
3264 	struct xhci_ring *ep_ring;
3265 	struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
3266 
3267 	ep_ring = xhci_triad_to_transfer_ring(xhci, xdev->slot_id, ep_index,
3268 					      stream_id);
3269 	if (!ep_ring) {
3270 		xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n",
3271 				stream_id);
3272 		return -EINVAL;
3273 	}
3274 
3275 	ret = prepare_ring(xhci, ep_ring, GET_EP_CTX_STATE(ep_ctx),
3276 			   num_trbs, mem_flags);
3277 	if (ret)
3278 		return ret;
3279 
3280 	urb_priv = urb->hcpriv;
3281 	td = &urb_priv->td[td_index];
3282 
3283 	INIT_LIST_HEAD(&td->td_list);
3284 	INIT_LIST_HEAD(&td->cancelled_td_list);
3285 
3286 	if (td_index == 0) {
3287 		ret = usb_hcd_link_urb_to_ep(bus_to_hcd(urb->dev->bus), urb);
3288 		if (unlikely(ret))
3289 			return ret;
3290 	}
3291 
3292 	td->urb = urb;
3293 	/* Add this TD to the tail of the endpoint ring's TD list */
3294 	list_add_tail(&td->td_list, &ep_ring->td_list);
3295 	td->start_seg = ep_ring->enq_seg;
3296 	td->first_trb = ep_ring->enqueue;
3297 
3298 	return 0;
3299 }
3300 
3301 unsigned int count_trbs(u64 addr, u64 len)
3302 {
3303 	unsigned int num_trbs;
3304 
3305 	num_trbs = DIV_ROUND_UP(len + (addr & (TRB_MAX_BUFF_SIZE - 1)),
3306 			TRB_MAX_BUFF_SIZE);
3307 	if (num_trbs == 0)
3308 		num_trbs++;
3309 
3310 	return num_trbs;
3311 }
3312 
3313 static inline unsigned int count_trbs_needed(struct urb *urb)
3314 {
3315 	return count_trbs(urb->transfer_dma, urb->transfer_buffer_length);
3316 }
3317 
3318 static unsigned int count_sg_trbs_needed(struct urb *urb)
3319 {
3320 	struct scatterlist *sg;
3321 	unsigned int i, len, full_len, num_trbs = 0;
3322 
3323 	full_len = urb->transfer_buffer_length;
3324 
3325 	for_each_sg(urb->sg, sg, urb->num_mapped_sgs, i) {
3326 		len = sg_dma_len(sg);
3327 		num_trbs += count_trbs(sg_dma_address(sg), len);
3328 		len = min_t(unsigned int, len, full_len);
3329 		full_len -= len;
3330 		if (full_len == 0)
3331 			break;
3332 	}
3333 
3334 	return num_trbs;
3335 }
3336 
3337 static unsigned int count_isoc_trbs_needed(struct urb *urb, int i)
3338 {
3339 	u64 addr, len;
3340 
3341 	addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset);
3342 	len = urb->iso_frame_desc[i].length;
3343 
3344 	return count_trbs(addr, len);
3345 }
3346 
3347 static void check_trb_math(struct urb *urb, int running_total)
3348 {
3349 	if (unlikely(running_total != urb->transfer_buffer_length))
3350 		dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, "
3351 				"queued %#x (%d), asked for %#x (%d)\n",
3352 				__func__,
3353 				urb->ep->desc.bEndpointAddress,
3354 				running_total, running_total,
3355 				urb->transfer_buffer_length,
3356 				urb->transfer_buffer_length);
3357 }
3358 
3359 static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id,
3360 		unsigned int ep_index, unsigned int stream_id, int start_cycle,
3361 		struct xhci_generic_trb *start_trb)
3362 {
3363 	/*
3364 	 * Pass all the TRBs to the hardware at once and make sure this write
3365 	 * isn't reordered.
3366 	 */
3367 	wmb();
3368 	if (start_cycle)
3369 		start_trb->field[3] |= cpu_to_le32(start_cycle);
3370 	else
3371 		start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE);
3372 	xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
3373 }
3374 
3375 static void check_interval(struct xhci_hcd *xhci, struct urb *urb,
3376 						struct xhci_ep_ctx *ep_ctx)
3377 {
3378 	int xhci_interval;
3379 	int ep_interval;
3380 
3381 	xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info));
3382 	ep_interval = urb->interval;
3383 
3384 	/* Convert to microframes */
3385 	if (urb->dev->speed == USB_SPEED_LOW ||
3386 			urb->dev->speed == USB_SPEED_FULL)
3387 		ep_interval *= 8;
3388 
3389 	/* FIXME change this to a warning and a suggestion to use the new API
3390 	 * to set the polling interval (once the API is added).
3391 	 */
3392 	if (xhci_interval != ep_interval) {
3393 		dev_dbg_ratelimited(&urb->dev->dev,
3394 				"Driver uses different interval (%d microframe%s) than xHCI (%d microframe%s)\n",
3395 				ep_interval, ep_interval == 1 ? "" : "s",
3396 				xhci_interval, xhci_interval == 1 ? "" : "s");
3397 		urb->interval = xhci_interval;
3398 		/* Convert back to frames for LS/FS devices */
3399 		if (urb->dev->speed == USB_SPEED_LOW ||
3400 				urb->dev->speed == USB_SPEED_FULL)
3401 			urb->interval /= 8;
3402 	}
3403 }
3404 
3405 /*
3406  * xHCI uses normal TRBs for both bulk and interrupt.  When the interrupt
3407  * endpoint is to be serviced, the xHC will consume (at most) one TD.  A TD
3408  * (comprised of sg list entries) can take several service intervals to
3409  * transmit.
3410  */
3411 int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3412 		struct urb *urb, int slot_id, unsigned int ep_index)
3413 {
3414 	struct xhci_ep_ctx *ep_ctx;
3415 
3416 	ep_ctx = xhci_get_ep_ctx(xhci, xhci->devs[slot_id]->out_ctx, ep_index);
3417 	check_interval(xhci, urb, ep_ctx);
3418 
3419 	return xhci_queue_bulk_tx(xhci, mem_flags, urb, slot_id, ep_index);
3420 }
3421 
3422 /*
3423  * For xHCI 1.0 host controllers, TD size is the number of max packet sized
3424  * packets remaining in the TD (*not* including this TRB).
3425  *
3426  * Total TD packet count = total_packet_count =
3427  *     DIV_ROUND_UP(TD size in bytes / wMaxPacketSize)
3428  *
3429  * Packets transferred up to and including this TRB = packets_transferred =
3430  *     rounddown(total bytes transferred including this TRB / wMaxPacketSize)
3431  *
3432  * TD size = total_packet_count - packets_transferred
3433  *
3434  * For xHCI 0.96 and older, TD size field should be the remaining bytes
3435  * including this TRB, right shifted by 10
3436  *
3437  * For all hosts it must fit in bits 21:17, so it can't be bigger than 31.
3438  * This is taken care of in the TRB_TD_SIZE() macro
3439  *
3440  * The last TRB in a TD must have the TD size set to zero.
3441  */
3442 static u32 xhci_td_remainder(struct xhci_hcd *xhci, int transferred,
3443 			      int trb_buff_len, unsigned int td_total_len,
3444 			      struct urb *urb, bool more_trbs_coming)
3445 {
3446 	u32 maxp, total_packet_count;
3447 
3448 	/* MTK xHCI 0.96 contains some features from 1.0 */
3449 	if (xhci->hci_version < 0x100 && !(xhci->quirks & XHCI_MTK_HOST))
3450 		return ((td_total_len - transferred) >> 10);
3451 
3452 	/* One TRB with a zero-length data packet. */
3453 	if (!more_trbs_coming || (transferred == 0 && trb_buff_len == 0) ||
3454 	    trb_buff_len == td_total_len)
3455 		return 0;
3456 
3457 	/* for MTK xHCI 0.96, TD size include this TRB, but not in 1.x */
3458 	if ((xhci->quirks & XHCI_MTK_HOST) && (xhci->hci_version < 0x100))
3459 		trb_buff_len = 0;
3460 
3461 	maxp = usb_endpoint_maxp(&urb->ep->desc);
3462 	total_packet_count = DIV_ROUND_UP(td_total_len, maxp);
3463 
3464 	/* Queueing functions don't count the current TRB into transferred */
3465 	return (total_packet_count - ((transferred + trb_buff_len) / maxp));
3466 }
3467 
3468 
3469 static int xhci_align_td(struct xhci_hcd *xhci, struct urb *urb, u32 enqd_len,
3470 			 u32 *trb_buff_len, struct xhci_segment *seg)
3471 {
3472 	struct device *dev = xhci_to_hcd(xhci)->self.controller;
3473 	unsigned int unalign;
3474 	unsigned int max_pkt;
3475 	u32 new_buff_len;
3476 	size_t len;
3477 
3478 	max_pkt = usb_endpoint_maxp(&urb->ep->desc);
3479 	unalign = (enqd_len + *trb_buff_len) % max_pkt;
3480 
3481 	/* we got lucky, last normal TRB data on segment is packet aligned */
3482 	if (unalign == 0)
3483 		return 0;
3484 
3485 	xhci_dbg(xhci, "Unaligned %d bytes, buff len %d\n",
3486 		 unalign, *trb_buff_len);
3487 
3488 	/* is the last nornal TRB alignable by splitting it */
3489 	if (*trb_buff_len > unalign) {
3490 		*trb_buff_len -= unalign;
3491 		xhci_dbg(xhci, "split align, new buff len %d\n", *trb_buff_len);
3492 		return 0;
3493 	}
3494 
3495 	/*
3496 	 * We want enqd_len + trb_buff_len to sum up to a number aligned to
3497 	 * number which is divisible by the endpoint's wMaxPacketSize. IOW:
3498 	 * (size of currently enqueued TRBs + remainder) % wMaxPacketSize == 0.
3499 	 */
3500 	new_buff_len = max_pkt - (enqd_len % max_pkt);
3501 
3502 	if (new_buff_len > (urb->transfer_buffer_length - enqd_len))
3503 		new_buff_len = (urb->transfer_buffer_length - enqd_len);
3504 
3505 	/* create a max max_pkt sized bounce buffer pointed to by last trb */
3506 	if (usb_urb_dir_out(urb)) {
3507 		if (urb->num_sgs) {
3508 			len = sg_pcopy_to_buffer(urb->sg, urb->num_sgs,
3509 						 seg->bounce_buf, new_buff_len, enqd_len);
3510 			if (len != new_buff_len)
3511 				xhci_warn(xhci, "WARN Wrong bounce buffer write length: %zu != %d\n",
3512 					  len, new_buff_len);
3513 		} else {
3514 			memcpy(seg->bounce_buf, urb->transfer_buffer + enqd_len, new_buff_len);
3515 		}
3516 
3517 		seg->bounce_dma = dma_map_single(dev, seg->bounce_buf,
3518 						 max_pkt, DMA_TO_DEVICE);
3519 	} else {
3520 		seg->bounce_dma = dma_map_single(dev, seg->bounce_buf,
3521 						 max_pkt, DMA_FROM_DEVICE);
3522 	}
3523 
3524 	if (dma_mapping_error(dev, seg->bounce_dma)) {
3525 		/* try without aligning. Some host controllers survive */
3526 		xhci_warn(xhci, "Failed mapping bounce buffer, not aligning\n");
3527 		return 0;
3528 	}
3529 	*trb_buff_len = new_buff_len;
3530 	seg->bounce_len = new_buff_len;
3531 	seg->bounce_offs = enqd_len;
3532 
3533 	xhci_dbg(xhci, "Bounce align, new buff len %d\n", *trb_buff_len);
3534 
3535 	return 1;
3536 }
3537 
3538 /* This is very similar to what ehci-q.c qtd_fill() does */
3539 int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3540 		struct urb *urb, int slot_id, unsigned int ep_index)
3541 {
3542 	struct xhci_ring *ring;
3543 	struct urb_priv *urb_priv;
3544 	struct xhci_td *td;
3545 	struct xhci_generic_trb *start_trb;
3546 	struct scatterlist *sg = NULL;
3547 	bool more_trbs_coming = true;
3548 	bool need_zero_pkt = false;
3549 	bool first_trb = true;
3550 	unsigned int num_trbs;
3551 	unsigned int start_cycle, num_sgs = 0;
3552 	unsigned int enqd_len, block_len, trb_buff_len, full_len;
3553 	int sent_len, ret;
3554 	u32 field, length_field, remainder;
3555 	u64 addr, send_addr;
3556 
3557 	ring = xhci_urb_to_transfer_ring(xhci, urb);
3558 	if (!ring)
3559 		return -EINVAL;
3560 
3561 	full_len = urb->transfer_buffer_length;
3562 	/* If we have scatter/gather list, we use it. */
3563 	if (urb->num_sgs && !(urb->transfer_flags & URB_DMA_MAP_SINGLE)) {
3564 		num_sgs = urb->num_mapped_sgs;
3565 		sg = urb->sg;
3566 		addr = (u64) sg_dma_address(sg);
3567 		block_len = sg_dma_len(sg);
3568 		num_trbs = count_sg_trbs_needed(urb);
3569 	} else {
3570 		num_trbs = count_trbs_needed(urb);
3571 		addr = (u64) urb->transfer_dma;
3572 		block_len = full_len;
3573 	}
3574 	ret = prepare_transfer(xhci, xhci->devs[slot_id],
3575 			ep_index, urb->stream_id,
3576 			num_trbs, urb, 0, mem_flags);
3577 	if (unlikely(ret < 0))
3578 		return ret;
3579 
3580 	urb_priv = urb->hcpriv;
3581 
3582 	/* Deal with URB_ZERO_PACKET - need one more td/trb */
3583 	if (urb->transfer_flags & URB_ZERO_PACKET && urb_priv->num_tds > 1)
3584 		need_zero_pkt = true;
3585 
3586 	td = &urb_priv->td[0];
3587 
3588 	/*
3589 	 * Don't give the first TRB to the hardware (by toggling the cycle bit)
3590 	 * until we've finished creating all the other TRBs.  The ring's cycle
3591 	 * state may change as we enqueue the other TRBs, so save it too.
3592 	 */
3593 	start_trb = &ring->enqueue->generic;
3594 	start_cycle = ring->cycle_state;
3595 	send_addr = addr;
3596 
3597 	/* Queue the TRBs, even if they are zero-length */
3598 	for (enqd_len = 0; first_trb || enqd_len < full_len;
3599 			enqd_len += trb_buff_len) {
3600 		field = TRB_TYPE(TRB_NORMAL);
3601 
3602 		/* TRB buffer should not cross 64KB boundaries */
3603 		trb_buff_len = TRB_BUFF_LEN_UP_TO_BOUNDARY(addr);
3604 		trb_buff_len = min_t(unsigned int, trb_buff_len, block_len);
3605 
3606 		if (enqd_len + trb_buff_len > full_len)
3607 			trb_buff_len = full_len - enqd_len;
3608 
3609 		/* Don't change the cycle bit of the first TRB until later */
3610 		if (first_trb) {
3611 			first_trb = false;
3612 			if (start_cycle == 0)
3613 				field |= TRB_CYCLE;
3614 		} else
3615 			field |= ring->cycle_state;
3616 
3617 		/* Chain all the TRBs together; clear the chain bit in the last
3618 		 * TRB to indicate it's the last TRB in the chain.
3619 		 */
3620 		if (enqd_len + trb_buff_len < full_len) {
3621 			field |= TRB_CHAIN;
3622 			if (trb_is_link(ring->enqueue + 1)) {
3623 				if (xhci_align_td(xhci, urb, enqd_len,
3624 						  &trb_buff_len,
3625 						  ring->enq_seg)) {
3626 					send_addr = ring->enq_seg->bounce_dma;
3627 					/* assuming TD won't span 2 segs */
3628 					td->bounce_seg = ring->enq_seg;
3629 				}
3630 			}
3631 		}
3632 		if (enqd_len + trb_buff_len >= full_len) {
3633 			field &= ~TRB_CHAIN;
3634 			field |= TRB_IOC;
3635 			more_trbs_coming = false;
3636 			td->last_trb = ring->enqueue;
3637 			td->last_trb_seg = ring->enq_seg;
3638 			if (xhci_urb_suitable_for_idt(urb)) {
3639 				memcpy(&send_addr, urb->transfer_buffer,
3640 				       trb_buff_len);
3641 				le64_to_cpus(&send_addr);
3642 				field |= TRB_IDT;
3643 			}
3644 		}
3645 
3646 		/* Only set interrupt on short packet for IN endpoints */
3647 		if (usb_urb_dir_in(urb))
3648 			field |= TRB_ISP;
3649 
3650 		/* Set the TRB length, TD size, and interrupter fields. */
3651 		remainder = xhci_td_remainder(xhci, enqd_len, trb_buff_len,
3652 					      full_len, urb, more_trbs_coming);
3653 
3654 		length_field = TRB_LEN(trb_buff_len) |
3655 			TRB_TD_SIZE(remainder) |
3656 			TRB_INTR_TARGET(0);
3657 
3658 		queue_trb(xhci, ring, more_trbs_coming | need_zero_pkt,
3659 				lower_32_bits(send_addr),
3660 				upper_32_bits(send_addr),
3661 				length_field,
3662 				field);
3663 		td->num_trbs++;
3664 		addr += trb_buff_len;
3665 		sent_len = trb_buff_len;
3666 
3667 		while (sg && sent_len >= block_len) {
3668 			/* New sg entry */
3669 			--num_sgs;
3670 			sent_len -= block_len;
3671 			sg = sg_next(sg);
3672 			if (num_sgs != 0 && sg) {
3673 				block_len = sg_dma_len(sg);
3674 				addr = (u64) sg_dma_address(sg);
3675 				addr += sent_len;
3676 			}
3677 		}
3678 		block_len -= sent_len;
3679 		send_addr = addr;
3680 	}
3681 
3682 	if (need_zero_pkt) {
3683 		ret = prepare_transfer(xhci, xhci->devs[slot_id],
3684 				       ep_index, urb->stream_id,
3685 				       1, urb, 1, mem_flags);
3686 		urb_priv->td[1].last_trb = ring->enqueue;
3687 		urb_priv->td[1].last_trb_seg = ring->enq_seg;
3688 		field = TRB_TYPE(TRB_NORMAL) | ring->cycle_state | TRB_IOC;
3689 		queue_trb(xhci, ring, 0, 0, 0, TRB_INTR_TARGET(0), field);
3690 		urb_priv->td[1].num_trbs++;
3691 	}
3692 
3693 	check_trb_math(urb, enqd_len);
3694 	giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
3695 			start_cycle, start_trb);
3696 	return 0;
3697 }
3698 
3699 /* Caller must have locked xhci->lock */
3700 int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3701 		struct urb *urb, int slot_id, unsigned int ep_index)
3702 {
3703 	struct xhci_ring *ep_ring;
3704 	int num_trbs;
3705 	int ret;
3706 	struct usb_ctrlrequest *setup;
3707 	struct xhci_generic_trb *start_trb;
3708 	int start_cycle;
3709 	u32 field;
3710 	struct urb_priv *urb_priv;
3711 	struct xhci_td *td;
3712 
3713 	ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
3714 	if (!ep_ring)
3715 		return -EINVAL;
3716 
3717 	/*
3718 	 * Need to copy setup packet into setup TRB, so we can't use the setup
3719 	 * DMA address.
3720 	 */
3721 	if (!urb->setup_packet)
3722 		return -EINVAL;
3723 
3724 	/* 1 TRB for setup, 1 for status */
3725 	num_trbs = 2;
3726 	/*
3727 	 * Don't need to check if we need additional event data and normal TRBs,
3728 	 * since data in control transfers will never get bigger than 16MB
3729 	 * XXX: can we get a buffer that crosses 64KB boundaries?
3730 	 */
3731 	if (urb->transfer_buffer_length > 0)
3732 		num_trbs++;
3733 	ret = prepare_transfer(xhci, xhci->devs[slot_id],
3734 			ep_index, urb->stream_id,
3735 			num_trbs, urb, 0, mem_flags);
3736 	if (ret < 0)
3737 		return ret;
3738 
3739 	urb_priv = urb->hcpriv;
3740 	td = &urb_priv->td[0];
3741 	td->num_trbs = num_trbs;
3742 
3743 	/*
3744 	 * Don't give the first TRB to the hardware (by toggling the cycle bit)
3745 	 * until we've finished creating all the other TRBs.  The ring's cycle
3746 	 * state may change as we enqueue the other TRBs, so save it too.
3747 	 */
3748 	start_trb = &ep_ring->enqueue->generic;
3749 	start_cycle = ep_ring->cycle_state;
3750 
3751 	/* Queue setup TRB - see section 6.4.1.2.1 */
3752 	/* FIXME better way to translate setup_packet into two u32 fields? */
3753 	setup = (struct usb_ctrlrequest *) urb->setup_packet;
3754 	field = 0;
3755 	field |= TRB_IDT | TRB_TYPE(TRB_SETUP);
3756 	if (start_cycle == 0)
3757 		field |= 0x1;
3758 
3759 	/* xHCI 1.0/1.1 6.4.1.2.1: Transfer Type field */
3760 	if ((xhci->hci_version >= 0x100) || (xhci->quirks & XHCI_MTK_HOST)) {
3761 		if (urb->transfer_buffer_length > 0) {
3762 			if (setup->bRequestType & USB_DIR_IN)
3763 				field |= TRB_TX_TYPE(TRB_DATA_IN);
3764 			else
3765 				field |= TRB_TX_TYPE(TRB_DATA_OUT);
3766 		}
3767 	}
3768 
3769 	queue_trb(xhci, ep_ring, true,
3770 		  setup->bRequestType | setup->bRequest << 8 | le16_to_cpu(setup->wValue) << 16,
3771 		  le16_to_cpu(setup->wIndex) | le16_to_cpu(setup->wLength) << 16,
3772 		  TRB_LEN(8) | TRB_INTR_TARGET(0),
3773 		  /* Immediate data in pointer */
3774 		  field);
3775 
3776 	/* If there's data, queue data TRBs */
3777 	/* Only set interrupt on short packet for IN endpoints */
3778 	if (usb_urb_dir_in(urb))
3779 		field = TRB_ISP | TRB_TYPE(TRB_DATA);
3780 	else
3781 		field = TRB_TYPE(TRB_DATA);
3782 
3783 	if (urb->transfer_buffer_length > 0) {
3784 		u32 length_field, remainder;
3785 		u64 addr;
3786 
3787 		if (xhci_urb_suitable_for_idt(urb)) {
3788 			memcpy(&addr, urb->transfer_buffer,
3789 			       urb->transfer_buffer_length);
3790 			le64_to_cpus(&addr);
3791 			field |= TRB_IDT;
3792 		} else {
3793 			addr = (u64) urb->transfer_dma;
3794 		}
3795 
3796 		remainder = xhci_td_remainder(xhci, 0,
3797 				urb->transfer_buffer_length,
3798 				urb->transfer_buffer_length,
3799 				urb, 1);
3800 		length_field = TRB_LEN(urb->transfer_buffer_length) |
3801 				TRB_TD_SIZE(remainder) |
3802 				TRB_INTR_TARGET(0);
3803 		if (setup->bRequestType & USB_DIR_IN)
3804 			field |= TRB_DIR_IN;
3805 		queue_trb(xhci, ep_ring, true,
3806 				lower_32_bits(addr),
3807 				upper_32_bits(addr),
3808 				length_field,
3809 				field | ep_ring->cycle_state);
3810 	}
3811 
3812 	/* Save the DMA address of the last TRB in the TD */
3813 	td->last_trb = ep_ring->enqueue;
3814 	td->last_trb_seg = ep_ring->enq_seg;
3815 
3816 	/* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */
3817 	/* If the device sent data, the status stage is an OUT transfer */
3818 	if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN)
3819 		field = 0;
3820 	else
3821 		field = TRB_DIR_IN;
3822 	queue_trb(xhci, ep_ring, false,
3823 			0,
3824 			0,
3825 			TRB_INTR_TARGET(0),
3826 			/* Event on completion */
3827 			field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state);
3828 
3829 	giveback_first_trb(xhci, slot_id, ep_index, 0,
3830 			start_cycle, start_trb);
3831 	return 0;
3832 }
3833 
3834 /*
3835  * The transfer burst count field of the isochronous TRB defines the number of
3836  * bursts that are required to move all packets in this TD.  Only SuperSpeed
3837  * devices can burst up to bMaxBurst number of packets per service interval.
3838  * This field is zero based, meaning a value of zero in the field means one
3839  * burst.  Basically, for everything but SuperSpeed devices, this field will be
3840  * zero.  Only xHCI 1.0 host controllers support this field.
3841  */
3842 static unsigned int xhci_get_burst_count(struct xhci_hcd *xhci,
3843 		struct urb *urb, unsigned int total_packet_count)
3844 {
3845 	unsigned int max_burst;
3846 
3847 	if (xhci->hci_version < 0x100 || urb->dev->speed < USB_SPEED_SUPER)
3848 		return 0;
3849 
3850 	max_burst = urb->ep->ss_ep_comp.bMaxBurst;
3851 	return DIV_ROUND_UP(total_packet_count, max_burst + 1) - 1;
3852 }
3853 
3854 /*
3855  * Returns the number of packets in the last "burst" of packets.  This field is
3856  * valid for all speeds of devices.  USB 2.0 devices can only do one "burst", so
3857  * the last burst packet count is equal to the total number of packets in the
3858  * TD.  SuperSpeed endpoints can have up to 3 bursts.  All but the last burst
3859  * must contain (bMaxBurst + 1) number of packets, but the last burst can
3860  * contain 1 to (bMaxBurst + 1) packets.
3861  */
3862 static unsigned int xhci_get_last_burst_packet_count(struct xhci_hcd *xhci,
3863 		struct urb *urb, unsigned int total_packet_count)
3864 {
3865 	unsigned int max_burst;
3866 	unsigned int residue;
3867 
3868 	if (xhci->hci_version < 0x100)
3869 		return 0;
3870 
3871 	if (urb->dev->speed >= USB_SPEED_SUPER) {
3872 		/* bMaxBurst is zero based: 0 means 1 packet per burst */
3873 		max_burst = urb->ep->ss_ep_comp.bMaxBurst;
3874 		residue = total_packet_count % (max_burst + 1);
3875 		/* If residue is zero, the last burst contains (max_burst + 1)
3876 		 * number of packets, but the TLBPC field is zero-based.
3877 		 */
3878 		if (residue == 0)
3879 			return max_burst;
3880 		return residue - 1;
3881 	}
3882 	if (total_packet_count == 0)
3883 		return 0;
3884 	return total_packet_count - 1;
3885 }
3886 
3887 /*
3888  * Calculates Frame ID field of the isochronous TRB identifies the
3889  * target frame that the Interval associated with this Isochronous
3890  * Transfer Descriptor will start on. Refer to 4.11.2.5 in 1.1 spec.
3891  *
3892  * Returns actual frame id on success, negative value on error.
3893  */
3894 static int xhci_get_isoc_frame_id(struct xhci_hcd *xhci,
3895 		struct urb *urb, int index)
3896 {
3897 	int start_frame, ist, ret = 0;
3898 	int start_frame_id, end_frame_id, current_frame_id;
3899 
3900 	if (urb->dev->speed == USB_SPEED_LOW ||
3901 			urb->dev->speed == USB_SPEED_FULL)
3902 		start_frame = urb->start_frame + index * urb->interval;
3903 	else
3904 		start_frame = (urb->start_frame + index * urb->interval) >> 3;
3905 
3906 	/* Isochronous Scheduling Threshold (IST, bits 0~3 in HCSPARAMS2):
3907 	 *
3908 	 * If bit [3] of IST is cleared to '0', software can add a TRB no
3909 	 * later than IST[2:0] Microframes before that TRB is scheduled to
3910 	 * be executed.
3911 	 * If bit [3] of IST is set to '1', software can add a TRB no later
3912 	 * than IST[2:0] Frames before that TRB is scheduled to be executed.
3913 	 */
3914 	ist = HCS_IST(xhci->hcs_params2) & 0x7;
3915 	if (HCS_IST(xhci->hcs_params2) & (1 << 3))
3916 		ist <<= 3;
3917 
3918 	/* Software shall not schedule an Isoch TD with a Frame ID value that
3919 	 * is less than the Start Frame ID or greater than the End Frame ID,
3920 	 * where:
3921 	 *
3922 	 * End Frame ID = (Current MFINDEX register value + 895 ms.) MOD 2048
3923 	 * Start Frame ID = (Current MFINDEX register value + IST + 1) MOD 2048
3924 	 *
3925 	 * Both the End Frame ID and Start Frame ID values are calculated
3926 	 * in microframes. When software determines the valid Frame ID value;
3927 	 * The End Frame ID value should be rounded down to the nearest Frame
3928 	 * boundary, and the Start Frame ID value should be rounded up to the
3929 	 * nearest Frame boundary.
3930 	 */
3931 	current_frame_id = readl(&xhci->run_regs->microframe_index);
3932 	start_frame_id = roundup(current_frame_id + ist + 1, 8);
3933 	end_frame_id = rounddown(current_frame_id + 895 * 8, 8);
3934 
3935 	start_frame &= 0x7ff;
3936 	start_frame_id = (start_frame_id >> 3) & 0x7ff;
3937 	end_frame_id = (end_frame_id >> 3) & 0x7ff;
3938 
3939 	xhci_dbg(xhci, "%s: index %d, reg 0x%x start_frame_id 0x%x, end_frame_id 0x%x, start_frame 0x%x\n",
3940 		 __func__, index, readl(&xhci->run_regs->microframe_index),
3941 		 start_frame_id, end_frame_id, start_frame);
3942 
3943 	if (start_frame_id < end_frame_id) {
3944 		if (start_frame > end_frame_id ||
3945 				start_frame < start_frame_id)
3946 			ret = -EINVAL;
3947 	} else if (start_frame_id > end_frame_id) {
3948 		if ((start_frame > end_frame_id &&
3949 				start_frame < start_frame_id))
3950 			ret = -EINVAL;
3951 	} else {
3952 			ret = -EINVAL;
3953 	}
3954 
3955 	if (index == 0) {
3956 		if (ret == -EINVAL || start_frame == start_frame_id) {
3957 			start_frame = start_frame_id + 1;
3958 			if (urb->dev->speed == USB_SPEED_LOW ||
3959 					urb->dev->speed == USB_SPEED_FULL)
3960 				urb->start_frame = start_frame;
3961 			else
3962 				urb->start_frame = start_frame << 3;
3963 			ret = 0;
3964 		}
3965 	}
3966 
3967 	if (ret) {
3968 		xhci_warn(xhci, "Frame ID %d (reg %d, index %d) beyond range (%d, %d)\n",
3969 				start_frame, current_frame_id, index,
3970 				start_frame_id, end_frame_id);
3971 		xhci_warn(xhci, "Ignore frame ID field, use SIA bit instead\n");
3972 		return ret;
3973 	}
3974 
3975 	return start_frame;
3976 }
3977 
3978 /* Check if we should generate event interrupt for a TD in an isoc URB */
3979 static bool trb_block_event_intr(struct xhci_hcd *xhci, int num_tds, int i)
3980 {
3981 	if (xhci->hci_version < 0x100)
3982 		return false;
3983 	/* always generate an event interrupt for the last TD */
3984 	if (i == num_tds - 1)
3985 		return false;
3986 	/*
3987 	 * If AVOID_BEI is set the host handles full event rings poorly,
3988 	 * generate an event at least every 8th TD to clear the event ring
3989 	 */
3990 	if (i && xhci->quirks & XHCI_AVOID_BEI)
3991 		return !!(i % xhci->isoc_bei_interval);
3992 
3993 	return true;
3994 }
3995 
3996 /* This is for isoc transfer */
3997 static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3998 		struct urb *urb, int slot_id, unsigned int ep_index)
3999 {
4000 	struct xhci_ring *ep_ring;
4001 	struct urb_priv *urb_priv;
4002 	struct xhci_td *td;
4003 	int num_tds, trbs_per_td;
4004 	struct xhci_generic_trb *start_trb;
4005 	bool first_trb;
4006 	int start_cycle;
4007 	u32 field, length_field;
4008 	int running_total, trb_buff_len, td_len, td_remain_len, ret;
4009 	u64 start_addr, addr;
4010 	int i, j;
4011 	bool more_trbs_coming;
4012 	struct xhci_virt_ep *xep;
4013 	int frame_id;
4014 
4015 	xep = &xhci->devs[slot_id]->eps[ep_index];
4016 	ep_ring = xhci->devs[slot_id]->eps[ep_index].ring;
4017 
4018 	num_tds = urb->number_of_packets;
4019 	if (num_tds < 1) {
4020 		xhci_dbg(xhci, "Isoc URB with zero packets?\n");
4021 		return -EINVAL;
4022 	}
4023 	start_addr = (u64) urb->transfer_dma;
4024 	start_trb = &ep_ring->enqueue->generic;
4025 	start_cycle = ep_ring->cycle_state;
4026 
4027 	urb_priv = urb->hcpriv;
4028 	/* Queue the TRBs for each TD, even if they are zero-length */
4029 	for (i = 0; i < num_tds; i++) {
4030 		unsigned int total_pkt_count, max_pkt;
4031 		unsigned int burst_count, last_burst_pkt_count;
4032 		u32 sia_frame_id;
4033 
4034 		first_trb = true;
4035 		running_total = 0;
4036 		addr = start_addr + urb->iso_frame_desc[i].offset;
4037 		td_len = urb->iso_frame_desc[i].length;
4038 		td_remain_len = td_len;
4039 		max_pkt = usb_endpoint_maxp(&urb->ep->desc);
4040 		total_pkt_count = DIV_ROUND_UP(td_len, max_pkt);
4041 
4042 		/* A zero-length transfer still involves at least one packet. */
4043 		if (total_pkt_count == 0)
4044 			total_pkt_count++;
4045 		burst_count = xhci_get_burst_count(xhci, urb, total_pkt_count);
4046 		last_burst_pkt_count = xhci_get_last_burst_packet_count(xhci,
4047 							urb, total_pkt_count);
4048 
4049 		trbs_per_td = count_isoc_trbs_needed(urb, i);
4050 
4051 		ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index,
4052 				urb->stream_id, trbs_per_td, urb, i, mem_flags);
4053 		if (ret < 0) {
4054 			if (i == 0)
4055 				return ret;
4056 			goto cleanup;
4057 		}
4058 		td = &urb_priv->td[i];
4059 		td->num_trbs = trbs_per_td;
4060 		/* use SIA as default, if frame id is used overwrite it */
4061 		sia_frame_id = TRB_SIA;
4062 		if (!(urb->transfer_flags & URB_ISO_ASAP) &&
4063 		    HCC_CFC(xhci->hcc_params)) {
4064 			frame_id = xhci_get_isoc_frame_id(xhci, urb, i);
4065 			if (frame_id >= 0)
4066 				sia_frame_id = TRB_FRAME_ID(frame_id);
4067 		}
4068 		/*
4069 		 * Set isoc specific data for the first TRB in a TD.
4070 		 * Prevent HW from getting the TRBs by keeping the cycle state
4071 		 * inverted in the first TDs isoc TRB.
4072 		 */
4073 		field = TRB_TYPE(TRB_ISOC) |
4074 			TRB_TLBPC(last_burst_pkt_count) |
4075 			sia_frame_id |
4076 			(i ? ep_ring->cycle_state : !start_cycle);
4077 
4078 		/* xhci 1.1 with ETE uses TD_Size field for TBC, old is Rsvdz */
4079 		if (!xep->use_extended_tbc)
4080 			field |= TRB_TBC(burst_count);
4081 
4082 		/* fill the rest of the TRB fields, and remaining normal TRBs */
4083 		for (j = 0; j < trbs_per_td; j++) {
4084 			u32 remainder = 0;
4085 
4086 			/* only first TRB is isoc, overwrite otherwise */
4087 			if (!first_trb)
4088 				field = TRB_TYPE(TRB_NORMAL) |
4089 					ep_ring->cycle_state;
4090 
4091 			/* Only set interrupt on short packet for IN EPs */
4092 			if (usb_urb_dir_in(urb))
4093 				field |= TRB_ISP;
4094 
4095 			/* Set the chain bit for all except the last TRB  */
4096 			if (j < trbs_per_td - 1) {
4097 				more_trbs_coming = true;
4098 				field |= TRB_CHAIN;
4099 			} else {
4100 				more_trbs_coming = false;
4101 				td->last_trb = ep_ring->enqueue;
4102 				td->last_trb_seg = ep_ring->enq_seg;
4103 				field |= TRB_IOC;
4104 				if (trb_block_event_intr(xhci, num_tds, i))
4105 					field |= TRB_BEI;
4106 			}
4107 			/* Calculate TRB length */
4108 			trb_buff_len = TRB_BUFF_LEN_UP_TO_BOUNDARY(addr);
4109 			if (trb_buff_len > td_remain_len)
4110 				trb_buff_len = td_remain_len;
4111 
4112 			/* Set the TRB length, TD size, & interrupter fields. */
4113 			remainder = xhci_td_remainder(xhci, running_total,
4114 						   trb_buff_len, td_len,
4115 						   urb, more_trbs_coming);
4116 
4117 			length_field = TRB_LEN(trb_buff_len) |
4118 				TRB_INTR_TARGET(0);
4119 
4120 			/* xhci 1.1 with ETE uses TD Size field for TBC */
4121 			if (first_trb && xep->use_extended_tbc)
4122 				length_field |= TRB_TD_SIZE_TBC(burst_count);
4123 			else
4124 				length_field |= TRB_TD_SIZE(remainder);
4125 			first_trb = false;
4126 
4127 			queue_trb(xhci, ep_ring, more_trbs_coming,
4128 				lower_32_bits(addr),
4129 				upper_32_bits(addr),
4130 				length_field,
4131 				field);
4132 			running_total += trb_buff_len;
4133 
4134 			addr += trb_buff_len;
4135 			td_remain_len -= trb_buff_len;
4136 		}
4137 
4138 		/* Check TD length */
4139 		if (running_total != td_len) {
4140 			xhci_err(xhci, "ISOC TD length unmatch\n");
4141 			ret = -EINVAL;
4142 			goto cleanup;
4143 		}
4144 	}
4145 
4146 	/* store the next frame id */
4147 	if (HCC_CFC(xhci->hcc_params))
4148 		xep->next_frame_id = urb->start_frame + num_tds * urb->interval;
4149 
4150 	if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) {
4151 		if (xhci->quirks & XHCI_AMD_PLL_FIX)
4152 			usb_amd_quirk_pll_disable();
4153 	}
4154 	xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs++;
4155 
4156 	giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
4157 			start_cycle, start_trb);
4158 	return 0;
4159 cleanup:
4160 	/* Clean up a partially enqueued isoc transfer. */
4161 
4162 	for (i--; i >= 0; i--)
4163 		list_del_init(&urb_priv->td[i].td_list);
4164 
4165 	/* Use the first TD as a temporary variable to turn the TDs we've queued
4166 	 * into No-ops with a software-owned cycle bit. That way the hardware
4167 	 * won't accidentally start executing bogus TDs when we partially
4168 	 * overwrite them.  td->first_trb and td->start_seg are already set.
4169 	 */
4170 	urb_priv->td[0].last_trb = ep_ring->enqueue;
4171 	/* Every TRB except the first & last will have its cycle bit flipped. */
4172 	td_to_noop(xhci, ep_ring, &urb_priv->td[0], true);
4173 
4174 	/* Reset the ring enqueue back to the first TRB and its cycle bit. */
4175 	ep_ring->enqueue = urb_priv->td[0].first_trb;
4176 	ep_ring->enq_seg = urb_priv->td[0].start_seg;
4177 	ep_ring->cycle_state = start_cycle;
4178 	usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb);
4179 	return ret;
4180 }
4181 
4182 /*
4183  * Check transfer ring to guarantee there is enough room for the urb.
4184  * Update ISO URB start_frame and interval.
4185  * Update interval as xhci_queue_intr_tx does. Use xhci frame_index to
4186  * update urb->start_frame if URB_ISO_ASAP is set in transfer_flags or
4187  * Contiguous Frame ID is not supported by HC.
4188  */
4189 int xhci_queue_isoc_tx_prepare(struct xhci_hcd *xhci, gfp_t mem_flags,
4190 		struct urb *urb, int slot_id, unsigned int ep_index)
4191 {
4192 	struct xhci_virt_device *xdev;
4193 	struct xhci_ring *ep_ring;
4194 	struct xhci_ep_ctx *ep_ctx;
4195 	int start_frame;
4196 	int num_tds, num_trbs, i;
4197 	int ret;
4198 	struct xhci_virt_ep *xep;
4199 	int ist;
4200 
4201 	xdev = xhci->devs[slot_id];
4202 	xep = &xhci->devs[slot_id]->eps[ep_index];
4203 	ep_ring = xdev->eps[ep_index].ring;
4204 	ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
4205 
4206 	num_trbs = 0;
4207 	num_tds = urb->number_of_packets;
4208 	for (i = 0; i < num_tds; i++)
4209 		num_trbs += count_isoc_trbs_needed(urb, i);
4210 
4211 	/* Check the ring to guarantee there is enough room for the whole urb.
4212 	 * Do not insert any td of the urb to the ring if the check failed.
4213 	 */
4214 	ret = prepare_ring(xhci, ep_ring, GET_EP_CTX_STATE(ep_ctx),
4215 			   num_trbs, mem_flags);
4216 	if (ret)
4217 		return ret;
4218 
4219 	/*
4220 	 * Check interval value. This should be done before we start to
4221 	 * calculate the start frame value.
4222 	 */
4223 	check_interval(xhci, urb, ep_ctx);
4224 
4225 	/* Calculate the start frame and put it in urb->start_frame. */
4226 	if (HCC_CFC(xhci->hcc_params) && !list_empty(&ep_ring->td_list)) {
4227 		if (GET_EP_CTX_STATE(ep_ctx) ==	EP_STATE_RUNNING) {
4228 			urb->start_frame = xep->next_frame_id;
4229 			goto skip_start_over;
4230 		}
4231 	}
4232 
4233 	start_frame = readl(&xhci->run_regs->microframe_index);
4234 	start_frame &= 0x3fff;
4235 	/*
4236 	 * Round up to the next frame and consider the time before trb really
4237 	 * gets scheduled by hardare.
4238 	 */
4239 	ist = HCS_IST(xhci->hcs_params2) & 0x7;
4240 	if (HCS_IST(xhci->hcs_params2) & (1 << 3))
4241 		ist <<= 3;
4242 	start_frame += ist + XHCI_CFC_DELAY;
4243 	start_frame = roundup(start_frame, 8);
4244 
4245 	/*
4246 	 * Round up to the next ESIT (Endpoint Service Interval Time) if ESIT
4247 	 * is greate than 8 microframes.
4248 	 */
4249 	if (urb->dev->speed == USB_SPEED_LOW ||
4250 			urb->dev->speed == USB_SPEED_FULL) {
4251 		start_frame = roundup(start_frame, urb->interval << 3);
4252 		urb->start_frame = start_frame >> 3;
4253 	} else {
4254 		start_frame = roundup(start_frame, urb->interval);
4255 		urb->start_frame = start_frame;
4256 	}
4257 
4258 skip_start_over:
4259 
4260 	return xhci_queue_isoc_tx(xhci, mem_flags, urb, slot_id, ep_index);
4261 }
4262 
4263 /****		Command Ring Operations		****/
4264 
4265 /* Generic function for queueing a command TRB on the command ring.
4266  * Check to make sure there's room on the command ring for one command TRB.
4267  * Also check that there's room reserved for commands that must not fail.
4268  * If this is a command that must not fail, meaning command_must_succeed = TRUE,
4269  * then only check for the number of reserved spots.
4270  * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB
4271  * because the command event handler may want to resubmit a failed command.
4272  */
4273 static int queue_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
4274 			 u32 field1, u32 field2,
4275 			 u32 field3, u32 field4, bool command_must_succeed)
4276 {
4277 	int reserved_trbs = xhci->cmd_ring_reserved_trbs;
4278 	int ret;
4279 
4280 	if ((xhci->xhc_state & XHCI_STATE_DYING) ||
4281 		(xhci->xhc_state & XHCI_STATE_HALTED)) {
4282 		xhci_dbg(xhci, "xHCI dying or halted, can't queue_command\n");
4283 		return -ESHUTDOWN;
4284 	}
4285 
4286 	if (!command_must_succeed)
4287 		reserved_trbs++;
4288 
4289 	ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING,
4290 			reserved_trbs, GFP_ATOMIC);
4291 	if (ret < 0) {
4292 		xhci_err(xhci, "ERR: No room for command on command ring\n");
4293 		if (command_must_succeed)
4294 			xhci_err(xhci, "ERR: Reserved TRB counting for "
4295 					"unfailable commands failed.\n");
4296 		return ret;
4297 	}
4298 
4299 	cmd->command_trb = xhci->cmd_ring->enqueue;
4300 
4301 	/* if there are no other commands queued we start the timeout timer */
4302 	if (list_empty(&xhci->cmd_list)) {
4303 		xhci->current_cmd = cmd;
4304 		xhci_mod_cmd_timer(xhci, XHCI_CMD_DEFAULT_TIMEOUT);
4305 	}
4306 
4307 	list_add_tail(&cmd->cmd_list, &xhci->cmd_list);
4308 
4309 	queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3,
4310 			field4 | xhci->cmd_ring->cycle_state);
4311 	return 0;
4312 }
4313 
4314 /* Queue a slot enable or disable request on the command ring */
4315 int xhci_queue_slot_control(struct xhci_hcd *xhci, struct xhci_command *cmd,
4316 		u32 trb_type, u32 slot_id)
4317 {
4318 	return queue_command(xhci, cmd, 0, 0, 0,
4319 			TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false);
4320 }
4321 
4322 /* Queue an address device command TRB */
4323 int xhci_queue_address_device(struct xhci_hcd *xhci, struct xhci_command *cmd,
4324 		dma_addr_t in_ctx_ptr, u32 slot_id, enum xhci_setup_dev setup)
4325 {
4326 	return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4327 			upper_32_bits(in_ctx_ptr), 0,
4328 			TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id)
4329 			| (setup == SETUP_CONTEXT_ONLY ? TRB_BSR : 0), false);
4330 }
4331 
4332 int xhci_queue_vendor_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
4333 		u32 field1, u32 field2, u32 field3, u32 field4)
4334 {
4335 	return queue_command(xhci, cmd, field1, field2, field3, field4, false);
4336 }
4337 
4338 /* Queue a reset device command TRB */
4339 int xhci_queue_reset_device(struct xhci_hcd *xhci, struct xhci_command *cmd,
4340 		u32 slot_id)
4341 {
4342 	return queue_command(xhci, cmd, 0, 0, 0,
4343 			TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id),
4344 			false);
4345 }
4346 
4347 /* Queue a configure endpoint command TRB */
4348 int xhci_queue_configure_endpoint(struct xhci_hcd *xhci,
4349 		struct xhci_command *cmd, dma_addr_t in_ctx_ptr,
4350 		u32 slot_id, bool command_must_succeed)
4351 {
4352 	return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4353 			upper_32_bits(in_ctx_ptr), 0,
4354 			TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id),
4355 			command_must_succeed);
4356 }
4357 
4358 /* Queue an evaluate context command TRB */
4359 int xhci_queue_evaluate_context(struct xhci_hcd *xhci, struct xhci_command *cmd,
4360 		dma_addr_t in_ctx_ptr, u32 slot_id, bool command_must_succeed)
4361 {
4362 	return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4363 			upper_32_bits(in_ctx_ptr), 0,
4364 			TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id),
4365 			command_must_succeed);
4366 }
4367 
4368 /*
4369  * Suspend is set to indicate "Stop Endpoint Command" is being issued to stop
4370  * activity on an endpoint that is about to be suspended.
4371  */
4372 int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, struct xhci_command *cmd,
4373 			     int slot_id, unsigned int ep_index, int suspend)
4374 {
4375 	u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
4376 	u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
4377 	u32 type = TRB_TYPE(TRB_STOP_RING);
4378 	u32 trb_suspend = SUSPEND_PORT_FOR_TRB(suspend);
4379 
4380 	return queue_command(xhci, cmd, 0, 0, 0,
4381 			trb_slot_id | trb_ep_index | type | trb_suspend, false);
4382 }
4383 
4384 int xhci_queue_reset_ep(struct xhci_hcd *xhci, struct xhci_command *cmd,
4385 			int slot_id, unsigned int ep_index,
4386 			enum xhci_ep_reset_type reset_type)
4387 {
4388 	u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
4389 	u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
4390 	u32 type = TRB_TYPE(TRB_RESET_EP);
4391 
4392 	if (reset_type == EP_SOFT_RESET)
4393 		type |= TRB_TSP;
4394 
4395 	return queue_command(xhci, cmd, 0, 0, 0,
4396 			trb_slot_id | trb_ep_index | type, false);
4397 }
4398