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