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