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