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