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