USB: xhci: Performance - move functions that find ep ring.
[linux-flexiantxendom0-natty.git] / drivers / usb / host / xhci.c
1 /*
2  * xHCI host controller driver
3  *
4  * Copyright (C) 2008 Intel Corp.
5  *
6  * Author: Sarah Sharp
7  * Some code borrowed from the Linux EHCI driver.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16  * for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22
23 #include <linux/pci.h>
24 #include <linux/irq.h>
25 #include <linux/log2.h>
26 #include <linux/module.h>
27 #include <linux/moduleparam.h>
28 #include <linux/slab.h>
29
30 #include "xhci.h"
31
32 #define DRIVER_AUTHOR "Sarah Sharp"
33 #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
34
35 /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
36 static int link_quirk;
37 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
38 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
39
40 /* TODO: copied from ehci-hcd.c - can this be refactored? */
41 /*
42  * handshake - spin reading hc until handshake completes or fails
43  * @ptr: address of hc register to be read
44  * @mask: bits to look at in result of read
45  * @done: value of those bits when handshake succeeds
46  * @usec: timeout in microseconds
47  *
48  * Returns negative errno, or zero on success
49  *
50  * Success happens when the "mask" bits have the specified value (hardware
51  * handshake done).  There are two failure modes:  "usec" have passed (major
52  * hardware flakeout), or the register reads as all-ones (hardware removed).
53  */
54 static int handshake(struct xhci_hcd *xhci, void __iomem *ptr,
55                       u32 mask, u32 done, int usec)
56 {
57         u32     result;
58
59         do {
60                 result = xhci_readl(xhci, ptr);
61                 if (result == ~(u32)0)          /* card removed */
62                         return -ENODEV;
63                 result &= mask;
64                 if (result == done)
65                         return 0;
66                 udelay(1);
67                 usec--;
68         } while (usec > 0);
69         return -ETIMEDOUT;
70 }
71
72 /*
73  * Disable interrupts and begin the xHCI halting process.
74  */
75 void xhci_quiesce(struct xhci_hcd *xhci)
76 {
77         u32 halted;
78         u32 cmd;
79         u32 mask;
80
81         mask = ~(XHCI_IRQS);
82         halted = xhci_readl(xhci, &xhci->op_regs->status) & STS_HALT;
83         if (!halted)
84                 mask &= ~CMD_RUN;
85
86         cmd = xhci_readl(xhci, &xhci->op_regs->command);
87         cmd &= mask;
88         xhci_writel(xhci, cmd, &xhci->op_regs->command);
89 }
90
91 /*
92  * Force HC into halt state.
93  *
94  * Disable any IRQs and clear the run/stop bit.
95  * HC will complete any current and actively pipelined transactions, and
96  * should halt within 16 microframes of the run/stop bit being cleared.
97  * Read HC Halted bit in the status register to see when the HC is finished.
98  * XXX: shouldn't we set HC_STATE_HALT here somewhere?
99  */
100 int xhci_halt(struct xhci_hcd *xhci)
101 {
102         xhci_dbg(xhci, "// Halt the HC\n");
103         xhci_quiesce(xhci);
104
105         return handshake(xhci, &xhci->op_regs->status,
106                         STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
107 }
108
109 /*
110  * Set the run bit and wait for the host to be running.
111  */
112 int xhci_start(struct xhci_hcd *xhci)
113 {
114         u32 temp;
115         int ret;
116
117         temp = xhci_readl(xhci, &xhci->op_regs->command);
118         temp |= (CMD_RUN);
119         xhci_dbg(xhci, "// Turn on HC, cmd = 0x%x.\n",
120                         temp);
121         xhci_writel(xhci, temp, &xhci->op_regs->command);
122
123         /*
124          * Wait for the HCHalted Status bit to be 0 to indicate the host is
125          * running.
126          */
127         ret = handshake(xhci, &xhci->op_regs->status,
128                         STS_HALT, 0, XHCI_MAX_HALT_USEC);
129         if (ret == -ETIMEDOUT)
130                 xhci_err(xhci, "Host took too long to start, "
131                                 "waited %u microseconds.\n",
132                                 XHCI_MAX_HALT_USEC);
133         return ret;
134 }
135
136 /*
137  * Reset a halted HC, and set the internal HC state to HC_STATE_HALT.
138  *
139  * This resets pipelines, timers, counters, state machines, etc.
140  * Transactions will be terminated immediately, and operational registers
141  * will be set to their defaults.
142  */
143 int xhci_reset(struct xhci_hcd *xhci)
144 {
145         u32 command;
146         u32 state;
147         int ret;
148
149         state = xhci_readl(xhci, &xhci->op_regs->status);
150         if ((state & STS_HALT) == 0) {
151                 xhci_warn(xhci, "Host controller not halted, aborting reset.\n");
152                 return 0;
153         }
154
155         xhci_dbg(xhci, "// Reset the HC\n");
156         command = xhci_readl(xhci, &xhci->op_regs->command);
157         command |= CMD_RESET;
158         xhci_writel(xhci, command, &xhci->op_regs->command);
159         /* XXX: Why does EHCI set this here?  Shouldn't other code do this? */
160         xhci_to_hcd(xhci)->state = HC_STATE_HALT;
161
162         ret = handshake(xhci, &xhci->op_regs->command,
163                         CMD_RESET, 0, 250 * 1000);
164         if (ret)
165                 return ret;
166
167         xhci_dbg(xhci, "Wait for controller to be ready for doorbell rings\n");
168         /*
169          * xHCI cannot write to any doorbells or operational registers other
170          * than status until the "Controller Not Ready" flag is cleared.
171          */
172         return handshake(xhci, &xhci->op_regs->status, STS_CNR, 0, 250 * 1000);
173 }
174
175 static irqreturn_t xhci_msi_irq(int irq, struct usb_hcd *hcd)
176 {
177         irqreturn_t ret;
178
179         set_bit(HCD_FLAG_SAW_IRQ, &hcd->flags);
180
181         ret = xhci_irq(hcd);
182
183         return ret;
184 }
185
186 /*
187  * Free IRQs
188  * free all IRQs request
189  */
190 static void xhci_free_irq(struct xhci_hcd *xhci)
191 {
192         int i;
193         struct pci_dev *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
194
195         /* return if using legacy interrupt */
196         if (xhci_to_hcd(xhci)->irq >= 0)
197                 return;
198
199         if (xhci->msix_entries) {
200                 for (i = 0; i < xhci->msix_count; i++)
201                         if (xhci->msix_entries[i].vector)
202                                 free_irq(xhci->msix_entries[i].vector,
203                                                 xhci_to_hcd(xhci));
204         } else if (pdev->irq >= 0)
205                 free_irq(pdev->irq, xhci_to_hcd(xhci));
206
207         return;
208 }
209
210 /*
211  * Set up MSI
212  */
213 static int xhci_setup_msi(struct xhci_hcd *xhci)
214 {
215         int ret;
216         struct pci_dev  *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
217
218         ret = pci_enable_msi(pdev);
219         if (ret) {
220                 xhci_err(xhci, "failed to allocate MSI entry\n");
221                 return ret;
222         }
223
224         ret = request_irq(pdev->irq, (irq_handler_t)xhci_msi_irq,
225                                 0, "xhci_hcd", xhci_to_hcd(xhci));
226         if (ret) {
227                 xhci_err(xhci, "disable MSI interrupt\n");
228                 pci_disable_msi(pdev);
229         }
230
231         return ret;
232 }
233
234 /*
235  * Set up MSI-X
236  */
237 static int xhci_setup_msix(struct xhci_hcd *xhci)
238 {
239         int i, ret = 0;
240         struct pci_dev *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
241
242         /*
243          * calculate number of msi-x vectors supported.
244          * - HCS_MAX_INTRS: the max number of interrupts the host can handle,
245          *   with max number of interrupters based on the xhci HCSPARAMS1.
246          * - num_online_cpus: maximum msi-x vectors per CPUs core.
247          *   Add additional 1 vector to ensure always available interrupt.
248          */
249         xhci->msix_count = min(num_online_cpus() + 1,
250                                 HCS_MAX_INTRS(xhci->hcs_params1));
251
252         xhci->msix_entries =
253                 kmalloc((sizeof(struct msix_entry))*xhci->msix_count,
254                                 GFP_KERNEL);
255         if (!xhci->msix_entries) {
256                 xhci_err(xhci, "Failed to allocate MSI-X entries\n");
257                 return -ENOMEM;
258         }
259
260         for (i = 0; i < xhci->msix_count; i++) {
261                 xhci->msix_entries[i].entry = i;
262                 xhci->msix_entries[i].vector = 0;
263         }
264
265         ret = pci_enable_msix(pdev, xhci->msix_entries, xhci->msix_count);
266         if (ret) {
267                 xhci_err(xhci, "Failed to enable MSI-X\n");
268                 goto free_entries;
269         }
270
271         for (i = 0; i < xhci->msix_count; i++) {
272                 ret = request_irq(xhci->msix_entries[i].vector,
273                                 (irq_handler_t)xhci_msi_irq,
274                                 0, "xhci_hcd", xhci_to_hcd(xhci));
275                 if (ret)
276                         goto disable_msix;
277         }
278
279         return ret;
280
281 disable_msix:
282         xhci_err(xhci, "disable MSI-X interrupt\n");
283         xhci_free_irq(xhci);
284         pci_disable_msix(pdev);
285 free_entries:
286         kfree(xhci->msix_entries);
287         xhci->msix_entries = NULL;
288         return ret;
289 }
290
291 /* Free any IRQs and disable MSI-X */
292 static void xhci_cleanup_msix(struct xhci_hcd *xhci)
293 {
294         struct pci_dev *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
295
296         xhci_free_irq(xhci);
297
298         if (xhci->msix_entries) {
299                 pci_disable_msix(pdev);
300                 kfree(xhci->msix_entries);
301                 xhci->msix_entries = NULL;
302         } else {
303                 pci_disable_msi(pdev);
304         }
305
306         return;
307 }
308
309 /*
310  * Initialize memory for HCD and xHC (one-time init).
311  *
312  * Program the PAGESIZE register, initialize the device context array, create
313  * device contexts (?), set up a command ring segment (or two?), create event
314  * ring (one for now).
315  */
316 int xhci_init(struct usb_hcd *hcd)
317 {
318         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
319         int retval = 0;
320
321         xhci_dbg(xhci, "xhci_init\n");
322         spin_lock_init(&xhci->lock);
323         if (link_quirk) {
324                 xhci_dbg(xhci, "QUIRK: Not clearing Link TRB chain bits.\n");
325                 xhci->quirks |= XHCI_LINK_TRB_QUIRK;
326         } else {
327                 xhci_dbg(xhci, "xHCI doesn't need link TRB QUIRK\n");
328         }
329         retval = xhci_mem_init(xhci, GFP_KERNEL);
330         xhci_dbg(xhci, "Finished xhci_init\n");
331
332         return retval;
333 }
334
335 /*
336  * Called in interrupt context when there might be work
337  * queued on the event ring
338  *
339  * xhci->lock must be held by caller.
340  */
341 static void xhci_work(struct xhci_hcd *xhci)
342 {
343         u32 temp;
344         u64 temp_64;
345
346         /*
347          * Clear the op reg interrupt status first,
348          * so we can receive interrupts from other MSI-X interrupters.
349          * Write 1 to clear the interrupt status.
350          */
351         temp = xhci_readl(xhci, &xhci->op_regs->status);
352         temp |= STS_EINT;
353         xhci_writel(xhci, temp, &xhci->op_regs->status);
354         /* FIXME when MSI-X is supported and there are multiple vectors */
355         /* Clear the MSI-X event interrupt status */
356
357         /* Acknowledge the interrupt */
358         temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
359         temp |= 0x3;
360         xhci_writel(xhci, temp, &xhci->ir_set->irq_pending);
361         /* Flush posted writes */
362         xhci_readl(xhci, &xhci->ir_set->irq_pending);
363
364         if (xhci->xhc_state & XHCI_STATE_DYING)
365                 xhci_dbg(xhci, "xHCI dying, ignoring interrupt. "
366                                 "Shouldn't IRQs be disabled?\n");
367         else
368                 /* FIXME this should be a delayed service routine
369                  * that clears the EHB.
370                  */
371                 xhci_handle_event(xhci);
372
373         /* Clear the event handler busy flag (RW1C); the event ring should be empty. */
374         temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
375         xhci_write_64(xhci, temp_64 | ERST_EHB, &xhci->ir_set->erst_dequeue);
376         /* Flush posted writes -- FIXME is this necessary? */
377         xhci_readl(xhci, &xhci->ir_set->irq_pending);
378 }
379
380 /*-------------------------------------------------------------------------*/
381
382 /*
383  * xHCI spec says we can get an interrupt, and if the HC has an error condition,
384  * we might get bad data out of the event ring.  Section 4.10.2.7 has a list of
385  * indicators of an event TRB error, but we check the status *first* to be safe.
386  */
387 irqreturn_t xhci_irq(struct usb_hcd *hcd)
388 {
389         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
390         u32 temp, temp2;
391         union xhci_trb *trb;
392
393         spin_lock(&xhci->lock);
394         trb = xhci->event_ring->dequeue;
395         /* Check if the xHC generated the interrupt, or the irq is shared */
396         temp = xhci_readl(xhci, &xhci->op_regs->status);
397         temp2 = xhci_readl(xhci, &xhci->ir_set->irq_pending);
398         if (temp == 0xffffffff && temp2 == 0xffffffff)
399                 goto hw_died;
400
401         if (!(temp & STS_EINT) && !ER_IRQ_PENDING(temp2)) {
402                 spin_unlock(&xhci->lock);
403                 return IRQ_NONE;
404         }
405         xhci_dbg(xhci, "op reg status = %08x\n", temp);
406         xhci_dbg(xhci, "ir set irq_pending = %08x\n", temp2);
407         xhci_dbg(xhci, "Event ring dequeue ptr:\n");
408         xhci_dbg(xhci, "@%llx %08x %08x %08x %08x\n",
409                         (unsigned long long)xhci_trb_virt_to_dma(xhci->event_ring->deq_seg, trb),
410                         lower_32_bits(trb->link.segment_ptr),
411                         upper_32_bits(trb->link.segment_ptr),
412                         (unsigned int) trb->link.intr_target,
413                         (unsigned int) trb->link.control);
414
415         if (temp & STS_FATAL) {
416                 xhci_warn(xhci, "WARNING: Host System Error\n");
417                 xhci_halt(xhci);
418 hw_died:
419                 xhci_to_hcd(xhci)->state = HC_STATE_HALT;
420                 spin_unlock(&xhci->lock);
421                 return -ESHUTDOWN;
422         }
423
424         xhci_work(xhci);
425         spin_unlock(&xhci->lock);
426
427         return IRQ_HANDLED;
428 }
429
430 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
431 void xhci_event_ring_work(unsigned long arg)
432 {
433         unsigned long flags;
434         int temp;
435         u64 temp_64;
436         struct xhci_hcd *xhci = (struct xhci_hcd *) arg;
437         int i, j;
438
439         xhci_dbg(xhci, "Poll event ring: %lu\n", jiffies);
440
441         spin_lock_irqsave(&xhci->lock, flags);
442         temp = xhci_readl(xhci, &xhci->op_regs->status);
443         xhci_dbg(xhci, "op reg status = 0x%x\n", temp);
444         if (temp == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING)) {
445                 xhci_dbg(xhci, "HW died, polling stopped.\n");
446                 spin_unlock_irqrestore(&xhci->lock, flags);
447                 return;
448         }
449
450         temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
451         xhci_dbg(xhci, "ir_set 0 pending = 0x%x\n", temp);
452         xhci_dbg(xhci, "No-op commands handled = %d\n", xhci->noops_handled);
453         xhci_dbg(xhci, "HC error bitmask = 0x%x\n", xhci->error_bitmask);
454         xhci->error_bitmask = 0;
455         xhci_dbg(xhci, "Event ring:\n");
456         xhci_debug_segment(xhci, xhci->event_ring->deq_seg);
457         xhci_dbg_ring_ptrs(xhci, xhci->event_ring);
458         temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
459         temp_64 &= ~ERST_PTR_MASK;
460         xhci_dbg(xhci, "ERST deq = 64'h%0lx\n", (long unsigned int) temp_64);
461         xhci_dbg(xhci, "Command ring:\n");
462         xhci_debug_segment(xhci, xhci->cmd_ring->deq_seg);
463         xhci_dbg_ring_ptrs(xhci, xhci->cmd_ring);
464         xhci_dbg_cmd_ptrs(xhci);
465         for (i = 0; i < MAX_HC_SLOTS; ++i) {
466                 if (!xhci->devs[i])
467                         continue;
468                 for (j = 0; j < 31; ++j) {
469                         xhci_dbg_ep_rings(xhci, i, j, &xhci->devs[i]->eps[j]);
470                 }
471         }
472
473         if (xhci->noops_submitted != NUM_TEST_NOOPS)
474                 if (xhci_setup_one_noop(xhci))
475                         xhci_ring_cmd_db(xhci);
476         spin_unlock_irqrestore(&xhci->lock, flags);
477
478         if (!xhci->zombie)
479                 mod_timer(&xhci->event_ring_timer, jiffies + POLL_TIMEOUT * HZ);
480         else
481                 xhci_dbg(xhci, "Quit polling the event ring.\n");
482 }
483 #endif
484
485 /*
486  * Start the HC after it was halted.
487  *
488  * This function is called by the USB core when the HC driver is added.
489  * Its opposite is xhci_stop().
490  *
491  * xhci_init() must be called once before this function can be called.
492  * Reset the HC, enable device slot contexts, program DCBAAP, and
493  * set command ring pointer and event ring pointer.
494  *
495  * Setup MSI-X vectors and enable interrupts.
496  */
497 int xhci_run(struct usb_hcd *hcd)
498 {
499         u32 temp;
500         u64 temp_64;
501         u32 ret;
502         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
503         struct pci_dev  *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
504         void (*doorbell)(struct xhci_hcd *) = NULL;
505
506         hcd->uses_new_polling = 1;
507
508         xhci_dbg(xhci, "xhci_run\n");
509         /* unregister the legacy interrupt */
510         if (hcd->irq)
511                 free_irq(hcd->irq, hcd);
512         hcd->irq = -1;
513
514         ret = xhci_setup_msix(xhci);
515         if (ret)
516                 /* fall back to msi*/
517                 ret = xhci_setup_msi(xhci);
518
519         if (ret) {
520                 /* fall back to legacy interrupt*/
521                 ret = request_irq(pdev->irq, &usb_hcd_irq, IRQF_SHARED,
522                                         hcd->irq_descr, hcd);
523                 if (ret) {
524                         xhci_err(xhci, "request interrupt %d failed\n",
525                                         pdev->irq);
526                         return ret;
527                 }
528                 hcd->irq = pdev->irq;
529         }
530
531 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
532         init_timer(&xhci->event_ring_timer);
533         xhci->event_ring_timer.data = (unsigned long) xhci;
534         xhci->event_ring_timer.function = xhci_event_ring_work;
535         /* Poll the event ring */
536         xhci->event_ring_timer.expires = jiffies + POLL_TIMEOUT * HZ;
537         xhci->zombie = 0;
538         xhci_dbg(xhci, "Setting event ring polling timer\n");
539         add_timer(&xhci->event_ring_timer);
540 #endif
541
542         xhci_dbg(xhci, "Command ring memory map follows:\n");
543         xhci_debug_ring(xhci, xhci->cmd_ring);
544         xhci_dbg_ring_ptrs(xhci, xhci->cmd_ring);
545         xhci_dbg_cmd_ptrs(xhci);
546
547         xhci_dbg(xhci, "ERST memory map follows:\n");
548         xhci_dbg_erst(xhci, &xhci->erst);
549         xhci_dbg(xhci, "Event ring:\n");
550         xhci_debug_ring(xhci, xhci->event_ring);
551         xhci_dbg_ring_ptrs(xhci, xhci->event_ring);
552         temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
553         temp_64 &= ~ERST_PTR_MASK;
554         xhci_dbg(xhci, "ERST deq = 64'h%0lx\n", (long unsigned int) temp_64);
555
556         xhci_dbg(xhci, "// Set the interrupt modulation register\n");
557         temp = xhci_readl(xhci, &xhci->ir_set->irq_control);
558         temp &= ~ER_IRQ_INTERVAL_MASK;
559         temp |= (u32) 160;
560         xhci_writel(xhci, temp, &xhci->ir_set->irq_control);
561
562         /* Set the HCD state before we enable the irqs */
563         hcd->state = HC_STATE_RUNNING;
564         temp = xhci_readl(xhci, &xhci->op_regs->command);
565         temp |= (CMD_EIE);
566         xhci_dbg(xhci, "// Enable interrupts, cmd = 0x%x.\n",
567                         temp);
568         xhci_writel(xhci, temp, &xhci->op_regs->command);
569
570         temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
571         xhci_dbg(xhci, "// Enabling event ring interrupter %p by writing 0x%x to irq_pending\n",
572                         xhci->ir_set, (unsigned int) ER_IRQ_ENABLE(temp));
573         xhci_writel(xhci, ER_IRQ_ENABLE(temp),
574                         &xhci->ir_set->irq_pending);
575         xhci_print_ir_set(xhci, xhci->ir_set, 0);
576
577         if (NUM_TEST_NOOPS > 0)
578                 doorbell = xhci_setup_one_noop(xhci);
579         if (xhci->quirks & XHCI_NEC_HOST)
580                 xhci_queue_vendor_command(xhci, 0, 0, 0,
581                                 TRB_TYPE(TRB_NEC_GET_FW));
582
583         if (xhci_start(xhci)) {
584                 xhci_halt(xhci);
585                 return -ENODEV;
586         }
587
588         if (doorbell)
589                 (*doorbell)(xhci);
590         if (xhci->quirks & XHCI_NEC_HOST)
591                 xhci_ring_cmd_db(xhci);
592
593         xhci_dbg(xhci, "Finished xhci_run\n");
594         return 0;
595 }
596
597 /*
598  * Stop xHCI driver.
599  *
600  * This function is called by the USB core when the HC driver is removed.
601  * Its opposite is xhci_run().
602  *
603  * Disable device contexts, disable IRQs, and quiesce the HC.
604  * Reset the HC, finish any completed transactions, and cleanup memory.
605  */
606 void xhci_stop(struct usb_hcd *hcd)
607 {
608         u32 temp;
609         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
610
611         spin_lock_irq(&xhci->lock);
612         xhci_halt(xhci);
613         xhci_reset(xhci);
614         xhci_cleanup_msix(xhci);
615         spin_unlock_irq(&xhci->lock);
616
617 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
618         /* Tell the event ring poll function not to reschedule */
619         xhci->zombie = 1;
620         del_timer_sync(&xhci->event_ring_timer);
621 #endif
622
623         xhci_dbg(xhci, "// Disabling event ring interrupts\n");
624         temp = xhci_readl(xhci, &xhci->op_regs->status);
625         xhci_writel(xhci, temp & ~STS_EINT, &xhci->op_regs->status);
626         temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
627         xhci_writel(xhci, ER_IRQ_DISABLE(temp),
628                         &xhci->ir_set->irq_pending);
629         xhci_print_ir_set(xhci, xhci->ir_set, 0);
630
631         xhci_dbg(xhci, "cleaning up memory\n");
632         xhci_mem_cleanup(xhci);
633         xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
634                     xhci_readl(xhci, &xhci->op_regs->status));
635 }
636
637 /*
638  * Shutdown HC (not bus-specific)
639  *
640  * This is called when the machine is rebooting or halting.  We assume that the
641  * machine will be powered off, and the HC's internal state will be reset.
642  * Don't bother to free memory.
643  */
644 void xhci_shutdown(struct usb_hcd *hcd)
645 {
646         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
647
648         spin_lock_irq(&xhci->lock);
649         xhci_halt(xhci);
650         xhci_cleanup_msix(xhci);
651         spin_unlock_irq(&xhci->lock);
652
653         xhci_dbg(xhci, "xhci_shutdown completed - status = %x\n",
654                     xhci_readl(xhci, &xhci->op_regs->status));
655 }
656
657 /*-------------------------------------------------------------------------*/
658
659 /**
660  * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
661  * HCDs.  Find the index for an endpoint given its descriptor.  Use the return
662  * value to right shift 1 for the bitmask.
663  *
664  * Index  = (epnum * 2) + direction - 1,
665  * where direction = 0 for OUT, 1 for IN.
666  * For control endpoints, the IN index is used (OUT index is unused), so
667  * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
668  */
669 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
670 {
671         unsigned int index;
672         if (usb_endpoint_xfer_control(desc))
673                 index = (unsigned int) (usb_endpoint_num(desc)*2);
674         else
675                 index = (unsigned int) (usb_endpoint_num(desc)*2) +
676                         (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
677         return index;
678 }
679
680 /* Find the flag for this endpoint (for use in the control context).  Use the
681  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
682  * bit 1, etc.
683  */
684 unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
685 {
686         return 1 << (xhci_get_endpoint_index(desc) + 1);
687 }
688
689 /* Find the flag for this endpoint (for use in the control context).  Use the
690  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
691  * bit 1, etc.
692  */
693 unsigned int xhci_get_endpoint_flag_from_index(unsigned int ep_index)
694 {
695         return 1 << (ep_index + 1);
696 }
697
698 /* Compute the last valid endpoint context index.  Basically, this is the
699  * endpoint index plus one.  For slot contexts with more than valid endpoint,
700  * we find the most significant bit set in the added contexts flags.
701  * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
702  * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
703  */
704 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
705 {
706         return fls(added_ctxs) - 1;
707 }
708
709 /* Returns 1 if the arguments are OK;
710  * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
711  */
712 int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
713                 struct usb_host_endpoint *ep, int check_ep, const char *func) {
714         if (!hcd || (check_ep && !ep) || !udev) {
715                 printk(KERN_DEBUG "xHCI %s called with invalid args\n",
716                                 func);
717                 return -EINVAL;
718         }
719         if (!udev->parent) {
720                 printk(KERN_DEBUG "xHCI %s called for root hub\n",
721                                 func);
722                 return 0;
723         }
724         if (!udev->slot_id) {
725                 printk(KERN_DEBUG "xHCI %s called with unaddressed device\n",
726                                 func);
727                 return -EINVAL;
728         }
729         return 1;
730 }
731
732 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
733                 struct usb_device *udev, struct xhci_command *command,
734                 bool ctx_change, bool must_succeed);
735
736 /*
737  * Full speed devices may have a max packet size greater than 8 bytes, but the
738  * USB core doesn't know that until it reads the first 8 bytes of the
739  * descriptor.  If the usb_device's max packet size changes after that point,
740  * we need to issue an evaluate context command and wait on it.
741  */
742 static int xhci_check_maxpacket(struct xhci_hcd *xhci, unsigned int slot_id,
743                 unsigned int ep_index, struct urb *urb)
744 {
745         struct xhci_container_ctx *in_ctx;
746         struct xhci_container_ctx *out_ctx;
747         struct xhci_input_control_ctx *ctrl_ctx;
748         struct xhci_ep_ctx *ep_ctx;
749         int max_packet_size;
750         int hw_max_packet_size;
751         int ret = 0;
752
753         out_ctx = xhci->devs[slot_id]->out_ctx;
754         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
755         hw_max_packet_size = MAX_PACKET_DECODED(ep_ctx->ep_info2);
756         max_packet_size = urb->dev->ep0.desc.wMaxPacketSize;
757         if (hw_max_packet_size != max_packet_size) {
758                 xhci_dbg(xhci, "Max Packet Size for ep 0 changed.\n");
759                 xhci_dbg(xhci, "Max packet size in usb_device = %d\n",
760                                 max_packet_size);
761                 xhci_dbg(xhci, "Max packet size in xHCI HW = %d\n",
762                                 hw_max_packet_size);
763                 xhci_dbg(xhci, "Issuing evaluate context command.\n");
764
765                 /* Set up the modified control endpoint 0 */
766                 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
767                                 xhci->devs[slot_id]->out_ctx, ep_index);
768                 in_ctx = xhci->devs[slot_id]->in_ctx;
769                 ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
770                 ep_ctx->ep_info2 &= ~MAX_PACKET_MASK;
771                 ep_ctx->ep_info2 |= MAX_PACKET(max_packet_size);
772
773                 /* Set up the input context flags for the command */
774                 /* FIXME: This won't work if a non-default control endpoint
775                  * changes max packet sizes.
776                  */
777                 ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
778                 ctrl_ctx->add_flags = EP0_FLAG;
779                 ctrl_ctx->drop_flags = 0;
780
781                 xhci_dbg(xhci, "Slot %d input context\n", slot_id);
782                 xhci_dbg_ctx(xhci, in_ctx, ep_index);
783                 xhci_dbg(xhci, "Slot %d output context\n", slot_id);
784                 xhci_dbg_ctx(xhci, out_ctx, ep_index);
785
786                 ret = xhci_configure_endpoint(xhci, urb->dev, NULL,
787                                 true, false);
788
789                 /* Clean up the input context for later use by bandwidth
790                  * functions.
791                  */
792                 ctrl_ctx->add_flags = SLOT_FLAG;
793         }
794         return ret;
795 }
796
797 /*
798  * non-error returns are a promise to giveback() the urb later
799  * we drop ownership so next owner (or urb unlink) can get it
800  */
801 int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
802 {
803         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
804         unsigned long flags;
805         int ret = 0;
806         unsigned int slot_id, ep_index;
807         struct urb_priv *urb_priv;
808         int size, i;
809
810         if (!urb || xhci_check_args(hcd, urb->dev, urb->ep, true, __func__) <= 0)
811                 return -EINVAL;
812
813         slot_id = urb->dev->slot_id;
814         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
815
816         if (!xhci->devs || !xhci->devs[slot_id]) {
817                 if (!in_interrupt())
818                         dev_warn(&urb->dev->dev, "WARN: urb submitted for dev with no Slot ID\n");
819                 ret = -EINVAL;
820                 goto exit;
821         }
822         if (!HCD_HW_ACCESSIBLE(hcd)) {
823                 if (!in_interrupt())
824                         xhci_dbg(xhci, "urb submitted during PCI suspend\n");
825                 ret = -ESHUTDOWN;
826                 goto exit;
827         }
828
829         if (usb_endpoint_xfer_isoc(&urb->ep->desc))
830                 size = urb->number_of_packets;
831         else
832                 size = 1;
833
834         urb_priv = kzalloc(sizeof(struct urb_priv) +
835                                   size * sizeof(struct xhci_td *), mem_flags);
836         if (!urb_priv)
837                 return -ENOMEM;
838
839         for (i = 0; i < size; i++) {
840                 urb_priv->td[i] = kzalloc(sizeof(struct xhci_td), mem_flags);
841                 if (!urb_priv->td[i]) {
842                         urb_priv->length = i;
843                         xhci_urb_free_priv(xhci, urb_priv);
844                         return -ENOMEM;
845                 }
846         }
847
848         urb_priv->length = size;
849         urb_priv->td_cnt = 0;
850         urb->hcpriv = urb_priv;
851
852         if (usb_endpoint_xfer_control(&urb->ep->desc)) {
853                 /* Check to see if the max packet size for the default control
854                  * endpoint changed during FS device enumeration
855                  */
856                 if (urb->dev->speed == USB_SPEED_FULL) {
857                         ret = xhci_check_maxpacket(xhci, slot_id,
858                                         ep_index, urb);
859                         if (ret < 0)
860                                 return ret;
861                 }
862
863                 /* We have a spinlock and interrupts disabled, so we must pass
864                  * atomic context to this function, which may allocate memory.
865                  */
866                 spin_lock_irqsave(&xhci->lock, flags);
867                 if (xhci->xhc_state & XHCI_STATE_DYING)
868                         goto dying;
869                 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
870                                 slot_id, ep_index);
871                 spin_unlock_irqrestore(&xhci->lock, flags);
872         } else if (usb_endpoint_xfer_bulk(&urb->ep->desc)) {
873                 spin_lock_irqsave(&xhci->lock, flags);
874                 if (xhci->xhc_state & XHCI_STATE_DYING)
875                         goto dying;
876                 if (xhci->devs[slot_id]->eps[ep_index].ep_state &
877                                 EP_GETTING_STREAMS) {
878                         xhci_warn(xhci, "WARN: Can't enqueue URB while bulk ep "
879                                         "is transitioning to using streams.\n");
880                         ret = -EINVAL;
881                 } else if (xhci->devs[slot_id]->eps[ep_index].ep_state &
882                                 EP_GETTING_NO_STREAMS) {
883                         xhci_warn(xhci, "WARN: Can't enqueue URB while bulk ep "
884                                         "is transitioning to "
885                                         "not having streams.\n");
886                         ret = -EINVAL;
887                 } else {
888                         ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
889                                         slot_id, ep_index);
890                 }
891                 spin_unlock_irqrestore(&xhci->lock, flags);
892         } else if (usb_endpoint_xfer_int(&urb->ep->desc)) {
893                 spin_lock_irqsave(&xhci->lock, flags);
894                 if (xhci->xhc_state & XHCI_STATE_DYING)
895                         goto dying;
896                 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
897                                 slot_id, ep_index);
898                 spin_unlock_irqrestore(&xhci->lock, flags);
899         } else {
900                 spin_lock_irqsave(&xhci->lock, flags);
901                 if (xhci->xhc_state & XHCI_STATE_DYING)
902                         goto dying;
903                 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
904                                 slot_id, ep_index);
905                 spin_unlock_irqrestore(&xhci->lock, flags);
906         }
907 exit:
908         return ret;
909 dying:
910         xhci_urb_free_priv(xhci, urb_priv);
911         urb->hcpriv = NULL;
912         xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for "
913                         "non-responsive xHCI host.\n",
914                         urb->ep->desc.bEndpointAddress, urb);
915         spin_unlock_irqrestore(&xhci->lock, flags);
916         return -ESHUTDOWN;
917 }
918
919 /* Get the right ring for the given URB.
920  * If the endpoint supports streams, boundary check the URB's stream ID.
921  * If the endpoint doesn't support streams, return the singular endpoint ring.
922  */
923 static struct xhci_ring *xhci_urb_to_transfer_ring(struct xhci_hcd *xhci,
924                 struct urb *urb)
925 {
926         unsigned int slot_id;
927         unsigned int ep_index;
928         unsigned int stream_id;
929         struct xhci_virt_ep *ep;
930
931         slot_id = urb->dev->slot_id;
932         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
933         stream_id = urb->stream_id;
934         ep = &xhci->devs[slot_id]->eps[ep_index];
935         /* Common case: no streams */
936         if (!(ep->ep_state & EP_HAS_STREAMS))
937                 return ep->ring;
938
939         if (stream_id == 0) {
940                 xhci_warn(xhci,
941                                 "WARN: Slot ID %u, ep index %u has streams, "
942                                 "but URB has no stream ID.\n",
943                                 slot_id, ep_index);
944                 return NULL;
945         }
946
947         if (stream_id < ep->stream_info->num_streams)
948                 return ep->stream_info->stream_rings[stream_id];
949
950         xhci_warn(xhci,
951                         "WARN: Slot ID %u, ep index %u has "
952                         "stream IDs 1 to %u allocated, "
953                         "but stream ID %u is requested.\n",
954                         slot_id, ep_index,
955                         ep->stream_info->num_streams - 1,
956                         stream_id);
957         return NULL;
958 }
959
960 /*
961  * Remove the URB's TD from the endpoint ring.  This may cause the HC to stop
962  * USB transfers, potentially stopping in the middle of a TRB buffer.  The HC
963  * should pick up where it left off in the TD, unless a Set Transfer Ring
964  * Dequeue Pointer is issued.
965  *
966  * The TRBs that make up the buffers for the canceled URB will be "removed" from
967  * the ring.  Since the ring is a contiguous structure, they can't be physically
968  * removed.  Instead, there are two options:
969  *
970  *  1) If the HC is in the middle of processing the URB to be canceled, we
971  *     simply move the ring's dequeue pointer past those TRBs using the Set
972  *     Transfer Ring Dequeue Pointer command.  This will be the common case,
973  *     when drivers timeout on the last submitted URB and attempt to cancel.
974  *
975  *  2) If the HC is in the middle of a different TD, we turn the TRBs into a
976  *     series of 1-TRB transfer no-op TDs.  (No-ops shouldn't be chained.)  The
977  *     HC will need to invalidate the any TRBs it has cached after the stop
978  *     endpoint command, as noted in the xHCI 0.95 errata.
979  *
980  *  3) The TD may have completed by the time the Stop Endpoint Command
981  *     completes, so software needs to handle that case too.
982  *
983  * This function should protect against the TD enqueueing code ringing the
984  * doorbell while this code is waiting for a Stop Endpoint command to complete.
985  * It also needs to account for multiple cancellations on happening at the same
986  * time for the same endpoint.
987  *
988  * Note that this function can be called in any context, or so says
989  * usb_hcd_unlink_urb()
990  */
991 int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
992 {
993         unsigned long flags;
994         int ret, i;
995         u32 temp;
996         struct xhci_hcd *xhci;
997         struct urb_priv *urb_priv;
998         struct xhci_td *td;
999         unsigned int ep_index;
1000         struct xhci_ring *ep_ring;
1001         struct xhci_virt_ep *ep;
1002
1003         xhci = hcd_to_xhci(hcd);
1004         spin_lock_irqsave(&xhci->lock, flags);
1005         /* Make sure the URB hasn't completed or been unlinked already */
1006         ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1007         if (ret || !urb->hcpriv)
1008                 goto done;
1009         temp = xhci_readl(xhci, &xhci->op_regs->status);
1010         if (temp == 0xffffffff) {
1011                 xhci_dbg(xhci, "HW died, freeing TD.\n");
1012                 urb_priv = urb->hcpriv;
1013
1014                 usb_hcd_unlink_urb_from_ep(hcd, urb);
1015                 spin_unlock_irqrestore(&xhci->lock, flags);
1016                 usb_hcd_giveback_urb(xhci_to_hcd(xhci), urb, -ESHUTDOWN);
1017                 xhci_urb_free_priv(xhci, urb_priv);
1018                 return ret;
1019         }
1020         if (xhci->xhc_state & XHCI_STATE_DYING) {
1021                 xhci_dbg(xhci, "Ep 0x%x: URB %p to be canceled on "
1022                                 "non-responsive xHCI host.\n",
1023                                 urb->ep->desc.bEndpointAddress, urb);
1024                 /* Let the stop endpoint command watchdog timer (which set this
1025                  * state) finish cleaning up the endpoint TD lists.  We must
1026                  * have caught it in the middle of dropping a lock and giving
1027                  * back an URB.
1028                  */
1029                 goto done;
1030         }
1031
1032         xhci_dbg(xhci, "Cancel URB %p\n", urb);
1033         xhci_dbg(xhci, "Event ring:\n");
1034         xhci_debug_ring(xhci, xhci->event_ring);
1035         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1036         ep = &xhci->devs[urb->dev->slot_id]->eps[ep_index];
1037         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1038         if (!ep_ring) {
1039                 ret = -EINVAL;
1040                 goto done;
1041         }
1042
1043         xhci_dbg(xhci, "Endpoint ring:\n");
1044         xhci_debug_ring(xhci, ep_ring);
1045
1046         urb_priv = urb->hcpriv;
1047
1048         for (i = urb_priv->td_cnt; i < urb_priv->length; i++) {
1049                 td = urb_priv->td[i];
1050                 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
1051         }
1052
1053         /* Queue a stop endpoint command, but only if this is
1054          * the first cancellation to be handled.
1055          */
1056         if (!(ep->ep_state & EP_HALT_PENDING)) {
1057                 ep->ep_state |= EP_HALT_PENDING;
1058                 ep->stop_cmds_pending++;
1059                 ep->stop_cmd_timer.expires = jiffies +
1060                         XHCI_STOP_EP_CMD_TIMEOUT * HZ;
1061                 add_timer(&ep->stop_cmd_timer);
1062                 xhci_queue_stop_endpoint(xhci, urb->dev->slot_id, ep_index);
1063                 xhci_ring_cmd_db(xhci);
1064         }
1065 done:
1066         spin_unlock_irqrestore(&xhci->lock, flags);
1067         return ret;
1068 }
1069
1070 /* Drop an endpoint from a new bandwidth configuration for this device.
1071  * Only one call to this function is allowed per endpoint before
1072  * check_bandwidth() or reset_bandwidth() must be called.
1073  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1074  * add the endpoint to the schedule with possibly new parameters denoted by a
1075  * different endpoint descriptor in usb_host_endpoint.
1076  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1077  * not allowed.
1078  *
1079  * The USB core will not allow URBs to be queued to an endpoint that is being
1080  * disabled, so there's no need for mutual exclusion to protect
1081  * the xhci->devs[slot_id] structure.
1082  */
1083 int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1084                 struct usb_host_endpoint *ep)
1085 {
1086         struct xhci_hcd *xhci;
1087         struct xhci_container_ctx *in_ctx, *out_ctx;
1088         struct xhci_input_control_ctx *ctrl_ctx;
1089         struct xhci_slot_ctx *slot_ctx;
1090         unsigned int last_ctx;
1091         unsigned int ep_index;
1092         struct xhci_ep_ctx *ep_ctx;
1093         u32 drop_flag;
1094         u32 new_add_flags, new_drop_flags, new_slot_info;
1095         int ret;
1096
1097         ret = xhci_check_args(hcd, udev, ep, 1, __func__);
1098         if (ret <= 0)
1099                 return ret;
1100         xhci = hcd_to_xhci(hcd);
1101         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1102
1103         drop_flag = xhci_get_endpoint_flag(&ep->desc);
1104         if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1105                 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1106                                 __func__, drop_flag);
1107                 return 0;
1108         }
1109
1110         if (!xhci->devs || !xhci->devs[udev->slot_id]) {
1111                 xhci_warn(xhci, "xHCI %s called with unaddressed device\n",
1112                                 __func__);
1113                 return -EINVAL;
1114         }
1115
1116         in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1117         out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1118         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1119         ep_index = xhci_get_endpoint_index(&ep->desc);
1120         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1121         /* If the HC already knows the endpoint is disabled,
1122          * or the HCD has noted it is disabled, ignore this request
1123          */
1124         if ((ep_ctx->ep_info & EP_STATE_MASK) == EP_STATE_DISABLED ||
1125                         ctrl_ctx->drop_flags & xhci_get_endpoint_flag(&ep->desc)) {
1126                 xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1127                                 __func__, ep);
1128                 return 0;
1129         }
1130
1131         ctrl_ctx->drop_flags |= drop_flag;
1132         new_drop_flags = ctrl_ctx->drop_flags;
1133
1134         ctrl_ctx->add_flags &= ~drop_flag;
1135         new_add_flags = ctrl_ctx->add_flags;
1136
1137         last_ctx = xhci_last_valid_endpoint(ctrl_ctx->add_flags);
1138         slot_ctx = xhci_get_slot_ctx(xhci, in_ctx);
1139         /* Update the last valid endpoint context, if we deleted the last one */
1140         if ((slot_ctx->dev_info & LAST_CTX_MASK) > LAST_CTX(last_ctx)) {
1141                 slot_ctx->dev_info &= ~LAST_CTX_MASK;
1142                 slot_ctx->dev_info |= LAST_CTX(last_ctx);
1143         }
1144         new_slot_info = slot_ctx->dev_info;
1145
1146         xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1147
1148         xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x, new slot info = %#x\n",
1149                         (unsigned int) ep->desc.bEndpointAddress,
1150                         udev->slot_id,
1151                         (unsigned int) new_drop_flags,
1152                         (unsigned int) new_add_flags,
1153                         (unsigned int) new_slot_info);
1154         return 0;
1155 }
1156
1157 /* Add an endpoint to a new possible bandwidth configuration for this device.
1158  * Only one call to this function is allowed per endpoint before
1159  * check_bandwidth() or reset_bandwidth() must be called.
1160  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1161  * add the endpoint to the schedule with possibly new parameters denoted by a
1162  * different endpoint descriptor in usb_host_endpoint.
1163  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1164  * not allowed.
1165  *
1166  * The USB core will not allow URBs to be queued to an endpoint until the
1167  * configuration or alt setting is installed in the device, so there's no need
1168  * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1169  */
1170 int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1171                 struct usb_host_endpoint *ep)
1172 {
1173         struct xhci_hcd *xhci;
1174         struct xhci_container_ctx *in_ctx, *out_ctx;
1175         unsigned int ep_index;
1176         struct xhci_ep_ctx *ep_ctx;
1177         struct xhci_slot_ctx *slot_ctx;
1178         struct xhci_input_control_ctx *ctrl_ctx;
1179         u32 added_ctxs;
1180         unsigned int last_ctx;
1181         u32 new_add_flags, new_drop_flags, new_slot_info;
1182         int ret = 0;
1183
1184         ret = xhci_check_args(hcd, udev, ep, 1, __func__);
1185         if (ret <= 0) {
1186                 /* So we won't queue a reset ep command for a root hub */
1187                 ep->hcpriv = NULL;
1188                 return ret;
1189         }
1190         xhci = hcd_to_xhci(hcd);
1191
1192         added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1193         last_ctx = xhci_last_valid_endpoint(added_ctxs);
1194         if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1195                 /* FIXME when we have to issue an evaluate endpoint command to
1196                  * deal with ep0 max packet size changing once we get the
1197                  * descriptors
1198                  */
1199                 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1200                                 __func__, added_ctxs);
1201                 return 0;
1202         }
1203
1204         if (!xhci->devs || !xhci->devs[udev->slot_id]) {
1205                 xhci_warn(xhci, "xHCI %s called with unaddressed device\n",
1206                                 __func__);
1207                 return -EINVAL;
1208         }
1209
1210         in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1211         out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1212         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1213         ep_index = xhci_get_endpoint_index(&ep->desc);
1214         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1215         /* If the HCD has already noted the endpoint is enabled,
1216          * ignore this request.
1217          */
1218         if (ctrl_ctx->add_flags & xhci_get_endpoint_flag(&ep->desc)) {
1219                 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1220                                 __func__, ep);
1221                 return 0;
1222         }
1223
1224         /*
1225          * Configuration and alternate setting changes must be done in
1226          * process context, not interrupt context (or so documenation
1227          * for usb_set_interface() and usb_set_configuration() claim).
1228          */
1229         if (xhci_endpoint_init(xhci, xhci->devs[udev->slot_id],
1230                                 udev, ep, GFP_NOIO) < 0) {
1231                 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1232                                 __func__, ep->desc.bEndpointAddress);
1233                 return -ENOMEM;
1234         }
1235
1236         ctrl_ctx->add_flags |= added_ctxs;
1237         new_add_flags = ctrl_ctx->add_flags;
1238
1239         /* If xhci_endpoint_disable() was called for this endpoint, but the
1240          * xHC hasn't been notified yet through the check_bandwidth() call,
1241          * this re-adds a new state for the endpoint from the new endpoint
1242          * descriptors.  We must drop and re-add this endpoint, so we leave the
1243          * drop flags alone.
1244          */
1245         new_drop_flags = ctrl_ctx->drop_flags;
1246
1247         slot_ctx = xhci_get_slot_ctx(xhci, in_ctx);
1248         /* Update the last valid endpoint context, if we just added one past */
1249         if ((slot_ctx->dev_info & LAST_CTX_MASK) < LAST_CTX(last_ctx)) {
1250                 slot_ctx->dev_info &= ~LAST_CTX_MASK;
1251                 slot_ctx->dev_info |= LAST_CTX(last_ctx);
1252         }
1253         new_slot_info = slot_ctx->dev_info;
1254
1255         /* Store the usb_device pointer for later use */
1256         ep->hcpriv = udev;
1257
1258         xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x, new slot info = %#x\n",
1259                         (unsigned int) ep->desc.bEndpointAddress,
1260                         udev->slot_id,
1261                         (unsigned int) new_drop_flags,
1262                         (unsigned int) new_add_flags,
1263                         (unsigned int) new_slot_info);
1264         return 0;
1265 }
1266
1267 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1268 {
1269         struct xhci_input_control_ctx *ctrl_ctx;
1270         struct xhci_ep_ctx *ep_ctx;
1271         struct xhci_slot_ctx *slot_ctx;
1272         int i;
1273
1274         /* When a device's add flag and drop flag are zero, any subsequent
1275          * configure endpoint command will leave that endpoint's state
1276          * untouched.  Make sure we don't leave any old state in the input
1277          * endpoint contexts.
1278          */
1279         ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx);
1280         ctrl_ctx->drop_flags = 0;
1281         ctrl_ctx->add_flags = 0;
1282         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1283         slot_ctx->dev_info &= ~LAST_CTX_MASK;
1284         /* Endpoint 0 is always valid */
1285         slot_ctx->dev_info |= LAST_CTX(1);
1286         for (i = 1; i < 31; ++i) {
1287                 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
1288                 ep_ctx->ep_info = 0;
1289                 ep_ctx->ep_info2 = 0;
1290                 ep_ctx->deq = 0;
1291                 ep_ctx->tx_info = 0;
1292         }
1293 }
1294
1295 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
1296                 struct usb_device *udev, int *cmd_status)
1297 {
1298         int ret;
1299
1300         switch (*cmd_status) {
1301         case COMP_ENOMEM:
1302                 dev_warn(&udev->dev, "Not enough host controller resources "
1303                                 "for new device state.\n");
1304                 ret = -ENOMEM;
1305                 /* FIXME: can we allocate more resources for the HC? */
1306                 break;
1307         case COMP_BW_ERR:
1308                 dev_warn(&udev->dev, "Not enough bandwidth "
1309                                 "for new device state.\n");
1310                 ret = -ENOSPC;
1311                 /* FIXME: can we go back to the old state? */
1312                 break;
1313         case COMP_TRB_ERR:
1314                 /* the HCD set up something wrong */
1315                 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
1316                                 "add flag = 1, "
1317                                 "and endpoint is not disabled.\n");
1318                 ret = -EINVAL;
1319                 break;
1320         case COMP_SUCCESS:
1321                 dev_dbg(&udev->dev, "Successful Endpoint Configure command\n");
1322                 ret = 0;
1323                 break;
1324         default:
1325                 xhci_err(xhci, "ERROR: unexpected command completion "
1326                                 "code 0x%x.\n", *cmd_status);
1327                 ret = -EINVAL;
1328                 break;
1329         }
1330         return ret;
1331 }
1332
1333 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
1334                 struct usb_device *udev, int *cmd_status)
1335 {
1336         int ret;
1337         struct xhci_virt_device *virt_dev = xhci->devs[udev->slot_id];
1338
1339         switch (*cmd_status) {
1340         case COMP_EINVAL:
1341                 dev_warn(&udev->dev, "WARN: xHCI driver setup invalid evaluate "
1342                                 "context command.\n");
1343                 ret = -EINVAL;
1344                 break;
1345         case COMP_EBADSLT:
1346                 dev_warn(&udev->dev, "WARN: slot not enabled for"
1347                                 "evaluate context command.\n");
1348         case COMP_CTX_STATE:
1349                 dev_warn(&udev->dev, "WARN: invalid context state for "
1350                                 "evaluate context command.\n");
1351                 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 1);
1352                 ret = -EINVAL;
1353                 break;
1354         case COMP_SUCCESS:
1355                 dev_dbg(&udev->dev, "Successful evaluate context command\n");
1356                 ret = 0;
1357                 break;
1358         default:
1359                 xhci_err(xhci, "ERROR: unexpected command completion "
1360                                 "code 0x%x.\n", *cmd_status);
1361                 ret = -EINVAL;
1362                 break;
1363         }
1364         return ret;
1365 }
1366
1367 /* Issue a configure endpoint command or evaluate context command
1368  * and wait for it to finish.
1369  */
1370 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1371                 struct usb_device *udev,
1372                 struct xhci_command *command,
1373                 bool ctx_change, bool must_succeed)
1374 {
1375         int ret;
1376         int timeleft;
1377         unsigned long flags;
1378         struct xhci_container_ctx *in_ctx;
1379         struct completion *cmd_completion;
1380         int *cmd_status;
1381         struct xhci_virt_device *virt_dev;
1382
1383         spin_lock_irqsave(&xhci->lock, flags);
1384         virt_dev = xhci->devs[udev->slot_id];
1385         if (command) {
1386                 in_ctx = command->in_ctx;
1387                 cmd_completion = command->completion;
1388                 cmd_status = &command->status;
1389                 command->command_trb = xhci->cmd_ring->enqueue;
1390                 list_add_tail(&command->cmd_list, &virt_dev->cmd_list);
1391         } else {
1392                 in_ctx = virt_dev->in_ctx;
1393                 cmd_completion = &virt_dev->cmd_completion;
1394                 cmd_status = &virt_dev->cmd_status;
1395         }
1396         init_completion(cmd_completion);
1397
1398         if (!ctx_change)
1399                 ret = xhci_queue_configure_endpoint(xhci, in_ctx->dma,
1400                                 udev->slot_id, must_succeed);
1401         else
1402                 ret = xhci_queue_evaluate_context(xhci, in_ctx->dma,
1403                                 udev->slot_id);
1404         if (ret < 0) {
1405                 if (command)
1406                         list_del(&command->cmd_list);
1407                 spin_unlock_irqrestore(&xhci->lock, flags);
1408                 xhci_dbg(xhci, "FIXME allocate a new ring segment\n");
1409                 return -ENOMEM;
1410         }
1411         xhci_ring_cmd_db(xhci);
1412         spin_unlock_irqrestore(&xhci->lock, flags);
1413
1414         /* Wait for the configure endpoint command to complete */
1415         timeleft = wait_for_completion_interruptible_timeout(
1416                         cmd_completion,
1417                         USB_CTRL_SET_TIMEOUT);
1418         if (timeleft <= 0) {
1419                 xhci_warn(xhci, "%s while waiting for %s command\n",
1420                                 timeleft == 0 ? "Timeout" : "Signal",
1421                                 ctx_change == 0 ?
1422                                         "configure endpoint" :
1423                                         "evaluate context");
1424                 /* FIXME cancel the configure endpoint command */
1425                 return -ETIME;
1426         }
1427
1428         if (!ctx_change)
1429                 return xhci_configure_endpoint_result(xhci, udev, cmd_status);
1430         return xhci_evaluate_context_result(xhci, udev, cmd_status);
1431 }
1432
1433 /* Called after one or more calls to xhci_add_endpoint() or
1434  * xhci_drop_endpoint().  If this call fails, the USB core is expected
1435  * to call xhci_reset_bandwidth().
1436  *
1437  * Since we are in the middle of changing either configuration or
1438  * installing a new alt setting, the USB core won't allow URBs to be
1439  * enqueued for any endpoint on the old config or interface.  Nothing
1440  * else should be touching the xhci->devs[slot_id] structure, so we
1441  * don't need to take the xhci->lock for manipulating that.
1442  */
1443 int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
1444 {
1445         int i;
1446         int ret = 0;
1447         struct xhci_hcd *xhci;
1448         struct xhci_virt_device *virt_dev;
1449         struct xhci_input_control_ctx *ctrl_ctx;
1450         struct xhci_slot_ctx *slot_ctx;
1451
1452         ret = xhci_check_args(hcd, udev, NULL, 0, __func__);
1453         if (ret <= 0)
1454                 return ret;
1455         xhci = hcd_to_xhci(hcd);
1456
1457         if (!udev->slot_id || !xhci->devs || !xhci->devs[udev->slot_id]) {
1458                 xhci_warn(xhci, "xHCI %s called with unaddressed device\n",
1459                                 __func__);
1460                 return -EINVAL;
1461         }
1462         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1463         virt_dev = xhci->devs[udev->slot_id];
1464
1465         /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
1466         ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx);
1467         ctrl_ctx->add_flags |= SLOT_FLAG;
1468         ctrl_ctx->add_flags &= ~EP0_FLAG;
1469         ctrl_ctx->drop_flags &= ~SLOT_FLAG;
1470         ctrl_ctx->drop_flags &= ~EP0_FLAG;
1471         xhci_dbg(xhci, "New Input Control Context:\n");
1472         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1473         xhci_dbg_ctx(xhci, virt_dev->in_ctx,
1474                         LAST_CTX_TO_EP_NUM(slot_ctx->dev_info));
1475
1476         ret = xhci_configure_endpoint(xhci, udev, NULL,
1477                         false, false);
1478         if (ret) {
1479                 /* Callee should call reset_bandwidth() */
1480                 return ret;
1481         }
1482
1483         xhci_dbg(xhci, "Output context after successful config ep cmd:\n");
1484         xhci_dbg_ctx(xhci, virt_dev->out_ctx,
1485                         LAST_CTX_TO_EP_NUM(slot_ctx->dev_info));
1486
1487         xhci_zero_in_ctx(xhci, virt_dev);
1488         /* Install new rings and free or cache any old rings */
1489         for (i = 1; i < 31; ++i) {
1490                 if (!virt_dev->eps[i].new_ring)
1491                         continue;
1492                 /* Only cache or free the old ring if it exists.
1493                  * It may not if this is the first add of an endpoint.
1494                  */
1495                 if (virt_dev->eps[i].ring) {
1496                         xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
1497                 }
1498                 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
1499                 virt_dev->eps[i].new_ring = NULL;
1500         }
1501
1502         return ret;
1503 }
1504
1505 void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
1506 {
1507         struct xhci_hcd *xhci;
1508         struct xhci_virt_device *virt_dev;
1509         int i, ret;
1510
1511         ret = xhci_check_args(hcd, udev, NULL, 0, __func__);
1512         if (ret <= 0)
1513                 return;
1514         xhci = hcd_to_xhci(hcd);
1515
1516         if (!xhci->devs || !xhci->devs[udev->slot_id]) {
1517                 xhci_warn(xhci, "xHCI %s called with unaddressed device\n",
1518                                 __func__);
1519                 return;
1520         }
1521         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1522         virt_dev = xhci->devs[udev->slot_id];
1523         /* Free any rings allocated for added endpoints */
1524         for (i = 0; i < 31; ++i) {
1525                 if (virt_dev->eps[i].new_ring) {
1526                         xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
1527                         virt_dev->eps[i].new_ring = NULL;
1528                 }
1529         }
1530         xhci_zero_in_ctx(xhci, virt_dev);
1531 }
1532
1533 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
1534                 struct xhci_container_ctx *in_ctx,
1535                 struct xhci_container_ctx *out_ctx,
1536                 u32 add_flags, u32 drop_flags)
1537 {
1538         struct xhci_input_control_ctx *ctrl_ctx;
1539         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1540         ctrl_ctx->add_flags = add_flags;
1541         ctrl_ctx->drop_flags = drop_flags;
1542         xhci_slot_copy(xhci, in_ctx, out_ctx);
1543         ctrl_ctx->add_flags |= SLOT_FLAG;
1544
1545         xhci_dbg(xhci, "Input Context:\n");
1546         xhci_dbg_ctx(xhci, in_ctx, xhci_last_valid_endpoint(add_flags));
1547 }
1548
1549 void xhci_setup_input_ctx_for_quirk(struct xhci_hcd *xhci,
1550                 unsigned int slot_id, unsigned int ep_index,
1551                 struct xhci_dequeue_state *deq_state)
1552 {
1553         struct xhci_container_ctx *in_ctx;
1554         struct xhci_ep_ctx *ep_ctx;
1555         u32 added_ctxs;
1556         dma_addr_t addr;
1557
1558         xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
1559                         xhci->devs[slot_id]->out_ctx, ep_index);
1560         in_ctx = xhci->devs[slot_id]->in_ctx;
1561         ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
1562         addr = xhci_trb_virt_to_dma(deq_state->new_deq_seg,
1563                         deq_state->new_deq_ptr);
1564         if (addr == 0) {
1565                 xhci_warn(xhci, "WARN Cannot submit config ep after "
1566                                 "reset ep command\n");
1567                 xhci_warn(xhci, "WARN deq seg = %p, deq ptr = %p\n",
1568                                 deq_state->new_deq_seg,
1569                                 deq_state->new_deq_ptr);
1570                 return;
1571         }
1572         ep_ctx->deq = addr | deq_state->new_cycle_state;
1573
1574         added_ctxs = xhci_get_endpoint_flag_from_index(ep_index);
1575         xhci_setup_input_ctx_for_config_ep(xhci, xhci->devs[slot_id]->in_ctx,
1576                         xhci->devs[slot_id]->out_ctx, added_ctxs, added_ctxs);
1577 }
1578
1579 void xhci_cleanup_stalled_ring(struct xhci_hcd *xhci,
1580                 struct usb_device *udev, unsigned int ep_index)
1581 {
1582         struct xhci_dequeue_state deq_state;
1583         struct xhci_virt_ep *ep;
1584
1585         xhci_dbg(xhci, "Cleaning up stalled endpoint ring\n");
1586         ep = &xhci->devs[udev->slot_id]->eps[ep_index];
1587         /* We need to move the HW's dequeue pointer past this TD,
1588          * or it will attempt to resend it on the next doorbell ring.
1589          */
1590         xhci_find_new_dequeue_state(xhci, udev->slot_id,
1591                         ep_index, ep->stopped_stream, ep->stopped_td,
1592                         &deq_state);
1593
1594         /* HW with the reset endpoint quirk will use the saved dequeue state to
1595          * issue a configure endpoint command later.
1596          */
1597         if (!(xhci->quirks & XHCI_RESET_EP_QUIRK)) {
1598                 xhci_dbg(xhci, "Queueing new dequeue state\n");
1599                 xhci_queue_new_dequeue_state(xhci, udev->slot_id,
1600                                 ep_index, ep->stopped_stream, &deq_state);
1601         } else {
1602                 /* Better hope no one uses the input context between now and the
1603                  * reset endpoint completion!
1604                  * XXX: No idea how this hardware will react when stream rings
1605                  * are enabled.
1606                  */
1607                 xhci_dbg(xhci, "Setting up input context for "
1608                                 "configure endpoint command\n");
1609                 xhci_setup_input_ctx_for_quirk(xhci, udev->slot_id,
1610                                 ep_index, &deq_state);
1611         }
1612 }
1613
1614 /* Deal with stalled endpoints.  The core should have sent the control message
1615  * to clear the halt condition.  However, we need to make the xHCI hardware
1616  * reset its sequence number, since a device will expect a sequence number of
1617  * zero after the halt condition is cleared.
1618  * Context: in_interrupt
1619  */
1620 void xhci_endpoint_reset(struct usb_hcd *hcd,
1621                 struct usb_host_endpoint *ep)
1622 {
1623         struct xhci_hcd *xhci;
1624         struct usb_device *udev;
1625         unsigned int ep_index;
1626         unsigned long flags;
1627         int ret;
1628         struct xhci_virt_ep *virt_ep;
1629
1630         xhci = hcd_to_xhci(hcd);
1631         udev = (struct usb_device *) ep->hcpriv;
1632         /* Called with a root hub endpoint (or an endpoint that wasn't added
1633          * with xhci_add_endpoint()
1634          */
1635         if (!ep->hcpriv)
1636                 return;
1637         ep_index = xhci_get_endpoint_index(&ep->desc);
1638         virt_ep = &xhci->devs[udev->slot_id]->eps[ep_index];
1639         if (!virt_ep->stopped_td) {
1640                 xhci_dbg(xhci, "Endpoint 0x%x not halted, refusing to reset.\n",
1641                                 ep->desc.bEndpointAddress);
1642                 return;
1643         }
1644         if (usb_endpoint_xfer_control(&ep->desc)) {
1645                 xhci_dbg(xhci, "Control endpoint stall already handled.\n");
1646                 return;
1647         }
1648
1649         xhci_dbg(xhci, "Queueing reset endpoint command\n");
1650         spin_lock_irqsave(&xhci->lock, flags);
1651         ret = xhci_queue_reset_ep(xhci, udev->slot_id, ep_index);
1652         /*
1653          * Can't change the ring dequeue pointer until it's transitioned to the
1654          * stopped state, which is only upon a successful reset endpoint
1655          * command.  Better hope that last command worked!
1656          */
1657         if (!ret) {
1658                 xhci_cleanup_stalled_ring(xhci, udev, ep_index);
1659                 kfree(virt_ep->stopped_td);
1660                 xhci_ring_cmd_db(xhci);
1661         }
1662         virt_ep->stopped_td = NULL;
1663         virt_ep->stopped_trb = NULL;
1664         virt_ep->stopped_stream = 0;
1665         spin_unlock_irqrestore(&xhci->lock, flags);
1666
1667         if (ret)
1668                 xhci_warn(xhci, "FIXME allocate a new ring segment\n");
1669 }
1670
1671 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
1672                 struct usb_device *udev, struct usb_host_endpoint *ep,
1673                 unsigned int slot_id)
1674 {
1675         int ret;
1676         unsigned int ep_index;
1677         unsigned int ep_state;
1678
1679         if (!ep)
1680                 return -EINVAL;
1681         ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, __func__);
1682         if (ret <= 0)
1683                 return -EINVAL;
1684         if (ep->ss_ep_comp.bmAttributes == 0) {
1685                 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
1686                                 " descriptor for ep 0x%x does not support streams\n",
1687                                 ep->desc.bEndpointAddress);
1688                 return -EINVAL;
1689         }
1690
1691         ep_index = xhci_get_endpoint_index(&ep->desc);
1692         ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
1693         if (ep_state & EP_HAS_STREAMS ||
1694                         ep_state & EP_GETTING_STREAMS) {
1695                 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
1696                                 "already has streams set up.\n",
1697                                 ep->desc.bEndpointAddress);
1698                 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
1699                                 "dynamic stream context array reallocation.\n");
1700                 return -EINVAL;
1701         }
1702         if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
1703                 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
1704                                 "endpoint 0x%x; URBs are pending.\n",
1705                                 ep->desc.bEndpointAddress);
1706                 return -EINVAL;
1707         }
1708         return 0;
1709 }
1710
1711 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
1712                 unsigned int *num_streams, unsigned int *num_stream_ctxs)
1713 {
1714         unsigned int max_streams;
1715
1716         /* The stream context array size must be a power of two */
1717         *num_stream_ctxs = roundup_pow_of_two(*num_streams);
1718         /*
1719          * Find out how many primary stream array entries the host controller
1720          * supports.  Later we may use secondary stream arrays (similar to 2nd
1721          * level page entries), but that's an optional feature for xHCI host
1722          * controllers. xHCs must support at least 4 stream IDs.
1723          */
1724         max_streams = HCC_MAX_PSA(xhci->hcc_params);
1725         if (*num_stream_ctxs > max_streams) {
1726                 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
1727                                 max_streams);
1728                 *num_stream_ctxs = max_streams;
1729                 *num_streams = max_streams;
1730         }
1731 }
1732
1733 /* Returns an error code if one of the endpoint already has streams.
1734  * This does not change any data structures, it only checks and gathers
1735  * information.
1736  */
1737 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
1738                 struct usb_device *udev,
1739                 struct usb_host_endpoint **eps, unsigned int num_eps,
1740                 unsigned int *num_streams, u32 *changed_ep_bitmask)
1741 {
1742         unsigned int max_streams;
1743         unsigned int endpoint_flag;
1744         int i;
1745         int ret;
1746
1747         for (i = 0; i < num_eps; i++) {
1748                 ret = xhci_check_streams_endpoint(xhci, udev,
1749                                 eps[i], udev->slot_id);
1750                 if (ret < 0)
1751                         return ret;
1752
1753                 max_streams = USB_SS_MAX_STREAMS(
1754                                 eps[i]->ss_ep_comp.bmAttributes);
1755                 if (max_streams < (*num_streams - 1)) {
1756                         xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
1757                                         eps[i]->desc.bEndpointAddress,
1758                                         max_streams);
1759                         *num_streams = max_streams+1;
1760                 }
1761
1762                 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
1763                 if (*changed_ep_bitmask & endpoint_flag)
1764                         return -EINVAL;
1765                 *changed_ep_bitmask |= endpoint_flag;
1766         }
1767         return 0;
1768 }
1769
1770 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
1771                 struct usb_device *udev,
1772                 struct usb_host_endpoint **eps, unsigned int num_eps)
1773 {
1774         u32 changed_ep_bitmask = 0;
1775         unsigned int slot_id;
1776         unsigned int ep_index;
1777         unsigned int ep_state;
1778         int i;
1779
1780         slot_id = udev->slot_id;
1781         if (!xhci->devs[slot_id])
1782                 return 0;
1783
1784         for (i = 0; i < num_eps; i++) {
1785                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
1786                 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
1787                 /* Are streams already being freed for the endpoint? */
1788                 if (ep_state & EP_GETTING_NO_STREAMS) {
1789                         xhci_warn(xhci, "WARN Can't disable streams for "
1790                                         "endpoint 0x%x\n, "
1791                                         "streams are being disabled already.",
1792                                         eps[i]->desc.bEndpointAddress);
1793                         return 0;
1794                 }
1795                 /* Are there actually any streams to free? */
1796                 if (!(ep_state & EP_HAS_STREAMS) &&
1797                                 !(ep_state & EP_GETTING_STREAMS)) {
1798                         xhci_warn(xhci, "WARN Can't disable streams for "
1799                                         "endpoint 0x%x\n, "
1800                                         "streams are already disabled!",
1801                                         eps[i]->desc.bEndpointAddress);
1802                         xhci_warn(xhci, "WARN xhci_free_streams() called "
1803                                         "with non-streams endpoint\n");
1804                         return 0;
1805                 }
1806                 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
1807         }
1808         return changed_ep_bitmask;
1809 }
1810
1811 /*
1812  * The USB device drivers use this function (though the HCD interface in USB
1813  * core) to prepare a set of bulk endpoints to use streams.  Streams are used to
1814  * coordinate mass storage command queueing across multiple endpoints (basically
1815  * a stream ID == a task ID).
1816  *
1817  * Setting up streams involves allocating the same size stream context array
1818  * for each endpoint and issuing a configure endpoint command for all endpoints.
1819  *
1820  * Don't allow the call to succeed if one endpoint only supports one stream
1821  * (which means it doesn't support streams at all).
1822  *
1823  * Drivers may get less stream IDs than they asked for, if the host controller
1824  * hardware or endpoints claim they can't support the number of requested
1825  * stream IDs.
1826  */
1827 int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
1828                 struct usb_host_endpoint **eps, unsigned int num_eps,
1829                 unsigned int num_streams, gfp_t mem_flags)
1830 {
1831         int i, ret;
1832         struct xhci_hcd *xhci;
1833         struct xhci_virt_device *vdev;
1834         struct xhci_command *config_cmd;
1835         unsigned int ep_index;
1836         unsigned int num_stream_ctxs;
1837         unsigned long flags;
1838         u32 changed_ep_bitmask = 0;
1839
1840         if (!eps)
1841                 return -EINVAL;
1842
1843         /* Add one to the number of streams requested to account for
1844          * stream 0 that is reserved for xHCI usage.
1845          */
1846         num_streams += 1;
1847         xhci = hcd_to_xhci(hcd);
1848         xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
1849                         num_streams);
1850
1851         config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
1852         if (!config_cmd) {
1853                 xhci_dbg(xhci, "Could not allocate xHCI command structure.\n");
1854                 return -ENOMEM;
1855         }
1856
1857         /* Check to make sure all endpoints are not already configured for
1858          * streams.  While we're at it, find the maximum number of streams that
1859          * all the endpoints will support and check for duplicate endpoints.
1860          */
1861         spin_lock_irqsave(&xhci->lock, flags);
1862         ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
1863                         num_eps, &num_streams, &changed_ep_bitmask);
1864         if (ret < 0) {
1865                 xhci_free_command(xhci, config_cmd);
1866                 spin_unlock_irqrestore(&xhci->lock, flags);
1867                 return ret;
1868         }
1869         if (num_streams <= 1) {
1870                 xhci_warn(xhci, "WARN: endpoints can't handle "
1871                                 "more than one stream.\n");
1872                 xhci_free_command(xhci, config_cmd);
1873                 spin_unlock_irqrestore(&xhci->lock, flags);
1874                 return -EINVAL;
1875         }
1876         vdev = xhci->devs[udev->slot_id];
1877         /* Mark each endpoint as being in transistion, so
1878          * xhci_urb_enqueue() will reject all URBs.
1879          */
1880         for (i = 0; i < num_eps; i++) {
1881                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
1882                 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
1883         }
1884         spin_unlock_irqrestore(&xhci->lock, flags);
1885
1886         /* Setup internal data structures and allocate HW data structures for
1887          * streams (but don't install the HW structures in the input context
1888          * until we're sure all memory allocation succeeded).
1889          */
1890         xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
1891         xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
1892                         num_stream_ctxs, num_streams);
1893
1894         for (i = 0; i < num_eps; i++) {
1895                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
1896                 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
1897                                 num_stream_ctxs,
1898                                 num_streams, mem_flags);
1899                 if (!vdev->eps[ep_index].stream_info)
1900                         goto cleanup;
1901                 /* Set maxPstreams in endpoint context and update deq ptr to
1902                  * point to stream context array. FIXME
1903                  */
1904         }
1905
1906         /* Set up the input context for a configure endpoint command. */
1907         for (i = 0; i < num_eps; i++) {
1908                 struct xhci_ep_ctx *ep_ctx;
1909
1910                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
1911                 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
1912
1913                 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
1914                                 vdev->out_ctx, ep_index);
1915                 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
1916                                 vdev->eps[ep_index].stream_info);
1917         }
1918         /* Tell the HW to drop its old copy of the endpoint context info
1919          * and add the updated copy from the input context.
1920          */
1921         xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
1922                         vdev->out_ctx, changed_ep_bitmask, changed_ep_bitmask);
1923
1924         /* Issue and wait for the configure endpoint command */
1925         ret = xhci_configure_endpoint(xhci, udev, config_cmd,
1926                         false, false);
1927
1928         /* xHC rejected the configure endpoint command for some reason, so we
1929          * leave the old ring intact and free our internal streams data
1930          * structure.
1931          */
1932         if (ret < 0)
1933                 goto cleanup;
1934
1935         spin_lock_irqsave(&xhci->lock, flags);
1936         for (i = 0; i < num_eps; i++) {
1937                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
1938                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
1939                 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
1940                          udev->slot_id, ep_index);
1941                 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
1942         }
1943         xhci_free_command(xhci, config_cmd);
1944         spin_unlock_irqrestore(&xhci->lock, flags);
1945
1946         /* Subtract 1 for stream 0, which drivers can't use */
1947         return num_streams - 1;
1948
1949 cleanup:
1950         /* If it didn't work, free the streams! */
1951         for (i = 0; i < num_eps; i++) {
1952                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
1953                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
1954                 vdev->eps[ep_index].stream_info = NULL;
1955                 /* FIXME Unset maxPstreams in endpoint context and
1956                  * update deq ptr to point to normal string ring.
1957                  */
1958                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
1959                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
1960                 xhci_endpoint_zero(xhci, vdev, eps[i]);
1961         }
1962         xhci_free_command(xhci, config_cmd);
1963         return -ENOMEM;
1964 }
1965
1966 /* Transition the endpoint from using streams to being a "normal" endpoint
1967  * without streams.
1968  *
1969  * Modify the endpoint context state, submit a configure endpoint command,
1970  * and free all endpoint rings for streams if that completes successfully.
1971  */
1972 int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
1973                 struct usb_host_endpoint **eps, unsigned int num_eps,
1974                 gfp_t mem_flags)
1975 {
1976         int i, ret;
1977         struct xhci_hcd *xhci;
1978         struct xhci_virt_device *vdev;
1979         struct xhci_command *command;
1980         unsigned int ep_index;
1981         unsigned long flags;
1982         u32 changed_ep_bitmask;
1983
1984         xhci = hcd_to_xhci(hcd);
1985         vdev = xhci->devs[udev->slot_id];
1986
1987         /* Set up a configure endpoint command to remove the streams rings */
1988         spin_lock_irqsave(&xhci->lock, flags);
1989         changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
1990                         udev, eps, num_eps);
1991         if (changed_ep_bitmask == 0) {
1992                 spin_unlock_irqrestore(&xhci->lock, flags);
1993                 return -EINVAL;
1994         }
1995
1996         /* Use the xhci_command structure from the first endpoint.  We may have
1997          * allocated too many, but the driver may call xhci_free_streams() for
1998          * each endpoint it grouped into one call to xhci_alloc_streams().
1999          */
2000         ep_index = xhci_get_endpoint_index(&eps[0]->desc);
2001         command = vdev->eps[ep_index].stream_info->free_streams_command;
2002         for (i = 0; i < num_eps; i++) {
2003                 struct xhci_ep_ctx *ep_ctx;
2004
2005                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
2006                 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
2007                 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
2008                         EP_GETTING_NO_STREAMS;
2009
2010                 xhci_endpoint_copy(xhci, command->in_ctx,
2011                                 vdev->out_ctx, ep_index);
2012                 xhci_setup_no_streams_ep_input_ctx(xhci, ep_ctx,
2013                                 &vdev->eps[ep_index]);
2014         }
2015         xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
2016                         vdev->out_ctx, changed_ep_bitmask, changed_ep_bitmask);
2017         spin_unlock_irqrestore(&xhci->lock, flags);
2018
2019         /* Issue and wait for the configure endpoint command,
2020          * which must succeed.
2021          */
2022         ret = xhci_configure_endpoint(xhci, udev, command,
2023                         false, true);
2024
2025         /* xHC rejected the configure endpoint command for some reason, so we
2026          * leave the streams rings intact.
2027          */
2028         if (ret < 0)
2029                 return ret;
2030
2031         spin_lock_irqsave(&xhci->lock, flags);
2032         for (i = 0; i < num_eps; i++) {
2033                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
2034                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
2035                 vdev->eps[ep_index].stream_info = NULL;
2036                 /* FIXME Unset maxPstreams in endpoint context and
2037                  * update deq ptr to point to normal string ring.
2038                  */
2039                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
2040                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
2041         }
2042         spin_unlock_irqrestore(&xhci->lock, flags);
2043
2044         return 0;
2045 }
2046
2047 /*
2048  * This submits a Reset Device Command, which will set the device state to 0,
2049  * set the device address to 0, and disable all the endpoints except the default
2050  * control endpoint.  The USB core should come back and call
2051  * xhci_address_device(), and then re-set up the configuration.  If this is
2052  * called because of a usb_reset_and_verify_device(), then the old alternate
2053  * settings will be re-installed through the normal bandwidth allocation
2054  * functions.
2055  *
2056  * Wait for the Reset Device command to finish.  Remove all structures
2057  * associated with the endpoints that were disabled.  Clear the input device
2058  * structure?  Cache the rings?  Reset the control endpoint 0 max packet size?
2059  */
2060 int xhci_reset_device(struct usb_hcd *hcd, struct usb_device *udev)
2061 {
2062         int ret, i;
2063         unsigned long flags;
2064         struct xhci_hcd *xhci;
2065         unsigned int slot_id;
2066         struct xhci_virt_device *virt_dev;
2067         struct xhci_command *reset_device_cmd;
2068         int timeleft;
2069         int last_freed_endpoint;
2070
2071         ret = xhci_check_args(hcd, udev, NULL, 0, __func__);
2072         if (ret <= 0)
2073                 return ret;
2074         xhci = hcd_to_xhci(hcd);
2075         slot_id = udev->slot_id;
2076         virt_dev = xhci->devs[slot_id];
2077         if (!virt_dev) {
2078                 xhci_dbg(xhci, "%s called with invalid slot ID %u\n",
2079                                 __func__, slot_id);
2080                 return -EINVAL;
2081         }
2082
2083         xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
2084         /* Allocate the command structure that holds the struct completion.
2085          * Assume we're in process context, since the normal device reset
2086          * process has to wait for the device anyway.  Storage devices are
2087          * reset as part of error handling, so use GFP_NOIO instead of
2088          * GFP_KERNEL.
2089          */
2090         reset_device_cmd = xhci_alloc_command(xhci, false, true, GFP_NOIO);
2091         if (!reset_device_cmd) {
2092                 xhci_dbg(xhci, "Couldn't allocate command structure.\n");
2093                 return -ENOMEM;
2094         }
2095
2096         /* Attempt to submit the Reset Device command to the command ring */
2097         spin_lock_irqsave(&xhci->lock, flags);
2098         reset_device_cmd->command_trb = xhci->cmd_ring->enqueue;
2099         list_add_tail(&reset_device_cmd->cmd_list, &virt_dev->cmd_list);
2100         ret = xhci_queue_reset_device(xhci, slot_id);
2101         if (ret) {
2102                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
2103                 list_del(&reset_device_cmd->cmd_list);
2104                 spin_unlock_irqrestore(&xhci->lock, flags);
2105                 goto command_cleanup;
2106         }
2107         xhci_ring_cmd_db(xhci);
2108         spin_unlock_irqrestore(&xhci->lock, flags);
2109
2110         /* Wait for the Reset Device command to finish */
2111         timeleft = wait_for_completion_interruptible_timeout(
2112                         reset_device_cmd->completion,
2113                         USB_CTRL_SET_TIMEOUT);
2114         if (timeleft <= 0) {
2115                 xhci_warn(xhci, "%s while waiting for reset device command\n",
2116                                 timeleft == 0 ? "Timeout" : "Signal");
2117                 spin_lock_irqsave(&xhci->lock, flags);
2118                 /* The timeout might have raced with the event ring handler, so
2119                  * only delete from the list if the item isn't poisoned.
2120                  */
2121                 if (reset_device_cmd->cmd_list.next != LIST_POISON1)
2122                         list_del(&reset_device_cmd->cmd_list);
2123                 spin_unlock_irqrestore(&xhci->lock, flags);
2124                 ret = -ETIME;
2125                 goto command_cleanup;
2126         }
2127
2128         /* The Reset Device command can't fail, according to the 0.95/0.96 spec,
2129          * unless we tried to reset a slot ID that wasn't enabled,
2130          * or the device wasn't in the addressed or configured state.
2131          */
2132         ret = reset_device_cmd->status;
2133         switch (ret) {
2134         case COMP_EBADSLT: /* 0.95 completion code for bad slot ID */
2135         case COMP_CTX_STATE: /* 0.96 completion code for same thing */
2136                 xhci_info(xhci, "Can't reset device (slot ID %u) in %s state\n",
2137                                 slot_id,
2138                                 xhci_get_slot_state(xhci, virt_dev->out_ctx));
2139                 xhci_info(xhci, "Not freeing device rings.\n");
2140                 /* Don't treat this as an error.  May change my mind later. */
2141                 ret = 0;
2142                 goto command_cleanup;
2143         case COMP_SUCCESS:
2144                 xhci_dbg(xhci, "Successful reset device command.\n");
2145                 break;
2146         default:
2147                 if (xhci_is_vendor_info_code(xhci, ret))
2148                         break;
2149                 xhci_warn(xhci, "Unknown completion code %u for "
2150                                 "reset device command.\n", ret);
2151                 ret = -EINVAL;
2152                 goto command_cleanup;
2153         }
2154
2155         /* Everything but endpoint 0 is disabled, so free or cache the rings. */
2156         last_freed_endpoint = 1;
2157         for (i = 1; i < 31; ++i) {
2158                 if (!virt_dev->eps[i].ring)
2159                         continue;
2160                 xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
2161                 last_freed_endpoint = i;
2162         }
2163         xhci_dbg(xhci, "Output context after successful reset device cmd:\n");
2164         xhci_dbg_ctx(xhci, virt_dev->out_ctx, last_freed_endpoint);
2165         ret = 0;
2166
2167 command_cleanup:
2168         xhci_free_command(xhci, reset_device_cmd);
2169         return ret;
2170 }
2171
2172 /*
2173  * At this point, the struct usb_device is about to go away, the device has
2174  * disconnected, and all traffic has been stopped and the endpoints have been
2175  * disabled.  Free any HC data structures associated with that device.
2176  */
2177 void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
2178 {
2179         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
2180         struct xhci_virt_device *virt_dev;
2181         unsigned long flags;
2182         u32 state;
2183         int i;
2184
2185         if (udev->slot_id == 0)
2186                 return;
2187         virt_dev = xhci->devs[udev->slot_id];
2188         if (!virt_dev)
2189                 return;
2190
2191         /* Stop any wayward timer functions (which may grab the lock) */
2192         for (i = 0; i < 31; ++i) {
2193                 virt_dev->eps[i].ep_state &= ~EP_HALT_PENDING;
2194                 del_timer_sync(&virt_dev->eps[i].stop_cmd_timer);
2195         }
2196
2197         spin_lock_irqsave(&xhci->lock, flags);
2198         /* Don't disable the slot if the host controller is dead. */
2199         state = xhci_readl(xhci, &xhci->op_regs->status);
2200         if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING)) {
2201                 xhci_free_virt_device(xhci, udev->slot_id);
2202                 spin_unlock_irqrestore(&xhci->lock, flags);
2203                 return;
2204         }
2205
2206         if (xhci_queue_slot_control(xhci, TRB_DISABLE_SLOT, udev->slot_id)) {
2207                 spin_unlock_irqrestore(&xhci->lock, flags);
2208                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
2209                 return;
2210         }
2211         xhci_ring_cmd_db(xhci);
2212         spin_unlock_irqrestore(&xhci->lock, flags);
2213         /*
2214          * Event command completion handler will free any data structures
2215          * associated with the slot.  XXX Can free sleep?
2216          */
2217 }
2218
2219 /*
2220  * Returns 0 if the xHC ran out of device slots, the Enable Slot command
2221  * timed out, or allocating memory failed.  Returns 1 on success.
2222  */
2223 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
2224 {
2225         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
2226         unsigned long flags;
2227         int timeleft;
2228         int ret;
2229
2230         spin_lock_irqsave(&xhci->lock, flags);
2231         ret = xhci_queue_slot_control(xhci, TRB_ENABLE_SLOT, 0);
2232         if (ret) {
2233                 spin_unlock_irqrestore(&xhci->lock, flags);
2234                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
2235                 return 0;
2236         }
2237         xhci_ring_cmd_db(xhci);
2238         spin_unlock_irqrestore(&xhci->lock, flags);
2239
2240         /* XXX: how much time for xHC slot assignment? */
2241         timeleft = wait_for_completion_interruptible_timeout(&xhci->addr_dev,
2242                         USB_CTRL_SET_TIMEOUT);
2243         if (timeleft <= 0) {
2244                 xhci_warn(xhci, "%s while waiting for a slot\n",
2245                                 timeleft == 0 ? "Timeout" : "Signal");
2246                 /* FIXME cancel the enable slot request */
2247                 return 0;
2248         }
2249
2250         if (!xhci->slot_id) {
2251                 xhci_err(xhci, "Error while assigning device slot ID\n");
2252                 return 0;
2253         }
2254         /* xhci_alloc_virt_device() does not touch rings; no need to lock */
2255         if (!xhci_alloc_virt_device(xhci, xhci->slot_id, udev, GFP_KERNEL)) {
2256                 /* Disable slot, if we can do it without mem alloc */
2257                 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
2258                 spin_lock_irqsave(&xhci->lock, flags);
2259                 if (!xhci_queue_slot_control(xhci, TRB_DISABLE_SLOT, udev->slot_id))
2260                         xhci_ring_cmd_db(xhci);
2261                 spin_unlock_irqrestore(&xhci->lock, flags);
2262                 return 0;
2263         }
2264         udev->slot_id = xhci->slot_id;
2265         /* Is this a LS or FS device under a HS hub? */
2266         /* Hub or peripherial? */
2267         return 1;
2268 }
2269
2270 /*
2271  * Issue an Address Device command (which will issue a SetAddress request to
2272  * the device).
2273  * We should be protected by the usb_address0_mutex in khubd's hub_port_init, so
2274  * we should only issue and wait on one address command at the same time.
2275  *
2276  * We add one to the device address issued by the hardware because the USB core
2277  * uses address 1 for the root hubs (even though they're not really devices).
2278  */
2279 int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev)
2280 {
2281         unsigned long flags;
2282         int timeleft;
2283         struct xhci_virt_device *virt_dev;
2284         int ret = 0;
2285         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
2286         struct xhci_slot_ctx *slot_ctx;
2287         struct xhci_input_control_ctx *ctrl_ctx;
2288         u64 temp_64;
2289
2290         if (!udev->slot_id) {
2291                 xhci_dbg(xhci, "Bad Slot ID %d\n", udev->slot_id);
2292                 return -EINVAL;
2293         }
2294
2295         virt_dev = xhci->devs[udev->slot_id];
2296
2297         /* If this is a Set Address to an unconfigured device, setup ep 0 */
2298         if (!udev->config)
2299                 xhci_setup_addressable_virt_dev(xhci, udev);
2300         else
2301                 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
2302         /* Otherwise, assume the core has the device configured how it wants */
2303         xhci_dbg(xhci, "Slot ID %d Input Context:\n", udev->slot_id);
2304         xhci_dbg_ctx(xhci, virt_dev->in_ctx, 2);
2305
2306         spin_lock_irqsave(&xhci->lock, flags);
2307         ret = xhci_queue_address_device(xhci, virt_dev->in_ctx->dma,
2308                                         udev->slot_id);
2309         if (ret) {
2310                 spin_unlock_irqrestore(&xhci->lock, flags);
2311                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
2312                 return ret;
2313         }
2314         xhci_ring_cmd_db(xhci);
2315         spin_unlock_irqrestore(&xhci->lock, flags);
2316
2317         /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
2318         timeleft = wait_for_completion_interruptible_timeout(&xhci->addr_dev,
2319                         USB_CTRL_SET_TIMEOUT);
2320         /* FIXME: From section 4.3.4: "Software shall be responsible for timing
2321          * the SetAddress() "recovery interval" required by USB and aborting the
2322          * command on a timeout.
2323          */
2324         if (timeleft <= 0) {
2325                 xhci_warn(xhci, "%s while waiting for a slot\n",
2326                                 timeleft == 0 ? "Timeout" : "Signal");
2327                 /* FIXME cancel the address device command */
2328                 return -ETIME;
2329         }
2330
2331         switch (virt_dev->cmd_status) {
2332         case COMP_CTX_STATE:
2333         case COMP_EBADSLT:
2334                 xhci_err(xhci, "Setup ERROR: address device command for slot %d.\n",
2335                                 udev->slot_id);
2336                 ret = -EINVAL;
2337                 break;
2338         case COMP_TX_ERR:
2339                 dev_warn(&udev->dev, "Device not responding to set address.\n");
2340                 ret = -EPROTO;
2341                 break;
2342         case COMP_SUCCESS:
2343                 xhci_dbg(xhci, "Successful Address Device command\n");
2344                 break;
2345         default:
2346                 xhci_err(xhci, "ERROR: unexpected command completion "
2347                                 "code 0x%x.\n", virt_dev->cmd_status);
2348                 xhci_dbg(xhci, "Slot ID %d Output Context:\n", udev->slot_id);
2349                 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 2);
2350                 ret = -EINVAL;
2351                 break;
2352         }
2353         if (ret) {
2354                 return ret;
2355         }
2356         temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
2357         xhci_dbg(xhci, "Op regs DCBAA ptr = %#016llx\n", temp_64);
2358         xhci_dbg(xhci, "Slot ID %d dcbaa entry @%p = %#016llx\n",
2359                         udev->slot_id,
2360                         &xhci->dcbaa->dev_context_ptrs[udev->slot_id],
2361                         (unsigned long long)
2362                                 xhci->dcbaa->dev_context_ptrs[udev->slot_id]);
2363         xhci_dbg(xhci, "Output Context DMA address = %#08llx\n",
2364                         (unsigned long long)virt_dev->out_ctx->dma);
2365         xhci_dbg(xhci, "Slot ID %d Input Context:\n", udev->slot_id);
2366         xhci_dbg_ctx(xhci, virt_dev->in_ctx, 2);
2367         xhci_dbg(xhci, "Slot ID %d Output Context:\n", udev->slot_id);
2368         xhci_dbg_ctx(xhci, virt_dev->out_ctx, 2);
2369         /*
2370          * USB core uses address 1 for the roothubs, so we add one to the
2371          * address given back to us by the HC.
2372          */
2373         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
2374         udev->devnum = (slot_ctx->dev_state & DEV_ADDR_MASK) + 1;
2375         /* Zero the input context control for later use */
2376         ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx);
2377         ctrl_ctx->add_flags = 0;
2378         ctrl_ctx->drop_flags = 0;
2379
2380         xhci_dbg(xhci, "Device address = %d\n", udev->devnum);
2381         /* XXX Meh, not sure if anyone else but choose_address uses this. */
2382         set_bit(udev->devnum, udev->bus->devmap.devicemap);
2383
2384         return 0;
2385 }
2386
2387 /* Once a hub descriptor is fetched for a device, we need to update the xHC's
2388  * internal data structures for the device.
2389  */
2390 int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
2391                         struct usb_tt *tt, gfp_t mem_flags)
2392 {
2393         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
2394         struct xhci_virt_device *vdev;
2395         struct xhci_command *config_cmd;
2396         struct xhci_input_control_ctx *ctrl_ctx;
2397         struct xhci_slot_ctx *slot_ctx;
2398         unsigned long flags;
2399         unsigned think_time;
2400         int ret;
2401
2402         /* Ignore root hubs */
2403         if (!hdev->parent)
2404                 return 0;
2405
2406         vdev = xhci->devs[hdev->slot_id];
2407         if (!vdev) {
2408                 xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
2409                 return -EINVAL;
2410         }
2411         config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
2412         if (!config_cmd) {
2413                 xhci_dbg(xhci, "Could not allocate xHCI command structure.\n");
2414                 return -ENOMEM;
2415         }
2416
2417         spin_lock_irqsave(&xhci->lock, flags);
2418         xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
2419         ctrl_ctx = xhci_get_input_control_ctx(xhci, config_cmd->in_ctx);
2420         ctrl_ctx->add_flags |= SLOT_FLAG;
2421         slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
2422         slot_ctx->dev_info |= DEV_HUB;
2423         if (tt->multi)
2424                 slot_ctx->dev_info |= DEV_MTT;
2425         if (xhci->hci_version > 0x95) {
2426                 xhci_dbg(xhci, "xHCI version %x needs hub "
2427                                 "TT think time and number of ports\n",
2428                                 (unsigned int) xhci->hci_version);
2429                 slot_ctx->dev_info2 |= XHCI_MAX_PORTS(hdev->maxchild);
2430                 /* Set TT think time - convert from ns to FS bit times.
2431                  * 0 = 8 FS bit times, 1 = 16 FS bit times,
2432                  * 2 = 24 FS bit times, 3 = 32 FS bit times.
2433                  */
2434                 think_time = tt->think_time;
2435                 if (think_time != 0)
2436                         think_time = (think_time / 666) - 1;
2437                 slot_ctx->tt_info |= TT_THINK_TIME(think_time);
2438         } else {
2439                 xhci_dbg(xhci, "xHCI version %x doesn't need hub "
2440                                 "TT think time or number of ports\n",
2441                                 (unsigned int) xhci->hci_version);
2442         }
2443         slot_ctx->dev_state = 0;
2444         spin_unlock_irqrestore(&xhci->lock, flags);
2445
2446         xhci_dbg(xhci, "Set up %s for hub device.\n",
2447                         (xhci->hci_version > 0x95) ?
2448                         "configure endpoint" : "evaluate context");
2449         xhci_dbg(xhci, "Slot %u Input Context:\n", hdev->slot_id);
2450         xhci_dbg_ctx(xhci, config_cmd->in_ctx, 0);
2451
2452         /* Issue and wait for the configure endpoint or
2453          * evaluate context command.
2454          */
2455         if (xhci->hci_version > 0x95)
2456                 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
2457                                 false, false);
2458         else
2459                 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
2460                                 true, false);
2461
2462         xhci_dbg(xhci, "Slot %u Output Context:\n", hdev->slot_id);
2463         xhci_dbg_ctx(xhci, vdev->out_ctx, 0);
2464
2465         xhci_free_command(xhci, config_cmd);
2466         return ret;
2467 }
2468
2469 int xhci_get_frame(struct usb_hcd *hcd)
2470 {
2471         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
2472         /* EHCI mods by the periodic size.  Why? */
2473         return xhci_readl(xhci, &xhci->run_regs->microframe_index) >> 3;
2474 }
2475
2476 MODULE_DESCRIPTION(DRIVER_DESC);
2477 MODULE_AUTHOR(DRIVER_AUTHOR);
2478 MODULE_LICENSE("GPL");
2479
2480 static int __init xhci_hcd_init(void)
2481 {
2482 #ifdef CONFIG_PCI
2483         int retval = 0;
2484
2485         retval = xhci_register_pci();
2486
2487         if (retval < 0) {
2488                 printk(KERN_DEBUG "Problem registering PCI driver.");
2489                 return retval;
2490         }
2491 #endif
2492         /*
2493          * Check the compiler generated sizes of structures that must be laid
2494          * out in specific ways for hardware access.
2495          */
2496         BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
2497         BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
2498         BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
2499         /* xhci_device_control has eight fields, and also
2500          * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
2501          */
2502         BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
2503         BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
2504         BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
2505         BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 7*32/8);
2506         BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
2507         /* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
2508         BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
2509         BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
2510         return 0;
2511 }
2512 module_init(xhci_hcd_init);
2513
2514 static void __exit xhci_hcd_cleanup(void)
2515 {
2516 #ifdef CONFIG_PCI
2517         xhci_unregister_pci();
2518 #endif
2519 }
2520 module_exit(xhci_hcd_cleanup);