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