Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/net
[pandora-kernel.git] / drivers / usb / host / xhci.c
1 /*
2  * xHCI host controller driver
3  *
4  * Copyright (C) 2008 Intel Corp.
5  *
6  * Author: Sarah Sharp
7  * Some code borrowed from the Linux EHCI driver.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16  * for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22
23 #include <linux/pci.h>
24 #include <linux/irq.h>
25 #include <linux/log2.h>
26 #include <linux/module.h>
27 #include <linux/moduleparam.h>
28 #include <linux/slab.h>
29
30 #include "xhci.h"
31
32 #define DRIVER_AUTHOR "Sarah Sharp"
33 #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
34
35 /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
36 static int link_quirk;
37 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
38 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
39
40 /* TODO: copied from ehci-hcd.c - can this be refactored? */
41 /*
42  * handshake - spin reading hc until handshake completes or fails
43  * @ptr: address of hc register to be read
44  * @mask: bits to look at in result of read
45  * @done: value of those bits when handshake succeeds
46  * @usec: timeout in microseconds
47  *
48  * Returns negative errno, or zero on success
49  *
50  * Success happens when the "mask" bits have the specified value (hardware
51  * handshake done).  There are two failure modes:  "usec" have passed (major
52  * hardware flakeout), or the register reads as all-ones (hardware removed).
53  */
54 static int handshake(struct xhci_hcd *xhci, void __iomem *ptr,
55                       u32 mask, u32 done, int usec)
56 {
57         u32     result;
58
59         do {
60                 result = xhci_readl(xhci, ptr);
61                 if (result == ~(u32)0)          /* card removed */
62                         return -ENODEV;
63                 result &= mask;
64                 if (result == done)
65                         return 0;
66                 udelay(1);
67                 usec--;
68         } while (usec > 0);
69         return -ETIMEDOUT;
70 }
71
72 /*
73  * Disable interrupts and begin the xHCI halting process.
74  */
75 void xhci_quiesce(struct xhci_hcd *xhci)
76 {
77         u32 halted;
78         u32 cmd;
79         u32 mask;
80
81         mask = ~(XHCI_IRQS);
82         halted = xhci_readl(xhci, &xhci->op_regs->status) & STS_HALT;
83         if (!halted)
84                 mask &= ~CMD_RUN;
85
86         cmd = xhci_readl(xhci, &xhci->op_regs->command);
87         cmd &= mask;
88         xhci_writel(xhci, cmd, &xhci->op_regs->command);
89 }
90
91 /*
92  * Force HC into halt state.
93  *
94  * Disable any IRQs and clear the run/stop bit.
95  * HC will complete any current and actively pipelined transactions, and
96  * should halt within 16 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         int ret;
102         xhci_dbg(xhci, "// Halt the HC\n");
103         xhci_quiesce(xhci);
104
105         ret = handshake(xhci, &xhci->op_regs->status,
106                         STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
107         if (!ret)
108                 xhci->xhc_state |= XHCI_STATE_HALTED;
109         return ret;
110 }
111
112 /*
113  * Set the run bit and wait for the host to be running.
114  */
115 static int xhci_start(struct xhci_hcd *xhci)
116 {
117         u32 temp;
118         int ret;
119
120         temp = xhci_readl(xhci, &xhci->op_regs->command);
121         temp |= (CMD_RUN);
122         xhci_dbg(xhci, "// Turn on HC, cmd = 0x%x.\n",
123                         temp);
124         xhci_writel(xhci, temp, &xhci->op_regs->command);
125
126         /*
127          * Wait for the HCHalted Status bit to be 0 to indicate the host is
128          * running.
129          */
130         ret = handshake(xhci, &xhci->op_regs->status,
131                         STS_HALT, 0, XHCI_MAX_HALT_USEC);
132         if (ret == -ETIMEDOUT)
133                 xhci_err(xhci, "Host took too long to start, "
134                                 "waited %u microseconds.\n",
135                                 XHCI_MAX_HALT_USEC);
136         if (!ret)
137                 xhci->xhc_state &= ~XHCI_STATE_HALTED;
138         return ret;
139 }
140
141 /*
142  * Reset a halted HC.
143  *
144  * This resets pipelines, timers, counters, state machines, etc.
145  * Transactions will be terminated immediately, and operational registers
146  * will be set to their defaults.
147  */
148 int xhci_reset(struct xhci_hcd *xhci)
149 {
150         u32 command;
151         u32 state;
152         int ret;
153
154         state = xhci_readl(xhci, &xhci->op_regs->status);
155         if ((state & STS_HALT) == 0) {
156                 xhci_warn(xhci, "Host controller not halted, aborting reset.\n");
157                 return 0;
158         }
159
160         xhci_dbg(xhci, "// Reset the HC\n");
161         command = xhci_readl(xhci, &xhci->op_regs->command);
162         command |= CMD_RESET;
163         xhci_writel(xhci, command, &xhci->op_regs->command);
164
165         ret = handshake(xhci, &xhci->op_regs->command,
166                         CMD_RESET, 0, 250 * 1000);
167         if (ret)
168                 return ret;
169
170         xhci_dbg(xhci, "Wait for controller to be ready for doorbell rings\n");
171         /*
172          * xHCI cannot write to any doorbells or operational registers other
173          * than status until the "Controller Not Ready" flag is cleared.
174          */
175         return handshake(xhci, &xhci->op_regs->status, STS_CNR, 0, 250 * 1000);
176 }
177
178 #ifdef CONFIG_PCI
179 static int xhci_free_msi(struct xhci_hcd *xhci)
180 {
181         int i;
182
183         if (!xhci->msix_entries)
184                 return -EINVAL;
185
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         return 0;
191 }
192
193 /*
194  * Set up MSI
195  */
196 static int xhci_setup_msi(struct xhci_hcd *xhci)
197 {
198         int ret;
199         struct pci_dev  *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
200
201         ret = pci_enable_msi(pdev);
202         if (ret) {
203                 xhci_err(xhci, "failed to allocate MSI entry\n");
204                 return ret;
205         }
206
207         ret = request_irq(pdev->irq, (irq_handler_t)xhci_msi_irq,
208                                 0, "xhci_hcd", xhci_to_hcd(xhci));
209         if (ret) {
210                 xhci_err(xhci, "disable MSI interrupt\n");
211                 pci_disable_msi(pdev);
212         }
213
214         return ret;
215 }
216
217 /*
218  * Free IRQs
219  * free all IRQs request
220  */
221 static void xhci_free_irq(struct xhci_hcd *xhci)
222 {
223         struct pci_dev *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
224         int ret;
225
226         /* return if using legacy interrupt */
227         if (xhci_to_hcd(xhci)->irq >= 0)
228                 return;
229
230         ret = xhci_free_msi(xhci);
231         if (!ret)
232                 return;
233         if (pdev->irq >= 0)
234                 free_irq(pdev->irq, xhci_to_hcd(xhci));
235
236         return;
237 }
238
239 /*
240  * Set up MSI-X
241  */
242 static int xhci_setup_msix(struct xhci_hcd *xhci)
243 {
244         int i, ret = 0;
245         struct usb_hcd *hcd = xhci_to_hcd(xhci);
246         struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
247
248         /*
249          * calculate number of msi-x vectors supported.
250          * - HCS_MAX_INTRS: the max number of interrupts the host can handle,
251          *   with max number of interrupters based on the xhci HCSPARAMS1.
252          * - num_online_cpus: maximum msi-x vectors per CPUs core.
253          *   Add additional 1 vector to ensure always available interrupt.
254          */
255         xhci->msix_count = min(num_online_cpus() + 1,
256                                 HCS_MAX_INTRS(xhci->hcs_params1));
257
258         xhci->msix_entries =
259                 kmalloc((sizeof(struct msix_entry))*xhci->msix_count,
260                                 GFP_KERNEL);
261         if (!xhci->msix_entries) {
262                 xhci_err(xhci, "Failed to allocate MSI-X entries\n");
263                 return -ENOMEM;
264         }
265
266         for (i = 0; i < xhci->msix_count; i++) {
267                 xhci->msix_entries[i].entry = i;
268                 xhci->msix_entries[i].vector = 0;
269         }
270
271         ret = pci_enable_msix(pdev, xhci->msix_entries, xhci->msix_count);
272         if (ret) {
273                 xhci_err(xhci, "Failed to enable MSI-X\n");
274                 goto free_entries;
275         }
276
277         for (i = 0; i < xhci->msix_count; i++) {
278                 ret = request_irq(xhci->msix_entries[i].vector,
279                                 (irq_handler_t)xhci_msi_irq,
280                                 0, "xhci_hcd", xhci_to_hcd(xhci));
281                 if (ret)
282                         goto disable_msix;
283         }
284
285         hcd->msix_enabled = 1;
286         return ret;
287
288 disable_msix:
289         xhci_err(xhci, "disable MSI-X interrupt\n");
290         xhci_free_irq(xhci);
291         pci_disable_msix(pdev);
292 free_entries:
293         kfree(xhci->msix_entries);
294         xhci->msix_entries = NULL;
295         return ret;
296 }
297
298 /* Free any IRQs and disable MSI-X */
299 static void xhci_cleanup_msix(struct xhci_hcd *xhci)
300 {
301         struct usb_hcd *hcd = xhci_to_hcd(xhci);
302         struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
303
304         xhci_free_irq(xhci);
305
306         if (xhci->msix_entries) {
307                 pci_disable_msix(pdev);
308                 kfree(xhci->msix_entries);
309                 xhci->msix_entries = NULL;
310         } else {
311                 pci_disable_msi(pdev);
312         }
313
314         hcd->msix_enabled = 0;
315         return;
316 }
317
318 static void xhci_msix_sync_irqs(struct xhci_hcd *xhci)
319 {
320         int i;
321
322         if (xhci->msix_entries) {
323                 for (i = 0; i < xhci->msix_count; i++)
324                         synchronize_irq(xhci->msix_entries[i].vector);
325         }
326 }
327
328 static int xhci_try_enable_msi(struct usb_hcd *hcd)
329 {
330         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
331         struct pci_dev  *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
332         int ret;
333
334         /*
335          * Some Fresco Logic host controllers advertise MSI, but fail to
336          * generate interrupts.  Don't even try to enable MSI.
337          */
338         if (xhci->quirks & XHCI_BROKEN_MSI)
339                 return 0;
340
341         /* unregister the legacy interrupt */
342         if (hcd->irq)
343                 free_irq(hcd->irq, hcd);
344         hcd->irq = -1;
345
346         ret = xhci_setup_msix(xhci);
347         if (ret)
348                 /* fall back to msi*/
349                 ret = xhci_setup_msi(xhci);
350
351         if (!ret)
352                 /* hcd->irq is -1, we have MSI */
353                 return 0;
354
355         /* fall back to legacy interrupt*/
356         ret = request_irq(pdev->irq, &usb_hcd_irq, IRQF_SHARED,
357                         hcd->irq_descr, hcd);
358         if (ret) {
359                 xhci_err(xhci, "request interrupt %d failed\n",
360                                 pdev->irq);
361                 return ret;
362         }
363         hcd->irq = pdev->irq;
364         return 0;
365 }
366
367 #else
368
369 static int xhci_try_enable_msi(struct usb_hcd *hcd)
370 {
371         return 0;
372 }
373
374 static void xhci_cleanup_msix(struct xhci_hcd *xhci)
375 {
376 }
377
378 static void xhci_msix_sync_irqs(struct xhci_hcd *xhci)
379 {
380 }
381
382 #endif
383
384 /*
385  * Initialize memory for HCD and xHC (one-time init).
386  *
387  * Program the PAGESIZE register, initialize the device context array, create
388  * device contexts (?), set up a command ring segment (or two?), create event
389  * ring (one for now).
390  */
391 int xhci_init(struct usb_hcd *hcd)
392 {
393         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
394         int retval = 0;
395
396         xhci_dbg(xhci, "xhci_init\n");
397         spin_lock_init(&xhci->lock);
398         if (xhci->hci_version == 0x95 && link_quirk) {
399                 xhci_dbg(xhci, "QUIRK: Not clearing Link TRB chain bits.\n");
400                 xhci->quirks |= XHCI_LINK_TRB_QUIRK;
401         } else {
402                 xhci_dbg(xhci, "xHCI doesn't need link TRB QUIRK\n");
403         }
404         retval = xhci_mem_init(xhci, GFP_KERNEL);
405         xhci_dbg(xhci, "Finished xhci_init\n");
406
407         return retval;
408 }
409
410 /*-------------------------------------------------------------------------*/
411
412
413 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
414 static void xhci_event_ring_work(unsigned long arg)
415 {
416         unsigned long flags;
417         int temp;
418         u64 temp_64;
419         struct xhci_hcd *xhci = (struct xhci_hcd *) arg;
420         int i, j;
421
422         xhci_dbg(xhci, "Poll event ring: %lu\n", jiffies);
423
424         spin_lock_irqsave(&xhci->lock, flags);
425         temp = xhci_readl(xhci, &xhci->op_regs->status);
426         xhci_dbg(xhci, "op reg status = 0x%x\n", temp);
427         if (temp == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
428                         (xhci->xhc_state & XHCI_STATE_HALTED)) {
429                 xhci_dbg(xhci, "HW died, polling stopped.\n");
430                 spin_unlock_irqrestore(&xhci->lock, flags);
431                 return;
432         }
433
434         temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
435         xhci_dbg(xhci, "ir_set 0 pending = 0x%x\n", temp);
436         xhci_dbg(xhci, "HC error bitmask = 0x%x\n", xhci->error_bitmask);
437         xhci->error_bitmask = 0;
438         xhci_dbg(xhci, "Event ring:\n");
439         xhci_debug_segment(xhci, xhci->event_ring->deq_seg);
440         xhci_dbg_ring_ptrs(xhci, xhci->event_ring);
441         temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
442         temp_64 &= ~ERST_PTR_MASK;
443         xhci_dbg(xhci, "ERST deq = 64'h%0lx\n", (long unsigned int) temp_64);
444         xhci_dbg(xhci, "Command ring:\n");
445         xhci_debug_segment(xhci, xhci->cmd_ring->deq_seg);
446         xhci_dbg_ring_ptrs(xhci, xhci->cmd_ring);
447         xhci_dbg_cmd_ptrs(xhci);
448         for (i = 0; i < MAX_HC_SLOTS; ++i) {
449                 if (!xhci->devs[i])
450                         continue;
451                 for (j = 0; j < 31; ++j) {
452                         xhci_dbg_ep_rings(xhci, i, j, &xhci->devs[i]->eps[j]);
453                 }
454         }
455         spin_unlock_irqrestore(&xhci->lock, flags);
456
457         if (!xhci->zombie)
458                 mod_timer(&xhci->event_ring_timer, jiffies + POLL_TIMEOUT * HZ);
459         else
460                 xhci_dbg(xhci, "Quit polling the event ring.\n");
461 }
462 #endif
463
464 static int xhci_run_finished(struct xhci_hcd *xhci)
465 {
466         if (xhci_start(xhci)) {
467                 xhci_halt(xhci);
468                 return -ENODEV;
469         }
470         xhci->shared_hcd->state = HC_STATE_RUNNING;
471
472         if (xhci->quirks & XHCI_NEC_HOST)
473                 xhci_ring_cmd_db(xhci);
474
475         xhci_dbg(xhci, "Finished xhci_run for USB3 roothub\n");
476         return 0;
477 }
478
479 /*
480  * Start the HC after it was halted.
481  *
482  * This function is called by the USB core when the HC driver is added.
483  * Its opposite is xhci_stop().
484  *
485  * xhci_init() must be called once before this function can be called.
486  * Reset the HC, enable device slot contexts, program DCBAAP, and
487  * set command ring pointer and event ring pointer.
488  *
489  * Setup MSI-X vectors and enable interrupts.
490  */
491 int xhci_run(struct usb_hcd *hcd)
492 {
493         u32 temp;
494         u64 temp_64;
495         int ret;
496         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
497
498         /* Start the xHCI host controller running only after the USB 2.0 roothub
499          * is setup.
500          */
501
502         hcd->uses_new_polling = 1;
503         if (!usb_hcd_is_primary_hcd(hcd))
504                 return xhci_run_finished(xhci);
505
506         xhci_dbg(xhci, "xhci_run\n");
507
508         ret = xhci_try_enable_msi(hcd);
509         if (ret)
510                 return ret;
511
512 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
513         init_timer(&xhci->event_ring_timer);
514         xhci->event_ring_timer.data = (unsigned long) xhci;
515         xhci->event_ring_timer.function = xhci_event_ring_work;
516         /* Poll the event ring */
517         xhci->event_ring_timer.expires = jiffies + POLL_TIMEOUT * HZ;
518         xhci->zombie = 0;
519         xhci_dbg(xhci, "Setting event ring polling timer\n");
520         add_timer(&xhci->event_ring_timer);
521 #endif
522
523         xhci_dbg(xhci, "Command ring memory map follows:\n");
524         xhci_debug_ring(xhci, xhci->cmd_ring);
525         xhci_dbg_ring_ptrs(xhci, xhci->cmd_ring);
526         xhci_dbg_cmd_ptrs(xhci);
527
528         xhci_dbg(xhci, "ERST memory map follows:\n");
529         xhci_dbg_erst(xhci, &xhci->erst);
530         xhci_dbg(xhci, "Event ring:\n");
531         xhci_debug_ring(xhci, xhci->event_ring);
532         xhci_dbg_ring_ptrs(xhci, xhci->event_ring);
533         temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
534         temp_64 &= ~ERST_PTR_MASK;
535         xhci_dbg(xhci, "ERST deq = 64'h%0lx\n", (long unsigned int) temp_64);
536
537         xhci_dbg(xhci, "// Set the interrupt modulation register\n");
538         temp = xhci_readl(xhci, &xhci->ir_set->irq_control);
539         temp &= ~ER_IRQ_INTERVAL_MASK;
540         temp |= (u32) 160;
541         xhci_writel(xhci, temp, &xhci->ir_set->irq_control);
542
543         /* Set the HCD state before we enable the irqs */
544         temp = xhci_readl(xhci, &xhci->op_regs->command);
545         temp |= (CMD_EIE);
546         xhci_dbg(xhci, "// Enable interrupts, cmd = 0x%x.\n",
547                         temp);
548         xhci_writel(xhci, temp, &xhci->op_regs->command);
549
550         temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
551         xhci_dbg(xhci, "// Enabling event ring interrupter %p by writing 0x%x to irq_pending\n",
552                         xhci->ir_set, (unsigned int) ER_IRQ_ENABLE(temp));
553         xhci_writel(xhci, ER_IRQ_ENABLE(temp),
554                         &xhci->ir_set->irq_pending);
555         xhci_print_ir_set(xhci, 0);
556
557         if (xhci->quirks & XHCI_NEC_HOST)
558                 xhci_queue_vendor_command(xhci, 0, 0, 0,
559                                 TRB_TYPE(TRB_NEC_GET_FW));
560
561         xhci_dbg(xhci, "Finished xhci_run for USB2 roothub\n");
562         return 0;
563 }
564
565 static void xhci_only_stop_hcd(struct usb_hcd *hcd)
566 {
567         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
568
569         spin_lock_irq(&xhci->lock);
570         xhci_halt(xhci);
571
572         /* The shared_hcd is going to be deallocated shortly (the USB core only
573          * calls this function when allocation fails in usb_add_hcd(), or
574          * usb_remove_hcd() is called).  So we need to unset xHCI's pointer.
575          */
576         xhci->shared_hcd = NULL;
577         spin_unlock_irq(&xhci->lock);
578 }
579
580 /*
581  * Stop xHCI driver.
582  *
583  * This function is called by the USB core when the HC driver is removed.
584  * Its opposite is xhci_run().
585  *
586  * Disable device contexts, disable IRQs, and quiesce the HC.
587  * Reset the HC, finish any completed transactions, and cleanup memory.
588  */
589 void xhci_stop(struct usb_hcd *hcd)
590 {
591         u32 temp;
592         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
593
594         if (!usb_hcd_is_primary_hcd(hcd)) {
595                 xhci_only_stop_hcd(xhci->shared_hcd);
596                 return;
597         }
598
599         spin_lock_irq(&xhci->lock);
600         /* Make sure the xHC is halted for a USB3 roothub
601          * (xhci_stop() could be called as part of failed init).
602          */
603         xhci_halt(xhci);
604         xhci_reset(xhci);
605         spin_unlock_irq(&xhci->lock);
606
607         xhci_cleanup_msix(xhci);
608
609 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
610         /* Tell the event ring poll function not to reschedule */
611         xhci->zombie = 1;
612         del_timer_sync(&xhci->event_ring_timer);
613 #endif
614
615         if (xhci->quirks & XHCI_AMD_PLL_FIX)
616                 usb_amd_dev_put();
617
618         xhci_dbg(xhci, "// Disabling event ring interrupts\n");
619         temp = xhci_readl(xhci, &xhci->op_regs->status);
620         xhci_writel(xhci, temp & ~STS_EINT, &xhci->op_regs->status);
621         temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
622         xhci_writel(xhci, ER_IRQ_DISABLE(temp),
623                         &xhci->ir_set->irq_pending);
624         xhci_print_ir_set(xhci, 0);
625
626         xhci_dbg(xhci, "cleaning up memory\n");
627         xhci_mem_cleanup(xhci);
628         xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
629                     xhci_readl(xhci, &xhci->op_regs->status));
630 }
631
632 /*
633  * Shutdown HC (not bus-specific)
634  *
635  * This is called when the machine is rebooting or halting.  We assume that the
636  * machine will be powered off, and the HC's internal state will be reset.
637  * Don't bother to free memory.
638  *
639  * This will only ever be called with the main usb_hcd (the USB3 roothub).
640  */
641 void xhci_shutdown(struct usb_hcd *hcd)
642 {
643         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
644
645         spin_lock_irq(&xhci->lock);
646         xhci_halt(xhci);
647         spin_unlock_irq(&xhci->lock);
648
649         xhci_cleanup_msix(xhci);
650
651         xhci_dbg(xhci, "xhci_shutdown completed - status = %x\n",
652                     xhci_readl(xhci, &xhci->op_regs->status));
653 }
654
655 #ifdef CONFIG_PM
656 static void xhci_save_registers(struct xhci_hcd *xhci)
657 {
658         xhci->s3.command = xhci_readl(xhci, &xhci->op_regs->command);
659         xhci->s3.dev_nt = xhci_readl(xhci, &xhci->op_regs->dev_notification);
660         xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
661         xhci->s3.config_reg = xhci_readl(xhci, &xhci->op_regs->config_reg);
662         xhci->s3.irq_pending = xhci_readl(xhci, &xhci->ir_set->irq_pending);
663         xhci->s3.irq_control = xhci_readl(xhci, &xhci->ir_set->irq_control);
664         xhci->s3.erst_size = xhci_readl(xhci, &xhci->ir_set->erst_size);
665         xhci->s3.erst_base = xhci_read_64(xhci, &xhci->ir_set->erst_base);
666         xhci->s3.erst_dequeue = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
667 }
668
669 static void xhci_restore_registers(struct xhci_hcd *xhci)
670 {
671         xhci_writel(xhci, xhci->s3.command, &xhci->op_regs->command);
672         xhci_writel(xhci, xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
673         xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
674         xhci_writel(xhci, xhci->s3.config_reg, &xhci->op_regs->config_reg);
675         xhci_writel(xhci, xhci->s3.irq_pending, &xhci->ir_set->irq_pending);
676         xhci_writel(xhci, xhci->s3.irq_control, &xhci->ir_set->irq_control);
677         xhci_writel(xhci, xhci->s3.erst_size, &xhci->ir_set->erst_size);
678         xhci_write_64(xhci, xhci->s3.erst_base, &xhci->ir_set->erst_base);
679 }
680
681 static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
682 {
683         u64     val_64;
684
685         /* step 2: initialize command ring buffer */
686         val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
687         val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
688                 (xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
689                                       xhci->cmd_ring->dequeue) &
690                  (u64) ~CMD_RING_RSVD_BITS) |
691                 xhci->cmd_ring->cycle_state;
692         xhci_dbg(xhci, "// Setting command ring address to 0x%llx\n",
693                         (long unsigned long) val_64);
694         xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
695 }
696
697 /*
698  * The whole command ring must be cleared to zero when we suspend the host.
699  *
700  * The host doesn't save the command ring pointer in the suspend well, so we
701  * need to re-program it on resume.  Unfortunately, the pointer must be 64-byte
702  * aligned, because of the reserved bits in the command ring dequeue pointer
703  * register.  Therefore, we can't just set the dequeue pointer back in the
704  * middle of the ring (TRBs are 16-byte aligned).
705  */
706 static void xhci_clear_command_ring(struct xhci_hcd *xhci)
707 {
708         struct xhci_ring *ring;
709         struct xhci_segment *seg;
710
711         ring = xhci->cmd_ring;
712         seg = ring->deq_seg;
713         do {
714                 memset(seg->trbs, 0, SEGMENT_SIZE);
715                 seg = seg->next;
716         } while (seg != ring->deq_seg);
717
718         /* Reset the software enqueue and dequeue pointers */
719         ring->deq_seg = ring->first_seg;
720         ring->dequeue = ring->first_seg->trbs;
721         ring->enq_seg = ring->deq_seg;
722         ring->enqueue = ring->dequeue;
723
724         /*
725          * Ring is now zeroed, so the HW should look for change of ownership
726          * when the cycle bit is set to 1.
727          */
728         ring->cycle_state = 1;
729
730         /*
731          * Reset the hardware dequeue pointer.
732          * Yes, this will need to be re-written after resume, but we're paranoid
733          * and want to make sure the hardware doesn't access bogus memory
734          * because, say, the BIOS or an SMI started the host without changing
735          * the command ring pointers.
736          */
737         xhci_set_cmd_ring_deq(xhci);
738 }
739
740 /*
741  * Stop HC (not bus-specific)
742  *
743  * This is called when the machine transition into S3/S4 mode.
744  *
745  */
746 int xhci_suspend(struct xhci_hcd *xhci)
747 {
748         int                     rc = 0;
749         struct usb_hcd          *hcd = xhci_to_hcd(xhci);
750         u32                     command;
751
752         spin_lock_irq(&xhci->lock);
753         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
754         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
755         /* step 1: stop endpoint */
756         /* skipped assuming that port suspend has done */
757
758         /* step 2: clear Run/Stop bit */
759         command = xhci_readl(xhci, &xhci->op_regs->command);
760         command &= ~CMD_RUN;
761         xhci_writel(xhci, command, &xhci->op_regs->command);
762         if (handshake(xhci, &xhci->op_regs->status,
763                       STS_HALT, STS_HALT, 100*100)) {
764                 xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
765                 spin_unlock_irq(&xhci->lock);
766                 return -ETIMEDOUT;
767         }
768         xhci_clear_command_ring(xhci);
769
770         /* step 3: save registers */
771         xhci_save_registers(xhci);
772
773         /* step 4: set CSS flag */
774         command = xhci_readl(xhci, &xhci->op_regs->command);
775         command |= CMD_CSS;
776         xhci_writel(xhci, command, &xhci->op_regs->command);
777         if (handshake(xhci, &xhci->op_regs->status, STS_SAVE, 0, 10*100)) {
778                 xhci_warn(xhci, "WARN: xHC CMD_CSS timeout\n");
779                 spin_unlock_irq(&xhci->lock);
780                 return -ETIMEDOUT;
781         }
782         spin_unlock_irq(&xhci->lock);
783
784         /* step 5: remove core well power */
785         /* synchronize irq when using MSI-X */
786         xhci_msix_sync_irqs(xhci);
787
788         return rc;
789 }
790
791 /*
792  * start xHC (not bus-specific)
793  *
794  * This is called when the machine transition from S3/S4 mode.
795  *
796  */
797 int xhci_resume(struct xhci_hcd *xhci, bool hibernated)
798 {
799         u32                     command, temp = 0;
800         struct usb_hcd          *hcd = xhci_to_hcd(xhci);
801         struct usb_hcd          *secondary_hcd;
802         int                     retval = 0;
803
804         /* Wait a bit if either of the roothubs need to settle from the
805          * transition into bus suspend.
806          */
807         if (time_before(jiffies, xhci->bus_state[0].next_statechange) ||
808                         time_before(jiffies,
809                                 xhci->bus_state[1].next_statechange))
810                 msleep(100);
811
812         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
813         set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
814
815         spin_lock_irq(&xhci->lock);
816         if (xhci->quirks & XHCI_RESET_ON_RESUME)
817                 hibernated = true;
818
819         if (!hibernated) {
820                 /* step 1: restore register */
821                 xhci_restore_registers(xhci);
822                 /* step 2: initialize command ring buffer */
823                 xhci_set_cmd_ring_deq(xhci);
824                 /* step 3: restore state and start state*/
825                 /* step 3: set CRS flag */
826                 command = xhci_readl(xhci, &xhci->op_regs->command);
827                 command |= CMD_CRS;
828                 xhci_writel(xhci, command, &xhci->op_regs->command);
829                 if (handshake(xhci, &xhci->op_regs->status,
830                               STS_RESTORE, 0, 10*100)) {
831                         xhci_dbg(xhci, "WARN: xHC CMD_CSS timeout\n");
832                         spin_unlock_irq(&xhci->lock);
833                         return -ETIMEDOUT;
834                 }
835                 temp = xhci_readl(xhci, &xhci->op_regs->status);
836         }
837
838         /* If restore operation fails, re-initialize the HC during resume */
839         if ((temp & STS_SRE) || hibernated) {
840                 /* Let the USB core know _both_ roothubs lost power. */
841                 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
842                 usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
843
844                 xhci_dbg(xhci, "Stop HCD\n");
845                 xhci_halt(xhci);
846                 xhci_reset(xhci);
847                 spin_unlock_irq(&xhci->lock);
848                 xhci_cleanup_msix(xhci);
849
850 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
851                 /* Tell the event ring poll function not to reschedule */
852                 xhci->zombie = 1;
853                 del_timer_sync(&xhci->event_ring_timer);
854 #endif
855
856                 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
857                 temp = xhci_readl(xhci, &xhci->op_regs->status);
858                 xhci_writel(xhci, temp & ~STS_EINT, &xhci->op_regs->status);
859                 temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
860                 xhci_writel(xhci, ER_IRQ_DISABLE(temp),
861                                 &xhci->ir_set->irq_pending);
862                 xhci_print_ir_set(xhci, 0);
863
864                 xhci_dbg(xhci, "cleaning up memory\n");
865                 xhci_mem_cleanup(xhci);
866                 xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
867                             xhci_readl(xhci, &xhci->op_regs->status));
868
869                 /* USB core calls the PCI reinit and start functions twice:
870                  * first with the primary HCD, and then with the secondary HCD.
871                  * If we don't do the same, the host will never be started.
872                  */
873                 if (!usb_hcd_is_primary_hcd(hcd))
874                         secondary_hcd = hcd;
875                 else
876                         secondary_hcd = xhci->shared_hcd;
877
878                 xhci_dbg(xhci, "Initialize the xhci_hcd\n");
879                 retval = xhci_init(hcd->primary_hcd);
880                 if (retval)
881                         return retval;
882                 xhci_dbg(xhci, "Start the primary HCD\n");
883                 retval = xhci_run(hcd->primary_hcd);
884                 if (!retval) {
885                         xhci_dbg(xhci, "Start the secondary HCD\n");
886                         retval = xhci_run(secondary_hcd);
887                 }
888                 hcd->state = HC_STATE_SUSPENDED;
889                 xhci->shared_hcd->state = HC_STATE_SUSPENDED;
890                 goto done;
891         }
892
893         /* step 4: set Run/Stop bit */
894         command = xhci_readl(xhci, &xhci->op_regs->command);
895         command |= CMD_RUN;
896         xhci_writel(xhci, command, &xhci->op_regs->command);
897         handshake(xhci, &xhci->op_regs->status, STS_HALT,
898                   0, 250 * 1000);
899
900         /* step 5: walk topology and initialize portsc,
901          * portpmsc and portli
902          */
903         /* this is done in bus_resume */
904
905         /* step 6: restart each of the previously
906          * Running endpoints by ringing their doorbells
907          */
908
909         spin_unlock_irq(&xhci->lock);
910
911  done:
912         if (retval == 0) {
913                 usb_hcd_resume_root_hub(hcd);
914                 usb_hcd_resume_root_hub(xhci->shared_hcd);
915         }
916         return retval;
917 }
918 #endif  /* CONFIG_PM */
919
920 /*-------------------------------------------------------------------------*/
921
922 /**
923  * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
924  * HCDs.  Find the index for an endpoint given its descriptor.  Use the return
925  * value to right shift 1 for the bitmask.
926  *
927  * Index  = (epnum * 2) + direction - 1,
928  * where direction = 0 for OUT, 1 for IN.
929  * For control endpoints, the IN index is used (OUT index is unused), so
930  * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
931  */
932 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
933 {
934         unsigned int index;
935         if (usb_endpoint_xfer_control(desc))
936                 index = (unsigned int) (usb_endpoint_num(desc)*2);
937         else
938                 index = (unsigned int) (usb_endpoint_num(desc)*2) +
939                         (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
940         return index;
941 }
942
943 /* Find the flag for this endpoint (for use in the control context).  Use the
944  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
945  * bit 1, etc.
946  */
947 unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
948 {
949         return 1 << (xhci_get_endpoint_index(desc) + 1);
950 }
951
952 /* Find the flag for this endpoint (for use in the control context).  Use the
953  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
954  * bit 1, etc.
955  */
956 unsigned int xhci_get_endpoint_flag_from_index(unsigned int ep_index)
957 {
958         return 1 << (ep_index + 1);
959 }
960
961 /* Compute the last valid endpoint context index.  Basically, this is the
962  * endpoint index plus one.  For slot contexts with more than valid endpoint,
963  * we find the most significant bit set in the added contexts flags.
964  * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
965  * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
966  */
967 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
968 {
969         return fls(added_ctxs) - 1;
970 }
971
972 /* Returns 1 if the arguments are OK;
973  * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
974  */
975 static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
976                 struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
977                 const char *func) {
978         struct xhci_hcd *xhci;
979         struct xhci_virt_device *virt_dev;
980
981         if (!hcd || (check_ep && !ep) || !udev) {
982                 printk(KERN_DEBUG "xHCI %s called with invalid args\n",
983                                 func);
984                 return -EINVAL;
985         }
986         if (!udev->parent) {
987                 printk(KERN_DEBUG "xHCI %s called for root hub\n",
988                                 func);
989                 return 0;
990         }
991
992         xhci = hcd_to_xhci(hcd);
993         if (xhci->xhc_state & XHCI_STATE_HALTED)
994                 return -ENODEV;
995
996         if (check_virt_dev) {
997                 if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
998                         printk(KERN_DEBUG "xHCI %s called with unaddressed "
999                                                 "device\n", func);
1000                         return -EINVAL;
1001                 }
1002
1003                 virt_dev = xhci->devs[udev->slot_id];
1004                 if (virt_dev->udev != udev) {
1005                         printk(KERN_DEBUG "xHCI %s called with udev and "
1006                                           "virt_dev does not match\n", func);
1007                         return -EINVAL;
1008                 }
1009         }
1010
1011         return 1;
1012 }
1013
1014 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1015                 struct usb_device *udev, struct xhci_command *command,
1016                 bool ctx_change, bool must_succeed);
1017
1018 /*
1019  * Full speed devices may have a max packet size greater than 8 bytes, but the
1020  * USB core doesn't know that until it reads the first 8 bytes of the
1021  * descriptor.  If the usb_device's max packet size changes after that point,
1022  * we need to issue an evaluate context command and wait on it.
1023  */
1024 static int xhci_check_maxpacket(struct xhci_hcd *xhci, unsigned int slot_id,
1025                 unsigned int ep_index, struct urb *urb)
1026 {
1027         struct xhci_container_ctx *in_ctx;
1028         struct xhci_container_ctx *out_ctx;
1029         struct xhci_input_control_ctx *ctrl_ctx;
1030         struct xhci_ep_ctx *ep_ctx;
1031         int max_packet_size;
1032         int hw_max_packet_size;
1033         int ret = 0;
1034
1035         out_ctx = xhci->devs[slot_id]->out_ctx;
1036         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1037         hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1038         max_packet_size = usb_endpoint_maxp(&urb->dev->ep0.desc);
1039         if (hw_max_packet_size != max_packet_size) {
1040                 xhci_dbg(xhci, "Max Packet Size for ep 0 changed.\n");
1041                 xhci_dbg(xhci, "Max packet size in usb_device = %d\n",
1042                                 max_packet_size);
1043                 xhci_dbg(xhci, "Max packet size in xHCI HW = %d\n",
1044                                 hw_max_packet_size);
1045                 xhci_dbg(xhci, "Issuing evaluate context command.\n");
1046
1047                 /* Set up the modified control endpoint 0 */
1048                 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
1049                                 xhci->devs[slot_id]->out_ctx, ep_index);
1050                 in_ctx = xhci->devs[slot_id]->in_ctx;
1051                 ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
1052                 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1053                 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1054
1055                 /* Set up the input context flags for the command */
1056                 /* FIXME: This won't work if a non-default control endpoint
1057                  * changes max packet sizes.
1058                  */
1059                 ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1060                 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1061                 ctrl_ctx->drop_flags = 0;
1062
1063                 xhci_dbg(xhci, "Slot %d input context\n", slot_id);
1064                 xhci_dbg_ctx(xhci, in_ctx, ep_index);
1065                 xhci_dbg(xhci, "Slot %d output context\n", slot_id);
1066                 xhci_dbg_ctx(xhci, out_ctx, ep_index);
1067
1068                 ret = xhci_configure_endpoint(xhci, urb->dev, NULL,
1069                                 true, false);
1070
1071                 /* Clean up the input context for later use by bandwidth
1072                  * functions.
1073                  */
1074                 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1075         }
1076         return ret;
1077 }
1078
1079 /*
1080  * non-error returns are a promise to giveback() the urb later
1081  * we drop ownership so next owner (or urb unlink) can get it
1082  */
1083 int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1084 {
1085         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1086         struct xhci_td *buffer;
1087         unsigned long flags;
1088         int ret = 0;
1089         unsigned int slot_id, ep_index;
1090         struct urb_priv *urb_priv;
1091         int size, i;
1092
1093         if (!urb || xhci_check_args(hcd, urb->dev, urb->ep,
1094                                         true, true, __func__) <= 0)
1095                 return -EINVAL;
1096
1097         slot_id = urb->dev->slot_id;
1098         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1099
1100         if (!HCD_HW_ACCESSIBLE(hcd)) {
1101                 if (!in_interrupt())
1102                         xhci_dbg(xhci, "urb submitted during PCI suspend\n");
1103                 ret = -ESHUTDOWN;
1104                 goto exit;
1105         }
1106
1107         if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1108                 size = urb->number_of_packets;
1109         else
1110                 size = 1;
1111
1112         urb_priv = kzalloc(sizeof(struct urb_priv) +
1113                                   size * sizeof(struct xhci_td *), mem_flags);
1114         if (!urb_priv)
1115                 return -ENOMEM;
1116
1117         buffer = kzalloc(size * sizeof(struct xhci_td), mem_flags);
1118         if (!buffer) {
1119                 kfree(urb_priv);
1120                 return -ENOMEM;
1121         }
1122
1123         for (i = 0; i < size; i++) {
1124                 urb_priv->td[i] = buffer;
1125                 buffer++;
1126         }
1127
1128         urb_priv->length = size;
1129         urb_priv->td_cnt = 0;
1130         urb->hcpriv = urb_priv;
1131
1132         if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1133                 /* Check to see if the max packet size for the default control
1134                  * endpoint changed during FS device enumeration
1135                  */
1136                 if (urb->dev->speed == USB_SPEED_FULL) {
1137                         ret = xhci_check_maxpacket(xhci, slot_id,
1138                                         ep_index, urb);
1139                         if (ret < 0) {
1140                                 xhci_urb_free_priv(xhci, urb_priv);
1141                                 urb->hcpriv = NULL;
1142                                 return ret;
1143                         }
1144                 }
1145
1146                 /* We have a spinlock and interrupts disabled, so we must pass
1147                  * atomic context to this function, which may allocate memory.
1148                  */
1149                 spin_lock_irqsave(&xhci->lock, flags);
1150                 if (xhci->xhc_state & XHCI_STATE_DYING)
1151                         goto dying;
1152                 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1153                                 slot_id, ep_index);
1154                 if (ret)
1155                         goto free_priv;
1156                 spin_unlock_irqrestore(&xhci->lock, flags);
1157         } else if (usb_endpoint_xfer_bulk(&urb->ep->desc)) {
1158                 spin_lock_irqsave(&xhci->lock, flags);
1159                 if (xhci->xhc_state & XHCI_STATE_DYING)
1160                         goto dying;
1161                 if (xhci->devs[slot_id]->eps[ep_index].ep_state &
1162                                 EP_GETTING_STREAMS) {
1163                         xhci_warn(xhci, "WARN: Can't enqueue URB while bulk ep "
1164                                         "is transitioning to using streams.\n");
1165                         ret = -EINVAL;
1166                 } else if (xhci->devs[slot_id]->eps[ep_index].ep_state &
1167                                 EP_GETTING_NO_STREAMS) {
1168                         xhci_warn(xhci, "WARN: Can't enqueue URB while bulk ep "
1169                                         "is transitioning to "
1170                                         "not having streams.\n");
1171                         ret = -EINVAL;
1172                 } else {
1173                         ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1174                                         slot_id, ep_index);
1175                 }
1176                 if (ret)
1177                         goto free_priv;
1178                 spin_unlock_irqrestore(&xhci->lock, flags);
1179         } else if (usb_endpoint_xfer_int(&urb->ep->desc)) {
1180                 spin_lock_irqsave(&xhci->lock, flags);
1181                 if (xhci->xhc_state & XHCI_STATE_DYING)
1182                         goto dying;
1183                 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1184                                 slot_id, ep_index);
1185                 if (ret)
1186                         goto free_priv;
1187                 spin_unlock_irqrestore(&xhci->lock, flags);
1188         } else {
1189                 spin_lock_irqsave(&xhci->lock, flags);
1190                 if (xhci->xhc_state & XHCI_STATE_DYING)
1191                         goto dying;
1192                 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1193                                 slot_id, ep_index);
1194                 if (ret)
1195                         goto free_priv;
1196                 spin_unlock_irqrestore(&xhci->lock, flags);
1197         }
1198 exit:
1199         return ret;
1200 dying:
1201         xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for "
1202                         "non-responsive xHCI host.\n",
1203                         urb->ep->desc.bEndpointAddress, urb);
1204         ret = -ESHUTDOWN;
1205 free_priv:
1206         xhci_urb_free_priv(xhci, urb_priv);
1207         urb->hcpriv = NULL;
1208         spin_unlock_irqrestore(&xhci->lock, flags);
1209         return ret;
1210 }
1211
1212 /* Get the right ring for the given URB.
1213  * If the endpoint supports streams, boundary check the URB's stream ID.
1214  * If the endpoint doesn't support streams, return the singular endpoint ring.
1215  */
1216 static struct xhci_ring *xhci_urb_to_transfer_ring(struct xhci_hcd *xhci,
1217                 struct urb *urb)
1218 {
1219         unsigned int slot_id;
1220         unsigned int ep_index;
1221         unsigned int stream_id;
1222         struct xhci_virt_ep *ep;
1223
1224         slot_id = urb->dev->slot_id;
1225         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1226         stream_id = urb->stream_id;
1227         ep = &xhci->devs[slot_id]->eps[ep_index];
1228         /* Common case: no streams */
1229         if (!(ep->ep_state & EP_HAS_STREAMS))
1230                 return ep->ring;
1231
1232         if (stream_id == 0) {
1233                 xhci_warn(xhci,
1234                                 "WARN: Slot ID %u, ep index %u has streams, "
1235                                 "but URB has no stream ID.\n",
1236                                 slot_id, ep_index);
1237                 return NULL;
1238         }
1239
1240         if (stream_id < ep->stream_info->num_streams)
1241                 return ep->stream_info->stream_rings[stream_id];
1242
1243         xhci_warn(xhci,
1244                         "WARN: Slot ID %u, ep index %u has "
1245                         "stream IDs 1 to %u allocated, "
1246                         "but stream ID %u is requested.\n",
1247                         slot_id, ep_index,
1248                         ep->stream_info->num_streams - 1,
1249                         stream_id);
1250         return NULL;
1251 }
1252
1253 /*
1254  * Remove the URB's TD from the endpoint ring.  This may cause the HC to stop
1255  * USB transfers, potentially stopping in the middle of a TRB buffer.  The HC
1256  * should pick up where it left off in the TD, unless a Set Transfer Ring
1257  * Dequeue Pointer is issued.
1258  *
1259  * The TRBs that make up the buffers for the canceled URB will be "removed" from
1260  * the ring.  Since the ring is a contiguous structure, they can't be physically
1261  * removed.  Instead, there are two options:
1262  *
1263  *  1) If the HC is in the middle of processing the URB to be canceled, we
1264  *     simply move the ring's dequeue pointer past those TRBs using the Set
1265  *     Transfer Ring Dequeue Pointer command.  This will be the common case,
1266  *     when drivers timeout on the last submitted URB and attempt to cancel.
1267  *
1268  *  2) If the HC is in the middle of a different TD, we turn the TRBs into a
1269  *     series of 1-TRB transfer no-op TDs.  (No-ops shouldn't be chained.)  The
1270  *     HC will need to invalidate the any TRBs it has cached after the stop
1271  *     endpoint command, as noted in the xHCI 0.95 errata.
1272  *
1273  *  3) The TD may have completed by the time the Stop Endpoint Command
1274  *     completes, so software needs to handle that case too.
1275  *
1276  * This function should protect against the TD enqueueing code ringing the
1277  * doorbell while this code is waiting for a Stop Endpoint command to complete.
1278  * It also needs to account for multiple cancellations on happening at the same
1279  * time for the same endpoint.
1280  *
1281  * Note that this function can be called in any context, or so says
1282  * usb_hcd_unlink_urb()
1283  */
1284 int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1285 {
1286         unsigned long flags;
1287         int ret, i;
1288         u32 temp;
1289         struct xhci_hcd *xhci;
1290         struct urb_priv *urb_priv;
1291         struct xhci_td *td;
1292         unsigned int ep_index;
1293         struct xhci_ring *ep_ring;
1294         struct xhci_virt_ep *ep;
1295
1296         xhci = hcd_to_xhci(hcd);
1297         spin_lock_irqsave(&xhci->lock, flags);
1298         /* Make sure the URB hasn't completed or been unlinked already */
1299         ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1300         if (ret || !urb->hcpriv)
1301                 goto done;
1302         temp = xhci_readl(xhci, &xhci->op_regs->status);
1303         if (temp == 0xffffffff || (xhci->xhc_state & XHCI_STATE_HALTED)) {
1304                 xhci_dbg(xhci, "HW died, freeing TD.\n");
1305                 urb_priv = urb->hcpriv;
1306                 for (i = urb_priv->td_cnt; i < urb_priv->length; i++) {
1307                         td = urb_priv->td[i];
1308                         if (!list_empty(&td->td_list))
1309                                 list_del_init(&td->td_list);
1310                         if (!list_empty(&td->cancelled_td_list))
1311                                 list_del_init(&td->cancelled_td_list);
1312                 }
1313
1314                 usb_hcd_unlink_urb_from_ep(hcd, urb);
1315                 spin_unlock_irqrestore(&xhci->lock, flags);
1316                 usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1317                 xhci_urb_free_priv(xhci, urb_priv);
1318                 return ret;
1319         }
1320         if ((xhci->xhc_state & XHCI_STATE_DYING) ||
1321                         (xhci->xhc_state & XHCI_STATE_HALTED)) {
1322                 xhci_dbg(xhci, "Ep 0x%x: URB %p to be canceled on "
1323                                 "non-responsive xHCI host.\n",
1324                                 urb->ep->desc.bEndpointAddress, urb);
1325                 /* Let the stop endpoint command watchdog timer (which set this
1326                  * state) finish cleaning up the endpoint TD lists.  We must
1327                  * have caught it in the middle of dropping a lock and giving
1328                  * back an URB.
1329                  */
1330                 goto done;
1331         }
1332
1333         xhci_dbg(xhci, "Cancel URB %p\n", urb);
1334         xhci_dbg(xhci, "Event ring:\n");
1335         xhci_debug_ring(xhci, xhci->event_ring);
1336         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1337         ep = &xhci->devs[urb->dev->slot_id]->eps[ep_index];
1338         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1339         if (!ep_ring) {
1340                 ret = -EINVAL;
1341                 goto done;
1342         }
1343
1344         xhci_dbg(xhci, "Endpoint ring:\n");
1345         xhci_debug_ring(xhci, ep_ring);
1346
1347         urb_priv = urb->hcpriv;
1348
1349         for (i = urb_priv->td_cnt; i < urb_priv->length; i++) {
1350                 td = urb_priv->td[i];
1351                 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
1352         }
1353
1354         /* Queue a stop endpoint command, but only if this is
1355          * the first cancellation to be handled.
1356          */
1357         if (!(ep->ep_state & EP_HALT_PENDING)) {
1358                 ep->ep_state |= EP_HALT_PENDING;
1359                 ep->stop_cmds_pending++;
1360                 ep->stop_cmd_timer.expires = jiffies +
1361                         XHCI_STOP_EP_CMD_TIMEOUT * HZ;
1362                 add_timer(&ep->stop_cmd_timer);
1363                 xhci_queue_stop_endpoint(xhci, urb->dev->slot_id, ep_index, 0);
1364                 xhci_ring_cmd_db(xhci);
1365         }
1366 done:
1367         spin_unlock_irqrestore(&xhci->lock, flags);
1368         return ret;
1369 }
1370
1371 /* Drop an endpoint from a new bandwidth configuration for this device.
1372  * Only one call to this function is allowed per endpoint before
1373  * check_bandwidth() or reset_bandwidth() must be called.
1374  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1375  * add the endpoint to the schedule with possibly new parameters denoted by a
1376  * different endpoint descriptor in usb_host_endpoint.
1377  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1378  * not allowed.
1379  *
1380  * The USB core will not allow URBs to be queued to an endpoint that is being
1381  * disabled, so there's no need for mutual exclusion to protect
1382  * the xhci->devs[slot_id] structure.
1383  */
1384 int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1385                 struct usb_host_endpoint *ep)
1386 {
1387         struct xhci_hcd *xhci;
1388         struct xhci_container_ctx *in_ctx, *out_ctx;
1389         struct xhci_input_control_ctx *ctrl_ctx;
1390         struct xhci_slot_ctx *slot_ctx;
1391         unsigned int last_ctx;
1392         unsigned int ep_index;
1393         struct xhci_ep_ctx *ep_ctx;
1394         u32 drop_flag;
1395         u32 new_add_flags, new_drop_flags, new_slot_info;
1396         int ret;
1397
1398         ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1399         if (ret <= 0)
1400                 return ret;
1401         xhci = hcd_to_xhci(hcd);
1402         if (xhci->xhc_state & XHCI_STATE_DYING)
1403                 return -ENODEV;
1404
1405         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1406         drop_flag = xhci_get_endpoint_flag(&ep->desc);
1407         if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1408                 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1409                                 __func__, drop_flag);
1410                 return 0;
1411         }
1412
1413         in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1414         out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1415         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1416         ep_index = xhci_get_endpoint_index(&ep->desc);
1417         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1418         /* If the HC already knows the endpoint is disabled,
1419          * or the HCD has noted it is disabled, ignore this request
1420          */
1421         if (((ep_ctx->ep_info & cpu_to_le32(EP_STATE_MASK)) ==
1422              cpu_to_le32(EP_STATE_DISABLED)) ||
1423             le32_to_cpu(ctrl_ctx->drop_flags) &
1424             xhci_get_endpoint_flag(&ep->desc)) {
1425                 xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1426                                 __func__, ep);
1427                 return 0;
1428         }
1429
1430         ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1431         new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1432
1433         ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1434         new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1435
1436         last_ctx = xhci_last_valid_endpoint(le32_to_cpu(ctrl_ctx->add_flags));
1437         slot_ctx = xhci_get_slot_ctx(xhci, in_ctx);
1438         /* Update the last valid endpoint context, if we deleted the last one */
1439         if ((le32_to_cpu(slot_ctx->dev_info) & LAST_CTX_MASK) >
1440             LAST_CTX(last_ctx)) {
1441                 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1442                 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(last_ctx));
1443         }
1444         new_slot_info = le32_to_cpu(slot_ctx->dev_info);
1445
1446         xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1447
1448         xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x, new slot info = %#x\n",
1449                         (unsigned int) ep->desc.bEndpointAddress,
1450                         udev->slot_id,
1451                         (unsigned int) new_drop_flags,
1452                         (unsigned int) new_add_flags,
1453                         (unsigned int) new_slot_info);
1454         return 0;
1455 }
1456
1457 /* Add an endpoint to a new possible bandwidth configuration for this device.
1458  * Only one call to this function is allowed per endpoint before
1459  * check_bandwidth() or reset_bandwidth() must be called.
1460  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1461  * add the endpoint to the schedule with possibly new parameters denoted by a
1462  * different endpoint descriptor in usb_host_endpoint.
1463  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1464  * not allowed.
1465  *
1466  * The USB core will not allow URBs to be queued to an endpoint until the
1467  * configuration or alt setting is installed in the device, so there's no need
1468  * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1469  */
1470 int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1471                 struct usb_host_endpoint *ep)
1472 {
1473         struct xhci_hcd *xhci;
1474         struct xhci_container_ctx *in_ctx, *out_ctx;
1475         unsigned int ep_index;
1476         struct xhci_ep_ctx *ep_ctx;
1477         struct xhci_slot_ctx *slot_ctx;
1478         struct xhci_input_control_ctx *ctrl_ctx;
1479         u32 added_ctxs;
1480         unsigned int last_ctx;
1481         u32 new_add_flags, new_drop_flags, new_slot_info;
1482         struct xhci_virt_device *virt_dev;
1483         int ret = 0;
1484
1485         ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1486         if (ret <= 0) {
1487                 /* So we won't queue a reset ep command for a root hub */
1488                 ep->hcpriv = NULL;
1489                 return ret;
1490         }
1491         xhci = hcd_to_xhci(hcd);
1492         if (xhci->xhc_state & XHCI_STATE_DYING)
1493                 return -ENODEV;
1494
1495         added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1496         last_ctx = xhci_last_valid_endpoint(added_ctxs);
1497         if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1498                 /* FIXME when we have to issue an evaluate endpoint command to
1499                  * deal with ep0 max packet size changing once we get the
1500                  * descriptors
1501                  */
1502                 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1503                                 __func__, added_ctxs);
1504                 return 0;
1505         }
1506
1507         virt_dev = xhci->devs[udev->slot_id];
1508         in_ctx = virt_dev->in_ctx;
1509         out_ctx = virt_dev->out_ctx;
1510         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1511         ep_index = xhci_get_endpoint_index(&ep->desc);
1512         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1513
1514         /* If this endpoint is already in use, and the upper layers are trying
1515          * to add it again without dropping it, reject the addition.
1516          */
1517         if (virt_dev->eps[ep_index].ring &&
1518                         !(le32_to_cpu(ctrl_ctx->drop_flags) &
1519                                 xhci_get_endpoint_flag(&ep->desc))) {
1520                 xhci_warn(xhci, "Trying to add endpoint 0x%x "
1521                                 "without dropping it.\n",
1522                                 (unsigned int) ep->desc.bEndpointAddress);
1523                 return -EINVAL;
1524         }
1525
1526         /* If the HCD has already noted the endpoint is enabled,
1527          * ignore this request.
1528          */
1529         if (le32_to_cpu(ctrl_ctx->add_flags) &
1530             xhci_get_endpoint_flag(&ep->desc)) {
1531                 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1532                                 __func__, ep);
1533                 return 0;
1534         }
1535
1536         /*
1537          * Configuration and alternate setting changes must be done in
1538          * process context, not interrupt context (or so documenation
1539          * for usb_set_interface() and usb_set_configuration() claim).
1540          */
1541         if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1542                 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1543                                 __func__, ep->desc.bEndpointAddress);
1544                 return -ENOMEM;
1545         }
1546
1547         ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
1548         new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1549
1550         /* If xhci_endpoint_disable() was called for this endpoint, but the
1551          * xHC hasn't been notified yet through the check_bandwidth() call,
1552          * this re-adds a new state for the endpoint from the new endpoint
1553          * descriptors.  We must drop and re-add this endpoint, so we leave the
1554          * drop flags alone.
1555          */
1556         new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1557
1558         slot_ctx = xhci_get_slot_ctx(xhci, in_ctx);
1559         /* Update the last valid endpoint context, if we just added one past */
1560         if ((le32_to_cpu(slot_ctx->dev_info) & LAST_CTX_MASK) <
1561             LAST_CTX(last_ctx)) {
1562                 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1563                 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(last_ctx));
1564         }
1565         new_slot_info = le32_to_cpu(slot_ctx->dev_info);
1566
1567         /* Store the usb_device pointer for later use */
1568         ep->hcpriv = udev;
1569
1570         xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x, new slot info = %#x\n",
1571                         (unsigned int) ep->desc.bEndpointAddress,
1572                         udev->slot_id,
1573                         (unsigned int) new_drop_flags,
1574                         (unsigned int) new_add_flags,
1575                         (unsigned int) new_slot_info);
1576         return 0;
1577 }
1578
1579 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1580 {
1581         struct xhci_input_control_ctx *ctrl_ctx;
1582         struct xhci_ep_ctx *ep_ctx;
1583         struct xhci_slot_ctx *slot_ctx;
1584         int i;
1585
1586         /* When a device's add flag and drop flag are zero, any subsequent
1587          * configure endpoint command will leave that endpoint's state
1588          * untouched.  Make sure we don't leave any old state in the input
1589          * endpoint contexts.
1590          */
1591         ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx);
1592         ctrl_ctx->drop_flags = 0;
1593         ctrl_ctx->add_flags = 0;
1594         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1595         slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1596         /* Endpoint 0 is always valid */
1597         slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
1598         for (i = 1; i < 31; ++i) {
1599                 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
1600                 ep_ctx->ep_info = 0;
1601                 ep_ctx->ep_info2 = 0;
1602                 ep_ctx->deq = 0;
1603                 ep_ctx->tx_info = 0;
1604         }
1605 }
1606
1607 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
1608                 struct usb_device *udev, u32 *cmd_status)
1609 {
1610         int ret;
1611
1612         switch (*cmd_status) {
1613         case COMP_ENOMEM:
1614                 dev_warn(&udev->dev, "Not enough host controller resources "
1615                                 "for new device state.\n");
1616                 ret = -ENOMEM;
1617                 /* FIXME: can we allocate more resources for the HC? */
1618                 break;
1619         case COMP_BW_ERR:
1620                 dev_warn(&udev->dev, "Not enough bandwidth "
1621                                 "for new device state.\n");
1622                 ret = -ENOSPC;
1623                 /* FIXME: can we go back to the old state? */
1624                 break;
1625         case COMP_TRB_ERR:
1626                 /* the HCD set up something wrong */
1627                 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
1628                                 "add flag = 1, "
1629                                 "and endpoint is not disabled.\n");
1630                 ret = -EINVAL;
1631                 break;
1632         case COMP_DEV_ERR:
1633                 dev_warn(&udev->dev, "ERROR: Incompatible device for endpoint "
1634                                 "configure command.\n");
1635                 ret = -ENODEV;
1636                 break;
1637         case COMP_SUCCESS:
1638                 dev_dbg(&udev->dev, "Successful Endpoint Configure command\n");
1639                 ret = 0;
1640                 break;
1641         default:
1642                 xhci_err(xhci, "ERROR: unexpected command completion "
1643                                 "code 0x%x.\n", *cmd_status);
1644                 ret = -EINVAL;
1645                 break;
1646         }
1647         return ret;
1648 }
1649
1650 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
1651                 struct usb_device *udev, u32 *cmd_status)
1652 {
1653         int ret;
1654         struct xhci_virt_device *virt_dev = xhci->devs[udev->slot_id];
1655
1656         switch (*cmd_status) {
1657         case COMP_EINVAL:
1658                 dev_warn(&udev->dev, "WARN: xHCI driver setup invalid evaluate "
1659                                 "context command.\n");
1660                 ret = -EINVAL;
1661                 break;
1662         case COMP_EBADSLT:
1663                 dev_warn(&udev->dev, "WARN: slot not enabled for"
1664                                 "evaluate context command.\n");
1665         case COMP_CTX_STATE:
1666                 dev_warn(&udev->dev, "WARN: invalid context state for "
1667                                 "evaluate context command.\n");
1668                 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 1);
1669                 ret = -EINVAL;
1670                 break;
1671         case COMP_DEV_ERR:
1672                 dev_warn(&udev->dev, "ERROR: Incompatible device for evaluate "
1673                                 "context command.\n");
1674                 ret = -ENODEV;
1675                 break;
1676         case COMP_MEL_ERR:
1677                 /* Max Exit Latency too large error */
1678                 dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
1679                 ret = -EINVAL;
1680                 break;
1681         case COMP_SUCCESS:
1682                 dev_dbg(&udev->dev, "Successful evaluate context command\n");
1683                 ret = 0;
1684                 break;
1685         default:
1686                 xhci_err(xhci, "ERROR: unexpected command completion "
1687                                 "code 0x%x.\n", *cmd_status);
1688                 ret = -EINVAL;
1689                 break;
1690         }
1691         return ret;
1692 }
1693
1694 static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
1695                 struct xhci_container_ctx *in_ctx)
1696 {
1697         struct xhci_input_control_ctx *ctrl_ctx;
1698         u32 valid_add_flags;
1699         u32 valid_drop_flags;
1700
1701         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1702         /* Ignore the slot flag (bit 0), and the default control endpoint flag
1703          * (bit 1).  The default control endpoint is added during the Address
1704          * Device command and is never removed until the slot is disabled.
1705          */
1706         valid_add_flags = ctrl_ctx->add_flags >> 2;
1707         valid_drop_flags = ctrl_ctx->drop_flags >> 2;
1708
1709         /* Use hweight32 to count the number of ones in the add flags, or
1710          * number of endpoints added.  Don't count endpoints that are changed
1711          * (both added and dropped).
1712          */
1713         return hweight32(valid_add_flags) -
1714                 hweight32(valid_add_flags & valid_drop_flags);
1715 }
1716
1717 static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
1718                 struct xhci_container_ctx *in_ctx)
1719 {
1720         struct xhci_input_control_ctx *ctrl_ctx;
1721         u32 valid_add_flags;
1722         u32 valid_drop_flags;
1723
1724         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1725         valid_add_flags = ctrl_ctx->add_flags >> 2;
1726         valid_drop_flags = ctrl_ctx->drop_flags >> 2;
1727
1728         return hweight32(valid_drop_flags) -
1729                 hweight32(valid_add_flags & valid_drop_flags);
1730 }
1731
1732 /*
1733  * We need to reserve the new number of endpoints before the configure endpoint
1734  * command completes.  We can't subtract the dropped endpoints from the number
1735  * of active endpoints until the command completes because we can oversubscribe
1736  * the host in this case:
1737  *
1738  *  - the first configure endpoint command drops more endpoints than it adds
1739  *  - a second configure endpoint command that adds more endpoints is queued
1740  *  - the first configure endpoint command fails, so the config is unchanged
1741  *  - the second command may succeed, even though there isn't enough resources
1742  *
1743  * Must be called with xhci->lock held.
1744  */
1745 static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
1746                 struct xhci_container_ctx *in_ctx)
1747 {
1748         u32 added_eps;
1749
1750         added_eps = xhci_count_num_new_endpoints(xhci, in_ctx);
1751         if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
1752                 xhci_dbg(xhci, "Not enough ep ctxs: "
1753                                 "%u active, need to add %u, limit is %u.\n",
1754                                 xhci->num_active_eps, added_eps,
1755                                 xhci->limit_active_eps);
1756                 return -ENOMEM;
1757         }
1758         xhci->num_active_eps += added_eps;
1759         xhci_dbg(xhci, "Adding %u ep ctxs, %u now active.\n", added_eps,
1760                         xhci->num_active_eps);
1761         return 0;
1762 }
1763
1764 /*
1765  * The configure endpoint was failed by the xHC for some other reason, so we
1766  * need to revert the resources that failed configuration would have used.
1767  *
1768  * Must be called with xhci->lock held.
1769  */
1770 static void xhci_free_host_resources(struct xhci_hcd *xhci,
1771                 struct xhci_container_ctx *in_ctx)
1772 {
1773         u32 num_failed_eps;
1774
1775         num_failed_eps = xhci_count_num_new_endpoints(xhci, in_ctx);
1776         xhci->num_active_eps -= num_failed_eps;
1777         xhci_dbg(xhci, "Removing %u failed ep ctxs, %u now active.\n",
1778                         num_failed_eps,
1779                         xhci->num_active_eps);
1780 }
1781
1782 /*
1783  * Now that the command has completed, clean up the active endpoint count by
1784  * subtracting out the endpoints that were dropped (but not changed).
1785  *
1786  * Must be called with xhci->lock held.
1787  */
1788 static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
1789                 struct xhci_container_ctx *in_ctx)
1790 {
1791         u32 num_dropped_eps;
1792
1793         num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, in_ctx);
1794         xhci->num_active_eps -= num_dropped_eps;
1795         if (num_dropped_eps)
1796                 xhci_dbg(xhci, "Removing %u dropped ep ctxs, %u now active.\n",
1797                                 num_dropped_eps,
1798                                 xhci->num_active_eps);
1799 }
1800
1801 unsigned int xhci_get_block_size(struct usb_device *udev)
1802 {
1803         switch (udev->speed) {
1804         case USB_SPEED_LOW:
1805         case USB_SPEED_FULL:
1806                 return FS_BLOCK;
1807         case USB_SPEED_HIGH:
1808                 return HS_BLOCK;
1809         case USB_SPEED_SUPER:
1810                 return SS_BLOCK;
1811         case USB_SPEED_UNKNOWN:
1812         case USB_SPEED_WIRELESS:
1813         default:
1814                 /* Should never happen */
1815                 return 1;
1816         }
1817 }
1818
1819 unsigned int xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
1820 {
1821         if (interval_bw->overhead[LS_OVERHEAD_TYPE])
1822                 return LS_OVERHEAD;
1823         if (interval_bw->overhead[FS_OVERHEAD_TYPE])
1824                 return FS_OVERHEAD;
1825         return HS_OVERHEAD;
1826 }
1827
1828 /* If we are changing a LS/FS device under a HS hub,
1829  * make sure (if we are activating a new TT) that the HS bus has enough
1830  * bandwidth for this new TT.
1831  */
1832 static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
1833                 struct xhci_virt_device *virt_dev,
1834                 int old_active_eps)
1835 {
1836         struct xhci_interval_bw_table *bw_table;
1837         struct xhci_tt_bw_info *tt_info;
1838
1839         /* Find the bandwidth table for the root port this TT is attached to. */
1840         bw_table = &xhci->rh_bw[virt_dev->real_port - 1].bw_table;
1841         tt_info = virt_dev->tt_info;
1842         /* If this TT already had active endpoints, the bandwidth for this TT
1843          * has already been added.  Removing all periodic endpoints (and thus
1844          * making the TT enactive) will only decrease the bandwidth used.
1845          */
1846         if (old_active_eps)
1847                 return 0;
1848         if (old_active_eps == 0 && tt_info->active_eps != 0) {
1849                 if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
1850                         return -ENOMEM;
1851                 return 0;
1852         }
1853         /* Not sure why we would have no new active endpoints...
1854          *
1855          * Maybe because of an Evaluate Context change for a hub update or a
1856          * control endpoint 0 max packet size change?
1857          * FIXME: skip the bandwidth calculation in that case.
1858          */
1859         return 0;
1860 }
1861
1862 static int xhci_check_ss_bw(struct xhci_hcd *xhci,
1863                 struct xhci_virt_device *virt_dev)
1864 {
1865         unsigned int bw_reserved;
1866
1867         bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
1868         if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
1869                 return -ENOMEM;
1870
1871         bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
1872         if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
1873                 return -ENOMEM;
1874
1875         return 0;
1876 }
1877
1878 /*
1879  * This algorithm is a very conservative estimate of the worst-case scheduling
1880  * scenario for any one interval.  The hardware dynamically schedules the
1881  * packets, so we can't tell which microframe could be the limiting factor in
1882  * the bandwidth scheduling.  This only takes into account periodic endpoints.
1883  *
1884  * Obviously, we can't solve an NP complete problem to find the minimum worst
1885  * case scenario.  Instead, we come up with an estimate that is no less than
1886  * the worst case bandwidth used for any one microframe, but may be an
1887  * over-estimate.
1888  *
1889  * We walk the requirements for each endpoint by interval, starting with the
1890  * smallest interval, and place packets in the schedule where there is only one
1891  * possible way to schedule packets for that interval.  In order to simplify
1892  * this algorithm, we record the largest max packet size for each interval, and
1893  * assume all packets will be that size.
1894  *
1895  * For interval 0, we obviously must schedule all packets for each interval.
1896  * The bandwidth for interval 0 is just the amount of data to be transmitted
1897  * (the sum of all max ESIT payload sizes, plus any overhead per packet times
1898  * the number of packets).
1899  *
1900  * For interval 1, we have two possible microframes to schedule those packets
1901  * in.  For this algorithm, if we can schedule the same number of packets for
1902  * each possible scheduling opportunity (each microframe), we will do so.  The
1903  * remaining number of packets will be saved to be transmitted in the gaps in
1904  * the next interval's scheduling sequence.
1905  *
1906  * As we move those remaining packets to be scheduled with interval 2 packets,
1907  * we have to double the number of remaining packets to transmit.  This is
1908  * because the intervals are actually powers of 2, and we would be transmitting
1909  * the previous interval's packets twice in this interval.  We also have to be
1910  * sure that when we look at the largest max packet size for this interval, we
1911  * also look at the largest max packet size for the remaining packets and take
1912  * the greater of the two.
1913  *
1914  * The algorithm continues to evenly distribute packets in each scheduling
1915  * opportunity, and push the remaining packets out, until we get to the last
1916  * interval.  Then those packets and their associated overhead are just added
1917  * to the bandwidth used.
1918  */
1919 static int xhci_check_bw_table(struct xhci_hcd *xhci,
1920                 struct xhci_virt_device *virt_dev,
1921                 int old_active_eps)
1922 {
1923         unsigned int bw_reserved;
1924         unsigned int max_bandwidth;
1925         unsigned int bw_used;
1926         unsigned int block_size;
1927         struct xhci_interval_bw_table *bw_table;
1928         unsigned int packet_size = 0;
1929         unsigned int overhead = 0;
1930         unsigned int packets_transmitted = 0;
1931         unsigned int packets_remaining = 0;
1932         unsigned int i;
1933
1934         if (virt_dev->udev->speed == USB_SPEED_SUPER)
1935                 return xhci_check_ss_bw(xhci, virt_dev);
1936
1937         if (virt_dev->udev->speed == USB_SPEED_HIGH) {
1938                 max_bandwidth = HS_BW_LIMIT;
1939                 /* Convert percent of bus BW reserved to blocks reserved */
1940                 bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
1941         } else {
1942                 max_bandwidth = FS_BW_LIMIT;
1943                 bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
1944         }
1945
1946         bw_table = virt_dev->bw_table;
1947         /* We need to translate the max packet size and max ESIT payloads into
1948          * the units the hardware uses.
1949          */
1950         block_size = xhci_get_block_size(virt_dev->udev);
1951
1952         /* If we are manipulating a LS/FS device under a HS hub, double check
1953          * that the HS bus has enough bandwidth if we are activing a new TT.
1954          */
1955         if (virt_dev->tt_info) {
1956                 xhci_dbg(xhci, "Recalculating BW for rootport %u\n",
1957                                 virt_dev->real_port);
1958                 if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
1959                         xhci_warn(xhci, "Not enough bandwidth on HS bus for "
1960                                         "newly activated TT.\n");
1961                         return -ENOMEM;
1962                 }
1963                 xhci_dbg(xhci, "Recalculating BW for TT slot %u port %u\n",
1964                                 virt_dev->tt_info->slot_id,
1965                                 virt_dev->tt_info->ttport);
1966         } else {
1967                 xhci_dbg(xhci, "Recalculating BW for rootport %u\n",
1968                                 virt_dev->real_port);
1969         }
1970
1971         /* Add in how much bandwidth will be used for interval zero, or the
1972          * rounded max ESIT payload + number of packets * largest overhead.
1973          */
1974         bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
1975                 bw_table->interval_bw[0].num_packets *
1976                 xhci_get_largest_overhead(&bw_table->interval_bw[0]);
1977
1978         for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
1979                 unsigned int bw_added;
1980                 unsigned int largest_mps;
1981                 unsigned int interval_overhead;
1982
1983                 /*
1984                  * How many packets could we transmit in this interval?
1985                  * If packets didn't fit in the previous interval, we will need
1986                  * to transmit that many packets twice within this interval.
1987                  */
1988                 packets_remaining = 2 * packets_remaining +
1989                         bw_table->interval_bw[i].num_packets;
1990
1991                 /* Find the largest max packet size of this or the previous
1992                  * interval.
1993                  */
1994                 if (list_empty(&bw_table->interval_bw[i].endpoints))
1995                         largest_mps = 0;
1996                 else {
1997                         struct xhci_virt_ep *virt_ep;
1998                         struct list_head *ep_entry;
1999
2000                         ep_entry = bw_table->interval_bw[i].endpoints.next;
2001                         virt_ep = list_entry(ep_entry,
2002                                         struct xhci_virt_ep, bw_endpoint_list);
2003                         /* Convert to blocks, rounding up */
2004                         largest_mps = DIV_ROUND_UP(
2005                                         virt_ep->bw_info.max_packet_size,
2006                                         block_size);
2007                 }
2008                 if (largest_mps > packet_size)
2009                         packet_size = largest_mps;
2010
2011                 /* Use the larger overhead of this or the previous interval. */
2012                 interval_overhead = xhci_get_largest_overhead(
2013                                 &bw_table->interval_bw[i]);
2014                 if (interval_overhead > overhead)
2015                         overhead = interval_overhead;
2016
2017                 /* How many packets can we evenly distribute across
2018                  * (1 << (i + 1)) possible scheduling opportunities?
2019                  */
2020                 packets_transmitted = packets_remaining >> (i + 1);
2021
2022                 /* Add in the bandwidth used for those scheduled packets */
2023                 bw_added = packets_transmitted * (overhead + packet_size);
2024
2025                 /* How many packets do we have remaining to transmit? */
2026                 packets_remaining = packets_remaining % (1 << (i + 1));
2027
2028                 /* What largest max packet size should those packets have? */
2029                 /* If we've transmitted all packets, don't carry over the
2030                  * largest packet size.
2031                  */
2032                 if (packets_remaining == 0) {
2033                         packet_size = 0;
2034                         overhead = 0;
2035                 } else if (packets_transmitted > 0) {
2036                         /* Otherwise if we do have remaining packets, and we've
2037                          * scheduled some packets in this interval, take the
2038                          * largest max packet size from endpoints with this
2039                          * interval.
2040                          */
2041                         packet_size = largest_mps;
2042                         overhead = interval_overhead;
2043                 }
2044                 /* Otherwise carry over packet_size and overhead from the last
2045                  * time we had a remainder.
2046                  */
2047                 bw_used += bw_added;
2048                 if (bw_used > max_bandwidth) {
2049                         xhci_warn(xhci, "Not enough bandwidth. "
2050                                         "Proposed: %u, Max: %u\n",
2051                                 bw_used, max_bandwidth);
2052                         return -ENOMEM;
2053                 }
2054         }
2055         /*
2056          * Ok, we know we have some packets left over after even-handedly
2057          * scheduling interval 15.  We don't know which microframes they will
2058          * fit into, so we over-schedule and say they will be scheduled every
2059          * microframe.
2060          */
2061         if (packets_remaining > 0)
2062                 bw_used += overhead + packet_size;
2063
2064         if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2065                 unsigned int port_index = virt_dev->real_port - 1;
2066
2067                 /* OK, we're manipulating a HS device attached to a
2068                  * root port bandwidth domain.  Include the number of active TTs
2069                  * in the bandwidth used.
2070                  */
2071                 bw_used += TT_HS_OVERHEAD *
2072                         xhci->rh_bw[port_index].num_active_tts;
2073         }
2074
2075         xhci_dbg(xhci, "Final bandwidth: %u, Limit: %u, Reserved: %u, "
2076                 "Available: %u " "percent\n",
2077                 bw_used, max_bandwidth, bw_reserved,
2078                 (max_bandwidth - bw_used - bw_reserved) * 100 /
2079                 max_bandwidth);
2080
2081         bw_used += bw_reserved;
2082         if (bw_used > max_bandwidth) {
2083                 xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2084                                 bw_used, max_bandwidth);
2085                 return -ENOMEM;
2086         }
2087
2088         bw_table->bw_used = bw_used;
2089         return 0;
2090 }
2091
2092 static bool xhci_is_async_ep(unsigned int ep_type)
2093 {
2094         return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2095                                         ep_type != ISOC_IN_EP &&
2096                                         ep_type != INT_IN_EP);
2097 }
2098
2099 static bool xhci_is_sync_in_ep(unsigned int ep_type)
2100 {
2101         return (ep_type == ISOC_IN_EP || ep_type != INT_IN_EP);
2102 }
2103
2104 static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2105 {
2106         unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2107
2108         if (ep_bw->ep_interval == 0)
2109                 return SS_OVERHEAD_BURST +
2110                         (ep_bw->mult * ep_bw->num_packets *
2111                                         (SS_OVERHEAD + mps));
2112         return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2113                                 (SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2114                                 1 << ep_bw->ep_interval);
2115
2116 }
2117
2118 void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2119                 struct xhci_bw_info *ep_bw,
2120                 struct xhci_interval_bw_table *bw_table,
2121                 struct usb_device *udev,
2122                 struct xhci_virt_ep *virt_ep,
2123                 struct xhci_tt_bw_info *tt_info)
2124 {
2125         struct xhci_interval_bw *interval_bw;
2126         int normalized_interval;
2127
2128         if (xhci_is_async_ep(ep_bw->type))
2129                 return;
2130
2131         if (udev->speed == USB_SPEED_SUPER) {
2132                 if (xhci_is_sync_in_ep(ep_bw->type))
2133                         xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2134                                 xhci_get_ss_bw_consumed(ep_bw);
2135                 else
2136                         xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2137                                 xhci_get_ss_bw_consumed(ep_bw);
2138                 return;
2139         }
2140
2141         /* SuperSpeed endpoints never get added to intervals in the table, so
2142          * this check is only valid for HS/FS/LS devices.
2143          */
2144         if (list_empty(&virt_ep->bw_endpoint_list))
2145                 return;
2146         /* For LS/FS devices, we need to translate the interval expressed in
2147          * microframes to frames.
2148          */
2149         if (udev->speed == USB_SPEED_HIGH)
2150                 normalized_interval = ep_bw->ep_interval;
2151         else
2152                 normalized_interval = ep_bw->ep_interval - 3;
2153
2154         if (normalized_interval == 0)
2155                 bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2156         interval_bw = &bw_table->interval_bw[normalized_interval];
2157         interval_bw->num_packets -= ep_bw->num_packets;
2158         switch (udev->speed) {
2159         case USB_SPEED_LOW:
2160                 interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2161                 break;
2162         case USB_SPEED_FULL:
2163                 interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2164                 break;
2165         case USB_SPEED_HIGH:
2166                 interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2167                 break;
2168         case USB_SPEED_SUPER:
2169         case USB_SPEED_UNKNOWN:
2170         case USB_SPEED_WIRELESS:
2171                 /* Should never happen because only LS/FS/HS endpoints will get
2172                  * added to the endpoint list.
2173                  */
2174                 return;
2175         }
2176         if (tt_info)
2177                 tt_info->active_eps -= 1;
2178         list_del_init(&virt_ep->bw_endpoint_list);
2179 }
2180
2181 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2182                 struct xhci_bw_info *ep_bw,
2183                 struct xhci_interval_bw_table *bw_table,
2184                 struct usb_device *udev,
2185                 struct xhci_virt_ep *virt_ep,
2186                 struct xhci_tt_bw_info *tt_info)
2187 {
2188         struct xhci_interval_bw *interval_bw;
2189         struct xhci_virt_ep *smaller_ep;
2190         int normalized_interval;
2191
2192         if (xhci_is_async_ep(ep_bw->type))
2193                 return;
2194
2195         if (udev->speed == USB_SPEED_SUPER) {
2196                 if (xhci_is_sync_in_ep(ep_bw->type))
2197                         xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2198                                 xhci_get_ss_bw_consumed(ep_bw);
2199                 else
2200                         xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2201                                 xhci_get_ss_bw_consumed(ep_bw);
2202                 return;
2203         }
2204
2205         /* For LS/FS devices, we need to translate the interval expressed in
2206          * microframes to frames.
2207          */
2208         if (udev->speed == USB_SPEED_HIGH)
2209                 normalized_interval = ep_bw->ep_interval;
2210         else
2211                 normalized_interval = ep_bw->ep_interval - 3;
2212
2213         if (normalized_interval == 0)
2214                 bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2215         interval_bw = &bw_table->interval_bw[normalized_interval];
2216         interval_bw->num_packets += ep_bw->num_packets;
2217         switch (udev->speed) {
2218         case USB_SPEED_LOW:
2219                 interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2220                 break;
2221         case USB_SPEED_FULL:
2222                 interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2223                 break;
2224         case USB_SPEED_HIGH:
2225                 interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2226                 break;
2227         case USB_SPEED_SUPER:
2228         case USB_SPEED_UNKNOWN:
2229         case USB_SPEED_WIRELESS:
2230                 /* Should never happen because only LS/FS/HS endpoints will get
2231                  * added to the endpoint list.
2232                  */
2233                 return;
2234         }
2235
2236         if (tt_info)
2237                 tt_info->active_eps += 1;
2238         /* Insert the endpoint into the list, largest max packet size first. */
2239         list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2240                         bw_endpoint_list) {
2241                 if (ep_bw->max_packet_size >=
2242                                 smaller_ep->bw_info.max_packet_size) {
2243                         /* Add the new ep before the smaller endpoint */
2244                         list_add_tail(&virt_ep->bw_endpoint_list,
2245                                         &smaller_ep->bw_endpoint_list);
2246                         return;
2247                 }
2248         }
2249         /* Add the new endpoint at the end of the list. */
2250         list_add_tail(&virt_ep->bw_endpoint_list,
2251                         &interval_bw->endpoints);
2252 }
2253
2254 void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2255                 struct xhci_virt_device *virt_dev,
2256                 int old_active_eps)
2257 {
2258         struct xhci_root_port_bw_info *rh_bw_info;
2259         if (!virt_dev->tt_info)
2260                 return;
2261
2262         rh_bw_info = &xhci->rh_bw[virt_dev->real_port - 1];
2263         if (old_active_eps == 0 &&
2264                                 virt_dev->tt_info->active_eps != 0) {
2265                 rh_bw_info->num_active_tts += 1;
2266                 rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2267         } else if (old_active_eps != 0 &&
2268                                 virt_dev->tt_info->active_eps == 0) {
2269                 rh_bw_info->num_active_tts -= 1;
2270                 rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2271         }
2272 }
2273
2274 static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2275                 struct xhci_virt_device *virt_dev,
2276                 struct xhci_container_ctx *in_ctx)
2277 {
2278         struct xhci_bw_info ep_bw_info[31];
2279         int i;
2280         struct xhci_input_control_ctx *ctrl_ctx;
2281         int old_active_eps = 0;
2282
2283         if (virt_dev->tt_info)
2284                 old_active_eps = virt_dev->tt_info->active_eps;
2285
2286         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
2287
2288         for (i = 0; i < 31; i++) {
2289                 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2290                         continue;
2291
2292                 /* Make a copy of the BW info in case we need to revert this */
2293                 memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2294                                 sizeof(ep_bw_info[i]));
2295                 /* Drop the endpoint from the interval table if the endpoint is
2296                  * being dropped or changed.
2297                  */
2298                 if (EP_IS_DROPPED(ctrl_ctx, i))
2299                         xhci_drop_ep_from_interval_table(xhci,
2300                                         &virt_dev->eps[i].bw_info,
2301                                         virt_dev->bw_table,
2302                                         virt_dev->udev,
2303                                         &virt_dev->eps[i],
2304                                         virt_dev->tt_info);
2305         }
2306         /* Overwrite the information stored in the endpoints' bw_info */
2307         xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2308         for (i = 0; i < 31; i++) {
2309                 /* Add any changed or added endpoints to the interval table */
2310                 if (EP_IS_ADDED(ctrl_ctx, i))
2311                         xhci_add_ep_to_interval_table(xhci,
2312                                         &virt_dev->eps[i].bw_info,
2313                                         virt_dev->bw_table,
2314                                         virt_dev->udev,
2315                                         &virt_dev->eps[i],
2316                                         virt_dev->tt_info);
2317         }
2318
2319         if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2320                 /* Ok, this fits in the bandwidth we have.
2321                  * Update the number of active TTs.
2322                  */
2323                 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2324                 return 0;
2325         }
2326
2327         /* We don't have enough bandwidth for this, revert the stored info. */
2328         for (i = 0; i < 31; i++) {
2329                 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2330                         continue;
2331
2332                 /* Drop the new copies of any added or changed endpoints from
2333                  * the interval table.
2334                  */
2335                 if (EP_IS_ADDED(ctrl_ctx, i)) {
2336                         xhci_drop_ep_from_interval_table(xhci,
2337                                         &virt_dev->eps[i].bw_info,
2338                                         virt_dev->bw_table,
2339                                         virt_dev->udev,
2340                                         &virt_dev->eps[i],
2341                                         virt_dev->tt_info);
2342                 }
2343                 /* Revert the endpoint back to its old information */
2344                 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2345                                 sizeof(ep_bw_info[i]));
2346                 /* Add any changed or dropped endpoints back into the table */
2347                 if (EP_IS_DROPPED(ctrl_ctx, i))
2348                         xhci_add_ep_to_interval_table(xhci,
2349                                         &virt_dev->eps[i].bw_info,
2350                                         virt_dev->bw_table,
2351                                         virt_dev->udev,
2352                                         &virt_dev->eps[i],
2353                                         virt_dev->tt_info);
2354         }
2355         return -ENOMEM;
2356 }
2357
2358
2359 /* Issue a configure endpoint command or evaluate context command
2360  * and wait for it to finish.
2361  */
2362 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2363                 struct usb_device *udev,
2364                 struct xhci_command *command,
2365                 bool ctx_change, bool must_succeed)
2366 {
2367         int ret;
2368         int timeleft;
2369         unsigned long flags;
2370         struct xhci_container_ctx *in_ctx;
2371         struct completion *cmd_completion;
2372         u32 *cmd_status;
2373         struct xhci_virt_device *virt_dev;
2374
2375         spin_lock_irqsave(&xhci->lock, flags);
2376         virt_dev = xhci->devs[udev->slot_id];
2377
2378         if (command)
2379                 in_ctx = command->in_ctx;
2380         else
2381                 in_ctx = virt_dev->in_ctx;
2382
2383         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
2384                         xhci_reserve_host_resources(xhci, in_ctx)) {
2385                 spin_unlock_irqrestore(&xhci->lock, flags);
2386                 xhci_warn(xhci, "Not enough host resources, "
2387                                 "active endpoint contexts = %u\n",
2388                                 xhci->num_active_eps);
2389                 return -ENOMEM;
2390         }
2391         if ((xhci->quirks & XHCI_SW_BW_CHECKING) &&
2392                         xhci_reserve_bandwidth(xhci, virt_dev, in_ctx)) {
2393                 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2394                         xhci_free_host_resources(xhci, in_ctx);
2395                 spin_unlock_irqrestore(&xhci->lock, flags);
2396                 xhci_warn(xhci, "Not enough bandwidth\n");
2397                 return -ENOMEM;
2398         }
2399
2400         if (command) {
2401                 cmd_completion = command->completion;
2402                 cmd_status = &command->status;
2403                 command->command_trb = xhci->cmd_ring->enqueue;
2404
2405                 /* Enqueue pointer can be left pointing to the link TRB,
2406                  * we must handle that
2407                  */
2408                 if (TRB_TYPE_LINK_LE32(command->command_trb->link.control))
2409                         command->command_trb =
2410                                 xhci->cmd_ring->enq_seg->next->trbs;
2411
2412                 list_add_tail(&command->cmd_list, &virt_dev->cmd_list);
2413         } else {
2414                 cmd_completion = &virt_dev->cmd_completion;
2415                 cmd_status = &virt_dev->cmd_status;
2416         }
2417         init_completion(cmd_completion);
2418
2419         if (!ctx_change)
2420                 ret = xhci_queue_configure_endpoint(xhci, in_ctx->dma,
2421                                 udev->slot_id, must_succeed);
2422         else
2423                 ret = xhci_queue_evaluate_context(xhci, in_ctx->dma,
2424                                 udev->slot_id);
2425         if (ret < 0) {
2426                 if (command)
2427                         list_del(&command->cmd_list);
2428                 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2429                         xhci_free_host_resources(xhci, in_ctx);
2430                 spin_unlock_irqrestore(&xhci->lock, flags);
2431                 xhci_dbg(xhci, "FIXME allocate a new ring segment\n");
2432                 return -ENOMEM;
2433         }
2434         xhci_ring_cmd_db(xhci);
2435         spin_unlock_irqrestore(&xhci->lock, flags);
2436
2437         /* Wait for the configure endpoint command to complete */
2438         timeleft = wait_for_completion_interruptible_timeout(
2439                         cmd_completion,
2440                         USB_CTRL_SET_TIMEOUT);
2441         if (timeleft <= 0) {
2442                 xhci_warn(xhci, "%s while waiting for %s command\n",
2443                                 timeleft == 0 ? "Timeout" : "Signal",
2444                                 ctx_change == 0 ?
2445                                         "configure endpoint" :
2446                                         "evaluate context");
2447                 /* FIXME cancel the configure endpoint command */
2448                 return -ETIME;
2449         }
2450
2451         if (!ctx_change)
2452                 ret = xhci_configure_endpoint_result(xhci, udev, cmd_status);
2453         else
2454                 ret = xhci_evaluate_context_result(xhci, udev, cmd_status);
2455
2456         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
2457                 spin_lock_irqsave(&xhci->lock, flags);
2458                 /* If the command failed, remove the reserved resources.
2459                  * Otherwise, clean up the estimate to include dropped eps.
2460                  */
2461                 if (ret)
2462                         xhci_free_host_resources(xhci, in_ctx);
2463                 else
2464                         xhci_finish_resource_reservation(xhci, in_ctx);
2465                 spin_unlock_irqrestore(&xhci->lock, flags);
2466         }
2467         return ret;
2468 }
2469
2470 /* Called after one or more calls to xhci_add_endpoint() or
2471  * xhci_drop_endpoint().  If this call fails, the USB core is expected
2472  * to call xhci_reset_bandwidth().
2473  *
2474  * Since we are in the middle of changing either configuration or
2475  * installing a new alt setting, the USB core won't allow URBs to be
2476  * enqueued for any endpoint on the old config or interface.  Nothing
2477  * else should be touching the xhci->devs[slot_id] structure, so we
2478  * don't need to take the xhci->lock for manipulating that.
2479  */
2480 int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2481 {
2482         int i;
2483         int ret = 0;
2484         struct xhci_hcd *xhci;
2485         struct xhci_virt_device *virt_dev;
2486         struct xhci_input_control_ctx *ctrl_ctx;
2487         struct xhci_slot_ctx *slot_ctx;
2488
2489         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2490         if (ret <= 0)
2491                 return ret;
2492         xhci = hcd_to_xhci(hcd);
2493         if (xhci->xhc_state & XHCI_STATE_DYING)
2494                 return -ENODEV;
2495
2496         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2497         virt_dev = xhci->devs[udev->slot_id];
2498
2499         /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
2500         ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx);
2501         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2502         ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
2503         ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
2504
2505         /* Don't issue the command if there's no endpoints to update. */
2506         if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
2507                         ctrl_ctx->drop_flags == 0)
2508                 return 0;
2509
2510         xhci_dbg(xhci, "New Input Control Context:\n");
2511         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2512         xhci_dbg_ctx(xhci, virt_dev->in_ctx,
2513                      LAST_CTX_TO_EP_NUM(le32_to_cpu(slot_ctx->dev_info)));
2514
2515         ret = xhci_configure_endpoint(xhci, udev, NULL,
2516                         false, false);
2517         if (ret) {
2518                 /* Callee should call reset_bandwidth() */
2519                 return ret;
2520         }
2521
2522         xhci_dbg(xhci, "Output context after successful config ep cmd:\n");
2523         xhci_dbg_ctx(xhci, virt_dev->out_ctx,
2524                      LAST_CTX_TO_EP_NUM(le32_to_cpu(slot_ctx->dev_info)));
2525
2526         /* Free any rings that were dropped, but not changed. */
2527         for (i = 1; i < 31; ++i) {
2528                 if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
2529                     !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1))))
2530                         xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
2531         }
2532         xhci_zero_in_ctx(xhci, virt_dev);
2533         /*
2534          * Install any rings for completely new endpoints or changed endpoints,
2535          * and free or cache any old rings from changed endpoints.
2536          */
2537         for (i = 1; i < 31; ++i) {
2538                 if (!virt_dev->eps[i].new_ring)
2539                         continue;
2540                 /* Only cache or free the old ring if it exists.
2541                  * It may not if this is the first add of an endpoint.
2542                  */
2543                 if (virt_dev->eps[i].ring) {
2544                         xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
2545                 }
2546                 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
2547                 virt_dev->eps[i].new_ring = NULL;
2548         }
2549
2550         return ret;
2551 }
2552
2553 void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2554 {
2555         struct xhci_hcd *xhci;
2556         struct xhci_virt_device *virt_dev;
2557         int i, ret;
2558
2559         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2560         if (ret <= 0)
2561                 return;
2562         xhci = hcd_to_xhci(hcd);
2563
2564         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2565         virt_dev = xhci->devs[udev->slot_id];
2566         /* Free any rings allocated for added endpoints */
2567         for (i = 0; i < 31; ++i) {
2568                 if (virt_dev->eps[i].new_ring) {
2569                         xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
2570                         virt_dev->eps[i].new_ring = NULL;
2571                 }
2572         }
2573         xhci_zero_in_ctx(xhci, virt_dev);
2574 }
2575
2576 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
2577                 struct xhci_container_ctx *in_ctx,
2578                 struct xhci_container_ctx *out_ctx,
2579                 u32 add_flags, u32 drop_flags)
2580 {
2581         struct xhci_input_control_ctx *ctrl_ctx;
2582         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
2583         ctrl_ctx->add_flags = cpu_to_le32(add_flags);
2584         ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
2585         xhci_slot_copy(xhci, in_ctx, out_ctx);
2586         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2587
2588         xhci_dbg(xhci, "Input Context:\n");
2589         xhci_dbg_ctx(xhci, in_ctx, xhci_last_valid_endpoint(add_flags));
2590 }
2591
2592 static void xhci_setup_input_ctx_for_quirk(struct xhci_hcd *xhci,
2593                 unsigned int slot_id, unsigned int ep_index,
2594                 struct xhci_dequeue_state *deq_state)
2595 {
2596         struct xhci_container_ctx *in_ctx;
2597         struct xhci_ep_ctx *ep_ctx;
2598         u32 added_ctxs;
2599         dma_addr_t addr;
2600
2601         xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
2602                         xhci->devs[slot_id]->out_ctx, ep_index);
2603         in_ctx = xhci->devs[slot_id]->in_ctx;
2604         ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
2605         addr = xhci_trb_virt_to_dma(deq_state->new_deq_seg,
2606                         deq_state->new_deq_ptr);
2607         if (addr == 0) {
2608                 xhci_warn(xhci, "WARN Cannot submit config ep after "
2609                                 "reset ep command\n");
2610                 xhci_warn(xhci, "WARN deq seg = %p, deq ptr = %p\n",
2611                                 deq_state->new_deq_seg,
2612                                 deq_state->new_deq_ptr);
2613                 return;
2614         }
2615         ep_ctx->deq = cpu_to_le64(addr | deq_state->new_cycle_state);
2616
2617         added_ctxs = xhci_get_endpoint_flag_from_index(ep_index);
2618         xhci_setup_input_ctx_for_config_ep(xhci, xhci->devs[slot_id]->in_ctx,
2619                         xhci->devs[slot_id]->out_ctx, added_ctxs, added_ctxs);
2620 }
2621
2622 void xhci_cleanup_stalled_ring(struct xhci_hcd *xhci,
2623                 struct usb_device *udev, unsigned int ep_index)
2624 {
2625         struct xhci_dequeue_state deq_state;
2626         struct xhci_virt_ep *ep;
2627
2628         xhci_dbg(xhci, "Cleaning up stalled endpoint ring\n");
2629         ep = &xhci->devs[udev->slot_id]->eps[ep_index];
2630         /* We need to move the HW's dequeue pointer past this TD,
2631          * or it will attempt to resend it on the next doorbell ring.
2632          */
2633         xhci_find_new_dequeue_state(xhci, udev->slot_id,
2634                         ep_index, ep->stopped_stream, ep->stopped_td,
2635                         &deq_state);
2636
2637         /* HW with the reset endpoint quirk will use the saved dequeue state to
2638          * issue a configure endpoint command later.
2639          */
2640         if (!(xhci->quirks & XHCI_RESET_EP_QUIRK)) {
2641                 xhci_dbg(xhci, "Queueing new dequeue state\n");
2642                 xhci_queue_new_dequeue_state(xhci, udev->slot_id,
2643                                 ep_index, ep->stopped_stream, &deq_state);
2644         } else {
2645                 /* Better hope no one uses the input context between now and the
2646                  * reset endpoint completion!
2647                  * XXX: No idea how this hardware will react when stream rings
2648                  * are enabled.
2649                  */
2650                 xhci_dbg(xhci, "Setting up input context for "
2651                                 "configure endpoint command\n");
2652                 xhci_setup_input_ctx_for_quirk(xhci, udev->slot_id,
2653                                 ep_index, &deq_state);
2654         }
2655 }
2656
2657 /* Deal with stalled endpoints.  The core should have sent the control message
2658  * to clear the halt condition.  However, we need to make the xHCI hardware
2659  * reset its sequence number, since a device will expect a sequence number of
2660  * zero after the halt condition is cleared.
2661  * Context: in_interrupt
2662  */
2663 void xhci_endpoint_reset(struct usb_hcd *hcd,
2664                 struct usb_host_endpoint *ep)
2665 {
2666         struct xhci_hcd *xhci;
2667         struct usb_device *udev;
2668         unsigned int ep_index;
2669         unsigned long flags;
2670         int ret;
2671         struct xhci_virt_ep *virt_ep;
2672
2673         xhci = hcd_to_xhci(hcd);
2674         udev = (struct usb_device *) ep->hcpriv;
2675         /* Called with a root hub endpoint (or an endpoint that wasn't added
2676          * with xhci_add_endpoint()
2677          */
2678         if (!ep->hcpriv)
2679                 return;
2680         ep_index = xhci_get_endpoint_index(&ep->desc);
2681         virt_ep = &xhci->devs[udev->slot_id]->eps[ep_index];
2682         if (!virt_ep->stopped_td) {
2683                 xhci_dbg(xhci, "Endpoint 0x%x not halted, refusing to reset.\n",
2684                                 ep->desc.bEndpointAddress);
2685                 return;
2686         }
2687         if (usb_endpoint_xfer_control(&ep->desc)) {
2688                 xhci_dbg(xhci, "Control endpoint stall already handled.\n");
2689                 return;
2690         }
2691
2692         xhci_dbg(xhci, "Queueing reset endpoint command\n");
2693         spin_lock_irqsave(&xhci->lock, flags);
2694         ret = xhci_queue_reset_ep(xhci, udev->slot_id, ep_index);
2695         /*
2696          * Can't change the ring dequeue pointer until it's transitioned to the
2697          * stopped state, which is only upon a successful reset endpoint
2698          * command.  Better hope that last command worked!
2699          */
2700         if (!ret) {
2701                 xhci_cleanup_stalled_ring(xhci, udev, ep_index);
2702                 kfree(virt_ep->stopped_td);
2703                 xhci_ring_cmd_db(xhci);
2704         }
2705         virt_ep->stopped_td = NULL;
2706         virt_ep->stopped_trb = NULL;
2707         virt_ep->stopped_stream = 0;
2708         spin_unlock_irqrestore(&xhci->lock, flags);
2709
2710         if (ret)
2711                 xhci_warn(xhci, "FIXME allocate a new ring segment\n");
2712 }
2713
2714 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
2715                 struct usb_device *udev, struct usb_host_endpoint *ep,
2716                 unsigned int slot_id)
2717 {
2718         int ret;
2719         unsigned int ep_index;
2720         unsigned int ep_state;
2721
2722         if (!ep)
2723                 return -EINVAL;
2724         ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
2725         if (ret <= 0)
2726                 return -EINVAL;
2727         if (ep->ss_ep_comp.bmAttributes == 0) {
2728                 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
2729                                 " descriptor for ep 0x%x does not support streams\n",
2730                                 ep->desc.bEndpointAddress);
2731                 return -EINVAL;
2732         }
2733
2734         ep_index = xhci_get_endpoint_index(&ep->desc);
2735         ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
2736         if (ep_state & EP_HAS_STREAMS ||
2737                         ep_state & EP_GETTING_STREAMS) {
2738                 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
2739                                 "already has streams set up.\n",
2740                                 ep->desc.bEndpointAddress);
2741                 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
2742                                 "dynamic stream context array reallocation.\n");
2743                 return -EINVAL;
2744         }
2745         if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
2746                 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
2747                                 "endpoint 0x%x; URBs are pending.\n",
2748                                 ep->desc.bEndpointAddress);
2749                 return -EINVAL;
2750         }
2751         return 0;
2752 }
2753
2754 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
2755                 unsigned int *num_streams, unsigned int *num_stream_ctxs)
2756 {
2757         unsigned int max_streams;
2758
2759         /* The stream context array size must be a power of two */
2760         *num_stream_ctxs = roundup_pow_of_two(*num_streams);
2761         /*
2762          * Find out how many primary stream array entries the host controller
2763          * supports.  Later we may use secondary stream arrays (similar to 2nd
2764          * level page entries), but that's an optional feature for xHCI host
2765          * controllers. xHCs must support at least 4 stream IDs.
2766          */
2767         max_streams = HCC_MAX_PSA(xhci->hcc_params);
2768         if (*num_stream_ctxs > max_streams) {
2769                 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
2770                                 max_streams);
2771                 *num_stream_ctxs = max_streams;
2772                 *num_streams = max_streams;
2773         }
2774 }
2775
2776 /* Returns an error code if one of the endpoint already has streams.
2777  * This does not change any data structures, it only checks and gathers
2778  * information.
2779  */
2780 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
2781                 struct usb_device *udev,
2782                 struct usb_host_endpoint **eps, unsigned int num_eps,
2783                 unsigned int *num_streams, u32 *changed_ep_bitmask)
2784 {
2785         unsigned int max_streams;
2786         unsigned int endpoint_flag;
2787         int i;
2788         int ret;
2789
2790         for (i = 0; i < num_eps; i++) {
2791                 ret = xhci_check_streams_endpoint(xhci, udev,
2792                                 eps[i], udev->slot_id);
2793                 if (ret < 0)
2794                         return ret;
2795
2796                 max_streams = USB_SS_MAX_STREAMS(
2797                                 eps[i]->ss_ep_comp.bmAttributes);
2798                 if (max_streams < (*num_streams - 1)) {
2799                         xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
2800                                         eps[i]->desc.bEndpointAddress,
2801                                         max_streams);
2802                         *num_streams = max_streams+1;
2803                 }
2804
2805                 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
2806                 if (*changed_ep_bitmask & endpoint_flag)
2807                         return -EINVAL;
2808                 *changed_ep_bitmask |= endpoint_flag;
2809         }
2810         return 0;
2811 }
2812
2813 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
2814                 struct usb_device *udev,
2815                 struct usb_host_endpoint **eps, unsigned int num_eps)
2816 {
2817         u32 changed_ep_bitmask = 0;
2818         unsigned int slot_id;
2819         unsigned int ep_index;
2820         unsigned int ep_state;
2821         int i;
2822
2823         slot_id = udev->slot_id;
2824         if (!xhci->devs[slot_id])
2825                 return 0;
2826
2827         for (i = 0; i < num_eps; i++) {
2828                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
2829                 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
2830                 /* Are streams already being freed for the endpoint? */
2831                 if (ep_state & EP_GETTING_NO_STREAMS) {
2832                         xhci_warn(xhci, "WARN Can't disable streams for "
2833                                         "endpoint 0x%x\n, "
2834                                         "streams are being disabled already.",
2835                                         eps[i]->desc.bEndpointAddress);
2836                         return 0;
2837                 }
2838                 /* Are there actually any streams to free? */
2839                 if (!(ep_state & EP_HAS_STREAMS) &&
2840                                 !(ep_state & EP_GETTING_STREAMS)) {
2841                         xhci_warn(xhci, "WARN Can't disable streams for "
2842                                         "endpoint 0x%x\n, "
2843                                         "streams are already disabled!",
2844                                         eps[i]->desc.bEndpointAddress);
2845                         xhci_warn(xhci, "WARN xhci_free_streams() called "
2846                                         "with non-streams endpoint\n");
2847                         return 0;
2848                 }
2849                 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
2850         }
2851         return changed_ep_bitmask;
2852 }
2853
2854 /*
2855  * The USB device drivers use this function (though the HCD interface in USB
2856  * core) to prepare a set of bulk endpoints to use streams.  Streams are used to
2857  * coordinate mass storage command queueing across multiple endpoints (basically
2858  * a stream ID == a task ID).
2859  *
2860  * Setting up streams involves allocating the same size stream context array
2861  * for each endpoint and issuing a configure endpoint command for all endpoints.
2862  *
2863  * Don't allow the call to succeed if one endpoint only supports one stream
2864  * (which means it doesn't support streams at all).
2865  *
2866  * Drivers may get less stream IDs than they asked for, if the host controller
2867  * hardware or endpoints claim they can't support the number of requested
2868  * stream IDs.
2869  */
2870 int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
2871                 struct usb_host_endpoint **eps, unsigned int num_eps,
2872                 unsigned int num_streams, gfp_t mem_flags)
2873 {
2874         int i, ret;
2875         struct xhci_hcd *xhci;
2876         struct xhci_virt_device *vdev;
2877         struct xhci_command *config_cmd;
2878         unsigned int ep_index;
2879         unsigned int num_stream_ctxs;
2880         unsigned long flags;
2881         u32 changed_ep_bitmask = 0;
2882
2883         if (!eps)
2884                 return -EINVAL;
2885
2886         /* Add one to the number of streams requested to account for
2887          * stream 0 that is reserved for xHCI usage.
2888          */
2889         num_streams += 1;
2890         xhci = hcd_to_xhci(hcd);
2891         xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
2892                         num_streams);
2893
2894         config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
2895         if (!config_cmd) {
2896                 xhci_dbg(xhci, "Could not allocate xHCI command structure.\n");
2897                 return -ENOMEM;
2898         }
2899
2900         /* Check to make sure all endpoints are not already configured for
2901          * streams.  While we're at it, find the maximum number of streams that
2902          * all the endpoints will support and check for duplicate endpoints.
2903          */
2904         spin_lock_irqsave(&xhci->lock, flags);
2905         ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
2906                         num_eps, &num_streams, &changed_ep_bitmask);
2907         if (ret < 0) {
2908                 xhci_free_command(xhci, config_cmd);
2909                 spin_unlock_irqrestore(&xhci->lock, flags);
2910                 return ret;
2911         }
2912         if (num_streams <= 1) {
2913                 xhci_warn(xhci, "WARN: endpoints can't handle "
2914                                 "more than one stream.\n");
2915                 xhci_free_command(xhci, config_cmd);
2916                 spin_unlock_irqrestore(&xhci->lock, flags);
2917                 return -EINVAL;
2918         }
2919         vdev = xhci->devs[udev->slot_id];
2920         /* Mark each endpoint as being in transition, so
2921          * xhci_urb_enqueue() will reject all URBs.
2922          */
2923         for (i = 0; i < num_eps; i++) {
2924                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
2925                 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
2926         }
2927         spin_unlock_irqrestore(&xhci->lock, flags);
2928
2929         /* Setup internal data structures and allocate HW data structures for
2930          * streams (but don't install the HW structures in the input context
2931          * until we're sure all memory allocation succeeded).
2932          */
2933         xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
2934         xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
2935                         num_stream_ctxs, num_streams);
2936
2937         for (i = 0; i < num_eps; i++) {
2938                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
2939                 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
2940                                 num_stream_ctxs,
2941                                 num_streams, mem_flags);
2942                 if (!vdev->eps[ep_index].stream_info)
2943                         goto cleanup;
2944                 /* Set maxPstreams in endpoint context and update deq ptr to
2945                  * point to stream context array. FIXME
2946                  */
2947         }
2948
2949         /* Set up the input context for a configure endpoint command. */
2950         for (i = 0; i < num_eps; i++) {
2951                 struct xhci_ep_ctx *ep_ctx;
2952
2953                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
2954                 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
2955
2956                 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
2957                                 vdev->out_ctx, ep_index);
2958                 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
2959                                 vdev->eps[ep_index].stream_info);
2960         }
2961         /* Tell the HW to drop its old copy of the endpoint context info
2962          * and add the updated copy from the input context.
2963          */
2964         xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
2965                         vdev->out_ctx, changed_ep_bitmask, changed_ep_bitmask);
2966
2967         /* Issue and wait for the configure endpoint command */
2968         ret = xhci_configure_endpoint(xhci, udev, config_cmd,
2969                         false, false);
2970
2971         /* xHC rejected the configure endpoint command for some reason, so we
2972          * leave the old ring intact and free our internal streams data
2973          * structure.
2974          */
2975         if (ret < 0)
2976                 goto cleanup;
2977
2978         spin_lock_irqsave(&xhci->lock, flags);
2979         for (i = 0; i < num_eps; i++) {
2980                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
2981                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
2982                 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
2983                          udev->slot_id, ep_index);
2984                 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
2985         }
2986         xhci_free_command(xhci, config_cmd);
2987         spin_unlock_irqrestore(&xhci->lock, flags);
2988
2989         /* Subtract 1 for stream 0, which drivers can't use */
2990         return num_streams - 1;
2991
2992 cleanup:
2993         /* If it didn't work, free the streams! */
2994         for (i = 0; i < num_eps; i++) {
2995                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
2996                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
2997                 vdev->eps[ep_index].stream_info = NULL;
2998                 /* FIXME Unset maxPstreams in endpoint context and
2999                  * update deq ptr to point to normal string ring.
3000                  */
3001                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3002                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3003                 xhci_endpoint_zero(xhci, vdev, eps[i]);
3004         }
3005         xhci_free_command(xhci, config_cmd);
3006         return -ENOMEM;
3007 }
3008
3009 /* Transition the endpoint from using streams to being a "normal" endpoint
3010  * without streams.
3011  *
3012  * Modify the endpoint context state, submit a configure endpoint command,
3013  * and free all endpoint rings for streams if that completes successfully.
3014  */
3015 int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3016                 struct usb_host_endpoint **eps, unsigned int num_eps,
3017                 gfp_t mem_flags)
3018 {
3019         int i, ret;
3020         struct xhci_hcd *xhci;
3021         struct xhci_virt_device *vdev;
3022         struct xhci_command *command;
3023         unsigned int ep_index;
3024         unsigned long flags;
3025         u32 changed_ep_bitmask;
3026
3027         xhci = hcd_to_xhci(hcd);
3028         vdev = xhci->devs[udev->slot_id];
3029
3030         /* Set up a configure endpoint command to remove the streams rings */
3031         spin_lock_irqsave(&xhci->lock, flags);
3032         changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3033                         udev, eps, num_eps);
3034         if (changed_ep_bitmask == 0) {
3035                 spin_unlock_irqrestore(&xhci->lock, flags);
3036                 return -EINVAL;
3037         }
3038
3039         /* Use the xhci_command structure from the first endpoint.  We may have
3040          * allocated too many, but the driver may call xhci_free_streams() for
3041          * each endpoint it grouped into one call to xhci_alloc_streams().
3042          */
3043         ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3044         command = vdev->eps[ep_index].stream_info->free_streams_command;
3045         for (i = 0; i < num_eps; i++) {
3046                 struct xhci_ep_ctx *ep_ctx;
3047
3048                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3049                 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3050                 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3051                         EP_GETTING_NO_STREAMS;
3052
3053                 xhci_endpoint_copy(xhci, command->in_ctx,
3054                                 vdev->out_ctx, ep_index);
3055                 xhci_setup_no_streams_ep_input_ctx(xhci, ep_ctx,
3056                                 &vdev->eps[ep_index]);
3057         }
3058         xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3059                         vdev->out_ctx, changed_ep_bitmask, changed_ep_bitmask);
3060         spin_unlock_irqrestore(&xhci->lock, flags);
3061
3062         /* Issue and wait for the configure endpoint command,
3063          * which must succeed.
3064          */
3065         ret = xhci_configure_endpoint(xhci, udev, command,
3066                         false, true);
3067
3068         /* xHC rejected the configure endpoint command for some reason, so we
3069          * leave the streams rings intact.
3070          */
3071         if (ret < 0)
3072                 return ret;
3073
3074         spin_lock_irqsave(&xhci->lock, flags);
3075         for (i = 0; i < num_eps; i++) {
3076                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3077                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3078                 vdev->eps[ep_index].stream_info = NULL;
3079                 /* FIXME Unset maxPstreams in endpoint context and
3080                  * update deq ptr to point to normal string ring.
3081                  */
3082                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
3083                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3084         }
3085         spin_unlock_irqrestore(&xhci->lock, flags);
3086
3087         return 0;
3088 }
3089
3090 /*
3091  * Deletes endpoint resources for endpoints that were active before a Reset
3092  * Device command, or a Disable Slot command.  The Reset Device command leaves
3093  * the control endpoint intact, whereas the Disable Slot command deletes it.
3094  *
3095  * Must be called with xhci->lock held.
3096  */
3097 void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
3098         struct xhci_virt_device *virt_dev, bool drop_control_ep)
3099 {
3100         int i;
3101         unsigned int num_dropped_eps = 0;
3102         unsigned int drop_flags = 0;
3103
3104         for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
3105                 if (virt_dev->eps[i].ring) {
3106                         drop_flags |= 1 << i;
3107                         num_dropped_eps++;
3108                 }
3109         }
3110         xhci->num_active_eps -= num_dropped_eps;
3111         if (num_dropped_eps)
3112                 xhci_dbg(xhci, "Dropped %u ep ctxs, flags = 0x%x, "
3113                                 "%u now active.\n",
3114                                 num_dropped_eps, drop_flags,
3115                                 xhci->num_active_eps);
3116 }
3117
3118 /*
3119  * This submits a Reset Device Command, which will set the device state to 0,
3120  * set the device address to 0, and disable all the endpoints except the default
3121  * control endpoint.  The USB core should come back and call
3122  * xhci_address_device(), and then re-set up the configuration.  If this is
3123  * called because of a usb_reset_and_verify_device(), then the old alternate
3124  * settings will be re-installed through the normal bandwidth allocation
3125  * functions.
3126  *
3127  * Wait for the Reset Device command to finish.  Remove all structures
3128  * associated with the endpoints that were disabled.  Clear the input device
3129  * structure?  Cache the rings?  Reset the control endpoint 0 max packet size?
3130  *
3131  * If the virt_dev to be reset does not exist or does not match the udev,
3132  * it means the device is lost, possibly due to the xHC restore error and
3133  * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3134  * re-allocate the device.
3135  */
3136 int xhci_discover_or_reset_device(struct usb_hcd *hcd, struct usb_device *udev)
3137 {
3138         int ret, i;
3139         unsigned long flags;
3140         struct xhci_hcd *xhci;
3141         unsigned int slot_id;
3142         struct xhci_virt_device *virt_dev;
3143         struct xhci_command *reset_device_cmd;
3144         int timeleft;
3145         int last_freed_endpoint;
3146         struct xhci_slot_ctx *slot_ctx;
3147         int old_active_eps = 0;
3148
3149         ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3150         if (ret <= 0)
3151                 return ret;
3152         xhci = hcd_to_xhci(hcd);
3153         slot_id = udev->slot_id;
3154         virt_dev = xhci->devs[slot_id];
3155         if (!virt_dev) {
3156                 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3157                                 "not exist. Re-allocate the device\n", slot_id);
3158                 ret = xhci_alloc_dev(hcd, udev);
3159                 if (ret == 1)
3160                         return 0;
3161                 else
3162                         return -EINVAL;
3163         }
3164
3165         if (virt_dev->udev != udev) {
3166                 /* If the virt_dev and the udev does not match, this virt_dev
3167                  * may belong to another udev.
3168                  * Re-allocate the device.
3169                  */
3170                 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3171                                 "not match the udev. Re-allocate the device\n",
3172                                 slot_id);
3173                 ret = xhci_alloc_dev(hcd, udev);
3174                 if (ret == 1)
3175                         return 0;
3176                 else
3177                         return -EINVAL;
3178         }
3179
3180         /* If device is not setup, there is no point in resetting it */
3181         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3182         if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3183                                                 SLOT_STATE_DISABLED)
3184                 return 0;
3185
3186         xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3187         /* Allocate the command structure that holds the struct completion.
3188          * Assume we're in process context, since the normal device reset
3189          * process has to wait for the device anyway.  Storage devices are
3190          * reset as part of error handling, so use GFP_NOIO instead of
3191          * GFP_KERNEL.
3192          */
3193         reset_device_cmd = xhci_alloc_command(xhci, false, true, GFP_NOIO);
3194         if (!reset_device_cmd) {
3195                 xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3196                 return -ENOMEM;
3197         }
3198
3199         /* Attempt to submit the Reset Device command to the command ring */
3200         spin_lock_irqsave(&xhci->lock, flags);
3201         reset_device_cmd->command_trb = xhci->cmd_ring->enqueue;
3202
3203         /* Enqueue pointer can be left pointing to the link TRB,
3204          * we must handle that
3205          */
3206         if (TRB_TYPE_LINK_LE32(reset_device_cmd->command_trb->link.control))
3207                 reset_device_cmd->command_trb =
3208                         xhci->cmd_ring->enq_seg->next->trbs;
3209
3210         list_add_tail(&reset_device_cmd->cmd_list, &virt_dev->cmd_list);
3211         ret = xhci_queue_reset_device(xhci, slot_id);
3212         if (ret) {
3213                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3214                 list_del(&reset_device_cmd->cmd_list);
3215                 spin_unlock_irqrestore(&xhci->lock, flags);
3216                 goto command_cleanup;
3217         }
3218         xhci_ring_cmd_db(xhci);
3219         spin_unlock_irqrestore(&xhci->lock, flags);
3220
3221         /* Wait for the Reset Device command to finish */
3222         timeleft = wait_for_completion_interruptible_timeout(
3223                         reset_device_cmd->completion,
3224                         USB_CTRL_SET_TIMEOUT);
3225         if (timeleft <= 0) {
3226                 xhci_warn(xhci, "%s while waiting for reset device command\n",
3227                                 timeleft == 0 ? "Timeout" : "Signal");
3228                 spin_lock_irqsave(&xhci->lock, flags);
3229                 /* The timeout might have raced with the event ring handler, so
3230                  * only delete from the list if the item isn't poisoned.
3231                  */
3232                 if (reset_device_cmd->cmd_list.next != LIST_POISON1)
3233                         list_del(&reset_device_cmd->cmd_list);
3234                 spin_unlock_irqrestore(&xhci->lock, flags);
3235                 ret = -ETIME;
3236                 goto command_cleanup;
3237         }
3238
3239         /* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3240          * unless we tried to reset a slot ID that wasn't enabled,
3241          * or the device wasn't in the addressed or configured state.
3242          */
3243         ret = reset_device_cmd->status;
3244         switch (ret) {
3245         case COMP_EBADSLT: /* 0.95 completion code for bad slot ID */
3246         case COMP_CTX_STATE: /* 0.96 completion code for same thing */
3247                 xhci_info(xhci, "Can't reset device (slot ID %u) in %s state\n",
3248                                 slot_id,
3249                                 xhci_get_slot_state(xhci, virt_dev->out_ctx));
3250                 xhci_info(xhci, "Not freeing device rings.\n");
3251                 /* Don't treat this as an error.  May change my mind later. */
3252                 ret = 0;
3253                 goto command_cleanup;
3254         case COMP_SUCCESS:
3255                 xhci_dbg(xhci, "Successful reset device command.\n");
3256                 break;
3257         default:
3258                 if (xhci_is_vendor_info_code(xhci, ret))
3259                         break;
3260                 xhci_warn(xhci, "Unknown completion code %u for "
3261                                 "reset device command.\n", ret);
3262                 ret = -EINVAL;
3263                 goto command_cleanup;
3264         }
3265
3266         /* Free up host controller endpoint resources */
3267         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3268                 spin_lock_irqsave(&xhci->lock, flags);
3269                 /* Don't delete the default control endpoint resources */
3270                 xhci_free_device_endpoint_resources(xhci, virt_dev, false);
3271                 spin_unlock_irqrestore(&xhci->lock, flags);
3272         }
3273
3274         /* Everything but endpoint 0 is disabled, so free or cache the rings. */
3275         last_freed_endpoint = 1;
3276         for (i = 1; i < 31; ++i) {
3277                 struct xhci_virt_ep *ep = &virt_dev->eps[i];
3278
3279                 if (ep->ep_state & EP_HAS_STREAMS) {
3280                         xhci_free_stream_info(xhci, ep->stream_info);
3281                         ep->stream_info = NULL;
3282                         ep->ep_state &= ~EP_HAS_STREAMS;
3283                 }
3284
3285                 if (ep->ring) {
3286                         xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
3287                         last_freed_endpoint = i;
3288                 }
3289                 if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
3290                         xhci_drop_ep_from_interval_table(xhci,
3291                                         &virt_dev->eps[i].bw_info,
3292                                         virt_dev->bw_table,
3293                                         udev,
3294                                         &virt_dev->eps[i],
3295                                         virt_dev->tt_info);
3296                 xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
3297         }
3298         /* If necessary, update the number of active TTs on this root port */
3299         xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
3300
3301         xhci_dbg(xhci, "Output context after successful reset device cmd:\n");
3302         xhci_dbg_ctx(xhci, virt_dev->out_ctx, last_freed_endpoint);
3303         ret = 0;
3304
3305 command_cleanup:
3306         xhci_free_command(xhci, reset_device_cmd);
3307         return ret;
3308 }
3309
3310 /*
3311  * At this point, the struct usb_device is about to go away, the device has
3312  * disconnected, and all traffic has been stopped and the endpoints have been
3313  * disabled.  Free any HC data structures associated with that device.
3314  */
3315 void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
3316 {
3317         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3318         struct xhci_virt_device *virt_dev;
3319         unsigned long flags;
3320         u32 state;
3321         int i, ret;
3322
3323         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3324         /* If the host is halted due to driver unload, we still need to free the
3325          * device.
3326          */
3327         if (ret <= 0 && ret != -ENODEV)
3328                 return;
3329
3330         virt_dev = xhci->devs[udev->slot_id];
3331
3332         /* Stop any wayward timer functions (which may grab the lock) */
3333         for (i = 0; i < 31; ++i) {
3334                 virt_dev->eps[i].ep_state &= ~EP_HALT_PENDING;
3335                 del_timer_sync(&virt_dev->eps[i].stop_cmd_timer);
3336         }
3337
3338         if (udev->usb2_hw_lpm_enabled) {
3339                 xhci_set_usb2_hardware_lpm(hcd, udev, 0);
3340                 udev->usb2_hw_lpm_enabled = 0;
3341         }
3342
3343         spin_lock_irqsave(&xhci->lock, flags);
3344         /* Don't disable the slot if the host controller is dead. */
3345         state = xhci_readl(xhci, &xhci->op_regs->status);
3346         if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
3347                         (xhci->xhc_state & XHCI_STATE_HALTED)) {
3348                 xhci_free_virt_device(xhci, udev->slot_id);
3349                 spin_unlock_irqrestore(&xhci->lock, flags);
3350                 return;
3351         }
3352
3353         if (xhci_queue_slot_control(xhci, TRB_DISABLE_SLOT, udev->slot_id)) {
3354                 spin_unlock_irqrestore(&xhci->lock, flags);
3355                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3356                 return;
3357         }
3358         xhci_ring_cmd_db(xhci);
3359         spin_unlock_irqrestore(&xhci->lock, flags);
3360         /*
3361          * Event command completion handler will free any data structures
3362          * associated with the slot.  XXX Can free sleep?
3363          */
3364 }
3365
3366 /*
3367  * Checks if we have enough host controller resources for the default control
3368  * endpoint.
3369  *
3370  * Must be called with xhci->lock held.
3371  */
3372 static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
3373 {
3374         if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
3375                 xhci_dbg(xhci, "Not enough ep ctxs: "
3376                                 "%u active, need to add 1, limit is %u.\n",
3377                                 xhci->num_active_eps, xhci->limit_active_eps);
3378                 return -ENOMEM;
3379         }
3380         xhci->num_active_eps += 1;
3381         xhci_dbg(xhci, "Adding 1 ep ctx, %u now active.\n",
3382                         xhci->num_active_eps);
3383         return 0;
3384 }
3385
3386
3387 /*
3388  * Returns 0 if the xHC ran out of device slots, the Enable Slot command
3389  * timed out, or allocating memory failed.  Returns 1 on success.
3390  */
3391 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
3392 {
3393         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3394         unsigned long flags;
3395         int timeleft;
3396         int ret;
3397
3398         spin_lock_irqsave(&xhci->lock, flags);
3399         ret = xhci_queue_slot_control(xhci, TRB_ENABLE_SLOT, 0);
3400         if (ret) {
3401                 spin_unlock_irqrestore(&xhci->lock, flags);
3402                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3403                 return 0;
3404         }
3405         xhci_ring_cmd_db(xhci);
3406         spin_unlock_irqrestore(&xhci->lock, flags);
3407
3408         /* XXX: how much time for xHC slot assignment? */
3409         timeleft = wait_for_completion_interruptible_timeout(&xhci->addr_dev,
3410                         USB_CTRL_SET_TIMEOUT);
3411         if (timeleft <= 0) {
3412                 xhci_warn(xhci, "%s while waiting for a slot\n",
3413                                 timeleft == 0 ? "Timeout" : "Signal");
3414                 /* FIXME cancel the enable slot request */
3415                 return 0;
3416         }
3417
3418         if (!xhci->slot_id) {
3419                 xhci_err(xhci, "Error while assigning device slot ID\n");
3420                 return 0;
3421         }
3422
3423         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3424                 spin_lock_irqsave(&xhci->lock, flags);
3425                 ret = xhci_reserve_host_control_ep_resources(xhci);
3426                 if (ret) {
3427                         spin_unlock_irqrestore(&xhci->lock, flags);
3428                         xhci_warn(xhci, "Not enough host resources, "
3429                                         "active endpoint contexts = %u\n",
3430                                         xhci->num_active_eps);
3431                         goto disable_slot;
3432                 }
3433                 spin_unlock_irqrestore(&xhci->lock, flags);
3434         }
3435         /* Use GFP_NOIO, since this function can be called from
3436          * xhci_discover_or_reset_device(), which may be called as part of
3437          * mass storage driver error handling.
3438          */
3439         if (!xhci_alloc_virt_device(xhci, xhci->slot_id, udev, GFP_NOIO)) {
3440                 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
3441                 goto disable_slot;
3442         }
3443         udev->slot_id = xhci->slot_id;
3444         /* Is this a LS or FS device under a HS hub? */
3445         /* Hub or peripherial? */
3446         return 1;
3447
3448 disable_slot:
3449         /* Disable slot, if we can do it without mem alloc */
3450         spin_lock_irqsave(&xhci->lock, flags);
3451         if (!xhci_queue_slot_control(xhci, TRB_DISABLE_SLOT, udev->slot_id))
3452                 xhci_ring_cmd_db(xhci);
3453         spin_unlock_irqrestore(&xhci->lock, flags);
3454         return 0;
3455 }
3456
3457 /*
3458  * Issue an Address Device command (which will issue a SetAddress request to
3459  * the device).
3460  * We should be protected by the usb_address0_mutex in khubd's hub_port_init, so
3461  * we should only issue and wait on one address command at the same time.
3462  *
3463  * We add one to the device address issued by the hardware because the USB core
3464  * uses address 1 for the root hubs (even though they're not really devices).
3465  */
3466 int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev)
3467 {
3468         unsigned long flags;
3469         int timeleft;
3470         struct xhci_virt_device *virt_dev;
3471         int ret = 0;
3472         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3473         struct xhci_slot_ctx *slot_ctx;
3474         struct xhci_input_control_ctx *ctrl_ctx;
3475         u64 temp_64;
3476
3477         if (!udev->slot_id) {
3478                 xhci_dbg(xhci, "Bad Slot ID %d\n", udev->slot_id);
3479                 return -EINVAL;
3480         }
3481
3482         virt_dev = xhci->devs[udev->slot_id];
3483
3484         if (WARN_ON(!virt_dev)) {
3485                 /*
3486                  * In plug/unplug torture test with an NEC controller,
3487                  * a zero-dereference was observed once due to virt_dev = 0.
3488                  * Print useful debug rather than crash if it is observed again!
3489                  */
3490                 xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
3491                         udev->slot_id);
3492                 return -EINVAL;
3493         }
3494
3495         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
3496         /*
3497          * If this is the first Set Address since device plug-in or
3498          * virt_device realloaction after a resume with an xHCI power loss,
3499          * then set up the slot context.
3500          */
3501         if (!slot_ctx->dev_info)
3502                 xhci_setup_addressable_virt_dev(xhci, udev);
3503         /* Otherwise, update the control endpoint ring enqueue pointer. */
3504         else
3505                 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
3506         ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx);
3507         ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
3508         ctrl_ctx->drop_flags = 0;
3509
3510         xhci_dbg(xhci, "Slot ID %d Input Context:\n", udev->slot_id);
3511         xhci_dbg_ctx(xhci, virt_dev->in_ctx, 2);
3512
3513         spin_lock_irqsave(&xhci->lock, flags);
3514         ret = xhci_queue_address_device(xhci, virt_dev->in_ctx->dma,
3515                                         udev->slot_id);
3516         if (ret) {
3517                 spin_unlock_irqrestore(&xhci->lock, flags);
3518                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3519                 return ret;
3520         }
3521         xhci_ring_cmd_db(xhci);
3522         spin_unlock_irqrestore(&xhci->lock, flags);
3523
3524         /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
3525         timeleft = wait_for_completion_interruptible_timeout(&xhci->addr_dev,
3526                         USB_CTRL_SET_TIMEOUT);
3527         /* FIXME: From section 4.3.4: "Software shall be responsible for timing
3528          * the SetAddress() "recovery interval" required by USB and aborting the
3529          * command on a timeout.
3530          */
3531         if (timeleft <= 0) {
3532                 xhci_warn(xhci, "%s while waiting for address device command\n",
3533                                 timeleft == 0 ? "Timeout" : "Signal");
3534                 /* FIXME cancel the address device command */
3535                 return -ETIME;
3536         }
3537
3538         switch (virt_dev->cmd_status) {
3539         case COMP_CTX_STATE:
3540         case COMP_EBADSLT:
3541                 xhci_err(xhci, "Setup ERROR: address device command for slot %d.\n",
3542                                 udev->slot_id);
3543                 ret = -EINVAL;
3544                 break;
3545         case COMP_TX_ERR:
3546                 dev_warn(&udev->dev, "Device not responding to set address.\n");
3547                 ret = -EPROTO;
3548                 break;
3549         case COMP_DEV_ERR:
3550                 dev_warn(&udev->dev, "ERROR: Incompatible device for address "
3551                                 "device command.\n");
3552                 ret = -ENODEV;
3553                 break;
3554         case COMP_SUCCESS:
3555                 xhci_dbg(xhci, "Successful Address Device command\n");
3556                 break;
3557         default:
3558                 xhci_err(xhci, "ERROR: unexpected command completion "
3559                                 "code 0x%x.\n", virt_dev->cmd_status);
3560                 xhci_dbg(xhci, "Slot ID %d Output Context:\n", udev->slot_id);
3561                 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 2);
3562                 ret = -EINVAL;
3563                 break;
3564         }
3565         if (ret) {
3566                 return ret;
3567         }
3568         temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
3569         xhci_dbg(xhci, "Op regs DCBAA ptr = %#016llx\n", temp_64);
3570         xhci_dbg(xhci, "Slot ID %d dcbaa entry @%p = %#016llx\n",
3571                  udev->slot_id,
3572                  &xhci->dcbaa->dev_context_ptrs[udev->slot_id],
3573                  (unsigned long long)
3574                  le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
3575         xhci_dbg(xhci, "Output Context DMA address = %#08llx\n",
3576                         (unsigned long long)virt_dev->out_ctx->dma);
3577         xhci_dbg(xhci, "Slot ID %d Input Context:\n", udev->slot_id);
3578         xhci_dbg_ctx(xhci, virt_dev->in_ctx, 2);
3579         xhci_dbg(xhci, "Slot ID %d Output Context:\n", udev->slot_id);
3580         xhci_dbg_ctx(xhci, virt_dev->out_ctx, 2);
3581         /*
3582          * USB core uses address 1 for the roothubs, so we add one to the
3583          * address given back to us by the HC.
3584          */
3585         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3586         /* Use kernel assigned address for devices; store xHC assigned
3587          * address locally. */
3588         virt_dev->address = (le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK)
3589                 + 1;
3590         /* Zero the input context control for later use */
3591         ctrl_ctx->add_flags = 0;
3592         ctrl_ctx->drop_flags = 0;
3593
3594         xhci_dbg(xhci, "Internal device address = %d\n", virt_dev->address);
3595
3596         return 0;
3597 }
3598
3599 #ifdef CONFIG_USB_SUSPEND
3600
3601 /* BESL to HIRD Encoding array for USB2 LPM */
3602 static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
3603         3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
3604
3605 /* Calculate HIRD/BESL for USB2 PORTPMSC*/
3606 static int xhci_calculate_hird_besl(int u2del, bool use_besl)
3607 {
3608         int hird;
3609
3610         if (use_besl) {
3611                 for (hird = 0; hird < 16; hird++) {
3612                         if (xhci_besl_encoding[hird] >= u2del)
3613                                 break;
3614                 }
3615         } else {
3616                 if (u2del <= 50)
3617                         hird = 0;
3618                 else
3619                         hird = (u2del - 51) / 75 + 1;
3620
3621                 if (hird > 15)
3622                         hird = 15;
3623         }
3624
3625         return hird;
3626 }
3627
3628 static int xhci_usb2_software_lpm_test(struct usb_hcd *hcd,
3629                                         struct usb_device *udev)
3630 {
3631         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3632         struct dev_info *dev_info;
3633         __le32 __iomem  **port_array;
3634         __le32 __iomem  *addr, *pm_addr;
3635         u32             temp, dev_id;
3636         unsigned int    port_num;
3637         unsigned long   flags;
3638         int             u2del, hird;
3639         int             ret;
3640
3641         if (hcd->speed == HCD_USB3 || !xhci->sw_lpm_support ||
3642                         !udev->lpm_capable)
3643                 return -EINVAL;
3644
3645         /* we only support lpm for non-hub device connected to root hub yet */
3646         if (!udev->parent || udev->parent->parent ||
3647                         udev->descriptor.bDeviceClass == USB_CLASS_HUB)
3648                 return -EINVAL;
3649
3650         spin_lock_irqsave(&xhci->lock, flags);
3651
3652         /* Look for devices in lpm_failed_devs list */
3653         dev_id = le16_to_cpu(udev->descriptor.idVendor) << 16 |
3654                         le16_to_cpu(udev->descriptor.idProduct);
3655         list_for_each_entry(dev_info, &xhci->lpm_failed_devs, list) {
3656                 if (dev_info->dev_id == dev_id) {
3657                         ret = -EINVAL;
3658                         goto finish;
3659                 }
3660         }
3661
3662         port_array = xhci->usb2_ports;
3663         port_num = udev->portnum - 1;
3664
3665         if (port_num > HCS_MAX_PORTS(xhci->hcs_params1)) {
3666                 xhci_dbg(xhci, "invalid port number %d\n", udev->portnum);
3667                 ret = -EINVAL;
3668                 goto finish;
3669         }
3670
3671         /*
3672          * Test USB 2.0 software LPM.
3673          * FIXME: some xHCI 1.0 hosts may implement a new register to set up
3674          * hardware-controlled USB 2.0 LPM. See section 5.4.11 and 4.23.5.1.1.1
3675          * in the June 2011 errata release.
3676          */
3677         xhci_dbg(xhci, "test port %d software LPM\n", port_num);
3678         /*
3679          * Set L1 Device Slot and HIRD/BESL.
3680          * Check device's USB 2.0 extension descriptor to determine whether
3681          * HIRD or BESL shoule be used. See USB2.0 LPM errata.
3682          */
3683         pm_addr = port_array[port_num] + 1;
3684         u2del = HCS_U2_LATENCY(xhci->hcs_params3);
3685         if (le32_to_cpu(udev->bos->ext_cap->bmAttributes) & (1 << 2))
3686                 hird = xhci_calculate_hird_besl(u2del, 1);
3687         else
3688                 hird = xhci_calculate_hird_besl(u2del, 0);
3689
3690         temp = PORT_L1DS(udev->slot_id) | PORT_HIRD(hird);
3691         xhci_writel(xhci, temp, pm_addr);
3692
3693         /* Set port link state to U2(L1) */
3694         addr = port_array[port_num];
3695         xhci_set_link_state(xhci, port_array, port_num, XDEV_U2);
3696
3697         /* wait for ACK */
3698         spin_unlock_irqrestore(&xhci->lock, flags);
3699         msleep(10);
3700         spin_lock_irqsave(&xhci->lock, flags);
3701
3702         /* Check L1 Status */
3703         ret = handshake(xhci, pm_addr, PORT_L1S_MASK, PORT_L1S_SUCCESS, 125);
3704         if (ret != -ETIMEDOUT) {
3705                 /* enter L1 successfully */
3706                 temp = xhci_readl(xhci, addr);
3707                 xhci_dbg(xhci, "port %d entered L1 state, port status 0x%x\n",
3708                                 port_num, temp);
3709                 ret = 0;
3710         } else {
3711                 temp = xhci_readl(xhci, pm_addr);
3712                 xhci_dbg(xhci, "port %d software lpm failed, L1 status %d\n",
3713                                 port_num, temp & PORT_L1S_MASK);
3714                 ret = -EINVAL;
3715         }
3716
3717         /* Resume the port */
3718         xhci_set_link_state(xhci, port_array, port_num, XDEV_U0);
3719
3720         spin_unlock_irqrestore(&xhci->lock, flags);
3721         msleep(10);
3722         spin_lock_irqsave(&xhci->lock, flags);
3723
3724         /* Clear PLC */
3725         xhci_test_and_clear_bit(xhci, port_array, port_num, PORT_PLC);
3726
3727         /* Check PORTSC to make sure the device is in the right state */
3728         if (!ret) {
3729                 temp = xhci_readl(xhci, addr);
3730                 xhci_dbg(xhci, "resumed port %d status 0x%x\n", port_num, temp);
3731                 if (!(temp & PORT_CONNECT) || !(temp & PORT_PE) ||
3732                                 (temp & PORT_PLS_MASK) != XDEV_U0) {
3733                         xhci_dbg(xhci, "port L1 resume fail\n");
3734                         ret = -EINVAL;
3735                 }
3736         }
3737
3738         if (ret) {
3739                 /* Insert dev to lpm_failed_devs list */
3740                 xhci_warn(xhci, "device LPM test failed, may disconnect and "
3741                                 "re-enumerate\n");
3742                 dev_info = kzalloc(sizeof(struct dev_info), GFP_ATOMIC);
3743                 if (!dev_info) {
3744                         ret = -ENOMEM;
3745                         goto finish;
3746                 }
3747                 dev_info->dev_id = dev_id;
3748                 INIT_LIST_HEAD(&dev_info->list);
3749                 list_add(&dev_info->list, &xhci->lpm_failed_devs);
3750         } else {
3751                 xhci_ring_device(xhci, udev->slot_id);
3752         }
3753
3754 finish:
3755         spin_unlock_irqrestore(&xhci->lock, flags);
3756         return ret;
3757 }
3758
3759 int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
3760                         struct usb_device *udev, int enable)
3761 {
3762         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3763         __le32 __iomem  **port_array;
3764         __le32 __iomem  *pm_addr;
3765         u32             temp;
3766         unsigned int    port_num;
3767         unsigned long   flags;
3768         int             u2del, hird;
3769
3770         if (hcd->speed == HCD_USB3 || !xhci->hw_lpm_support ||
3771                         !udev->lpm_capable)
3772                 return -EPERM;
3773
3774         if (!udev->parent || udev->parent->parent ||
3775                         udev->descriptor.bDeviceClass == USB_CLASS_HUB)
3776                 return -EPERM;
3777
3778         if (udev->usb2_hw_lpm_capable != 1)
3779                 return -EPERM;
3780
3781         spin_lock_irqsave(&xhci->lock, flags);
3782
3783         port_array = xhci->usb2_ports;
3784         port_num = udev->portnum - 1;
3785         pm_addr = port_array[port_num] + 1;
3786         temp = xhci_readl(xhci, pm_addr);
3787
3788         xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
3789                         enable ? "enable" : "disable", port_num);
3790
3791         u2del = HCS_U2_LATENCY(xhci->hcs_params3);
3792         if (le32_to_cpu(udev->bos->ext_cap->bmAttributes) & (1 << 2))
3793                 hird = xhci_calculate_hird_besl(u2del, 1);
3794         else
3795                 hird = xhci_calculate_hird_besl(u2del, 0);
3796
3797         if (enable) {
3798                 temp &= ~PORT_HIRD_MASK;
3799                 temp |= PORT_HIRD(hird) | PORT_RWE;
3800                 xhci_writel(xhci, temp, pm_addr);
3801                 temp = xhci_readl(xhci, pm_addr);
3802                 temp |= PORT_HLE;
3803                 xhci_writel(xhci, temp, pm_addr);
3804         } else {
3805                 temp &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK);
3806                 xhci_writel(xhci, temp, pm_addr);
3807         }
3808
3809         spin_unlock_irqrestore(&xhci->lock, flags);
3810         return 0;
3811 }
3812
3813 int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
3814 {
3815         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3816         int             ret;
3817
3818         ret = xhci_usb2_software_lpm_test(hcd, udev);
3819         if (!ret) {
3820                 xhci_dbg(xhci, "software LPM test succeed\n");
3821                 if (xhci->hw_lpm_support == 1) {
3822                         udev->usb2_hw_lpm_capable = 1;
3823                         ret = xhci_set_usb2_hardware_lpm(hcd, udev, 1);
3824                         if (!ret)
3825                                 udev->usb2_hw_lpm_enabled = 1;
3826                 }
3827         }
3828
3829         return 0;
3830 }
3831
3832 #else
3833
3834 int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
3835                                 struct usb_device *udev, int enable)
3836 {
3837         return 0;
3838 }
3839
3840 int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
3841 {
3842         return 0;
3843 }
3844
3845 #endif /* CONFIG_USB_SUSPEND */
3846
3847 /* Once a hub descriptor is fetched for a device, we need to update the xHC's
3848  * internal data structures for the device.
3849  */
3850 int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
3851                         struct usb_tt *tt, gfp_t mem_flags)
3852 {
3853         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3854         struct xhci_virt_device *vdev;
3855         struct xhci_command *config_cmd;
3856         struct xhci_input_control_ctx *ctrl_ctx;
3857         struct xhci_slot_ctx *slot_ctx;
3858         unsigned long flags;
3859         unsigned think_time;
3860         int ret;
3861
3862         /* Ignore root hubs */
3863         if (!hdev->parent)
3864                 return 0;
3865
3866         vdev = xhci->devs[hdev->slot_id];
3867         if (!vdev) {
3868                 xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
3869                 return -EINVAL;
3870         }
3871         config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
3872         if (!config_cmd) {
3873                 xhci_dbg(xhci, "Could not allocate xHCI command structure.\n");
3874                 return -ENOMEM;
3875         }
3876
3877         spin_lock_irqsave(&xhci->lock, flags);
3878         if (hdev->speed == USB_SPEED_HIGH &&
3879                         xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
3880                 xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
3881                 xhci_free_command(xhci, config_cmd);
3882                 spin_unlock_irqrestore(&xhci->lock, flags);
3883                 return -ENOMEM;
3884         }
3885
3886         xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
3887         ctrl_ctx = xhci_get_input_control_ctx(xhci, config_cmd->in_ctx);
3888         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
3889         slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
3890         slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
3891         if (tt->multi)
3892                 slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
3893         if (xhci->hci_version > 0x95) {
3894                 xhci_dbg(xhci, "xHCI version %x needs hub "
3895                                 "TT think time and number of ports\n",
3896                                 (unsigned int) xhci->hci_version);
3897                 slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
3898                 /* Set TT think time - convert from ns to FS bit times.
3899                  * 0 = 8 FS bit times, 1 = 16 FS bit times,
3900                  * 2 = 24 FS bit times, 3 = 32 FS bit times.
3901                  *
3902                  * xHCI 1.0: this field shall be 0 if the device is not a
3903                  * High-spped hub.
3904                  */
3905                 think_time = tt->think_time;
3906                 if (think_time != 0)
3907                         think_time = (think_time / 666) - 1;
3908                 if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
3909                         slot_ctx->tt_info |=
3910                                 cpu_to_le32(TT_THINK_TIME(think_time));
3911         } else {
3912                 xhci_dbg(xhci, "xHCI version %x doesn't need hub "
3913                                 "TT think time or number of ports\n",
3914                                 (unsigned int) xhci->hci_version);
3915         }
3916         slot_ctx->dev_state = 0;
3917         spin_unlock_irqrestore(&xhci->lock, flags);
3918
3919         xhci_dbg(xhci, "Set up %s for hub device.\n",
3920                         (xhci->hci_version > 0x95) ?
3921                         "configure endpoint" : "evaluate context");
3922         xhci_dbg(xhci, "Slot %u Input Context:\n", hdev->slot_id);
3923         xhci_dbg_ctx(xhci, config_cmd->in_ctx, 0);
3924
3925         /* Issue and wait for the configure endpoint or
3926          * evaluate context command.
3927          */
3928         if (xhci->hci_version > 0x95)
3929                 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
3930                                 false, false);
3931         else
3932                 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
3933                                 true, false);
3934
3935         xhci_dbg(xhci, "Slot %u Output Context:\n", hdev->slot_id);
3936         xhci_dbg_ctx(xhci, vdev->out_ctx, 0);
3937
3938         xhci_free_command(xhci, config_cmd);
3939         return ret;
3940 }
3941
3942 int xhci_get_frame(struct usb_hcd *hcd)
3943 {
3944         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3945         /* EHCI mods by the periodic size.  Why? */
3946         return xhci_readl(xhci, &xhci->run_regs->microframe_index) >> 3;
3947 }
3948
3949 int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks)
3950 {
3951         struct xhci_hcd         *xhci;
3952         struct device           *dev = hcd->self.controller;
3953         int                     retval;
3954         u32                     temp;
3955
3956         hcd->self.sg_tablesize = TRBS_PER_SEGMENT - 2;
3957
3958         if (usb_hcd_is_primary_hcd(hcd)) {
3959                 xhci = kzalloc(sizeof(struct xhci_hcd), GFP_KERNEL);
3960                 if (!xhci)
3961                         return -ENOMEM;
3962                 *((struct xhci_hcd **) hcd->hcd_priv) = xhci;
3963                 xhci->main_hcd = hcd;
3964                 /* Mark the first roothub as being USB 2.0.
3965                  * The xHCI driver will register the USB 3.0 roothub.
3966                  */
3967                 hcd->speed = HCD_USB2;
3968                 hcd->self.root_hub->speed = USB_SPEED_HIGH;
3969                 /*
3970                  * USB 2.0 roothub under xHCI has an integrated TT,
3971                  * (rate matching hub) as opposed to having an OHCI/UHCI
3972                  * companion controller.
3973                  */
3974                 hcd->has_tt = 1;
3975         } else {
3976                 /* xHCI private pointer was set in xhci_pci_probe for the second
3977                  * registered roothub.
3978                  */
3979                 xhci = hcd_to_xhci(hcd);
3980                 temp = xhci_readl(xhci, &xhci->cap_regs->hcc_params);
3981                 if (HCC_64BIT_ADDR(temp)) {
3982                         xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
3983                         dma_set_mask(hcd->self.controller, DMA_BIT_MASK(64));
3984                 } else {
3985                         dma_set_mask(hcd->self.controller, DMA_BIT_MASK(32));
3986                 }
3987                 return 0;
3988         }
3989
3990         xhci->cap_regs = hcd->regs;
3991         xhci->op_regs = hcd->regs +
3992                 HC_LENGTH(xhci_readl(xhci, &xhci->cap_regs->hc_capbase));
3993         xhci->run_regs = hcd->regs +
3994                 (xhci_readl(xhci, &xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
3995         /* Cache read-only capability registers */
3996         xhci->hcs_params1 = xhci_readl(xhci, &xhci->cap_regs->hcs_params1);
3997         xhci->hcs_params2 = xhci_readl(xhci, &xhci->cap_regs->hcs_params2);
3998         xhci->hcs_params3 = xhci_readl(xhci, &xhci->cap_regs->hcs_params3);
3999         xhci->hcc_params = xhci_readl(xhci, &xhci->cap_regs->hc_capbase);
4000         xhci->hci_version = HC_VERSION(xhci->hcc_params);
4001         xhci->hcc_params = xhci_readl(xhci, &xhci->cap_regs->hcc_params);
4002         xhci_print_registers(xhci);
4003
4004         get_quirks(dev, xhci);
4005
4006         /* Make sure the HC is halted. */
4007         retval = xhci_halt(xhci);
4008         if (retval)
4009                 goto error;
4010
4011         xhci_dbg(xhci, "Resetting HCD\n");
4012         /* Reset the internal HC memory state and registers. */
4013         retval = xhci_reset(xhci);
4014         if (retval)
4015                 goto error;
4016         xhci_dbg(xhci, "Reset complete\n");
4017
4018         temp = xhci_readl(xhci, &xhci->cap_regs->hcc_params);
4019         if (HCC_64BIT_ADDR(temp)) {
4020                 xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
4021                 dma_set_mask(hcd->self.controller, DMA_BIT_MASK(64));
4022         } else {
4023                 dma_set_mask(hcd->self.controller, DMA_BIT_MASK(32));
4024         }
4025
4026         xhci_dbg(xhci, "Calling HCD init\n");
4027         /* Initialize HCD and host controller data structures. */
4028         retval = xhci_init(hcd);
4029         if (retval)
4030                 goto error;
4031         xhci_dbg(xhci, "Called HCD init\n");
4032         return 0;
4033 error:
4034         kfree(xhci);
4035         return retval;
4036 }
4037
4038 MODULE_DESCRIPTION(DRIVER_DESC);
4039 MODULE_AUTHOR(DRIVER_AUTHOR);
4040 MODULE_LICENSE("GPL");
4041
4042 static int __init xhci_hcd_init(void)
4043 {
4044         int retval;
4045
4046         retval = xhci_register_pci();
4047         if (retval < 0) {
4048                 printk(KERN_DEBUG "Problem registering PCI driver.");
4049                 return retval;
4050         }
4051         /*
4052          * Check the compiler generated sizes of structures that must be laid
4053          * out in specific ways for hardware access.
4054          */
4055         BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
4056         BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
4057         BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
4058         /* xhci_device_control has eight fields, and also
4059          * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
4060          */
4061         BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
4062         BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
4063         BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
4064         BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 7*32/8);
4065         BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
4066         /* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
4067         BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
4068         BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
4069         return 0;
4070 }
4071 module_init(xhci_hcd_init);
4072
4073 static void __exit xhci_hcd_cleanup(void)
4074 {
4075         xhci_unregister_pci();
4076 }
4077 module_exit(xhci_hcd_cleanup);