xref: /openbmc/linux/drivers/usb/host/xhci-ring.c (revision 060f35a317ef09101b128f399dce7ed13d019461)
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, reset ep\n");
1184 			if (ep->ep_state & EP_HAS_STREAMS) {
1185 				reset_type = EP_SOFT_RESET;
1186 			} else {
1187 				reset_type = EP_HARD_RESET;
1188 				td = find_halted_td(ep);
1189 				if (td)
1190 					td->status = -EPROTO;
1191 			}
1192 			/* reset ep, reset handler cleans up cancelled tds */
1193 			err = xhci_handle_halted_endpoint(xhci, ep, td, reset_type);
1194 			if (err)
1195 				break;
1196 			ep->ep_state &= ~EP_STOP_CMD_PENDING;
1197 			return;
1198 		case EP_STATE_STOPPED:
1199 			/*
1200 			 * Per xHCI 4.6.9, Stop Endpoint command on a Stopped
1201 			 * EP is a Context State Error, and EP stays Stopped.
1202 			 *
1203 			 * But maybe it failed on Halted, and somebody ran Reset
1204 			 * Endpoint later. EP state is now Stopped and EP_HALTED
1205 			 * still set because Reset EP handler will run after us.
1206 			 */
1207 			if (ep->ep_state & EP_HALTED)
1208 				break;
1209 			/*
1210 			 * On some HCs EP state remains Stopped for some tens of
1211 			 * us to a few ms or more after a doorbell ring, and any
1212 			 * new Stop Endpoint fails without aborting the restart.
1213 			 * This handler may run quickly enough to still see this
1214 			 * Stopped state, but it will soon change to Running.
1215 			 *
1216 			 * Assume this bug on unexpected Stop Endpoint failures.
1217 			 * Keep retrying until the EP starts and stops again, on
1218 			 * chips where this is known to help. Wait for 100ms.
1219 			 */
1220 			if (time_is_before_jiffies(ep->stop_time + msecs_to_jiffies(100)))
1221 				break;
1222 			fallthrough;
1223 		case EP_STATE_RUNNING:
1224 			/* Race, HW handled stop ep cmd before ep was running */
1225 			xhci_dbg(xhci, "Stop ep completion ctx error, ctx_state %d\n",
1226 					GET_EP_CTX_STATE(ep_ctx));
1227 
1228 			command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
1229 			if (!command) {
1230 				ep->ep_state &= ~EP_STOP_CMD_PENDING;
1231 				return;
1232 			}
1233 			xhci_queue_stop_endpoint(xhci, command, slot_id, ep_index, 0);
1234 			xhci_ring_cmd_db(xhci);
1235 
1236 			return;
1237 		default:
1238 			break;
1239 		}
1240 	}
1241 
1242 	/* will queue a set TR deq if stopped on a cancelled, uncleared TD */
1243 	xhci_invalidate_cancelled_tds(ep);
1244 	ep->ep_state &= ~EP_STOP_CMD_PENDING;
1245 
1246 	/* Otherwise ring the doorbell(s) to restart queued transfers */
1247 	xhci_giveback_invalidated_tds(ep);
1248 	ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1249 }
1250 
xhci_kill_ring_urbs(struct xhci_hcd * xhci,struct xhci_ring * ring)1251 static void xhci_kill_ring_urbs(struct xhci_hcd *xhci, struct xhci_ring *ring)
1252 {
1253 	struct xhci_td *cur_td;
1254 	struct xhci_td *tmp;
1255 
1256 	list_for_each_entry_safe(cur_td, tmp, &ring->td_list, td_list) {
1257 		list_del_init(&cur_td->td_list);
1258 
1259 		if (!list_empty(&cur_td->cancelled_td_list))
1260 			list_del_init(&cur_td->cancelled_td_list);
1261 
1262 		xhci_unmap_td_bounce_buffer(xhci, ring, cur_td);
1263 
1264 		inc_td_cnt(cur_td->urb);
1265 		if (last_td_in_urb(cur_td))
1266 			xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN);
1267 	}
1268 }
1269 
xhci_kill_endpoint_urbs(struct xhci_hcd * xhci,int slot_id,int ep_index)1270 static void xhci_kill_endpoint_urbs(struct xhci_hcd *xhci,
1271 		int slot_id, int ep_index)
1272 {
1273 	struct xhci_td *cur_td;
1274 	struct xhci_td *tmp;
1275 	struct xhci_virt_ep *ep;
1276 	struct xhci_ring *ring;
1277 
1278 	ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1279 	if (!ep)
1280 		return;
1281 
1282 	if ((ep->ep_state & EP_HAS_STREAMS) ||
1283 			(ep->ep_state & EP_GETTING_NO_STREAMS)) {
1284 		int stream_id;
1285 
1286 		for (stream_id = 1; stream_id < ep->stream_info->num_streams;
1287 				stream_id++) {
1288 			ring = ep->stream_info->stream_rings[stream_id];
1289 			if (!ring)
1290 				continue;
1291 
1292 			xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1293 					"Killing URBs for slot ID %u, ep index %u, stream %u",
1294 					slot_id, ep_index, stream_id);
1295 			xhci_kill_ring_urbs(xhci, ring);
1296 		}
1297 	} else {
1298 		ring = ep->ring;
1299 		if (!ring)
1300 			return;
1301 		xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1302 				"Killing URBs for slot ID %u, ep index %u",
1303 				slot_id, ep_index);
1304 		xhci_kill_ring_urbs(xhci, ring);
1305 	}
1306 
1307 	list_for_each_entry_safe(cur_td, tmp, &ep->cancelled_td_list,
1308 			cancelled_td_list) {
1309 		list_del_init(&cur_td->cancelled_td_list);
1310 		inc_td_cnt(cur_td->urb);
1311 
1312 		if (last_td_in_urb(cur_td))
1313 			xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN);
1314 	}
1315 }
1316 
1317 /*
1318  * host controller died, register read returns 0xffffffff
1319  * Complete pending commands, mark them ABORTED.
1320  * URBs need to be given back as usb core might be waiting with device locks
1321  * held for the URBs to finish during device disconnect, blocking host remove.
1322  *
1323  * Call with xhci->lock held.
1324  * lock is relased and re-acquired while giving back urb.
1325  */
xhci_hc_died(struct xhci_hcd * xhci)1326 void xhci_hc_died(struct xhci_hcd *xhci)
1327 {
1328 	int i, j;
1329 
1330 	if (xhci->xhc_state & XHCI_STATE_DYING)
1331 		return;
1332 
1333 	xhci_err(xhci, "xHCI host controller not responding, assume dead\n");
1334 	xhci->xhc_state |= XHCI_STATE_DYING;
1335 
1336 	xhci_cleanup_command_queue(xhci);
1337 
1338 	/* return any pending urbs, remove may be waiting for them */
1339 	for (i = 0; i <= HCS_MAX_SLOTS(xhci->hcs_params1); i++) {
1340 		if (!xhci->devs[i])
1341 			continue;
1342 		for (j = 0; j < 31; j++)
1343 			xhci_kill_endpoint_urbs(xhci, i, j);
1344 	}
1345 
1346 	/* inform usb core hc died if PCI remove isn't already handling it */
1347 	if (!(xhci->xhc_state & XHCI_STATE_REMOVING))
1348 		usb_hc_died(xhci_to_hcd(xhci));
1349 }
1350 
update_ring_for_set_deq_completion(struct xhci_hcd * xhci,struct xhci_virt_device * dev,struct xhci_ring * ep_ring,unsigned int ep_index)1351 static void update_ring_for_set_deq_completion(struct xhci_hcd *xhci,
1352 		struct xhci_virt_device *dev,
1353 		struct xhci_ring *ep_ring,
1354 		unsigned int ep_index)
1355 {
1356 	union xhci_trb *dequeue_temp;
1357 
1358 	dequeue_temp = ep_ring->dequeue;
1359 
1360 	/* If we get two back-to-back stalls, and the first stalled transfer
1361 	 * ends just before a link TRB, the dequeue pointer will be left on
1362 	 * the link TRB by the code in the while loop.  So we have to update
1363 	 * the dequeue pointer one segment further, or we'll jump off
1364 	 * the segment into la-la-land.
1365 	 */
1366 	if (trb_is_link(ep_ring->dequeue)) {
1367 		ep_ring->deq_seg = ep_ring->deq_seg->next;
1368 		ep_ring->dequeue = ep_ring->deq_seg->trbs;
1369 	}
1370 
1371 	while (ep_ring->dequeue != dev->eps[ep_index].queued_deq_ptr) {
1372 		/* We have more usable TRBs */
1373 		ep_ring->dequeue++;
1374 		if (trb_is_link(ep_ring->dequeue)) {
1375 			if (ep_ring->dequeue ==
1376 					dev->eps[ep_index].queued_deq_ptr)
1377 				break;
1378 			ep_ring->deq_seg = ep_ring->deq_seg->next;
1379 			ep_ring->dequeue = ep_ring->deq_seg->trbs;
1380 		}
1381 		if (ep_ring->dequeue == dequeue_temp) {
1382 			xhci_dbg(xhci, "Unable to find new dequeue pointer\n");
1383 			break;
1384 		}
1385 	}
1386 }
1387 
1388 /*
1389  * When we get a completion for a Set Transfer Ring Dequeue Pointer command,
1390  * we need to clear the set deq pending flag in the endpoint ring state, so that
1391  * the TD queueing code can ring the doorbell again.  We also need to ring the
1392  * endpoint doorbell to restart the ring, but only if there aren't more
1393  * cancellations pending.
1394  */
xhci_handle_cmd_set_deq(struct xhci_hcd * xhci,int slot_id,union xhci_trb * trb,u32 cmd_comp_code)1395 static void xhci_handle_cmd_set_deq(struct xhci_hcd *xhci, int slot_id,
1396 		union xhci_trb *trb, u32 cmd_comp_code)
1397 {
1398 	unsigned int ep_index;
1399 	unsigned int stream_id;
1400 	struct xhci_ring *ep_ring;
1401 	struct xhci_virt_ep *ep;
1402 	struct xhci_ep_ctx *ep_ctx;
1403 	struct xhci_slot_ctx *slot_ctx;
1404 	struct xhci_td *td, *tmp_td;
1405 
1406 	ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1407 	stream_id = TRB_TO_STREAM_ID(le32_to_cpu(trb->generic.field[2]));
1408 	ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1409 	if (!ep)
1410 		return;
1411 
1412 	ep_ring = xhci_virt_ep_to_ring(xhci, ep, stream_id);
1413 	if (!ep_ring) {
1414 		xhci_warn(xhci, "WARN Set TR deq ptr command for freed stream ID %u\n",
1415 				stream_id);
1416 		/* XXX: Harmless??? */
1417 		goto cleanup;
1418 	}
1419 
1420 	ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1421 	slot_ctx = xhci_get_slot_ctx(xhci, ep->vdev->out_ctx);
1422 	trace_xhci_handle_cmd_set_deq(slot_ctx);
1423 	trace_xhci_handle_cmd_set_deq_ep(ep_ctx);
1424 
1425 	if (cmd_comp_code != COMP_SUCCESS) {
1426 		unsigned int ep_state;
1427 		unsigned int slot_state;
1428 
1429 		switch (cmd_comp_code) {
1430 		case COMP_TRB_ERROR:
1431 			xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because of stream ID configuration\n");
1432 			break;
1433 		case COMP_CONTEXT_STATE_ERROR:
1434 			xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due to incorrect slot or ep state.\n");
1435 			ep_state = GET_EP_CTX_STATE(ep_ctx);
1436 			slot_state = le32_to_cpu(slot_ctx->dev_state);
1437 			slot_state = GET_SLOT_STATE(slot_state);
1438 			xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1439 					"Slot state = %u, EP state = %u",
1440 					slot_state, ep_state);
1441 			break;
1442 		case COMP_SLOT_NOT_ENABLED_ERROR:
1443 			xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because slot %u was not enabled.\n",
1444 					slot_id);
1445 			break;
1446 		default:
1447 			xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown completion code of %u.\n",
1448 					cmd_comp_code);
1449 			break;
1450 		}
1451 		/* OK what do we do now?  The endpoint state is hosed, and we
1452 		 * should never get to this point if the synchronization between
1453 		 * queueing, and endpoint state are correct.  This might happen
1454 		 * if the device gets disconnected after we've finished
1455 		 * cancelling URBs, which might not be an error...
1456 		 */
1457 	} else {
1458 		u64 deq;
1459 		/* 4.6.10 deq ptr is written to the stream ctx for streams */
1460 		if (ep->ep_state & EP_HAS_STREAMS) {
1461 			struct xhci_stream_ctx *ctx =
1462 				&ep->stream_info->stream_ctx_array[stream_id];
1463 			deq = le64_to_cpu(ctx->stream_ring) & SCTX_DEQ_MASK;
1464 
1465 			/*
1466 			 * Cadence xHCI controllers store some endpoint state
1467 			 * information within Rsvd0 fields of Stream Endpoint
1468 			 * context. This field is not cleared during Set TR
1469 			 * Dequeue Pointer command which causes XDMA to skip
1470 			 * over transfer ring and leads to data loss on stream
1471 			 * pipe.
1472 			 * To fix this issue driver must clear Rsvd0 field.
1473 			 */
1474 			if (xhci->quirks & XHCI_CDNS_SCTX_QUIRK) {
1475 				ctx->reserved[0] = 0;
1476 				ctx->reserved[1] = 0;
1477 			}
1478 		} else {
1479 			deq = le64_to_cpu(ep_ctx->deq) & ~EP_CTX_CYCLE_MASK;
1480 		}
1481 		xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1482 			"Successful Set TR Deq Ptr cmd, deq = @%08llx", deq);
1483 		if (xhci_trb_virt_to_dma(ep->queued_deq_seg,
1484 					 ep->queued_deq_ptr) == deq) {
1485 			/* Update the ring's dequeue segment and dequeue pointer
1486 			 * to reflect the new position.
1487 			 */
1488 			update_ring_for_set_deq_completion(xhci, ep->vdev,
1489 				ep_ring, ep_index);
1490 		} else {
1491 			xhci_warn(xhci, "Mismatch between completed Set TR Deq Ptr command & xHCI internal state.\n");
1492 			xhci_warn(xhci, "ep deq seg = %p, deq ptr = %p\n",
1493 				  ep->queued_deq_seg, ep->queued_deq_ptr);
1494 		}
1495 	}
1496 	/* HW cached TDs cleared from cache, give them back */
1497 	list_for_each_entry_safe(td, tmp_td, &ep->cancelled_td_list,
1498 				 cancelled_td_list) {
1499 		ep_ring = xhci_urb_to_transfer_ring(ep->xhci, td->urb);
1500 		if (td->cancel_status == TD_CLEARING_CACHE) {
1501 			td->cancel_status = TD_CLEARED;
1502 			xhci_dbg(ep->xhci, "%s: Giveback cancelled URB %p TD\n",
1503 				 __func__, td->urb);
1504 			xhci_td_cleanup(ep->xhci, td, ep_ring, td->status);
1505 		} else {
1506 			xhci_dbg(ep->xhci, "%s: Keep cancelled URB %p TD as cancel_status is %d\n",
1507 				 __func__, td->urb, td->cancel_status);
1508 		}
1509 	}
1510 cleanup:
1511 	ep->ep_state &= ~SET_DEQ_PENDING;
1512 	ep->queued_deq_seg = NULL;
1513 	ep->queued_deq_ptr = NULL;
1514 
1515 	/* Check for deferred or newly cancelled TDs */
1516 	if (!list_empty(&ep->cancelled_td_list)) {
1517 		xhci_dbg(ep->xhci, "%s: Pending TDs to clear, continuing with invalidation\n",
1518 			 __func__);
1519 		xhci_invalidate_cancelled_tds(ep);
1520 		/* Try to restart the endpoint if all is done */
1521 		ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1522 		/* Start giving back any TDs invalidated above */
1523 		xhci_giveback_invalidated_tds(ep);
1524 	} else {
1525 		/* Restart any rings with pending URBs */
1526 		xhci_dbg(ep->xhci, "%s: All TDs cleared, ring doorbell\n", __func__);
1527 		ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1528 	}
1529 }
1530 
xhci_handle_cmd_reset_ep(struct xhci_hcd * xhci,int slot_id,union xhci_trb * trb,u32 cmd_comp_code)1531 static void xhci_handle_cmd_reset_ep(struct xhci_hcd *xhci, int slot_id,
1532 		union xhci_trb *trb, u32 cmd_comp_code)
1533 {
1534 	struct xhci_virt_ep *ep;
1535 	struct xhci_ep_ctx *ep_ctx;
1536 	unsigned int ep_index;
1537 
1538 	ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3]));
1539 	ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
1540 	if (!ep)
1541 		return;
1542 
1543 	ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
1544 	trace_xhci_handle_cmd_reset_ep(ep_ctx);
1545 
1546 	/* This command will only fail if the endpoint wasn't halted,
1547 	 * but we don't care.
1548 	 */
1549 	xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
1550 		"Ignoring reset ep completion code of %u", cmd_comp_code);
1551 
1552 	/* Cleanup cancelled TDs as ep is stopped. May queue a Set TR Deq cmd */
1553 	xhci_invalidate_cancelled_tds(ep);
1554 
1555 	/* Clear our internal halted state */
1556 	ep->ep_state &= ~EP_HALTED;
1557 
1558 	xhci_giveback_invalidated_tds(ep);
1559 
1560 	/* if this was a soft reset, then restart */
1561 	if ((le32_to_cpu(trb->generic.field[3])) & TRB_TSP)
1562 		ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
1563 }
1564 
xhci_handle_cmd_enable_slot(struct xhci_hcd * xhci,int slot_id,struct xhci_command * command,u32 cmd_comp_code)1565 static void xhci_handle_cmd_enable_slot(struct xhci_hcd *xhci, int slot_id,
1566 		struct xhci_command *command, u32 cmd_comp_code)
1567 {
1568 	if (cmd_comp_code == COMP_SUCCESS)
1569 		command->slot_id = slot_id;
1570 	else
1571 		command->slot_id = 0;
1572 }
1573 
xhci_handle_cmd_disable_slot(struct xhci_hcd * xhci,int slot_id)1574 static void xhci_handle_cmd_disable_slot(struct xhci_hcd *xhci, int slot_id)
1575 {
1576 	struct xhci_virt_device *virt_dev;
1577 	struct xhci_slot_ctx *slot_ctx;
1578 
1579 	virt_dev = xhci->devs[slot_id];
1580 	if (!virt_dev)
1581 		return;
1582 
1583 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
1584 	trace_xhci_handle_cmd_disable_slot(slot_ctx);
1585 
1586 	if (xhci->quirks & XHCI_EP_LIMIT_QUIRK)
1587 		/* Delete default control endpoint resources */
1588 		xhci_free_device_endpoint_resources(xhci, virt_dev, true);
1589 }
1590 
xhci_handle_cmd_config_ep(struct xhci_hcd * xhci,int slot_id,u32 cmd_comp_code)1591 static void xhci_handle_cmd_config_ep(struct xhci_hcd *xhci, int slot_id,
1592 		u32 cmd_comp_code)
1593 {
1594 	struct xhci_virt_device *virt_dev;
1595 	struct xhci_input_control_ctx *ctrl_ctx;
1596 	struct xhci_ep_ctx *ep_ctx;
1597 	unsigned int ep_index;
1598 	u32 add_flags;
1599 
1600 	/*
1601 	 * Configure endpoint commands can come from the USB core configuration
1602 	 * or alt setting changes, or when streams were being configured.
1603 	 */
1604 
1605 	virt_dev = xhci->devs[slot_id];
1606 	if (!virt_dev)
1607 		return;
1608 	ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1609 	if (!ctrl_ctx) {
1610 		xhci_warn(xhci, "Could not get input context, bad type.\n");
1611 		return;
1612 	}
1613 
1614 	add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1615 
1616 	/* Input ctx add_flags are the endpoint index plus one */
1617 	ep_index = xhci_last_valid_endpoint(add_flags) - 1;
1618 
1619 	ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->out_ctx, ep_index);
1620 	trace_xhci_handle_cmd_config_ep(ep_ctx);
1621 
1622 	return;
1623 }
1624 
xhci_handle_cmd_addr_dev(struct xhci_hcd * xhci,int slot_id)1625 static void xhci_handle_cmd_addr_dev(struct xhci_hcd *xhci, int slot_id)
1626 {
1627 	struct xhci_virt_device *vdev;
1628 	struct xhci_slot_ctx *slot_ctx;
1629 
1630 	vdev = xhci->devs[slot_id];
1631 	if (!vdev)
1632 		return;
1633 	slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
1634 	trace_xhci_handle_cmd_addr_dev(slot_ctx);
1635 }
1636 
xhci_handle_cmd_reset_dev(struct xhci_hcd * xhci,int slot_id)1637 static void xhci_handle_cmd_reset_dev(struct xhci_hcd *xhci, int slot_id)
1638 {
1639 	struct xhci_virt_device *vdev;
1640 	struct xhci_slot_ctx *slot_ctx;
1641 
1642 	vdev = xhci->devs[slot_id];
1643 	if (!vdev) {
1644 		xhci_warn(xhci, "Reset device command completion for disabled slot %u\n",
1645 			  slot_id);
1646 		return;
1647 	}
1648 	slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
1649 	trace_xhci_handle_cmd_reset_dev(slot_ctx);
1650 
1651 	xhci_dbg(xhci, "Completed reset device command.\n");
1652 }
1653 
xhci_handle_cmd_nec_get_fw(struct xhci_hcd * xhci,struct xhci_event_cmd * event)1654 static void xhci_handle_cmd_nec_get_fw(struct xhci_hcd *xhci,
1655 		struct xhci_event_cmd *event)
1656 {
1657 	if (!(xhci->quirks & XHCI_NEC_HOST)) {
1658 		xhci_warn(xhci, "WARN NEC_GET_FW command on non-NEC host\n");
1659 		return;
1660 	}
1661 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1662 			"NEC firmware version %2x.%02x",
1663 			NEC_FW_MAJOR(le32_to_cpu(event->status)),
1664 			NEC_FW_MINOR(le32_to_cpu(event->status)));
1665 }
1666 
xhci_complete_del_and_free_cmd(struct xhci_command * cmd,u32 status)1667 static void xhci_complete_del_and_free_cmd(struct xhci_command *cmd, u32 status)
1668 {
1669 	list_del(&cmd->cmd_list);
1670 
1671 	if (cmd->completion) {
1672 		cmd->status = status;
1673 		complete(cmd->completion);
1674 	} else {
1675 		kfree(cmd);
1676 	}
1677 }
1678 
xhci_cleanup_command_queue(struct xhci_hcd * xhci)1679 void xhci_cleanup_command_queue(struct xhci_hcd *xhci)
1680 {
1681 	struct xhci_command *cur_cmd, *tmp_cmd;
1682 	xhci->current_cmd = NULL;
1683 	list_for_each_entry_safe(cur_cmd, tmp_cmd, &xhci->cmd_list, cmd_list)
1684 		xhci_complete_del_and_free_cmd(cur_cmd, COMP_COMMAND_ABORTED);
1685 }
1686 
xhci_handle_command_timeout(struct work_struct * work)1687 void xhci_handle_command_timeout(struct work_struct *work)
1688 {
1689 	struct xhci_hcd	*xhci;
1690 	unsigned long	flags;
1691 	char		str[XHCI_MSG_MAX];
1692 	u64		hw_ring_state;
1693 	u32		cmd_field3;
1694 	u32		usbsts;
1695 
1696 	xhci = container_of(to_delayed_work(work), struct xhci_hcd, cmd_timer);
1697 
1698 	spin_lock_irqsave(&xhci->lock, flags);
1699 
1700 	/*
1701 	 * If timeout work is pending, or current_cmd is NULL, it means we
1702 	 * raced with command completion. Command is handled so just return.
1703 	 */
1704 	if (!xhci->current_cmd || delayed_work_pending(&xhci->cmd_timer)) {
1705 		spin_unlock_irqrestore(&xhci->lock, flags);
1706 		return;
1707 	}
1708 
1709 	cmd_field3 = le32_to_cpu(xhci->current_cmd->command_trb->generic.field[3]);
1710 	usbsts = readl(&xhci->op_regs->status);
1711 	xhci_dbg(xhci, "Command timeout, USBSTS:%s\n", xhci_decode_usbsts(str, usbsts));
1712 
1713 	/* Bail out and tear down xhci if a stop endpoint command failed */
1714 	if (TRB_FIELD_TO_TYPE(cmd_field3) == TRB_STOP_RING) {
1715 		struct xhci_virt_ep	*ep;
1716 
1717 		xhci_warn(xhci, "xHCI host not responding to stop endpoint command\n");
1718 
1719 		ep = xhci_get_virt_ep(xhci, TRB_TO_SLOT_ID(cmd_field3),
1720 				      TRB_TO_EP_INDEX(cmd_field3));
1721 		if (ep)
1722 			ep->ep_state &= ~EP_STOP_CMD_PENDING;
1723 
1724 		xhci_halt(xhci);
1725 		xhci_hc_died(xhci);
1726 		goto time_out_completed;
1727 	}
1728 
1729 	/* mark this command to be cancelled */
1730 	xhci->current_cmd->status = COMP_COMMAND_ABORTED;
1731 
1732 	/* Make sure command ring is running before aborting it */
1733 	hw_ring_state = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
1734 	if (hw_ring_state == ~(u64)0) {
1735 		xhci_hc_died(xhci);
1736 		goto time_out_completed;
1737 	}
1738 
1739 	if ((xhci->cmd_ring_state & CMD_RING_STATE_RUNNING) &&
1740 	    (hw_ring_state & CMD_RING_RUNNING))  {
1741 		/* Prevent new doorbell, and start command abort */
1742 		xhci->cmd_ring_state = CMD_RING_STATE_ABORTED;
1743 		xhci_dbg(xhci, "Command timeout\n");
1744 		xhci_abort_cmd_ring(xhci, flags);
1745 		goto time_out_completed;
1746 	}
1747 
1748 	/* host removed. Bail out */
1749 	if (xhci->xhc_state & XHCI_STATE_REMOVING) {
1750 		xhci_dbg(xhci, "host removed, ring start fail?\n");
1751 		xhci_cleanup_command_queue(xhci);
1752 
1753 		goto time_out_completed;
1754 	}
1755 
1756 	/* command timeout on stopped ring, ring can't be aborted */
1757 	xhci_dbg(xhci, "Command timeout on stopped ring\n");
1758 	xhci_handle_stopped_cmd_ring(xhci, xhci->current_cmd);
1759 
1760 time_out_completed:
1761 	spin_unlock_irqrestore(&xhci->lock, flags);
1762 	return;
1763 }
1764 
handle_cmd_completion(struct xhci_hcd * xhci,struct xhci_event_cmd * event)1765 static void handle_cmd_completion(struct xhci_hcd *xhci,
1766 		struct xhci_event_cmd *event)
1767 {
1768 	unsigned int slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
1769 	u64 cmd_dma;
1770 	dma_addr_t cmd_dequeue_dma;
1771 	u32 cmd_comp_code;
1772 	union xhci_trb *cmd_trb;
1773 	struct xhci_command *cmd;
1774 	u32 cmd_type;
1775 
1776 	if (slot_id >= MAX_HC_SLOTS) {
1777 		xhci_warn(xhci, "Invalid slot_id %u\n", slot_id);
1778 		return;
1779 	}
1780 
1781 	cmd_dma = le64_to_cpu(event->cmd_trb);
1782 	cmd_trb = xhci->cmd_ring->dequeue;
1783 
1784 	trace_xhci_handle_command(xhci->cmd_ring, &cmd_trb->generic);
1785 
1786 	cmd_comp_code = GET_COMP_CODE(le32_to_cpu(event->status));
1787 
1788 	/* If CMD ring stopped we own the trbs between enqueue and dequeue */
1789 	if (cmd_comp_code == COMP_COMMAND_RING_STOPPED) {
1790 		complete_all(&xhci->cmd_ring_stop_completion);
1791 		return;
1792 	}
1793 
1794 	cmd_dequeue_dma = xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
1795 			cmd_trb);
1796 	/*
1797 	 * Check whether the completion event is for our internal kept
1798 	 * command.
1799 	 */
1800 	if (!cmd_dequeue_dma || cmd_dma != (u64)cmd_dequeue_dma) {
1801 		xhci_warn(xhci,
1802 			  "ERROR mismatched command completion event\n");
1803 		return;
1804 	}
1805 
1806 	cmd = list_first_entry(&xhci->cmd_list, struct xhci_command, cmd_list);
1807 
1808 	cancel_delayed_work(&xhci->cmd_timer);
1809 
1810 	if (cmd->command_trb != xhci->cmd_ring->dequeue) {
1811 		xhci_err(xhci,
1812 			 "Command completion event does not match command\n");
1813 		return;
1814 	}
1815 
1816 	/*
1817 	 * Host aborted the command ring, check if the current command was
1818 	 * supposed to be aborted, otherwise continue normally.
1819 	 * The command ring is stopped now, but the xHC will issue a Command
1820 	 * Ring Stopped event which will cause us to restart it.
1821 	 */
1822 	if (cmd_comp_code == COMP_COMMAND_ABORTED) {
1823 		xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
1824 		if (cmd->status == COMP_COMMAND_ABORTED) {
1825 			if (xhci->current_cmd == cmd)
1826 				xhci->current_cmd = NULL;
1827 			goto event_handled;
1828 		}
1829 	}
1830 
1831 	cmd_type = TRB_FIELD_TO_TYPE(le32_to_cpu(cmd_trb->generic.field[3]));
1832 	switch (cmd_type) {
1833 	case TRB_ENABLE_SLOT:
1834 		xhci_handle_cmd_enable_slot(xhci, slot_id, cmd, cmd_comp_code);
1835 		break;
1836 	case TRB_DISABLE_SLOT:
1837 		xhci_handle_cmd_disable_slot(xhci, slot_id);
1838 		break;
1839 	case TRB_CONFIG_EP:
1840 		if (!cmd->completion)
1841 			xhci_handle_cmd_config_ep(xhci, slot_id, cmd_comp_code);
1842 		break;
1843 	case TRB_EVAL_CONTEXT:
1844 		break;
1845 	case TRB_ADDR_DEV:
1846 		xhci_handle_cmd_addr_dev(xhci, slot_id);
1847 		break;
1848 	case TRB_STOP_RING:
1849 		WARN_ON(slot_id != TRB_TO_SLOT_ID(
1850 				le32_to_cpu(cmd_trb->generic.field[3])));
1851 		if (!cmd->completion)
1852 			xhci_handle_cmd_stop_ep(xhci, slot_id, cmd_trb,
1853 						cmd_comp_code);
1854 		break;
1855 	case TRB_SET_DEQ:
1856 		WARN_ON(slot_id != TRB_TO_SLOT_ID(
1857 				le32_to_cpu(cmd_trb->generic.field[3])));
1858 		xhci_handle_cmd_set_deq(xhci, slot_id, cmd_trb, cmd_comp_code);
1859 		break;
1860 	case TRB_CMD_NOOP:
1861 		/* Is this an aborted command turned to NO-OP? */
1862 		if (cmd->status == COMP_COMMAND_RING_STOPPED)
1863 			cmd_comp_code = COMP_COMMAND_RING_STOPPED;
1864 		break;
1865 	case TRB_RESET_EP:
1866 		WARN_ON(slot_id != TRB_TO_SLOT_ID(
1867 				le32_to_cpu(cmd_trb->generic.field[3])));
1868 		xhci_handle_cmd_reset_ep(xhci, slot_id, cmd_trb, cmd_comp_code);
1869 		break;
1870 	case TRB_RESET_DEV:
1871 		/* SLOT_ID field in reset device cmd completion event TRB is 0.
1872 		 * Use the SLOT_ID from the command TRB instead (xhci 4.6.11)
1873 		 */
1874 		slot_id = TRB_TO_SLOT_ID(
1875 				le32_to_cpu(cmd_trb->generic.field[3]));
1876 		xhci_handle_cmd_reset_dev(xhci, slot_id);
1877 		break;
1878 	case TRB_NEC_GET_FW:
1879 		xhci_handle_cmd_nec_get_fw(xhci, event);
1880 		break;
1881 	default:
1882 		/* Skip over unknown commands on the event ring */
1883 		xhci_info(xhci, "INFO unknown command type %d\n", cmd_type);
1884 		break;
1885 	}
1886 
1887 	/* restart timer if this wasn't the last command */
1888 	if (!list_is_singular(&xhci->cmd_list)) {
1889 		xhci->current_cmd = list_first_entry(&cmd->cmd_list,
1890 						struct xhci_command, cmd_list);
1891 		xhci_mod_cmd_timer(xhci);
1892 	} else if (xhci->current_cmd == cmd) {
1893 		xhci->current_cmd = NULL;
1894 	}
1895 
1896 event_handled:
1897 	xhci_complete_del_and_free_cmd(cmd, cmd_comp_code);
1898 
1899 	inc_deq(xhci, xhci->cmd_ring);
1900 }
1901 
handle_vendor_event(struct xhci_hcd * xhci,union xhci_trb * event,u32 trb_type)1902 static void handle_vendor_event(struct xhci_hcd *xhci,
1903 				union xhci_trb *event, u32 trb_type)
1904 {
1905 	xhci_dbg(xhci, "Vendor specific event TRB type = %u\n", trb_type);
1906 	if (trb_type == TRB_NEC_CMD_COMP && (xhci->quirks & XHCI_NEC_HOST))
1907 		handle_cmd_completion(xhci, &event->event_cmd);
1908 }
1909 
handle_device_notification(struct xhci_hcd * xhci,union xhci_trb * event)1910 static void handle_device_notification(struct xhci_hcd *xhci,
1911 		union xhci_trb *event)
1912 {
1913 	u32 slot_id;
1914 	struct usb_device *udev;
1915 
1916 	slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->generic.field[3]));
1917 	if (!xhci->devs[slot_id]) {
1918 		xhci_warn(xhci, "Device Notification event for "
1919 				"unused slot %u\n", slot_id);
1920 		return;
1921 	}
1922 
1923 	xhci_dbg(xhci, "Device Wake Notification event for slot ID %u\n",
1924 			slot_id);
1925 	udev = xhci->devs[slot_id]->udev;
1926 	if (udev && udev->parent)
1927 		usb_wakeup_notification(udev->parent, udev->portnum);
1928 }
1929 
1930 /*
1931  * Quirk hanlder for errata seen on Cavium ThunderX2 processor XHCI
1932  * Controller.
1933  * As per ThunderX2errata-129 USB 2 device may come up as USB 1
1934  * If a connection to a USB 1 device is followed by another connection
1935  * to a USB 2 device.
1936  *
1937  * Reset the PHY after the USB device is disconnected if device speed
1938  * is less than HCD_USB3.
1939  * Retry the reset sequence max of 4 times checking the PLL lock status.
1940  *
1941  */
xhci_cavium_reset_phy_quirk(struct xhci_hcd * xhci)1942 static void xhci_cavium_reset_phy_quirk(struct xhci_hcd *xhci)
1943 {
1944 	struct usb_hcd *hcd = xhci_to_hcd(xhci);
1945 	u32 pll_lock_check;
1946 	u32 retry_count = 4;
1947 
1948 	do {
1949 		/* Assert PHY reset */
1950 		writel(0x6F, hcd->regs + 0x1048);
1951 		udelay(10);
1952 		/* De-assert the PHY reset */
1953 		writel(0x7F, hcd->regs + 0x1048);
1954 		udelay(200);
1955 		pll_lock_check = readl(hcd->regs + 0x1070);
1956 	} while (!(pll_lock_check & 0x1) && --retry_count);
1957 }
1958 
handle_port_status(struct xhci_hcd * xhci,struct xhci_interrupter * ir,union xhci_trb * event)1959 static void handle_port_status(struct xhci_hcd *xhci,
1960 			       struct xhci_interrupter *ir,
1961 			       union xhci_trb *event)
1962 {
1963 	struct usb_hcd *hcd;
1964 	u32 port_id;
1965 	u32 portsc, cmd_reg;
1966 	int max_ports;
1967 	int slot_id;
1968 	unsigned int hcd_portnum;
1969 	struct xhci_bus_state *bus_state;
1970 	bool bogus_port_status = false;
1971 	struct xhci_port *port;
1972 
1973 	/* Port status change events always have a successful completion code */
1974 	if (GET_COMP_CODE(le32_to_cpu(event->generic.field[2])) != COMP_SUCCESS)
1975 		xhci_warn(xhci,
1976 			  "WARN: xHC returned failed port status event\n");
1977 
1978 	port_id = GET_PORT_ID(le32_to_cpu(event->generic.field[0]));
1979 	max_ports = HCS_MAX_PORTS(xhci->hcs_params1);
1980 
1981 	if ((port_id <= 0) || (port_id > max_ports)) {
1982 		xhci_warn(xhci, "Port change event with invalid port ID %d\n",
1983 			  port_id);
1984 		inc_deq(xhci, ir->event_ring);
1985 		return;
1986 	}
1987 
1988 	port = &xhci->hw_ports[port_id - 1];
1989 	if (!port || !port->rhub || port->hcd_portnum == DUPLICATE_ENTRY) {
1990 		xhci_warn(xhci, "Port change event, no port for port ID %u\n",
1991 			  port_id);
1992 		bogus_port_status = true;
1993 		goto cleanup;
1994 	}
1995 
1996 	/* We might get interrupts after shared_hcd is removed */
1997 	if (port->rhub == &xhci->usb3_rhub && xhci->shared_hcd == NULL) {
1998 		xhci_dbg(xhci, "ignore port event for removed USB3 hcd\n");
1999 		bogus_port_status = true;
2000 		goto cleanup;
2001 	}
2002 
2003 	hcd = port->rhub->hcd;
2004 	bus_state = &port->rhub->bus_state;
2005 	hcd_portnum = port->hcd_portnum;
2006 	portsc = readl(port->addr);
2007 
2008 	xhci_dbg(xhci, "Port change event, %d-%d, id %d, portsc: 0x%x\n",
2009 		 hcd->self.busnum, hcd_portnum + 1, port_id, portsc);
2010 
2011 	trace_xhci_handle_port_status(hcd_portnum, portsc);
2012 
2013 	if (hcd->state == HC_STATE_SUSPENDED) {
2014 		xhci_dbg(xhci, "resume root hub\n");
2015 		usb_hcd_resume_root_hub(hcd);
2016 	}
2017 
2018 	if (hcd->speed >= HCD_USB3 &&
2019 	    (portsc & PORT_PLS_MASK) == XDEV_INACTIVE) {
2020 		slot_id = xhci_find_slot_id_by_port(hcd, xhci, hcd_portnum + 1);
2021 		if (slot_id && xhci->devs[slot_id])
2022 			xhci->devs[slot_id]->flags |= VDEV_PORT_ERROR;
2023 	}
2024 
2025 	if ((portsc & PORT_PLC) && (portsc & PORT_PLS_MASK) == XDEV_RESUME) {
2026 		xhci_dbg(xhci, "port resume event for port %d\n", port_id);
2027 
2028 		cmd_reg = readl(&xhci->op_regs->command);
2029 		if (!(cmd_reg & CMD_RUN)) {
2030 			xhci_warn(xhci, "xHC is not running.\n");
2031 			goto cleanup;
2032 		}
2033 
2034 		if (DEV_SUPERSPEED_ANY(portsc)) {
2035 			xhci_dbg(xhci, "remote wake SS port %d\n", port_id);
2036 			/* Set a flag to say the port signaled remote wakeup,
2037 			 * so we can tell the difference between the end of
2038 			 * device and host initiated resume.
2039 			 */
2040 			bus_state->port_remote_wakeup |= 1 << hcd_portnum;
2041 			xhci_test_and_clear_bit(xhci, port, PORT_PLC);
2042 			usb_hcd_start_port_resume(&hcd->self, hcd_portnum);
2043 			xhci_set_link_state(xhci, port, XDEV_U0);
2044 			/* Need to wait until the next link state change
2045 			 * indicates the device is actually in U0.
2046 			 */
2047 			bogus_port_status = true;
2048 			goto cleanup;
2049 		} else if (!test_bit(hcd_portnum, &bus_state->resuming_ports)) {
2050 			xhci_dbg(xhci, "resume HS port %d\n", port_id);
2051 			port->resume_timestamp = jiffies +
2052 				msecs_to_jiffies(USB_RESUME_TIMEOUT);
2053 			set_bit(hcd_portnum, &bus_state->resuming_ports);
2054 			/* Do the rest in GetPortStatus after resume time delay.
2055 			 * Avoid polling roothub status before that so that a
2056 			 * usb device auto-resume latency around ~40ms.
2057 			 */
2058 			set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2059 			mod_timer(&hcd->rh_timer,
2060 				  port->resume_timestamp);
2061 			usb_hcd_start_port_resume(&hcd->self, hcd_portnum);
2062 			bogus_port_status = true;
2063 		}
2064 	}
2065 
2066 	if ((portsc & PORT_PLC) &&
2067 	    DEV_SUPERSPEED_ANY(portsc) &&
2068 	    ((portsc & PORT_PLS_MASK) == XDEV_U0 ||
2069 	     (portsc & PORT_PLS_MASK) == XDEV_U1 ||
2070 	     (portsc & PORT_PLS_MASK) == XDEV_U2)) {
2071 		xhci_dbg(xhci, "resume SS port %d finished\n", port_id);
2072 		complete(&port->u3exit_done);
2073 		/* We've just brought the device into U0/1/2 through either the
2074 		 * Resume state after a device remote wakeup, or through the
2075 		 * U3Exit state after a host-initiated resume.  If it's a device
2076 		 * initiated remote wake, don't pass up the link state change,
2077 		 * so the roothub behavior is consistent with external
2078 		 * USB 3.0 hub behavior.
2079 		 */
2080 		slot_id = xhci_find_slot_id_by_port(hcd, xhci, hcd_portnum + 1);
2081 		if (slot_id && xhci->devs[slot_id])
2082 			xhci_ring_device(xhci, slot_id);
2083 		if (bus_state->port_remote_wakeup & (1 << hcd_portnum)) {
2084 			xhci_test_and_clear_bit(xhci, port, PORT_PLC);
2085 			usb_wakeup_notification(hcd->self.root_hub,
2086 					hcd_portnum + 1);
2087 			bogus_port_status = true;
2088 			goto cleanup;
2089 		}
2090 	}
2091 
2092 	/*
2093 	 * Check to see if xhci-hub.c is waiting on RExit to U0 transition (or
2094 	 * RExit to a disconnect state).  If so, let the driver know it's
2095 	 * out of the RExit state.
2096 	 */
2097 	if (hcd->speed < HCD_USB3 && port->rexit_active) {
2098 		complete(&port->rexit_done);
2099 		port->rexit_active = false;
2100 		bogus_port_status = true;
2101 		goto cleanup;
2102 	}
2103 
2104 	if (hcd->speed < HCD_USB3) {
2105 		xhci_test_and_clear_bit(xhci, port, PORT_PLC);
2106 		if ((xhci->quirks & XHCI_RESET_PLL_ON_DISCONNECT) &&
2107 		    (portsc & PORT_CSC) && !(portsc & PORT_CONNECT))
2108 			xhci_cavium_reset_phy_quirk(xhci);
2109 	}
2110 
2111 cleanup:
2112 	/* Update event ring dequeue pointer before dropping the lock */
2113 	inc_deq(xhci, ir->event_ring);
2114 
2115 	/* Don't make the USB core poll the roothub if we got a bad port status
2116 	 * change event.  Besides, at that point we can't tell which roothub
2117 	 * (USB 2.0 or USB 3.0) to kick.
2118 	 */
2119 	if (bogus_port_status)
2120 		return;
2121 
2122 	/*
2123 	 * xHCI port-status-change events occur when the "or" of all the
2124 	 * status-change bits in the portsc register changes from 0 to 1.
2125 	 * New status changes won't cause an event if any other change
2126 	 * bits are still set.  When an event occurs, switch over to
2127 	 * polling to avoid losing status changes.
2128 	 */
2129 	xhci_dbg(xhci, "%s: starting usb%d port polling.\n",
2130 		 __func__, hcd->self.busnum);
2131 	set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2132 	spin_unlock(&xhci->lock);
2133 	/* Pass this up to the core */
2134 	usb_hcd_poll_rh_status(hcd);
2135 	spin_lock(&xhci->lock);
2136 }
2137 
2138 /*
2139  * This TD is defined by the TRBs starting at start_trb in start_seg and ending
2140  * at end_trb, which may be in another segment.  If the suspect DMA address is a
2141  * TRB in this TD, this function returns that TRB's segment.  Otherwise it
2142  * returns 0.
2143  */
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)2144 struct xhci_segment *trb_in_td(struct xhci_hcd *xhci,
2145 		struct xhci_segment *start_seg,
2146 		union xhci_trb	*start_trb,
2147 		union xhci_trb	*end_trb,
2148 		dma_addr_t	suspect_dma,
2149 		bool		debug)
2150 {
2151 	dma_addr_t start_dma;
2152 	dma_addr_t end_seg_dma;
2153 	dma_addr_t end_trb_dma;
2154 	struct xhci_segment *cur_seg;
2155 
2156 	start_dma = xhci_trb_virt_to_dma(start_seg, start_trb);
2157 	cur_seg = start_seg;
2158 
2159 	do {
2160 		if (start_dma == 0)
2161 			return NULL;
2162 		/* We may get an event for a Link TRB in the middle of a TD */
2163 		end_seg_dma = xhci_trb_virt_to_dma(cur_seg,
2164 				&cur_seg->trbs[TRBS_PER_SEGMENT - 1]);
2165 		/* If the end TRB isn't in this segment, this is set to 0 */
2166 		end_trb_dma = xhci_trb_virt_to_dma(cur_seg, end_trb);
2167 
2168 		if (debug)
2169 			xhci_warn(xhci,
2170 				"Looking for event-dma %016llx trb-start %016llx trb-end %016llx seg-start %016llx seg-end %016llx\n",
2171 				(unsigned long long)suspect_dma,
2172 				(unsigned long long)start_dma,
2173 				(unsigned long long)end_trb_dma,
2174 				(unsigned long long)cur_seg->dma,
2175 				(unsigned long long)end_seg_dma);
2176 
2177 		if (end_trb_dma > 0) {
2178 			/* The end TRB is in this segment, so suspect should be here */
2179 			if (start_dma <= end_trb_dma) {
2180 				if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma)
2181 					return cur_seg;
2182 			} else {
2183 				/* Case for one segment with
2184 				 * a TD wrapped around to the top
2185 				 */
2186 				if ((suspect_dma >= start_dma &&
2187 							suspect_dma <= end_seg_dma) ||
2188 						(suspect_dma >= cur_seg->dma &&
2189 						 suspect_dma <= end_trb_dma))
2190 					return cur_seg;
2191 			}
2192 			return NULL;
2193 		} else {
2194 			/* Might still be somewhere in this segment */
2195 			if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma)
2196 				return cur_seg;
2197 		}
2198 		cur_seg = cur_seg->next;
2199 		start_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[0]);
2200 	} while (cur_seg != start_seg);
2201 
2202 	return NULL;
2203 }
2204 
xhci_clear_hub_tt_buffer(struct xhci_hcd * xhci,struct xhci_td * td,struct xhci_virt_ep * ep)2205 static void xhci_clear_hub_tt_buffer(struct xhci_hcd *xhci, struct xhci_td *td,
2206 		struct xhci_virt_ep *ep)
2207 {
2208 	/*
2209 	 * As part of low/full-speed endpoint-halt processing
2210 	 * we must clear the TT buffer (USB 2.0 specification 11.17.5).
2211 	 */
2212 	if (td->urb->dev->tt && !usb_pipeint(td->urb->pipe) &&
2213 	    (td->urb->dev->tt->hub != xhci_to_hcd(xhci)->self.root_hub) &&
2214 	    !(ep->ep_state & EP_CLEARING_TT)) {
2215 		ep->ep_state |= EP_CLEARING_TT;
2216 		td->urb->ep->hcpriv = td->urb->dev;
2217 		if (usb_hub_clear_tt_buffer(td->urb))
2218 			ep->ep_state &= ~EP_CLEARING_TT;
2219 	}
2220 }
2221 
2222 /* Check if an error has halted the endpoint ring.  The class driver will
2223  * cleanup the halt for a non-default control endpoint if we indicate a stall.
2224  * However, a babble and other errors also halt the endpoint ring, and the class
2225  * driver won't clear the halt in that case, so we need to issue a Set Transfer
2226  * Ring Dequeue Pointer command manually.
2227  */
xhci_requires_manual_halt_cleanup(struct xhci_hcd * xhci,struct xhci_ep_ctx * ep_ctx,unsigned int trb_comp_code)2228 static int xhci_requires_manual_halt_cleanup(struct xhci_hcd *xhci,
2229 		struct xhci_ep_ctx *ep_ctx,
2230 		unsigned int trb_comp_code)
2231 {
2232 	/* TRB completion codes that may require a manual halt cleanup */
2233 	if (trb_comp_code == COMP_USB_TRANSACTION_ERROR ||
2234 			trb_comp_code == COMP_BABBLE_DETECTED_ERROR ||
2235 			trb_comp_code == COMP_SPLIT_TRANSACTION_ERROR)
2236 		/* The 0.95 spec says a babbling control endpoint
2237 		 * is not halted. The 0.96 spec says it is.  Some HW
2238 		 * claims to be 0.95 compliant, but it halts the control
2239 		 * endpoint anyway.  Check if a babble halted the
2240 		 * endpoint.
2241 		 */
2242 		if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_HALTED)
2243 			return 1;
2244 
2245 	return 0;
2246 }
2247 
xhci_is_vendor_info_code(struct xhci_hcd * xhci,unsigned int trb_comp_code)2248 int xhci_is_vendor_info_code(struct xhci_hcd *xhci, unsigned int trb_comp_code)
2249 {
2250 	if (trb_comp_code >= 224 && trb_comp_code <= 255) {
2251 		/* Vendor defined "informational" completion code,
2252 		 * treat as not-an-error.
2253 		 */
2254 		xhci_dbg(xhci, "Vendor defined info completion code %u\n",
2255 				trb_comp_code);
2256 		xhci_dbg(xhci, "Treating code as success.\n");
2257 		return 1;
2258 	}
2259 	return 0;
2260 }
2261 
finish_td(struct xhci_hcd * xhci,struct xhci_virt_ep * ep,struct xhci_ring * ep_ring,struct xhci_td * td,u32 trb_comp_code)2262 static int finish_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2263 		     struct xhci_ring *ep_ring, struct xhci_td *td,
2264 		     u32 trb_comp_code)
2265 {
2266 	struct xhci_ep_ctx *ep_ctx;
2267 
2268 	ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep->ep_index);
2269 
2270 	switch (trb_comp_code) {
2271 	case COMP_STOPPED_LENGTH_INVALID:
2272 	case COMP_STOPPED_SHORT_PACKET:
2273 	case COMP_STOPPED:
2274 		/*
2275 		 * The "Stop Endpoint" completion will take care of any
2276 		 * stopped TDs. A stopped TD may be restarted, so don't update
2277 		 * the ring dequeue pointer or take this TD off any lists yet.
2278 		 */
2279 		return 0;
2280 	case COMP_USB_TRANSACTION_ERROR:
2281 	case COMP_BABBLE_DETECTED_ERROR:
2282 	case COMP_SPLIT_TRANSACTION_ERROR:
2283 		/*
2284 		 * If endpoint context state is not halted we might be
2285 		 * racing with a reset endpoint command issued by a unsuccessful
2286 		 * stop endpoint completion (context error). In that case the
2287 		 * td should be on the cancelled list, and EP_HALTED flag set.
2288 		 *
2289 		 * Or then it's not halted due to the 0.95 spec stating that a
2290 		 * babbling control endpoint should not halt. The 0.96 spec
2291 		 * again says it should.  Some HW claims to be 0.95 compliant,
2292 		 * but it halts the control endpoint anyway.
2293 		 */
2294 		if (GET_EP_CTX_STATE(ep_ctx) != EP_STATE_HALTED) {
2295 			/*
2296 			 * If EP_HALTED is set and TD is on the cancelled list
2297 			 * the TD and dequeue pointer will be handled by reset
2298 			 * ep command completion
2299 			 */
2300 			if ((ep->ep_state & EP_HALTED) &&
2301 			    !list_empty(&td->cancelled_td_list)) {
2302 				xhci_dbg(xhci, "Already resolving halted ep for 0x%llx\n",
2303 					 (unsigned long long)xhci_trb_virt_to_dma(
2304 						 td->start_seg, td->first_trb));
2305 				return 0;
2306 			}
2307 			/* endpoint not halted, don't reset it */
2308 			break;
2309 		}
2310 		/* Almost same procedure as for STALL_ERROR below */
2311 		xhci_clear_hub_tt_buffer(xhci, td, ep);
2312 		xhci_handle_halted_endpoint(xhci, ep, td, EP_HARD_RESET);
2313 		return 0;
2314 	case COMP_STALL_ERROR:
2315 		/*
2316 		 * xhci internal endpoint state will go to a "halt" state for
2317 		 * any stall, including default control pipe protocol stall.
2318 		 * To clear the host side halt we need to issue a reset endpoint
2319 		 * command, followed by a set dequeue command to move past the
2320 		 * TD.
2321 		 * Class drivers clear the device side halt from a functional
2322 		 * stall later. Hub TT buffer should only be cleared for FS/LS
2323 		 * devices behind HS hubs for functional stalls.
2324 		 */
2325 		if (ep->ep_index != 0)
2326 			xhci_clear_hub_tt_buffer(xhci, td, ep);
2327 
2328 		xhci_handle_halted_endpoint(xhci, ep, td, EP_HARD_RESET);
2329 
2330 		return 0; /* xhci_handle_halted_endpoint marked td cancelled */
2331 	default:
2332 		break;
2333 	}
2334 
2335 	/* Update ring dequeue pointer */
2336 	ep_ring->dequeue = td->last_trb;
2337 	ep_ring->deq_seg = td->last_trb_seg;
2338 	inc_deq(xhci, ep_ring);
2339 
2340 	return xhci_td_cleanup(xhci, td, ep_ring, td->status);
2341 }
2342 
2343 /* 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)2344 static int sum_trb_lengths(struct xhci_hcd *xhci, struct xhci_ring *ring,
2345 			   union xhci_trb *stop_trb)
2346 {
2347 	u32 sum;
2348 	union xhci_trb *trb = ring->dequeue;
2349 	struct xhci_segment *seg = ring->deq_seg;
2350 
2351 	for (sum = 0; trb != stop_trb; next_trb(xhci, ring, &seg, &trb)) {
2352 		if (!trb_is_noop(trb) && !trb_is_link(trb))
2353 			sum += TRB_LEN(le32_to_cpu(trb->generic.field[2]));
2354 	}
2355 	return sum;
2356 }
2357 
2358 /*
2359  * Process control tds, update urb status and actual_length.
2360  */
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)2361 static int process_ctrl_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2362 		struct xhci_ring *ep_ring,  struct xhci_td *td,
2363 			   union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2364 {
2365 	struct xhci_ep_ctx *ep_ctx;
2366 	u32 trb_comp_code;
2367 	u32 remaining, requested;
2368 	u32 trb_type;
2369 
2370 	trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(ep_trb->generic.field[3]));
2371 	ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep->ep_index);
2372 	trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2373 	requested = td->urb->transfer_buffer_length;
2374 	remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2375 
2376 	switch (trb_comp_code) {
2377 	case COMP_SUCCESS:
2378 		if (trb_type != TRB_STATUS) {
2379 			xhci_warn(xhci, "WARN: Success on ctrl %s TRB without IOC set?\n",
2380 				  (trb_type == TRB_DATA) ? "data" : "setup");
2381 			td->status = -ESHUTDOWN;
2382 			break;
2383 		}
2384 		td->status = 0;
2385 		break;
2386 	case COMP_SHORT_PACKET:
2387 		td->status = 0;
2388 		break;
2389 	case COMP_STOPPED_SHORT_PACKET:
2390 		if (trb_type == TRB_DATA || trb_type == TRB_NORMAL)
2391 			td->urb->actual_length = remaining;
2392 		else
2393 			xhci_warn(xhci, "WARN: Stopped Short Packet on ctrl setup or status TRB\n");
2394 		goto finish_td;
2395 	case COMP_STOPPED:
2396 		switch (trb_type) {
2397 		case TRB_SETUP:
2398 			td->urb->actual_length = 0;
2399 			goto finish_td;
2400 		case TRB_DATA:
2401 		case TRB_NORMAL:
2402 			td->urb->actual_length = requested - remaining;
2403 			goto finish_td;
2404 		case TRB_STATUS:
2405 			td->urb->actual_length = requested;
2406 			goto finish_td;
2407 		default:
2408 			xhci_warn(xhci, "WARN: unexpected TRB Type %d\n",
2409 				  trb_type);
2410 			goto finish_td;
2411 		}
2412 	case COMP_STOPPED_LENGTH_INVALID:
2413 		goto finish_td;
2414 	default:
2415 		if (!xhci_requires_manual_halt_cleanup(xhci,
2416 						       ep_ctx, trb_comp_code))
2417 			break;
2418 		xhci_dbg(xhci, "TRB error %u, halted endpoint index = %u\n",
2419 			 trb_comp_code, ep->ep_index);
2420 		fallthrough;
2421 	case COMP_STALL_ERROR:
2422 		/* Did we transfer part of the data (middle) phase? */
2423 		if (trb_type == TRB_DATA || trb_type == TRB_NORMAL)
2424 			td->urb->actual_length = requested - remaining;
2425 		else if (!td->urb_length_set)
2426 			td->urb->actual_length = 0;
2427 		goto finish_td;
2428 	}
2429 
2430 	/* stopped at setup stage, no data transferred */
2431 	if (trb_type == TRB_SETUP)
2432 		goto finish_td;
2433 
2434 	/*
2435 	 * if on data stage then update the actual_length of the URB and flag it
2436 	 * as set, so it won't be overwritten in the event for the last TRB.
2437 	 */
2438 	if (trb_type == TRB_DATA ||
2439 		trb_type == TRB_NORMAL) {
2440 		td->urb_length_set = true;
2441 		td->urb->actual_length = requested - remaining;
2442 		xhci_dbg(xhci, "Waiting for status stage event\n");
2443 		return 0;
2444 	}
2445 
2446 	/* at status stage */
2447 	if (!td->urb_length_set)
2448 		td->urb->actual_length = requested;
2449 
2450 finish_td:
2451 	return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2452 }
2453 
2454 /*
2455  * Process isochronous tds, update urb packet status and actual_length.
2456  */
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)2457 static int process_isoc_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2458 		struct xhci_ring *ep_ring, struct xhci_td *td,
2459 		union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2460 {
2461 	struct urb_priv *urb_priv;
2462 	int idx;
2463 	struct usb_iso_packet_descriptor *frame;
2464 	u32 trb_comp_code;
2465 	bool sum_trbs_for_length = false;
2466 	u32 remaining, requested, ep_trb_len;
2467 	int short_framestatus;
2468 
2469 	trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2470 	urb_priv = td->urb->hcpriv;
2471 	idx = urb_priv->num_tds_done;
2472 	frame = &td->urb->iso_frame_desc[idx];
2473 	requested = frame->length;
2474 	remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2475 	ep_trb_len = TRB_LEN(le32_to_cpu(ep_trb->generic.field[2]));
2476 	short_framestatus = td->urb->transfer_flags & URB_SHORT_NOT_OK ?
2477 		-EREMOTEIO : 0;
2478 
2479 	/* handle completion code */
2480 	switch (trb_comp_code) {
2481 	case COMP_SUCCESS:
2482 		/* Don't overwrite status if TD had an error, see xHCI 4.9.1 */
2483 		if (td->error_mid_td)
2484 			break;
2485 		if (remaining) {
2486 			frame->status = short_framestatus;
2487 			sum_trbs_for_length = true;
2488 			break;
2489 		}
2490 		frame->status = 0;
2491 		break;
2492 	case COMP_SHORT_PACKET:
2493 		frame->status = short_framestatus;
2494 		sum_trbs_for_length = true;
2495 		break;
2496 	case COMP_BANDWIDTH_OVERRUN_ERROR:
2497 		frame->status = -ECOMM;
2498 		break;
2499 	case COMP_BABBLE_DETECTED_ERROR:
2500 		sum_trbs_for_length = true;
2501 		fallthrough;
2502 	case COMP_ISOCH_BUFFER_OVERRUN:
2503 		frame->status = -EOVERFLOW;
2504 		if (ep_trb != td->last_trb)
2505 			td->error_mid_td = true;
2506 		break;
2507 	case COMP_INCOMPATIBLE_DEVICE_ERROR:
2508 	case COMP_STALL_ERROR:
2509 		frame->status = -EPROTO;
2510 		break;
2511 	case COMP_USB_TRANSACTION_ERROR:
2512 		frame->status = -EPROTO;
2513 		sum_trbs_for_length = true;
2514 		if (ep_trb != td->last_trb)
2515 			td->error_mid_td = true;
2516 		break;
2517 	case COMP_STOPPED:
2518 		sum_trbs_for_length = true;
2519 		break;
2520 	case COMP_STOPPED_SHORT_PACKET:
2521 		/* field normally containing residue now contains tranferred */
2522 		frame->status = short_framestatus;
2523 		requested = remaining;
2524 		break;
2525 	case COMP_STOPPED_LENGTH_INVALID:
2526 		requested = 0;
2527 		remaining = 0;
2528 		break;
2529 	default:
2530 		sum_trbs_for_length = true;
2531 		frame->status = -1;
2532 		break;
2533 	}
2534 
2535 	if (td->urb_length_set)
2536 		goto finish_td;
2537 
2538 	if (sum_trbs_for_length)
2539 		frame->actual_length = sum_trb_lengths(xhci, ep->ring, ep_trb) +
2540 			ep_trb_len - remaining;
2541 	else
2542 		frame->actual_length = requested;
2543 
2544 	td->urb->actual_length += frame->actual_length;
2545 
2546 finish_td:
2547 	/* Don't give back TD yet if we encountered an error mid TD */
2548 	if (td->error_mid_td && ep_trb != td->last_trb) {
2549 		xhci_dbg(xhci, "Error mid isoc TD, wait for final completion event\n");
2550 		td->urb_length_set = true;
2551 		return 0;
2552 	}
2553 
2554 	return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2555 }
2556 
skip_isoc_td(struct xhci_hcd * xhci,struct xhci_td * td,struct xhci_virt_ep * ep,int status)2557 static int skip_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td,
2558 			struct xhci_virt_ep *ep, int status)
2559 {
2560 	struct urb_priv *urb_priv;
2561 	struct usb_iso_packet_descriptor *frame;
2562 	int idx;
2563 
2564 	urb_priv = td->urb->hcpriv;
2565 	idx = urb_priv->num_tds_done;
2566 	frame = &td->urb->iso_frame_desc[idx];
2567 
2568 	/* The transfer is partly done. */
2569 	frame->status = -EXDEV;
2570 
2571 	/* calc actual length */
2572 	frame->actual_length = 0;
2573 
2574 	/* Update ring dequeue pointer */
2575 	ep->ring->dequeue = td->last_trb;
2576 	ep->ring->deq_seg = td->last_trb_seg;
2577 	inc_deq(xhci, ep->ring);
2578 
2579 	return xhci_td_cleanup(xhci, td, ep->ring, status);
2580 }
2581 
2582 /*
2583  * Process bulk and interrupt tds, update urb status and actual_length.
2584  */
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)2585 static int process_bulk_intr_td(struct xhci_hcd *xhci, struct xhci_virt_ep *ep,
2586 		struct xhci_ring *ep_ring, struct xhci_td *td,
2587 		union xhci_trb *ep_trb, struct xhci_transfer_event *event)
2588 {
2589 	struct xhci_slot_ctx *slot_ctx;
2590 	u32 trb_comp_code;
2591 	u32 remaining, requested, ep_trb_len;
2592 
2593 	slot_ctx = xhci_get_slot_ctx(xhci, ep->vdev->out_ctx);
2594 	trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2595 	remaining = EVENT_TRB_LEN(le32_to_cpu(event->transfer_len));
2596 	ep_trb_len = TRB_LEN(le32_to_cpu(ep_trb->generic.field[2]));
2597 	requested = td->urb->transfer_buffer_length;
2598 
2599 	switch (trb_comp_code) {
2600 	case COMP_SUCCESS:
2601 		ep->err_count = 0;
2602 		/* handle success with untransferred data as short packet */
2603 		if (ep_trb != td->last_trb || remaining) {
2604 			xhci_warn(xhci, "WARN Successful completion on short TX\n");
2605 			xhci_dbg(xhci, "ep %#x - asked for %d bytes, %d bytes untransferred\n",
2606 				 td->urb->ep->desc.bEndpointAddress,
2607 				 requested, remaining);
2608 		}
2609 		td->status = 0;
2610 		break;
2611 	case COMP_SHORT_PACKET:
2612 		xhci_dbg(xhci, "ep %#x - asked for %d bytes, %d bytes untransferred\n",
2613 			 td->urb->ep->desc.bEndpointAddress,
2614 			 requested, remaining);
2615 		td->status = 0;
2616 		break;
2617 	case COMP_STOPPED_SHORT_PACKET:
2618 		td->urb->actual_length = remaining;
2619 		goto finish_td;
2620 	case COMP_STOPPED_LENGTH_INVALID:
2621 		/* stopped on ep trb with invalid length, exclude it */
2622 		td->urb->actual_length = sum_trb_lengths(xhci, ep_ring, ep_trb);
2623 		goto finish_td;
2624 	case COMP_USB_TRANSACTION_ERROR:
2625 		if (xhci->quirks & XHCI_NO_SOFT_RETRY ||
2626 		    (ep->err_count++ > MAX_SOFT_RETRY) ||
2627 		    le32_to_cpu(slot_ctx->tt_info) & TT_SLOT)
2628 			break;
2629 
2630 		td->status = 0;
2631 
2632 		xhci_handle_halted_endpoint(xhci, ep, td, EP_SOFT_RESET);
2633 		return 0;
2634 	default:
2635 		/* do nothing */
2636 		break;
2637 	}
2638 
2639 	if (ep_trb == td->last_trb)
2640 		td->urb->actual_length = requested - remaining;
2641 	else
2642 		td->urb->actual_length =
2643 			sum_trb_lengths(xhci, ep_ring, ep_trb) +
2644 			ep_trb_len - remaining;
2645 finish_td:
2646 	if (remaining > requested) {
2647 		xhci_warn(xhci, "bad transfer trb length %d in event trb\n",
2648 			  remaining);
2649 		td->urb->actual_length = 0;
2650 	}
2651 
2652 	return finish_td(xhci, ep, ep_ring, td, trb_comp_code);
2653 }
2654 
2655 /*
2656  * If this function returns an error condition, it means it got a Transfer
2657  * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address.
2658  * At this point, the host controller is probably hosed and should be reset.
2659  */
handle_tx_event(struct xhci_hcd * xhci,struct xhci_interrupter * ir,struct xhci_transfer_event * event)2660 static int handle_tx_event(struct xhci_hcd *xhci,
2661 			   struct xhci_interrupter *ir,
2662 			   struct xhci_transfer_event *event)
2663 {
2664 	struct xhci_virt_ep *ep;
2665 	struct xhci_ring *ep_ring;
2666 	unsigned int slot_id;
2667 	int ep_index;
2668 	struct xhci_td *td = NULL;
2669 	dma_addr_t ep_trb_dma;
2670 	struct xhci_segment *ep_seg;
2671 	union xhci_trb *ep_trb;
2672 	int status = -EINPROGRESS;
2673 	struct xhci_ep_ctx *ep_ctx;
2674 	u32 trb_comp_code;
2675 	int td_num = 0;
2676 	bool handling_skipped_tds = false;
2677 
2678 	slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
2679 	ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1;
2680 	trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
2681 	ep_trb_dma = le64_to_cpu(event->buffer);
2682 
2683 	ep = xhci_get_virt_ep(xhci, slot_id, ep_index);
2684 	if (!ep) {
2685 		xhci_err(xhci, "ERROR Invalid Transfer event\n");
2686 		goto err_out;
2687 	}
2688 
2689 	ep_ring = xhci_dma_to_transfer_ring(ep, ep_trb_dma);
2690 	ep_ctx = xhci_get_ep_ctx(xhci, ep->vdev->out_ctx, ep_index);
2691 
2692 	if (GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) {
2693 		xhci_err(xhci,
2694 			 "ERROR Transfer event for disabled endpoint slot %u ep %u\n",
2695 			  slot_id, ep_index);
2696 		goto err_out;
2697 	}
2698 
2699 	/* Some transfer events don't always point to a trb, see xhci 4.17.4 */
2700 	if (!ep_ring) {
2701 		switch (trb_comp_code) {
2702 		case COMP_STALL_ERROR:
2703 		case COMP_USB_TRANSACTION_ERROR:
2704 		case COMP_INVALID_STREAM_TYPE_ERROR:
2705 		case COMP_INVALID_STREAM_ID_ERROR:
2706 			xhci_dbg(xhci, "Stream transaction error ep %u no id\n",
2707 				 ep_index);
2708 			if (ep->err_count++ > MAX_SOFT_RETRY)
2709 				xhci_handle_halted_endpoint(xhci, ep, NULL,
2710 							    EP_HARD_RESET);
2711 			else
2712 				xhci_handle_halted_endpoint(xhci, ep, NULL,
2713 							    EP_SOFT_RESET);
2714 			goto cleanup;
2715 		case COMP_RING_UNDERRUN:
2716 		case COMP_RING_OVERRUN:
2717 		case COMP_STOPPED_LENGTH_INVALID:
2718 			goto cleanup;
2719 		default:
2720 			xhci_err(xhci, "ERROR Transfer event for unknown stream ring slot %u ep %u\n",
2721 				 slot_id, ep_index);
2722 			goto err_out;
2723 		}
2724 	}
2725 
2726 	/* Count current td numbers if ep->skip is set */
2727 	if (ep->skip)
2728 		td_num += list_count_nodes(&ep_ring->td_list);
2729 
2730 	/* Look for common error cases */
2731 	switch (trb_comp_code) {
2732 	/* Skip codes that require special handling depending on
2733 	 * transfer type
2734 	 */
2735 	case COMP_SUCCESS:
2736 		if (EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)) != 0) {
2737 			trb_comp_code = COMP_SHORT_PACKET;
2738 			xhci_dbg(xhci, "Successful completion on short TX for slot %u ep %u with last td short %d\n",
2739 				 slot_id, ep_index, ep_ring->last_td_was_short);
2740 		}
2741 		break;
2742 	case COMP_SHORT_PACKET:
2743 		break;
2744 	/* Completion codes for endpoint stopped state */
2745 	case COMP_STOPPED:
2746 		xhci_dbg(xhci, "Stopped on Transfer TRB for slot %u ep %u\n",
2747 			 slot_id, ep_index);
2748 		break;
2749 	case COMP_STOPPED_LENGTH_INVALID:
2750 		xhci_dbg(xhci,
2751 			 "Stopped on No-op or Link TRB for slot %u ep %u\n",
2752 			 slot_id, ep_index);
2753 		break;
2754 	case COMP_STOPPED_SHORT_PACKET:
2755 		xhci_dbg(xhci,
2756 			 "Stopped with short packet transfer detected for slot %u ep %u\n",
2757 			 slot_id, ep_index);
2758 		break;
2759 	/* Completion codes for endpoint halted state */
2760 	case COMP_STALL_ERROR:
2761 		xhci_dbg(xhci, "Stalled endpoint for slot %u ep %u\n", slot_id,
2762 			 ep_index);
2763 		status = -EPIPE;
2764 		break;
2765 	case COMP_SPLIT_TRANSACTION_ERROR:
2766 		xhci_dbg(xhci, "Split transaction error for slot %u ep %u\n",
2767 			 slot_id, ep_index);
2768 		status = -EPROTO;
2769 		break;
2770 	case COMP_USB_TRANSACTION_ERROR:
2771 		xhci_dbg(xhci, "Transfer error for slot %u ep %u on endpoint\n",
2772 			 slot_id, ep_index);
2773 		status = -EPROTO;
2774 		break;
2775 	case COMP_BABBLE_DETECTED_ERROR:
2776 		xhci_dbg(xhci, "Babble error for slot %u ep %u on endpoint\n",
2777 			 slot_id, ep_index);
2778 		status = -EOVERFLOW;
2779 		break;
2780 	/* Completion codes for endpoint error state */
2781 	case COMP_TRB_ERROR:
2782 		xhci_warn(xhci,
2783 			  "WARN: TRB error for slot %u ep %u on endpoint\n",
2784 			  slot_id, ep_index);
2785 		status = -EILSEQ;
2786 		break;
2787 	/* completion codes not indicating endpoint state change */
2788 	case COMP_DATA_BUFFER_ERROR:
2789 		xhci_warn(xhci,
2790 			  "WARN: HC couldn't access mem fast enough for slot %u ep %u\n",
2791 			  slot_id, ep_index);
2792 		status = -ENOSR;
2793 		break;
2794 	case COMP_BANDWIDTH_OVERRUN_ERROR:
2795 		xhci_warn(xhci,
2796 			  "WARN: bandwidth overrun event for slot %u ep %u on endpoint\n",
2797 			  slot_id, ep_index);
2798 		break;
2799 	case COMP_ISOCH_BUFFER_OVERRUN:
2800 		xhci_warn(xhci,
2801 			  "WARN: buffer overrun event for slot %u ep %u on endpoint",
2802 			  slot_id, ep_index);
2803 		break;
2804 	case COMP_RING_UNDERRUN:
2805 		/*
2806 		 * When the Isoch ring is empty, the xHC will generate
2807 		 * a Ring Overrun Event for IN Isoch endpoint or Ring
2808 		 * Underrun Event for OUT Isoch endpoint.
2809 		 */
2810 		xhci_dbg(xhci, "underrun event on endpoint\n");
2811 		if (!list_empty(&ep_ring->td_list))
2812 			xhci_dbg(xhci, "Underrun Event for slot %d ep %d "
2813 					"still with TDs queued?\n",
2814 				 TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2815 				 ep_index);
2816 		goto cleanup;
2817 	case COMP_RING_OVERRUN:
2818 		xhci_dbg(xhci, "overrun event on endpoint\n");
2819 		if (!list_empty(&ep_ring->td_list))
2820 			xhci_dbg(xhci, "Overrun Event for slot %d ep %d "
2821 					"still with TDs queued?\n",
2822 				 TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2823 				 ep_index);
2824 		goto cleanup;
2825 	case COMP_MISSED_SERVICE_ERROR:
2826 		/*
2827 		 * When encounter missed service error, one or more isoc tds
2828 		 * may be missed by xHC.
2829 		 * Set skip flag of the ep_ring; Complete the missed tds as
2830 		 * short transfer when process the ep_ring next time.
2831 		 */
2832 		ep->skip = true;
2833 		xhci_dbg(xhci,
2834 			 "Miss service interval error for slot %u ep %u, set skip flag\n",
2835 			 slot_id, ep_index);
2836 		goto cleanup;
2837 	case COMP_NO_PING_RESPONSE_ERROR:
2838 		ep->skip = true;
2839 		xhci_dbg(xhci,
2840 			 "No Ping response error for slot %u ep %u, Skip one Isoc TD\n",
2841 			 slot_id, ep_index);
2842 		goto cleanup;
2843 
2844 	case COMP_INCOMPATIBLE_DEVICE_ERROR:
2845 		/* needs disable slot command to recover */
2846 		xhci_warn(xhci,
2847 			  "WARN: detect an incompatible device for slot %u ep %u",
2848 			  slot_id, ep_index);
2849 		status = -EPROTO;
2850 		break;
2851 	default:
2852 		if (xhci_is_vendor_info_code(xhci, trb_comp_code)) {
2853 			status = 0;
2854 			break;
2855 		}
2856 		xhci_warn(xhci,
2857 			  "ERROR Unknown event condition %u for slot %u ep %u , HC probably busted\n",
2858 			  trb_comp_code, slot_id, ep_index);
2859 		goto cleanup;
2860 	}
2861 
2862 	do {
2863 		/* This TRB should be in the TD at the head of this ring's
2864 		 * TD list.
2865 		 */
2866 		if (list_empty(&ep_ring->td_list)) {
2867 			/*
2868 			 * Don't print wanings if it's due to a stopped endpoint
2869 			 * generating an extra completion event if the device
2870 			 * was suspended. Or, a event for the last TRB of a
2871 			 * short TD we already got a short event for.
2872 			 * The short TD is already removed from the TD list.
2873 			 */
2874 
2875 			if (!(trb_comp_code == COMP_STOPPED ||
2876 			      trb_comp_code == COMP_STOPPED_LENGTH_INVALID ||
2877 			      ep_ring->last_td_was_short)) {
2878 				xhci_warn(xhci, "WARN Event TRB for slot %d ep %d with no TDs queued?\n",
2879 						TRB_TO_SLOT_ID(le32_to_cpu(event->flags)),
2880 						ep_index);
2881 			}
2882 			if (ep->skip) {
2883 				ep->skip = false;
2884 				xhci_dbg(xhci, "td_list is empty while skip flag set. Clear skip flag for slot %u ep %u.\n",
2885 					 slot_id, ep_index);
2886 			}
2887 			if (trb_comp_code == COMP_STALL_ERROR ||
2888 			    xhci_requires_manual_halt_cleanup(xhci, ep_ctx,
2889 							      trb_comp_code)) {
2890 				xhci_handle_halted_endpoint(xhci, ep, NULL,
2891 							    EP_HARD_RESET);
2892 			}
2893 			goto cleanup;
2894 		}
2895 
2896 		/* We've skipped all the TDs on the ep ring when ep->skip set */
2897 		if (ep->skip && td_num == 0) {
2898 			ep->skip = false;
2899 			xhci_dbg(xhci, "All tds on the ep_ring skipped. Clear skip flag for slot %u ep %u.\n",
2900 				 slot_id, ep_index);
2901 			goto cleanup;
2902 		}
2903 
2904 		td = list_first_entry(&ep_ring->td_list, struct xhci_td,
2905 				      td_list);
2906 		if (ep->skip)
2907 			td_num--;
2908 
2909 		/* Is this a TRB in the currently executing TD? */
2910 		ep_seg = trb_in_td(xhci, ep_ring->deq_seg, ep_ring->dequeue,
2911 				td->last_trb, ep_trb_dma, false);
2912 
2913 		/*
2914 		 * Skip the Force Stopped Event. The event_trb(event_dma) of FSE
2915 		 * is not in the current TD pointed by ep_ring->dequeue because
2916 		 * that the hardware dequeue pointer still at the previous TRB
2917 		 * of the current TD. The previous TRB maybe a Link TD or the
2918 		 * last TRB of the previous TD. The command completion handle
2919 		 * will take care the rest.
2920 		 */
2921 		if (!ep_seg && (trb_comp_code == COMP_STOPPED ||
2922 			   trb_comp_code == COMP_STOPPED_LENGTH_INVALID)) {
2923 			goto cleanup;
2924 		}
2925 
2926 		if (!ep_seg) {
2927 
2928 			if (ep->skip && usb_endpoint_xfer_isoc(&td->urb->ep->desc)) {
2929 				skip_isoc_td(xhci, td, ep, status);
2930 				goto cleanup;
2931 			}
2932 
2933 			/*
2934 			 * Some hosts give a spurious success event after a short
2935 			 * transfer. Ignore it.
2936 			 */
2937 			if ((xhci->quirks & XHCI_SPURIOUS_SUCCESS) &&
2938 			    ep_ring->last_td_was_short) {
2939 				ep_ring->last_td_was_short = false;
2940 				goto cleanup;
2941 			}
2942 
2943 			/*
2944 			 * xhci 4.10.2 states isoc endpoints should continue
2945 			 * processing the next TD if there was an error mid TD.
2946 			 * So host like NEC don't generate an event for the last
2947 			 * isoc TRB even if the IOC flag is set.
2948 			 * xhci 4.9.1 states that if there are errors in mult-TRB
2949 			 * TDs xHC should generate an error for that TRB, and if xHC
2950 			 * proceeds to the next TD it should genete an event for
2951 			 * any TRB with IOC flag on the way. Other host follow this.
2952 			 * So this event might be for the next TD.
2953 			 */
2954 			if (td->error_mid_td &&
2955 			    !list_is_last(&td->td_list, &ep_ring->td_list)) {
2956 				struct xhci_td *td_next = list_next_entry(td, td_list);
2957 
2958 				ep_seg = trb_in_td(xhci, td_next->start_seg, td_next->first_trb,
2959 						   td_next->last_trb, ep_trb_dma, false);
2960 				if (ep_seg) {
2961 					/* give back previous TD, start handling new */
2962 					xhci_dbg(xhci, "Missing TD completion event after mid TD error\n");
2963 					ep_ring->dequeue = td->last_trb;
2964 					ep_ring->deq_seg = td->last_trb_seg;
2965 					inc_deq(xhci, ep_ring);
2966 					xhci_td_cleanup(xhci, td, ep_ring, td->status);
2967 					td = td_next;
2968 				}
2969 			}
2970 
2971 			if (!ep_seg) {
2972 				/* HC is busted, give up! */
2973 				xhci_err(xhci,
2974 					"ERROR Transfer event TRB DMA ptr not "
2975 					"part of current TD ep_index %d "
2976 					"comp_code %u\n", ep_index,
2977 					trb_comp_code);
2978 				trb_in_td(xhci, ep_ring->deq_seg,
2979 					  ep_ring->dequeue, td->last_trb,
2980 					  ep_trb_dma, true);
2981 				return -ESHUTDOWN;
2982 			}
2983 		}
2984 		if (trb_comp_code == COMP_SHORT_PACKET)
2985 			ep_ring->last_td_was_short = true;
2986 		else
2987 			ep_ring->last_td_was_short = false;
2988 
2989 		if (ep->skip) {
2990 			xhci_dbg(xhci,
2991 				 "Found td. Clear skip flag for slot %u ep %u.\n",
2992 				 slot_id, ep_index);
2993 			ep->skip = false;
2994 		}
2995 
2996 		ep_trb = &ep_seg->trbs[(ep_trb_dma - ep_seg->dma) /
2997 						sizeof(*ep_trb)];
2998 
2999 		trace_xhci_handle_transfer(ep_ring,
3000 				(struct xhci_generic_trb *) ep_trb);
3001 
3002 		/*
3003 		 * No-op TRB could trigger interrupts in a case where
3004 		 * a URB was killed and a STALL_ERROR happens right
3005 		 * after the endpoint ring stopped. Reset the halted
3006 		 * endpoint. Otherwise, the endpoint remains stalled
3007 		 * indefinitely.
3008 		 */
3009 
3010 		if (trb_is_noop(ep_trb)) {
3011 			if (trb_comp_code == COMP_STALL_ERROR ||
3012 			    xhci_requires_manual_halt_cleanup(xhci, ep_ctx,
3013 							      trb_comp_code))
3014 				xhci_handle_halted_endpoint(xhci, ep, td,
3015 							    EP_HARD_RESET);
3016 			goto cleanup;
3017 		}
3018 
3019 		td->status = status;
3020 
3021 		/* update the urb's actual_length and give back to the core */
3022 		if (usb_endpoint_xfer_control(&td->urb->ep->desc))
3023 			process_ctrl_td(xhci, ep, ep_ring, td, ep_trb, event);
3024 		else if (usb_endpoint_xfer_isoc(&td->urb->ep->desc))
3025 			process_isoc_td(xhci, ep, ep_ring, td, ep_trb, event);
3026 		else
3027 			process_bulk_intr_td(xhci, ep, ep_ring, td, ep_trb, event);
3028 cleanup:
3029 		handling_skipped_tds = ep->skip &&
3030 			trb_comp_code != COMP_MISSED_SERVICE_ERROR &&
3031 			trb_comp_code != COMP_NO_PING_RESPONSE_ERROR;
3032 
3033 		/*
3034 		 * Do not update event ring dequeue pointer if we're in a loop
3035 		 * processing missed tds.
3036 		 */
3037 		if (!handling_skipped_tds)
3038 			inc_deq(xhci, ir->event_ring);
3039 
3040 	/*
3041 	 * If ep->skip is set, it means there are missed tds on the
3042 	 * endpoint ring need to take care of.
3043 	 * Process them as short transfer until reach the td pointed by
3044 	 * the event.
3045 	 */
3046 	} while (handling_skipped_tds);
3047 
3048 	return 0;
3049 
3050 err_out:
3051 	xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n",
3052 		 (unsigned long long) xhci_trb_virt_to_dma(
3053 			 ir->event_ring->deq_seg,
3054 			 ir->event_ring->dequeue),
3055 		 lower_32_bits(le64_to_cpu(event->buffer)),
3056 		 upper_32_bits(le64_to_cpu(event->buffer)),
3057 		 le32_to_cpu(event->transfer_len),
3058 		 le32_to_cpu(event->flags));
3059 	return -ENODEV;
3060 }
3061 
3062 /*
3063  * This function handles all OS-owned events on the event ring.  It may drop
3064  * xhci->lock between event processing (e.g. to pass up port status changes).
3065  * Returns >0 for "possibly more events to process" (caller should call again),
3066  * otherwise 0 if done.  In future, <0 returns should indicate error code.
3067  */
xhci_handle_event(struct xhci_hcd * xhci,struct xhci_interrupter * ir)3068 static int xhci_handle_event(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
3069 {
3070 	union xhci_trb *event;
3071 	int update_ptrs = 1;
3072 	u32 trb_type;
3073 	int ret;
3074 
3075 	/* Event ring hasn't been allocated yet. */
3076 	if (!ir || !ir->event_ring || !ir->event_ring->dequeue) {
3077 		xhci_err(xhci, "ERROR interrupter not ready\n");
3078 		return -ENOMEM;
3079 	}
3080 
3081 	event = ir->event_ring->dequeue;
3082 	/* Does the HC or OS own the TRB? */
3083 	if ((le32_to_cpu(event->event_cmd.flags) & TRB_CYCLE) !=
3084 	    ir->event_ring->cycle_state)
3085 		return 0;
3086 
3087 	trace_xhci_handle_event(ir->event_ring, &event->generic);
3088 
3089 	/*
3090 	 * Barrier between reading the TRB_CYCLE (valid) flag above and any
3091 	 * speculative reads of the event's flags/data below.
3092 	 */
3093 	rmb();
3094 	trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(event->event_cmd.flags));
3095 	/* FIXME: Handle more event types. */
3096 
3097 	switch (trb_type) {
3098 	case TRB_COMPLETION:
3099 		handle_cmd_completion(xhci, &event->event_cmd);
3100 		break;
3101 	case TRB_PORT_STATUS:
3102 		handle_port_status(xhci, ir, event);
3103 		update_ptrs = 0;
3104 		break;
3105 	case TRB_TRANSFER:
3106 		ret = handle_tx_event(xhci, ir, &event->trans_event);
3107 		if (ret >= 0)
3108 			update_ptrs = 0;
3109 		break;
3110 	case TRB_DEV_NOTE:
3111 		handle_device_notification(xhci, event);
3112 		break;
3113 	default:
3114 		if (trb_type >= TRB_VENDOR_DEFINED_LOW)
3115 			handle_vendor_event(xhci, event, trb_type);
3116 		else
3117 			xhci_warn(xhci, "ERROR unknown event type %d\n", trb_type);
3118 	}
3119 	/* Any of the above functions may drop and re-acquire the lock, so check
3120 	 * to make sure a watchdog timer didn't mark the host as non-responsive.
3121 	 */
3122 	if (xhci->xhc_state & XHCI_STATE_DYING) {
3123 		xhci_dbg(xhci, "xHCI host dying, returning from "
3124 				"event handler.\n");
3125 		return 0;
3126 	}
3127 
3128 	if (update_ptrs)
3129 		/* Update SW event ring dequeue pointer */
3130 		inc_deq(xhci, ir->event_ring);
3131 
3132 	/* Are there more items on the event ring?  Caller will call us again to
3133 	 * check.
3134 	 */
3135 	return 1;
3136 }
3137 
3138 /*
3139  * Update Event Ring Dequeue Pointer:
3140  * - When all events have finished
3141  * - To avoid "Event Ring Full Error" condition
3142  */
xhci_update_erst_dequeue(struct xhci_hcd * xhci,struct xhci_interrupter * ir,union xhci_trb * event_ring_deq,bool clear_ehb)3143 static void xhci_update_erst_dequeue(struct xhci_hcd *xhci,
3144 				     struct xhci_interrupter *ir,
3145 				     union xhci_trb *event_ring_deq,
3146 				     bool clear_ehb)
3147 {
3148 	u64 temp_64;
3149 	dma_addr_t deq;
3150 
3151 	temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
3152 	/* If necessary, update the HW's version of the event ring deq ptr. */
3153 	if (event_ring_deq != ir->event_ring->dequeue) {
3154 		deq = xhci_trb_virt_to_dma(ir->event_ring->deq_seg,
3155 				ir->event_ring->dequeue);
3156 		if (deq == 0)
3157 			xhci_warn(xhci, "WARN something wrong with SW event ring dequeue ptr\n");
3158 		/*
3159 		 * Per 4.9.4, Software writes to the ERDP register shall
3160 		 * always advance the Event Ring Dequeue Pointer value.
3161 		 */
3162 		if ((temp_64 & (u64) ~ERST_PTR_MASK) ==
3163 				((u64) deq & (u64) ~ERST_PTR_MASK))
3164 			return;
3165 
3166 		/* Update HC event ring dequeue pointer */
3167 		temp_64 &= ERST_DESI_MASK;
3168 		temp_64 |= ((u64) deq & (u64) ~ERST_PTR_MASK);
3169 	}
3170 
3171 	/* Clear the event handler busy flag (RW1C) */
3172 	if (clear_ehb)
3173 		temp_64 |= ERST_EHB;
3174 	xhci_write_64(xhci, temp_64, &ir->ir_set->erst_dequeue);
3175 }
3176 
3177 /*
3178  * xHCI spec says we can get an interrupt, and if the HC has an error condition,
3179  * we might get bad data out of the event ring.  Section 4.10.2.7 has a list of
3180  * indicators of an event TRB error, but we check the status *first* to be safe.
3181  */
xhci_irq(struct usb_hcd * hcd)3182 irqreturn_t xhci_irq(struct usb_hcd *hcd)
3183 {
3184 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3185 	union xhci_trb *event_ring_deq;
3186 	struct xhci_interrupter *ir;
3187 	irqreturn_t ret = IRQ_NONE;
3188 	u64 temp_64;
3189 	u32 status;
3190 	int event_loop = 0;
3191 
3192 	spin_lock(&xhci->lock);
3193 	/* Check if the xHC generated the interrupt, or the irq is shared */
3194 	status = readl(&xhci->op_regs->status);
3195 	if (status == ~(u32)0) {
3196 		xhci_hc_died(xhci);
3197 		ret = IRQ_HANDLED;
3198 		goto out;
3199 	}
3200 
3201 	if (!(status & STS_EINT))
3202 		goto out;
3203 
3204 	if (status & STS_HCE) {
3205 		xhci_warn(xhci, "WARNING: Host Controller Error\n");
3206 		goto out;
3207 	}
3208 
3209 	if (status & STS_FATAL) {
3210 		xhci_warn(xhci, "WARNING: Host System Error\n");
3211 		xhci_halt(xhci);
3212 		ret = IRQ_HANDLED;
3213 		goto out;
3214 	}
3215 
3216 	/*
3217 	 * Clear the op reg interrupt status first,
3218 	 * so we can receive interrupts from other MSI-X interrupters.
3219 	 * Write 1 to clear the interrupt status.
3220 	 */
3221 	status |= STS_EINT;
3222 	writel(status, &xhci->op_regs->status);
3223 
3224 	/* This is the handler of the primary interrupter */
3225 	ir = xhci->interrupter;
3226 	if (!hcd->msi_enabled) {
3227 		u32 irq_pending;
3228 		irq_pending = readl(&ir->ir_set->irq_pending);
3229 		irq_pending |= IMAN_IP;
3230 		writel(irq_pending, &ir->ir_set->irq_pending);
3231 	}
3232 
3233 	if (xhci->xhc_state & XHCI_STATE_DYING ||
3234 	    xhci->xhc_state & XHCI_STATE_HALTED) {
3235 		xhci_dbg(xhci, "xHCI dying, ignoring interrupt. "
3236 				"Shouldn't IRQs be disabled?\n");
3237 		/* Clear the event handler busy flag (RW1C);
3238 		 * the event ring should be empty.
3239 		 */
3240 		temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
3241 		xhci_write_64(xhci, temp_64 | ERST_EHB,
3242 				&ir->ir_set->erst_dequeue);
3243 		ret = IRQ_HANDLED;
3244 		goto out;
3245 	}
3246 
3247 	event_ring_deq = ir->event_ring->dequeue;
3248 	/* FIXME this should be a delayed service routine
3249 	 * that clears the EHB.
3250 	 */
3251 	while (xhci_handle_event(xhci, ir) > 0) {
3252 		if (event_loop++ < TRBS_PER_SEGMENT / 2)
3253 			continue;
3254 		xhci_update_erst_dequeue(xhci, ir, event_ring_deq, false);
3255 		event_ring_deq = ir->event_ring->dequeue;
3256 
3257 		/* ring is half-full, force isoc trbs to interrupt more often */
3258 		if (xhci->isoc_bei_interval > AVOID_BEI_INTERVAL_MIN)
3259 			xhci->isoc_bei_interval = xhci->isoc_bei_interval / 2;
3260 
3261 		event_loop = 0;
3262 	}
3263 
3264 	xhci_update_erst_dequeue(xhci, ir, event_ring_deq, true);
3265 	ret = IRQ_HANDLED;
3266 
3267 out:
3268 	spin_unlock(&xhci->lock);
3269 
3270 	return ret;
3271 }
3272 
xhci_msi_irq(int irq,void * hcd)3273 irqreturn_t xhci_msi_irq(int irq, void *hcd)
3274 {
3275 	return xhci_irq(hcd);
3276 }
3277 EXPORT_SYMBOL_GPL(xhci_msi_irq);
3278 
3279 /****		Endpoint Ring Operations	****/
3280 
3281 /*
3282  * Generic function for queueing a TRB on a ring.
3283  * The caller must have checked to make sure there's room on the ring.
3284  *
3285  * @more_trbs_coming:	Will you enqueue more TRBs before calling
3286  *			prepare_transfer()?
3287  */
queue_trb(struct xhci_hcd * xhci,struct xhci_ring * ring,bool more_trbs_coming,u32 field1,u32 field2,u32 field3,u32 field4)3288 static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
3289 		bool more_trbs_coming,
3290 		u32 field1, u32 field2, u32 field3, u32 field4)
3291 {
3292 	struct xhci_generic_trb *trb;
3293 
3294 	trb = &ring->enqueue->generic;
3295 	trb->field[0] = cpu_to_le32(field1);
3296 	trb->field[1] = cpu_to_le32(field2);
3297 	trb->field[2] = cpu_to_le32(field3);
3298 	/* make sure TRB is fully written before giving it to the controller */
3299 	wmb();
3300 	trb->field[3] = cpu_to_le32(field4);
3301 
3302 	trace_xhci_queue_trb(ring, trb);
3303 
3304 	inc_enq(xhci, ring, more_trbs_coming);
3305 }
3306 
3307 /*
3308  * Does various checks on the endpoint ring, and makes it ready to queue num_trbs.
3309  * expand ring if it start to be full.
3310  */
prepare_ring(struct xhci_hcd * xhci,struct xhci_ring * ep_ring,u32 ep_state,unsigned int num_trbs,gfp_t mem_flags)3311 static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
3312 		u32 ep_state, unsigned int num_trbs, gfp_t mem_flags)
3313 {
3314 	unsigned int link_trb_count = 0;
3315 	unsigned int new_segs = 0;
3316 
3317 	/* Make sure the endpoint has been added to xHC schedule */
3318 	switch (ep_state) {
3319 	case EP_STATE_DISABLED:
3320 		/*
3321 		 * USB core changed config/interfaces without notifying us,
3322 		 * or hardware is reporting the wrong state.
3323 		 */
3324 		xhci_warn(xhci, "WARN urb submitted to disabled ep\n");
3325 		return -ENOENT;
3326 	case EP_STATE_ERROR:
3327 		xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n");
3328 		/* FIXME event handling code for error needs to clear it */
3329 		/* XXX not sure if this should be -ENOENT or not */
3330 		return -EINVAL;
3331 	case EP_STATE_HALTED:
3332 		xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n");
3333 		break;
3334 	case EP_STATE_STOPPED:
3335 	case EP_STATE_RUNNING:
3336 		break;
3337 	default:
3338 		xhci_err(xhci, "ERROR unknown endpoint state for ep\n");
3339 		/*
3340 		 * FIXME issue Configure Endpoint command to try to get the HC
3341 		 * back into a known state.
3342 		 */
3343 		return -EINVAL;
3344 	}
3345 
3346 	if (ep_ring != xhci->cmd_ring) {
3347 		new_segs = xhci_ring_expansion_needed(xhci, ep_ring, num_trbs);
3348 	} else if (xhci_num_trbs_free(xhci, ep_ring) <= num_trbs) {
3349 		xhci_err(xhci, "Do not support expand command ring\n");
3350 		return -ENOMEM;
3351 	}
3352 
3353 	if (new_segs) {
3354 		xhci_dbg_trace(xhci, trace_xhci_dbg_ring_expansion,
3355 				"ERROR no room on ep ring, try ring expansion");
3356 		if (xhci_ring_expansion(xhci, ep_ring, new_segs, mem_flags)) {
3357 			xhci_err(xhci, "Ring expansion failed\n");
3358 			return -ENOMEM;
3359 		}
3360 	}
3361 
3362 	while (trb_is_link(ep_ring->enqueue)) {
3363 		/* If we're not dealing with 0.95 hardware or isoc rings
3364 		 * on AMD 0.96 host, clear the chain bit.
3365 		 */
3366 		if (!xhci_link_trb_quirk(xhci) &&
3367 		    !(ep_ring->type == TYPE_ISOC &&
3368 		      (xhci->quirks & XHCI_AMD_0x96_HOST)))
3369 			ep_ring->enqueue->link.control &=
3370 				cpu_to_le32(~TRB_CHAIN);
3371 		else
3372 			ep_ring->enqueue->link.control |=
3373 				cpu_to_le32(TRB_CHAIN);
3374 
3375 		wmb();
3376 		ep_ring->enqueue->link.control ^= cpu_to_le32(TRB_CYCLE);
3377 
3378 		/* Toggle the cycle bit after the last ring segment. */
3379 		if (link_trb_toggles_cycle(ep_ring->enqueue))
3380 			ep_ring->cycle_state ^= 1;
3381 
3382 		ep_ring->enq_seg = ep_ring->enq_seg->next;
3383 		ep_ring->enqueue = ep_ring->enq_seg->trbs;
3384 
3385 		/* prevent infinite loop if all first trbs are link trbs */
3386 		if (link_trb_count++ > ep_ring->num_segs) {
3387 			xhci_warn(xhci, "Ring is an endless link TRB loop\n");
3388 			return -EINVAL;
3389 		}
3390 	}
3391 
3392 	if (last_trb_on_seg(ep_ring->enq_seg, ep_ring->enqueue)) {
3393 		xhci_warn(xhci, "Missing link TRB at end of ring segment\n");
3394 		return -EINVAL;
3395 	}
3396 
3397 	return 0;
3398 }
3399 
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)3400 static int prepare_transfer(struct xhci_hcd *xhci,
3401 		struct xhci_virt_device *xdev,
3402 		unsigned int ep_index,
3403 		unsigned int stream_id,
3404 		unsigned int num_trbs,
3405 		struct urb *urb,
3406 		unsigned int td_index,
3407 		gfp_t mem_flags)
3408 {
3409 	int ret;
3410 	struct urb_priv *urb_priv;
3411 	struct xhci_td	*td;
3412 	struct xhci_ring *ep_ring;
3413 	struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
3414 
3415 	ep_ring = xhci_triad_to_transfer_ring(xhci, xdev->slot_id, ep_index,
3416 					      stream_id);
3417 	if (!ep_ring) {
3418 		xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n",
3419 				stream_id);
3420 		return -EINVAL;
3421 	}
3422 
3423 	ret = prepare_ring(xhci, ep_ring, GET_EP_CTX_STATE(ep_ctx),
3424 			   num_trbs, mem_flags);
3425 	if (ret)
3426 		return ret;
3427 
3428 	urb_priv = urb->hcpriv;
3429 	td = &urb_priv->td[td_index];
3430 
3431 	INIT_LIST_HEAD(&td->td_list);
3432 	INIT_LIST_HEAD(&td->cancelled_td_list);
3433 
3434 	if (td_index == 0) {
3435 		ret = usb_hcd_link_urb_to_ep(bus_to_hcd(urb->dev->bus), urb);
3436 		if (unlikely(ret))
3437 			return ret;
3438 	}
3439 
3440 	td->urb = urb;
3441 	/* Add this TD to the tail of the endpoint ring's TD list */
3442 	list_add_tail(&td->td_list, &ep_ring->td_list);
3443 	td->start_seg = ep_ring->enq_seg;
3444 	td->first_trb = ep_ring->enqueue;
3445 
3446 	return 0;
3447 }
3448 
count_trbs(u64 addr,u64 len)3449 unsigned int count_trbs(u64 addr, u64 len)
3450 {
3451 	unsigned int num_trbs;
3452 
3453 	num_trbs = DIV_ROUND_UP(len + (addr & (TRB_MAX_BUFF_SIZE - 1)),
3454 			TRB_MAX_BUFF_SIZE);
3455 	if (num_trbs == 0)
3456 		num_trbs++;
3457 
3458 	return num_trbs;
3459 }
3460 
count_trbs_needed(struct urb * urb)3461 static inline unsigned int count_trbs_needed(struct urb *urb)
3462 {
3463 	return count_trbs(urb->transfer_dma, urb->transfer_buffer_length);
3464 }
3465 
count_sg_trbs_needed(struct urb * urb)3466 static unsigned int count_sg_trbs_needed(struct urb *urb)
3467 {
3468 	struct scatterlist *sg;
3469 	unsigned int i, len, full_len, num_trbs = 0;
3470 
3471 	full_len = urb->transfer_buffer_length;
3472 
3473 	for_each_sg(urb->sg, sg, urb->num_mapped_sgs, i) {
3474 		len = sg_dma_len(sg);
3475 		num_trbs += count_trbs(sg_dma_address(sg), len);
3476 		len = min_t(unsigned int, len, full_len);
3477 		full_len -= len;
3478 		if (full_len == 0)
3479 			break;
3480 	}
3481 
3482 	return num_trbs;
3483 }
3484 
count_isoc_trbs_needed(struct urb * urb,int i)3485 static unsigned int count_isoc_trbs_needed(struct urb *urb, int i)
3486 {
3487 	u64 addr, len;
3488 
3489 	addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset);
3490 	len = urb->iso_frame_desc[i].length;
3491 
3492 	return count_trbs(addr, len);
3493 }
3494 
check_trb_math(struct urb * urb,int running_total)3495 static void check_trb_math(struct urb *urb, int running_total)
3496 {
3497 	if (unlikely(running_total != urb->transfer_buffer_length))
3498 		dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, "
3499 				"queued %#x (%d), asked for %#x (%d)\n",
3500 				__func__,
3501 				urb->ep->desc.bEndpointAddress,
3502 				running_total, running_total,
3503 				urb->transfer_buffer_length,
3504 				urb->transfer_buffer_length);
3505 }
3506 
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)3507 static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id,
3508 		unsigned int ep_index, unsigned int stream_id, int start_cycle,
3509 		struct xhci_generic_trb *start_trb)
3510 {
3511 	/*
3512 	 * Pass all the TRBs to the hardware at once and make sure this write
3513 	 * isn't reordered.
3514 	 */
3515 	wmb();
3516 	if (start_cycle)
3517 		start_trb->field[3] |= cpu_to_le32(start_cycle);
3518 	else
3519 		start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE);
3520 	xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
3521 }
3522 
check_interval(struct xhci_hcd * xhci,struct urb * urb,struct xhci_ep_ctx * ep_ctx)3523 static void check_interval(struct xhci_hcd *xhci, struct urb *urb,
3524 						struct xhci_ep_ctx *ep_ctx)
3525 {
3526 	int xhci_interval;
3527 	int ep_interval;
3528 
3529 	xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info));
3530 	ep_interval = urb->interval;
3531 
3532 	/* Convert to microframes */
3533 	if (urb->dev->speed == USB_SPEED_LOW ||
3534 			urb->dev->speed == USB_SPEED_FULL)
3535 		ep_interval *= 8;
3536 
3537 	/* FIXME change this to a warning and a suggestion to use the new API
3538 	 * to set the polling interval (once the API is added).
3539 	 */
3540 	if (xhci_interval != ep_interval) {
3541 		dev_dbg_ratelimited(&urb->dev->dev,
3542 				"Driver uses different interval (%d microframe%s) than xHCI (%d microframe%s)\n",
3543 				ep_interval, ep_interval == 1 ? "" : "s",
3544 				xhci_interval, xhci_interval == 1 ? "" : "s");
3545 		urb->interval = xhci_interval;
3546 		/* Convert back to frames for LS/FS devices */
3547 		if (urb->dev->speed == USB_SPEED_LOW ||
3548 				urb->dev->speed == USB_SPEED_FULL)
3549 			urb->interval /= 8;
3550 	}
3551 }
3552 
3553 /*
3554  * xHCI uses normal TRBs for both bulk and interrupt.  When the interrupt
3555  * endpoint is to be serviced, the xHC will consume (at most) one TD.  A TD
3556  * (comprised of sg list entries) can take several service intervals to
3557  * transmit.
3558  */
xhci_queue_intr_tx(struct xhci_hcd * xhci,gfp_t mem_flags,struct urb * urb,int slot_id,unsigned int ep_index)3559 int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3560 		struct urb *urb, int slot_id, unsigned int ep_index)
3561 {
3562 	struct xhci_ep_ctx *ep_ctx;
3563 
3564 	ep_ctx = xhci_get_ep_ctx(xhci, xhci->devs[slot_id]->out_ctx, ep_index);
3565 	check_interval(xhci, urb, ep_ctx);
3566 
3567 	return xhci_queue_bulk_tx(xhci, mem_flags, urb, slot_id, ep_index);
3568 }
3569 
3570 /*
3571  * For xHCI 1.0 host controllers, TD size is the number of max packet sized
3572  * packets remaining in the TD (*not* including this TRB).
3573  *
3574  * Total TD packet count = total_packet_count =
3575  *     DIV_ROUND_UP(TD size in bytes / wMaxPacketSize)
3576  *
3577  * Packets transferred up to and including this TRB = packets_transferred =
3578  *     rounddown(total bytes transferred including this TRB / wMaxPacketSize)
3579  *
3580  * TD size = total_packet_count - packets_transferred
3581  *
3582  * For xHCI 0.96 and older, TD size field should be the remaining bytes
3583  * including this TRB, right shifted by 10
3584  *
3585  * For all hosts it must fit in bits 21:17, so it can't be bigger than 31.
3586  * This is taken care of in the TRB_TD_SIZE() macro
3587  *
3588  * The last TRB in a TD must have the TD size set to zero.
3589  */
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)3590 static u32 xhci_td_remainder(struct xhci_hcd *xhci, int transferred,
3591 			      int trb_buff_len, unsigned int td_total_len,
3592 			      struct urb *urb, bool more_trbs_coming)
3593 {
3594 	u32 maxp, total_packet_count;
3595 
3596 	/* MTK xHCI 0.96 contains some features from 1.0 */
3597 	if (xhci->hci_version < 0x100 && !(xhci->quirks & XHCI_MTK_HOST))
3598 		return ((td_total_len - transferred) >> 10);
3599 
3600 	/* One TRB with a zero-length data packet. */
3601 	if (!more_trbs_coming || (transferred == 0 && trb_buff_len == 0) ||
3602 	    trb_buff_len == td_total_len)
3603 		return 0;
3604 
3605 	/* for MTK xHCI 0.96, TD size include this TRB, but not in 1.x */
3606 	if ((xhci->quirks & XHCI_MTK_HOST) && (xhci->hci_version < 0x100))
3607 		trb_buff_len = 0;
3608 
3609 	maxp = usb_endpoint_maxp(&urb->ep->desc);
3610 	total_packet_count = DIV_ROUND_UP(td_total_len, maxp);
3611 
3612 	/* Queueing functions don't count the current TRB into transferred */
3613 	return (total_packet_count - ((transferred + trb_buff_len) / maxp));
3614 }
3615 
3616 
xhci_align_td(struct xhci_hcd * xhci,struct urb * urb,u32 enqd_len,u32 * trb_buff_len,struct xhci_segment * seg)3617 static int xhci_align_td(struct xhci_hcd *xhci, struct urb *urb, u32 enqd_len,
3618 			 u32 *trb_buff_len, struct xhci_segment *seg)
3619 {
3620 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
3621 	unsigned int unalign;
3622 	unsigned int max_pkt;
3623 	u32 new_buff_len;
3624 	size_t len;
3625 
3626 	max_pkt = usb_endpoint_maxp(&urb->ep->desc);
3627 	unalign = (enqd_len + *trb_buff_len) % max_pkt;
3628 
3629 	/* we got lucky, last normal TRB data on segment is packet aligned */
3630 	if (unalign == 0)
3631 		return 0;
3632 
3633 	xhci_dbg(xhci, "Unaligned %d bytes, buff len %d\n",
3634 		 unalign, *trb_buff_len);
3635 
3636 	/* is the last nornal TRB alignable by splitting it */
3637 	if (*trb_buff_len > unalign) {
3638 		*trb_buff_len -= unalign;
3639 		xhci_dbg(xhci, "split align, new buff len %d\n", *trb_buff_len);
3640 		return 0;
3641 	}
3642 
3643 	/*
3644 	 * We want enqd_len + trb_buff_len to sum up to a number aligned to
3645 	 * number which is divisible by the endpoint's wMaxPacketSize. IOW:
3646 	 * (size of currently enqueued TRBs + remainder) % wMaxPacketSize == 0.
3647 	 */
3648 	new_buff_len = max_pkt - (enqd_len % max_pkt);
3649 
3650 	if (new_buff_len > (urb->transfer_buffer_length - enqd_len))
3651 		new_buff_len = (urb->transfer_buffer_length - enqd_len);
3652 
3653 	/* create a max max_pkt sized bounce buffer pointed to by last trb */
3654 	if (usb_urb_dir_out(urb)) {
3655 		if (urb->num_sgs) {
3656 			len = sg_pcopy_to_buffer(urb->sg, urb->num_sgs,
3657 						 seg->bounce_buf, new_buff_len, enqd_len);
3658 			if (len != new_buff_len)
3659 				xhci_warn(xhci, "WARN Wrong bounce buffer write length: %zu != %d\n",
3660 					  len, new_buff_len);
3661 		} else {
3662 			memcpy(seg->bounce_buf, urb->transfer_buffer + enqd_len, new_buff_len);
3663 		}
3664 
3665 		seg->bounce_dma = dma_map_single(dev, seg->bounce_buf,
3666 						 max_pkt, DMA_TO_DEVICE);
3667 	} else {
3668 		seg->bounce_dma = dma_map_single(dev, seg->bounce_buf,
3669 						 max_pkt, DMA_FROM_DEVICE);
3670 	}
3671 
3672 	if (dma_mapping_error(dev, seg->bounce_dma)) {
3673 		/* try without aligning. Some host controllers survive */
3674 		xhci_warn(xhci, "Failed mapping bounce buffer, not aligning\n");
3675 		return 0;
3676 	}
3677 	*trb_buff_len = new_buff_len;
3678 	seg->bounce_len = new_buff_len;
3679 	seg->bounce_offs = enqd_len;
3680 
3681 	xhci_dbg(xhci, "Bounce align, new buff len %d\n", *trb_buff_len);
3682 
3683 	return 1;
3684 }
3685 
3686 /* 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)3687 int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3688 		struct urb *urb, int slot_id, unsigned int ep_index)
3689 {
3690 	struct xhci_ring *ring;
3691 	struct urb_priv *urb_priv;
3692 	struct xhci_td *td;
3693 	struct xhci_generic_trb *start_trb;
3694 	struct scatterlist *sg = NULL;
3695 	bool more_trbs_coming = true;
3696 	bool need_zero_pkt = false;
3697 	bool first_trb = true;
3698 	unsigned int num_trbs;
3699 	unsigned int start_cycle, num_sgs = 0;
3700 	unsigned int enqd_len, block_len, trb_buff_len, full_len;
3701 	int sent_len, ret;
3702 	u32 field, length_field, remainder;
3703 	u64 addr, send_addr;
3704 
3705 	ring = xhci_urb_to_transfer_ring(xhci, urb);
3706 	if (!ring)
3707 		return -EINVAL;
3708 
3709 	full_len = urb->transfer_buffer_length;
3710 	/* If we have scatter/gather list, we use it. */
3711 	if (urb->num_sgs && !(urb->transfer_flags & URB_DMA_MAP_SINGLE)) {
3712 		num_sgs = urb->num_mapped_sgs;
3713 		sg = urb->sg;
3714 		addr = (u64) sg_dma_address(sg);
3715 		block_len = sg_dma_len(sg);
3716 		num_trbs = count_sg_trbs_needed(urb);
3717 	} else {
3718 		num_trbs = count_trbs_needed(urb);
3719 		addr = (u64) urb->transfer_dma;
3720 		block_len = full_len;
3721 	}
3722 	ret = prepare_transfer(xhci, xhci->devs[slot_id],
3723 			ep_index, urb->stream_id,
3724 			num_trbs, urb, 0, mem_flags);
3725 	if (unlikely(ret < 0))
3726 		return ret;
3727 
3728 	urb_priv = urb->hcpriv;
3729 
3730 	/* Deal with URB_ZERO_PACKET - need one more td/trb */
3731 	if (urb->transfer_flags & URB_ZERO_PACKET && urb_priv->num_tds > 1)
3732 		need_zero_pkt = true;
3733 
3734 	td = &urb_priv->td[0];
3735 
3736 	/*
3737 	 * Don't give the first TRB to the hardware (by toggling the cycle bit)
3738 	 * until we've finished creating all the other TRBs.  The ring's cycle
3739 	 * state may change as we enqueue the other TRBs, so save it too.
3740 	 */
3741 	start_trb = &ring->enqueue->generic;
3742 	start_cycle = ring->cycle_state;
3743 	send_addr = addr;
3744 
3745 	/* Queue the TRBs, even if they are zero-length */
3746 	for (enqd_len = 0; first_trb || enqd_len < full_len;
3747 			enqd_len += trb_buff_len) {
3748 		field = TRB_TYPE(TRB_NORMAL);
3749 
3750 		/* TRB buffer should not cross 64KB boundaries */
3751 		trb_buff_len = TRB_BUFF_LEN_UP_TO_BOUNDARY(addr);
3752 		trb_buff_len = min_t(unsigned int, trb_buff_len, block_len);
3753 
3754 		if (enqd_len + trb_buff_len > full_len)
3755 			trb_buff_len = full_len - enqd_len;
3756 
3757 		/* Don't change the cycle bit of the first TRB until later */
3758 		if (first_trb) {
3759 			first_trb = false;
3760 			if (start_cycle == 0)
3761 				field |= TRB_CYCLE;
3762 		} else
3763 			field |= ring->cycle_state;
3764 
3765 		/* Chain all the TRBs together; clear the chain bit in the last
3766 		 * TRB to indicate it's the last TRB in the chain.
3767 		 */
3768 		if (enqd_len + trb_buff_len < full_len) {
3769 			field |= TRB_CHAIN;
3770 			if (trb_is_link(ring->enqueue + 1)) {
3771 				if (xhci_align_td(xhci, urb, enqd_len,
3772 						  &trb_buff_len,
3773 						  ring->enq_seg)) {
3774 					send_addr = ring->enq_seg->bounce_dma;
3775 					/* assuming TD won't span 2 segs */
3776 					td->bounce_seg = ring->enq_seg;
3777 				}
3778 			}
3779 		}
3780 		if (enqd_len + trb_buff_len >= full_len) {
3781 			field &= ~TRB_CHAIN;
3782 			field |= TRB_IOC;
3783 			more_trbs_coming = false;
3784 			td->last_trb = ring->enqueue;
3785 			td->last_trb_seg = ring->enq_seg;
3786 			if (xhci_urb_suitable_for_idt(urb)) {
3787 				memcpy(&send_addr, urb->transfer_buffer,
3788 				       trb_buff_len);
3789 				le64_to_cpus(&send_addr);
3790 				field |= TRB_IDT;
3791 			}
3792 		}
3793 
3794 		/* Only set interrupt on short packet for IN endpoints */
3795 		if (usb_urb_dir_in(urb))
3796 			field |= TRB_ISP;
3797 
3798 		/* Set the TRB length, TD size, and interrupter fields. */
3799 		remainder = xhci_td_remainder(xhci, enqd_len, trb_buff_len,
3800 					      full_len, urb, more_trbs_coming);
3801 
3802 		length_field = TRB_LEN(trb_buff_len) |
3803 			TRB_TD_SIZE(remainder) |
3804 			TRB_INTR_TARGET(0);
3805 
3806 		queue_trb(xhci, ring, more_trbs_coming | need_zero_pkt,
3807 				lower_32_bits(send_addr),
3808 				upper_32_bits(send_addr),
3809 				length_field,
3810 				field);
3811 		td->num_trbs++;
3812 		addr += trb_buff_len;
3813 		sent_len = trb_buff_len;
3814 
3815 		while (sg && sent_len >= block_len) {
3816 			/* New sg entry */
3817 			--num_sgs;
3818 			sent_len -= block_len;
3819 			sg = sg_next(sg);
3820 			if (num_sgs != 0 && sg) {
3821 				block_len = sg_dma_len(sg);
3822 				addr = (u64) sg_dma_address(sg);
3823 				addr += sent_len;
3824 			}
3825 		}
3826 		block_len -= sent_len;
3827 		send_addr = addr;
3828 	}
3829 
3830 	if (need_zero_pkt) {
3831 		ret = prepare_transfer(xhci, xhci->devs[slot_id],
3832 				       ep_index, urb->stream_id,
3833 				       1, urb, 1, mem_flags);
3834 		urb_priv->td[1].last_trb = ring->enqueue;
3835 		urb_priv->td[1].last_trb_seg = ring->enq_seg;
3836 		field = TRB_TYPE(TRB_NORMAL) | ring->cycle_state | TRB_IOC;
3837 		queue_trb(xhci, ring, 0, 0, 0, TRB_INTR_TARGET(0), field);
3838 		urb_priv->td[1].num_trbs++;
3839 	}
3840 
3841 	check_trb_math(urb, enqd_len);
3842 	giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
3843 			start_cycle, start_trb);
3844 	return 0;
3845 }
3846 
3847 /* 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)3848 int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
3849 		struct urb *urb, int slot_id, unsigned int ep_index)
3850 {
3851 	struct xhci_ring *ep_ring;
3852 	int num_trbs;
3853 	int ret;
3854 	struct usb_ctrlrequest *setup;
3855 	struct xhci_generic_trb *start_trb;
3856 	int start_cycle;
3857 	u32 field;
3858 	struct urb_priv *urb_priv;
3859 	struct xhci_td *td;
3860 
3861 	ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
3862 	if (!ep_ring)
3863 		return -EINVAL;
3864 
3865 	/*
3866 	 * Need to copy setup packet into setup TRB, so we can't use the setup
3867 	 * DMA address.
3868 	 */
3869 	if (!urb->setup_packet)
3870 		return -EINVAL;
3871 
3872 	if ((xhci->quirks & XHCI_ETRON_HOST) &&
3873 	    urb->dev->speed >= USB_SPEED_SUPER) {
3874 		/*
3875 		 * If next available TRB is the Link TRB in the ring segment then
3876 		 * enqueue a No Op TRB, this can prevent the Setup and Data Stage
3877 		 * TRB to be breaked by the Link TRB.
3878 		 */
3879 		if (trb_is_link(ep_ring->enqueue + 1)) {
3880 			field = TRB_TYPE(TRB_TR_NOOP) | ep_ring->cycle_state;
3881 			queue_trb(xhci, ep_ring, false, 0, 0,
3882 					TRB_INTR_TARGET(0), field);
3883 		}
3884 	}
3885 
3886 	/* 1 TRB for setup, 1 for status */
3887 	num_trbs = 2;
3888 	/*
3889 	 * Don't need to check if we need additional event data and normal TRBs,
3890 	 * since data in control transfers will never get bigger than 16MB
3891 	 * XXX: can we get a buffer that crosses 64KB boundaries?
3892 	 */
3893 	if (urb->transfer_buffer_length > 0)
3894 		num_trbs++;
3895 	ret = prepare_transfer(xhci, xhci->devs[slot_id],
3896 			ep_index, urb->stream_id,
3897 			num_trbs, urb, 0, mem_flags);
3898 	if (ret < 0)
3899 		return ret;
3900 
3901 	urb_priv = urb->hcpriv;
3902 	td = &urb_priv->td[0];
3903 	td->num_trbs = num_trbs;
3904 
3905 	/*
3906 	 * Don't give the first TRB to the hardware (by toggling the cycle bit)
3907 	 * until we've finished creating all the other TRBs.  The ring's cycle
3908 	 * state may change as we enqueue the other TRBs, so save it too.
3909 	 */
3910 	start_trb = &ep_ring->enqueue->generic;
3911 	start_cycle = ep_ring->cycle_state;
3912 
3913 	/* Queue setup TRB - see section 6.4.1.2.1 */
3914 	/* FIXME better way to translate setup_packet into two u32 fields? */
3915 	setup = (struct usb_ctrlrequest *) urb->setup_packet;
3916 	field = 0;
3917 	field |= TRB_IDT | TRB_TYPE(TRB_SETUP);
3918 	if (start_cycle == 0)
3919 		field |= 0x1;
3920 
3921 	/* xHCI 1.0/1.1 6.4.1.2.1: Transfer Type field */
3922 	if ((xhci->hci_version >= 0x100) || (xhci->quirks & XHCI_MTK_HOST)) {
3923 		if (urb->transfer_buffer_length > 0) {
3924 			if (setup->bRequestType & USB_DIR_IN)
3925 				field |= TRB_TX_TYPE(TRB_DATA_IN);
3926 			else
3927 				field |= TRB_TX_TYPE(TRB_DATA_OUT);
3928 		}
3929 	}
3930 
3931 	queue_trb(xhci, ep_ring, true,
3932 		  setup->bRequestType | setup->bRequest << 8 | le16_to_cpu(setup->wValue) << 16,
3933 		  le16_to_cpu(setup->wIndex) | le16_to_cpu(setup->wLength) << 16,
3934 		  TRB_LEN(8) | TRB_INTR_TARGET(0),
3935 		  /* Immediate data in pointer */
3936 		  field);
3937 
3938 	/* If there's data, queue data TRBs */
3939 	/* Only set interrupt on short packet for IN endpoints */
3940 	if (usb_urb_dir_in(urb))
3941 		field = TRB_ISP | TRB_TYPE(TRB_DATA);
3942 	else
3943 		field = TRB_TYPE(TRB_DATA);
3944 
3945 	if (urb->transfer_buffer_length > 0) {
3946 		u32 length_field, remainder;
3947 		u64 addr;
3948 
3949 		if (xhci_urb_suitable_for_idt(urb)) {
3950 			memcpy(&addr, urb->transfer_buffer,
3951 			       urb->transfer_buffer_length);
3952 			le64_to_cpus(&addr);
3953 			field |= TRB_IDT;
3954 		} else {
3955 			addr = (u64) urb->transfer_dma;
3956 		}
3957 
3958 		remainder = xhci_td_remainder(xhci, 0,
3959 				urb->transfer_buffer_length,
3960 				urb->transfer_buffer_length,
3961 				urb, 1);
3962 		length_field = TRB_LEN(urb->transfer_buffer_length) |
3963 				TRB_TD_SIZE(remainder) |
3964 				TRB_INTR_TARGET(0);
3965 		if (setup->bRequestType & USB_DIR_IN)
3966 			field |= TRB_DIR_IN;
3967 		queue_trb(xhci, ep_ring, true,
3968 				lower_32_bits(addr),
3969 				upper_32_bits(addr),
3970 				length_field,
3971 				field | ep_ring->cycle_state);
3972 	}
3973 
3974 	/* Save the DMA address of the last TRB in the TD */
3975 	td->last_trb = ep_ring->enqueue;
3976 	td->last_trb_seg = ep_ring->enq_seg;
3977 
3978 	/* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */
3979 	/* If the device sent data, the status stage is an OUT transfer */
3980 	if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN)
3981 		field = 0;
3982 	else
3983 		field = TRB_DIR_IN;
3984 	queue_trb(xhci, ep_ring, false,
3985 			0,
3986 			0,
3987 			TRB_INTR_TARGET(0),
3988 			/* Event on completion */
3989 			field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state);
3990 
3991 	giveback_first_trb(xhci, slot_id, ep_index, 0,
3992 			start_cycle, start_trb);
3993 	return 0;
3994 }
3995 
3996 /*
3997  * The transfer burst count field of the isochronous TRB defines the number of
3998  * bursts that are required to move all packets in this TD.  Only SuperSpeed
3999  * devices can burst up to bMaxBurst number of packets per service interval.
4000  * This field is zero based, meaning a value of zero in the field means one
4001  * burst.  Basically, for everything but SuperSpeed devices, this field will be
4002  * zero.  Only xHCI 1.0 host controllers support this field.
4003  */
xhci_get_burst_count(struct xhci_hcd * xhci,struct urb * urb,unsigned int total_packet_count)4004 static unsigned int xhci_get_burst_count(struct xhci_hcd *xhci,
4005 		struct urb *urb, unsigned int total_packet_count)
4006 {
4007 	unsigned int max_burst;
4008 
4009 	if (xhci->hci_version < 0x100 || urb->dev->speed < USB_SPEED_SUPER)
4010 		return 0;
4011 
4012 	max_burst = urb->ep->ss_ep_comp.bMaxBurst;
4013 	return DIV_ROUND_UP(total_packet_count, max_burst + 1) - 1;
4014 }
4015 
4016 /*
4017  * Returns the number of packets in the last "burst" of packets.  This field is
4018  * valid for all speeds of devices.  USB 2.0 devices can only do one "burst", so
4019  * the last burst packet count is equal to the total number of packets in the
4020  * TD.  SuperSpeed endpoints can have up to 3 bursts.  All but the last burst
4021  * must contain (bMaxBurst + 1) number of packets, but the last burst can
4022  * contain 1 to (bMaxBurst + 1) packets.
4023  */
xhci_get_last_burst_packet_count(struct xhci_hcd * xhci,struct urb * urb,unsigned int total_packet_count)4024 static unsigned int xhci_get_last_burst_packet_count(struct xhci_hcd *xhci,
4025 		struct urb *urb, unsigned int total_packet_count)
4026 {
4027 	unsigned int max_burst;
4028 	unsigned int residue;
4029 
4030 	if (xhci->hci_version < 0x100)
4031 		return 0;
4032 
4033 	if (urb->dev->speed >= USB_SPEED_SUPER) {
4034 		/* bMaxBurst is zero based: 0 means 1 packet per burst */
4035 		max_burst = urb->ep->ss_ep_comp.bMaxBurst;
4036 		residue = total_packet_count % (max_burst + 1);
4037 		/* If residue is zero, the last burst contains (max_burst + 1)
4038 		 * number of packets, but the TLBPC field is zero-based.
4039 		 */
4040 		if (residue == 0)
4041 			return max_burst;
4042 		return residue - 1;
4043 	}
4044 	if (total_packet_count == 0)
4045 		return 0;
4046 	return total_packet_count - 1;
4047 }
4048 
4049 /*
4050  * Calculates Frame ID field of the isochronous TRB identifies the
4051  * target frame that the Interval associated with this Isochronous
4052  * Transfer Descriptor will start on. Refer to 4.11.2.5 in 1.1 spec.
4053  *
4054  * Returns actual frame id on success, negative value on error.
4055  */
xhci_get_isoc_frame_id(struct xhci_hcd * xhci,struct urb * urb,int index)4056 static int xhci_get_isoc_frame_id(struct xhci_hcd *xhci,
4057 		struct urb *urb, int index)
4058 {
4059 	int start_frame, ist, ret = 0;
4060 	int start_frame_id, end_frame_id, current_frame_id;
4061 
4062 	if (urb->dev->speed == USB_SPEED_LOW ||
4063 			urb->dev->speed == USB_SPEED_FULL)
4064 		start_frame = urb->start_frame + index * urb->interval;
4065 	else
4066 		start_frame = (urb->start_frame + index * urb->interval) >> 3;
4067 
4068 	/* Isochronous Scheduling Threshold (IST, bits 0~3 in HCSPARAMS2):
4069 	 *
4070 	 * If bit [3] of IST is cleared to '0', software can add a TRB no
4071 	 * later than IST[2:0] Microframes before that TRB is scheduled to
4072 	 * be executed.
4073 	 * If bit [3] of IST is set to '1', software can add a TRB no later
4074 	 * than IST[2:0] Frames before that TRB is scheduled to be executed.
4075 	 */
4076 	ist = HCS_IST(xhci->hcs_params2) & 0x7;
4077 	if (HCS_IST(xhci->hcs_params2) & (1 << 3))
4078 		ist <<= 3;
4079 
4080 	/* Software shall not schedule an Isoch TD with a Frame ID value that
4081 	 * is less than the Start Frame ID or greater than the End Frame ID,
4082 	 * where:
4083 	 *
4084 	 * End Frame ID = (Current MFINDEX register value + 895 ms.) MOD 2048
4085 	 * Start Frame ID = (Current MFINDEX register value + IST + 1) MOD 2048
4086 	 *
4087 	 * Both the End Frame ID and Start Frame ID values are calculated
4088 	 * in microframes. When software determines the valid Frame ID value;
4089 	 * The End Frame ID value should be rounded down to the nearest Frame
4090 	 * boundary, and the Start Frame ID value should be rounded up to the
4091 	 * nearest Frame boundary.
4092 	 */
4093 	current_frame_id = readl(&xhci->run_regs->microframe_index);
4094 	start_frame_id = roundup(current_frame_id + ist + 1, 8);
4095 	end_frame_id = rounddown(current_frame_id + 895 * 8, 8);
4096 
4097 	start_frame &= 0x7ff;
4098 	start_frame_id = (start_frame_id >> 3) & 0x7ff;
4099 	end_frame_id = (end_frame_id >> 3) & 0x7ff;
4100 
4101 	xhci_dbg(xhci, "%s: index %d, reg 0x%x start_frame_id 0x%x, end_frame_id 0x%x, start_frame 0x%x\n",
4102 		 __func__, index, readl(&xhci->run_regs->microframe_index),
4103 		 start_frame_id, end_frame_id, start_frame);
4104 
4105 	if (start_frame_id < end_frame_id) {
4106 		if (start_frame > end_frame_id ||
4107 				start_frame < start_frame_id)
4108 			ret = -EINVAL;
4109 	} else if (start_frame_id > end_frame_id) {
4110 		if ((start_frame > end_frame_id &&
4111 				start_frame < start_frame_id))
4112 			ret = -EINVAL;
4113 	} else {
4114 			ret = -EINVAL;
4115 	}
4116 
4117 	if (index == 0) {
4118 		if (ret == -EINVAL || start_frame == start_frame_id) {
4119 			start_frame = start_frame_id + 1;
4120 			if (urb->dev->speed == USB_SPEED_LOW ||
4121 					urb->dev->speed == USB_SPEED_FULL)
4122 				urb->start_frame = start_frame;
4123 			else
4124 				urb->start_frame = start_frame << 3;
4125 			ret = 0;
4126 		}
4127 	}
4128 
4129 	if (ret) {
4130 		xhci_warn(xhci, "Frame ID %d (reg %d, index %d) beyond range (%d, %d)\n",
4131 				start_frame, current_frame_id, index,
4132 				start_frame_id, end_frame_id);
4133 		xhci_warn(xhci, "Ignore frame ID field, use SIA bit instead\n");
4134 		return ret;
4135 	}
4136 
4137 	return start_frame;
4138 }
4139 
4140 /* 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)4141 static bool trb_block_event_intr(struct xhci_hcd *xhci, int num_tds, int i)
4142 {
4143 	if (xhci->hci_version < 0x100)
4144 		return false;
4145 	/* always generate an event interrupt for the last TD */
4146 	if (i == num_tds - 1)
4147 		return false;
4148 	/*
4149 	 * If AVOID_BEI is set the host handles full event rings poorly,
4150 	 * generate an event at least every 8th TD to clear the event ring
4151 	 */
4152 	if (i && xhci->quirks & XHCI_AVOID_BEI)
4153 		return !!(i % xhci->isoc_bei_interval);
4154 
4155 	return true;
4156 }
4157 
4158 /* 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)4159 static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
4160 		struct urb *urb, int slot_id, unsigned int ep_index)
4161 {
4162 	struct xhci_ring *ep_ring;
4163 	struct urb_priv *urb_priv;
4164 	struct xhci_td *td;
4165 	int num_tds, trbs_per_td;
4166 	struct xhci_generic_trb *start_trb;
4167 	bool first_trb;
4168 	int start_cycle;
4169 	u32 field, length_field;
4170 	int running_total, trb_buff_len, td_len, td_remain_len, ret;
4171 	u64 start_addr, addr;
4172 	int i, j;
4173 	bool more_trbs_coming;
4174 	struct xhci_virt_ep *xep;
4175 	int frame_id;
4176 
4177 	xep = &xhci->devs[slot_id]->eps[ep_index];
4178 	ep_ring = xhci->devs[slot_id]->eps[ep_index].ring;
4179 
4180 	num_tds = urb->number_of_packets;
4181 	if (num_tds < 1) {
4182 		xhci_dbg(xhci, "Isoc URB with zero packets?\n");
4183 		return -EINVAL;
4184 	}
4185 	start_addr = (u64) urb->transfer_dma;
4186 	start_trb = &ep_ring->enqueue->generic;
4187 	start_cycle = ep_ring->cycle_state;
4188 
4189 	urb_priv = urb->hcpriv;
4190 	/* Queue the TRBs for each TD, even if they are zero-length */
4191 	for (i = 0; i < num_tds; i++) {
4192 		unsigned int total_pkt_count, max_pkt;
4193 		unsigned int burst_count, last_burst_pkt_count;
4194 		u32 sia_frame_id;
4195 
4196 		first_trb = true;
4197 		running_total = 0;
4198 		addr = start_addr + urb->iso_frame_desc[i].offset;
4199 		td_len = urb->iso_frame_desc[i].length;
4200 		td_remain_len = td_len;
4201 		max_pkt = usb_endpoint_maxp(&urb->ep->desc);
4202 		total_pkt_count = DIV_ROUND_UP(td_len, max_pkt);
4203 
4204 		/* A zero-length transfer still involves at least one packet. */
4205 		if (total_pkt_count == 0)
4206 			total_pkt_count++;
4207 		burst_count = xhci_get_burst_count(xhci, urb, total_pkt_count);
4208 		last_burst_pkt_count = xhci_get_last_burst_packet_count(xhci,
4209 							urb, total_pkt_count);
4210 
4211 		trbs_per_td = count_isoc_trbs_needed(urb, i);
4212 
4213 		ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index,
4214 				urb->stream_id, trbs_per_td, urb, i, mem_flags);
4215 		if (ret < 0) {
4216 			if (i == 0)
4217 				return ret;
4218 			goto cleanup;
4219 		}
4220 		td = &urb_priv->td[i];
4221 		td->num_trbs = trbs_per_td;
4222 		/* use SIA as default, if frame id is used overwrite it */
4223 		sia_frame_id = TRB_SIA;
4224 		if (!(urb->transfer_flags & URB_ISO_ASAP) &&
4225 		    HCC_CFC(xhci->hcc_params)) {
4226 			frame_id = xhci_get_isoc_frame_id(xhci, urb, i);
4227 			if (frame_id >= 0)
4228 				sia_frame_id = TRB_FRAME_ID(frame_id);
4229 		}
4230 		/*
4231 		 * Set isoc specific data for the first TRB in a TD.
4232 		 * Prevent HW from getting the TRBs by keeping the cycle state
4233 		 * inverted in the first TDs isoc TRB.
4234 		 */
4235 		field = TRB_TYPE(TRB_ISOC) |
4236 			TRB_TLBPC(last_burst_pkt_count) |
4237 			sia_frame_id |
4238 			(i ? ep_ring->cycle_state : !start_cycle);
4239 
4240 		/* xhci 1.1 with ETE uses TD_Size field for TBC, old is Rsvdz */
4241 		if (!xep->use_extended_tbc)
4242 			field |= TRB_TBC(burst_count);
4243 
4244 		/* fill the rest of the TRB fields, and remaining normal TRBs */
4245 		for (j = 0; j < trbs_per_td; j++) {
4246 			u32 remainder = 0;
4247 
4248 			/* only first TRB is isoc, overwrite otherwise */
4249 			if (!first_trb)
4250 				field = TRB_TYPE(TRB_NORMAL) |
4251 					ep_ring->cycle_state;
4252 
4253 			/* Only set interrupt on short packet for IN EPs */
4254 			if (usb_urb_dir_in(urb))
4255 				field |= TRB_ISP;
4256 
4257 			/* Set the chain bit for all except the last TRB  */
4258 			if (j < trbs_per_td - 1) {
4259 				more_trbs_coming = true;
4260 				field |= TRB_CHAIN;
4261 			} else {
4262 				more_trbs_coming = false;
4263 				td->last_trb = ep_ring->enqueue;
4264 				td->last_trb_seg = ep_ring->enq_seg;
4265 				field |= TRB_IOC;
4266 				if (trb_block_event_intr(xhci, num_tds, i))
4267 					field |= TRB_BEI;
4268 			}
4269 			/* Calculate TRB length */
4270 			trb_buff_len = TRB_BUFF_LEN_UP_TO_BOUNDARY(addr);
4271 			if (trb_buff_len > td_remain_len)
4272 				trb_buff_len = td_remain_len;
4273 
4274 			/* Set the TRB length, TD size, & interrupter fields. */
4275 			remainder = xhci_td_remainder(xhci, running_total,
4276 						   trb_buff_len, td_len,
4277 						   urb, more_trbs_coming);
4278 
4279 			length_field = TRB_LEN(trb_buff_len) |
4280 				TRB_INTR_TARGET(0);
4281 
4282 			/* xhci 1.1 with ETE uses TD Size field for TBC */
4283 			if (first_trb && xep->use_extended_tbc)
4284 				length_field |= TRB_TD_SIZE_TBC(burst_count);
4285 			else
4286 				length_field |= TRB_TD_SIZE(remainder);
4287 			first_trb = false;
4288 
4289 			queue_trb(xhci, ep_ring, more_trbs_coming,
4290 				lower_32_bits(addr),
4291 				upper_32_bits(addr),
4292 				length_field,
4293 				field);
4294 			running_total += trb_buff_len;
4295 
4296 			addr += trb_buff_len;
4297 			td_remain_len -= trb_buff_len;
4298 		}
4299 
4300 		/* Check TD length */
4301 		if (running_total != td_len) {
4302 			xhci_err(xhci, "ISOC TD length unmatch\n");
4303 			ret = -EINVAL;
4304 			goto cleanup;
4305 		}
4306 	}
4307 
4308 	/* store the next frame id */
4309 	if (HCC_CFC(xhci->hcc_params))
4310 		xep->next_frame_id = urb->start_frame + num_tds * urb->interval;
4311 
4312 	if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) {
4313 		if (xhci->quirks & XHCI_AMD_PLL_FIX)
4314 			usb_amd_quirk_pll_disable();
4315 	}
4316 	xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs++;
4317 
4318 	giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
4319 			start_cycle, start_trb);
4320 	return 0;
4321 cleanup:
4322 	/* Clean up a partially enqueued isoc transfer. */
4323 
4324 	for (i--; i >= 0; i--)
4325 		list_del_init(&urb_priv->td[i].td_list);
4326 
4327 	/* Use the first TD as a temporary variable to turn the TDs we've queued
4328 	 * into No-ops with a software-owned cycle bit. That way the hardware
4329 	 * won't accidentally start executing bogus TDs when we partially
4330 	 * overwrite them.  td->first_trb and td->start_seg are already set.
4331 	 */
4332 	urb_priv->td[0].last_trb = ep_ring->enqueue;
4333 	/* Every TRB except the first & last will have its cycle bit flipped. */
4334 	td_to_noop(xhci, ep_ring, &urb_priv->td[0], true);
4335 
4336 	/* Reset the ring enqueue back to the first TRB and its cycle bit. */
4337 	ep_ring->enqueue = urb_priv->td[0].first_trb;
4338 	ep_ring->enq_seg = urb_priv->td[0].start_seg;
4339 	ep_ring->cycle_state = start_cycle;
4340 	usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb);
4341 	return ret;
4342 }
4343 
4344 /*
4345  * Check transfer ring to guarantee there is enough room for the urb.
4346  * Update ISO URB start_frame and interval.
4347  * Update interval as xhci_queue_intr_tx does. Use xhci frame_index to
4348  * update urb->start_frame if URB_ISO_ASAP is set in transfer_flags or
4349  * Contiguous Frame ID is not supported by HC.
4350  */
xhci_queue_isoc_tx_prepare(struct xhci_hcd * xhci,gfp_t mem_flags,struct urb * urb,int slot_id,unsigned int ep_index)4351 int xhci_queue_isoc_tx_prepare(struct xhci_hcd *xhci, gfp_t mem_flags,
4352 		struct urb *urb, int slot_id, unsigned int ep_index)
4353 {
4354 	struct xhci_virt_device *xdev;
4355 	struct xhci_ring *ep_ring;
4356 	struct xhci_ep_ctx *ep_ctx;
4357 	int start_frame;
4358 	int num_tds, num_trbs, i;
4359 	int ret;
4360 	struct xhci_virt_ep *xep;
4361 	int ist;
4362 
4363 	xdev = xhci->devs[slot_id];
4364 	xep = &xhci->devs[slot_id]->eps[ep_index];
4365 	ep_ring = xdev->eps[ep_index].ring;
4366 	ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
4367 
4368 	num_trbs = 0;
4369 	num_tds = urb->number_of_packets;
4370 	for (i = 0; i < num_tds; i++)
4371 		num_trbs += count_isoc_trbs_needed(urb, i);
4372 
4373 	/* Check the ring to guarantee there is enough room for the whole urb.
4374 	 * Do not insert any td of the urb to the ring if the check failed.
4375 	 */
4376 	ret = prepare_ring(xhci, ep_ring, GET_EP_CTX_STATE(ep_ctx),
4377 			   num_trbs, mem_flags);
4378 	if (ret)
4379 		return ret;
4380 
4381 	/*
4382 	 * Check interval value. This should be done before we start to
4383 	 * calculate the start frame value.
4384 	 */
4385 	check_interval(xhci, urb, ep_ctx);
4386 
4387 	/* Calculate the start frame and put it in urb->start_frame. */
4388 	if (HCC_CFC(xhci->hcc_params) && !list_empty(&ep_ring->td_list)) {
4389 		if (GET_EP_CTX_STATE(ep_ctx) ==	EP_STATE_RUNNING) {
4390 			urb->start_frame = xep->next_frame_id;
4391 			goto skip_start_over;
4392 		}
4393 	}
4394 
4395 	start_frame = readl(&xhci->run_regs->microframe_index);
4396 	start_frame &= 0x3fff;
4397 	/*
4398 	 * Round up to the next frame and consider the time before trb really
4399 	 * gets scheduled by hardare.
4400 	 */
4401 	ist = HCS_IST(xhci->hcs_params2) & 0x7;
4402 	if (HCS_IST(xhci->hcs_params2) & (1 << 3))
4403 		ist <<= 3;
4404 	start_frame += ist + XHCI_CFC_DELAY;
4405 	start_frame = roundup(start_frame, 8);
4406 
4407 	/*
4408 	 * Round up to the next ESIT (Endpoint Service Interval Time) if ESIT
4409 	 * is greate than 8 microframes.
4410 	 */
4411 	if (urb->dev->speed == USB_SPEED_LOW ||
4412 			urb->dev->speed == USB_SPEED_FULL) {
4413 		start_frame = roundup(start_frame, urb->interval << 3);
4414 		urb->start_frame = start_frame >> 3;
4415 	} else {
4416 		start_frame = roundup(start_frame, urb->interval);
4417 		urb->start_frame = start_frame;
4418 	}
4419 
4420 skip_start_over:
4421 
4422 	return xhci_queue_isoc_tx(xhci, mem_flags, urb, slot_id, ep_index);
4423 }
4424 
4425 /****		Command Ring Operations		****/
4426 
4427 /* Generic function for queueing a command TRB on the command ring.
4428  * Check to make sure there's room on the command ring for one command TRB.
4429  * Also check that there's room reserved for commands that must not fail.
4430  * If this is a command that must not fail, meaning command_must_succeed = TRUE,
4431  * then only check for the number of reserved spots.
4432  * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB
4433  * because the command event handler may want to resubmit a failed command.
4434  */
queue_command(struct xhci_hcd * xhci,struct xhci_command * cmd,u32 field1,u32 field2,u32 field3,u32 field4,bool command_must_succeed)4435 static int queue_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
4436 			 u32 field1, u32 field2,
4437 			 u32 field3, u32 field4, bool command_must_succeed)
4438 {
4439 	int reserved_trbs = xhci->cmd_ring_reserved_trbs;
4440 	int ret;
4441 
4442 	if ((xhci->xhc_state & XHCI_STATE_DYING) ||
4443 		(xhci->xhc_state & XHCI_STATE_HALTED)) {
4444 		xhci_dbg(xhci, "xHCI dying or halted, can't queue_command\n");
4445 		return -ESHUTDOWN;
4446 	}
4447 
4448 	if (!command_must_succeed)
4449 		reserved_trbs++;
4450 
4451 	ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING,
4452 			reserved_trbs, GFP_ATOMIC);
4453 	if (ret < 0) {
4454 		xhci_err(xhci, "ERR: No room for command on command ring\n");
4455 		if (command_must_succeed)
4456 			xhci_err(xhci, "ERR: Reserved TRB counting for "
4457 					"unfailable commands failed.\n");
4458 		return ret;
4459 	}
4460 
4461 	cmd->command_trb = xhci->cmd_ring->enqueue;
4462 
4463 	/* if there are no other commands queued we start the timeout timer */
4464 	if (list_empty(&xhci->cmd_list)) {
4465 		xhci->current_cmd = cmd;
4466 		xhci_mod_cmd_timer(xhci);
4467 	}
4468 
4469 	list_add_tail(&cmd->cmd_list, &xhci->cmd_list);
4470 
4471 	queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3,
4472 			field4 | xhci->cmd_ring->cycle_state);
4473 	return 0;
4474 }
4475 
4476 /* 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)4477 int xhci_queue_slot_control(struct xhci_hcd *xhci, struct xhci_command *cmd,
4478 		u32 trb_type, u32 slot_id)
4479 {
4480 	return queue_command(xhci, cmd, 0, 0, 0,
4481 			TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false);
4482 }
4483 
4484 /* 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)4485 int xhci_queue_address_device(struct xhci_hcd *xhci, struct xhci_command *cmd,
4486 		dma_addr_t in_ctx_ptr, u32 slot_id, enum xhci_setup_dev setup)
4487 {
4488 	return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4489 			upper_32_bits(in_ctx_ptr), 0,
4490 			TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id)
4491 			| (setup == SETUP_CONTEXT_ONLY ? TRB_BSR : 0), false);
4492 }
4493 
xhci_queue_vendor_command(struct xhci_hcd * xhci,struct xhci_command * cmd,u32 field1,u32 field2,u32 field3,u32 field4)4494 int xhci_queue_vendor_command(struct xhci_hcd *xhci, struct xhci_command *cmd,
4495 		u32 field1, u32 field2, u32 field3, u32 field4)
4496 {
4497 	return queue_command(xhci, cmd, field1, field2, field3, field4, false);
4498 }
4499 
4500 /* Queue a reset device command TRB */
xhci_queue_reset_device(struct xhci_hcd * xhci,struct xhci_command * cmd,u32 slot_id)4501 int xhci_queue_reset_device(struct xhci_hcd *xhci, struct xhci_command *cmd,
4502 		u32 slot_id)
4503 {
4504 	return queue_command(xhci, cmd, 0, 0, 0,
4505 			TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id),
4506 			false);
4507 }
4508 
4509 /* 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)4510 int xhci_queue_configure_endpoint(struct xhci_hcd *xhci,
4511 		struct xhci_command *cmd, dma_addr_t in_ctx_ptr,
4512 		u32 slot_id, bool command_must_succeed)
4513 {
4514 	return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4515 			upper_32_bits(in_ctx_ptr), 0,
4516 			TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id),
4517 			command_must_succeed);
4518 }
4519 
4520 /* 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)4521 int xhci_queue_evaluate_context(struct xhci_hcd *xhci, struct xhci_command *cmd,
4522 		dma_addr_t in_ctx_ptr, u32 slot_id, bool command_must_succeed)
4523 {
4524 	return queue_command(xhci, cmd, lower_32_bits(in_ctx_ptr),
4525 			upper_32_bits(in_ctx_ptr), 0,
4526 			TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id),
4527 			command_must_succeed);
4528 }
4529 
4530 /*
4531  * Suspend is set to indicate "Stop Endpoint Command" is being issued to stop
4532  * activity on an endpoint that is about to be suspended.
4533  */
xhci_queue_stop_endpoint(struct xhci_hcd * xhci,struct xhci_command * cmd,int slot_id,unsigned int ep_index,int suspend)4534 int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, struct xhci_command *cmd,
4535 			     int slot_id, unsigned int ep_index, int suspend)
4536 {
4537 	u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
4538 	u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
4539 	u32 type = TRB_TYPE(TRB_STOP_RING);
4540 	u32 trb_suspend = SUSPEND_PORT_FOR_TRB(suspend);
4541 
4542 	return queue_command(xhci, cmd, 0, 0, 0,
4543 			trb_slot_id | trb_ep_index | type | trb_suspend, false);
4544 }
4545 
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)4546 int xhci_queue_reset_ep(struct xhci_hcd *xhci, struct xhci_command *cmd,
4547 			int slot_id, unsigned int ep_index,
4548 			enum xhci_ep_reset_type reset_type)
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_RESET_EP);
4553 
4554 	if (reset_type == EP_SOFT_RESET)
4555 		type |= TRB_TSP;
4556 
4557 	return queue_command(xhci, cmd, 0, 0, 0,
4558 			trb_slot_id | trb_ep_index | type, false);
4559 }
4560