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