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