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