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