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