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