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