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