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