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