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