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