GNU Linux-libre 4.4.283-gnu1
[releases.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/iopoll.h>
25 #include <linux/irq.h>
26 #include <linux/log2.h>
27 #include <linux/module.h>
28 #include <linux/moduleparam.h>
29 #include <linux/slab.h>
30 #include <linux/dmi.h>
31 #include <linux/dma-mapping.h>
32
33 #include "xhci.h"
34 #include "xhci-trace.h"
35
36 #define DRIVER_AUTHOR "Sarah Sharp"
37 #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
38
39 #define PORT_WAKE_BITS  (PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E)
40
41 /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
42 static int link_quirk;
43 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
44 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
45
46 static unsigned int quirks;
47 module_param(quirks, uint, S_IRUGO);
48 MODULE_PARM_DESC(quirks, "Bit flags for quirks to be enabled as default");
49
50 /*
51  * xhci_handshake - spin reading hc until handshake completes or fails
52  * @ptr: address of hc register to be read
53  * @mask: bits to look at in result of read
54  * @done: value of those bits when handshake succeeds
55  * @usec: timeout in microseconds
56  *
57  * Returns negative errno, or zero on success
58  *
59  * Success happens when the "mask" bits have the specified value (hardware
60  * handshake done).  There are two failure modes:  "usec" have passed (major
61  * hardware flakeout), or the register reads as all-ones (hardware removed).
62  */
63 int xhci_handshake(void __iomem *ptr, u32 mask, u32 done, int usec)
64 {
65         u32     result;
66         int     ret;
67
68         ret = readl_poll_timeout_atomic(ptr, result,
69                                         (result & mask) == done ||
70                                         result == U32_MAX,
71                                         1, usec);
72         if (result == U32_MAX)          /* card removed */
73                 return -ENODEV;
74
75         return ret;
76 }
77
78 /*
79  * Disable interrupts and begin the xHCI halting process.
80  */
81 void xhci_quiesce(struct xhci_hcd *xhci)
82 {
83         u32 halted;
84         u32 cmd;
85         u32 mask;
86
87         mask = ~(XHCI_IRQS);
88         halted = readl(&xhci->op_regs->status) & STS_HALT;
89         if (!halted)
90                 mask &= ~CMD_RUN;
91
92         cmd = readl(&xhci->op_regs->command);
93         cmd &= mask;
94         writel(cmd, &xhci->op_regs->command);
95 }
96
97 /*
98  * Force HC into halt state.
99  *
100  * Disable any IRQs and clear the run/stop bit.
101  * HC will complete any current and actively pipelined transactions, and
102  * should halt within 16 ms of the run/stop bit being cleared.
103  * Read HC Halted bit in the status register to see when the HC is finished.
104  */
105 int xhci_halt(struct xhci_hcd *xhci)
106 {
107         int ret;
108         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Halt the HC");
109         xhci_quiesce(xhci);
110
111         ret = xhci_handshake(&xhci->op_regs->status,
112                         STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
113         if (!ret) {
114                 xhci->xhc_state |= XHCI_STATE_HALTED;
115                 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
116         } else
117                 xhci_warn(xhci, "Host not halted after %u microseconds.\n",
118                                 XHCI_MAX_HALT_USEC);
119         return ret;
120 }
121
122 /*
123  * Set the run bit and wait for the host to be running.
124  */
125 static int xhci_start(struct xhci_hcd *xhci)
126 {
127         u32 temp;
128         int ret;
129
130         temp = readl(&xhci->op_regs->command);
131         temp |= (CMD_RUN);
132         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Turn on HC, cmd = 0x%x.",
133                         temp);
134         writel(temp, &xhci->op_regs->command);
135
136         /*
137          * Wait for the HCHalted Status bit to be 0 to indicate the host is
138          * running.
139          */
140         ret = xhci_handshake(&xhci->op_regs->status,
141                         STS_HALT, 0, XHCI_MAX_HALT_USEC);
142         if (ret == -ETIMEDOUT)
143                 xhci_err(xhci, "Host took too long to start, "
144                                 "waited %u microseconds.\n",
145                                 XHCI_MAX_HALT_USEC);
146         if (!ret)
147                 /* clear state flags. Including dying, halted or removing */
148                 xhci->xhc_state = 0;
149
150         return ret;
151 }
152
153 /*
154  * Reset a halted HC.
155  *
156  * This resets pipelines, timers, counters, state machines, etc.
157  * Transactions will be terminated immediately, and operational registers
158  * will be set to their defaults.
159  */
160 int xhci_reset(struct xhci_hcd *xhci)
161 {
162         u32 command;
163         u32 state;
164         int ret, i;
165
166         state = readl(&xhci->op_regs->status);
167         if ((state & STS_HALT) == 0) {
168                 xhci_warn(xhci, "Host controller not halted, aborting reset.\n");
169                 return 0;
170         }
171
172         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Reset the HC");
173         command = readl(&xhci->op_regs->command);
174         command |= CMD_RESET;
175         writel(command, &xhci->op_regs->command);
176
177         /* Existing Intel xHCI controllers require a delay of 1 mS,
178          * after setting the CMD_RESET bit, and before accessing any
179          * HC registers. This allows the HC to complete the
180          * reset operation and be ready for HC register access.
181          * Without this delay, the subsequent HC register access,
182          * may result in a system hang very rarely.
183          */
184         if (xhci->quirks & XHCI_INTEL_HOST)
185                 udelay(1000);
186
187         ret = xhci_handshake(&xhci->op_regs->command,
188                         CMD_RESET, 0, 10 * 1000 * 1000);
189         if (ret)
190                 return ret;
191
192         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
193                          "Wait for controller to be ready for doorbell rings");
194         /*
195          * xHCI cannot write to any doorbells or operational registers other
196          * than status until the "Controller Not Ready" flag is cleared.
197          */
198         ret = xhci_handshake(&xhci->op_regs->status,
199                         STS_CNR, 0, 10 * 1000 * 1000);
200
201         for (i = 0; i < 2; ++i) {
202                 xhci->bus_state[i].port_c_suspend = 0;
203                 xhci->bus_state[i].suspended_ports = 0;
204                 xhci->bus_state[i].resuming_ports = 0;
205         }
206
207         return ret;
208 }
209
210 #ifdef CONFIG_PCI
211 static int xhci_free_msi(struct xhci_hcd *xhci)
212 {
213         int i;
214
215         if (!xhci->msix_entries)
216                 return -EINVAL;
217
218         for (i = 0; i < xhci->msix_count; i++)
219                 if (xhci->msix_entries[i].vector)
220                         free_irq(xhci->msix_entries[i].vector,
221                                         xhci_to_hcd(xhci));
222         return 0;
223 }
224
225 /*
226  * Set up MSI
227  */
228 static int xhci_setup_msi(struct xhci_hcd *xhci)
229 {
230         int ret;
231         struct pci_dev  *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
232
233         ret = pci_enable_msi(pdev);
234         if (ret) {
235                 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
236                                 "failed to allocate MSI entry");
237                 return ret;
238         }
239
240         ret = request_irq(pdev->irq, xhci_msi_irq,
241                                 0, "xhci_hcd", xhci_to_hcd(xhci));
242         if (ret) {
243                 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
244                                 "disable MSI interrupt");
245                 pci_disable_msi(pdev);
246         }
247
248         return ret;
249 }
250
251 /*
252  * Free IRQs
253  * free all IRQs request
254  */
255 static void xhci_free_irq(struct xhci_hcd *xhci)
256 {
257         struct pci_dev *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
258         int ret;
259
260         /* return if using legacy interrupt */
261         if (xhci_to_hcd(xhci)->irq > 0)
262                 return;
263
264         ret = xhci_free_msi(xhci);
265         if (!ret)
266                 return;
267         if (pdev->irq > 0)
268                 free_irq(pdev->irq, xhci_to_hcd(xhci));
269
270         return;
271 }
272
273 /*
274  * Set up MSI-X
275  */
276 static int xhci_setup_msix(struct xhci_hcd *xhci)
277 {
278         int i, ret = 0;
279         struct usb_hcd *hcd = xhci_to_hcd(xhci);
280         struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
281
282         /*
283          * calculate number of msi-x vectors supported.
284          * - HCS_MAX_INTRS: the max number of interrupts the host can handle,
285          *   with max number of interrupters based on the xhci HCSPARAMS1.
286          * - num_online_cpus: maximum msi-x vectors per CPUs core.
287          *   Add additional 1 vector to ensure always available interrupt.
288          */
289         xhci->msix_count = min(num_online_cpus() + 1,
290                                 HCS_MAX_INTRS(xhci->hcs_params1));
291
292         xhci->msix_entries =
293                 kmalloc((sizeof(struct msix_entry))*xhci->msix_count,
294                                 GFP_KERNEL);
295         if (!xhci->msix_entries) {
296                 xhci_err(xhci, "Failed to allocate MSI-X entries\n");
297                 return -ENOMEM;
298         }
299
300         for (i = 0; i < xhci->msix_count; i++) {
301                 xhci->msix_entries[i].entry = i;
302                 xhci->msix_entries[i].vector = 0;
303         }
304
305         ret = pci_enable_msix_exact(pdev, xhci->msix_entries, xhci->msix_count);
306         if (ret) {
307                 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
308                                 "Failed to enable MSI-X");
309                 goto free_entries;
310         }
311
312         for (i = 0; i < xhci->msix_count; i++) {
313                 ret = request_irq(xhci->msix_entries[i].vector,
314                                 xhci_msi_irq,
315                                 0, "xhci_hcd", xhci_to_hcd(xhci));
316                 if (ret)
317                         goto disable_msix;
318         }
319
320         hcd->msix_enabled = 1;
321         return ret;
322
323 disable_msix:
324         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "disable MSI-X interrupt");
325         xhci_free_irq(xhci);
326         pci_disable_msix(pdev);
327 free_entries:
328         kfree(xhci->msix_entries);
329         xhci->msix_entries = NULL;
330         return ret;
331 }
332
333 /* Free any IRQs and disable MSI-X */
334 static void xhci_cleanup_msix(struct xhci_hcd *xhci)
335 {
336         struct usb_hcd *hcd = xhci_to_hcd(xhci);
337         struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
338
339         if (xhci->quirks & XHCI_PLAT)
340                 return;
341
342         xhci_free_irq(xhci);
343
344         if (xhci->msix_entries) {
345                 pci_disable_msix(pdev);
346                 kfree(xhci->msix_entries);
347                 xhci->msix_entries = NULL;
348         } else {
349                 pci_disable_msi(pdev);
350         }
351
352         hcd->msix_enabled = 0;
353         return;
354 }
355
356 static void __maybe_unused xhci_msix_sync_irqs(struct xhci_hcd *xhci)
357 {
358         int i;
359
360         if (xhci->msix_entries) {
361                 for (i = 0; i < xhci->msix_count; i++)
362                         synchronize_irq(xhci->msix_entries[i].vector);
363         }
364 }
365
366 static int xhci_try_enable_msi(struct usb_hcd *hcd)
367 {
368         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
369         struct pci_dev  *pdev;
370         int ret;
371
372         /* The xhci platform device has set up IRQs through usb_add_hcd. */
373         if (xhci->quirks & XHCI_PLAT)
374                 return 0;
375
376         pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
377         /*
378          * Some Fresco Logic host controllers advertise MSI, but fail to
379          * generate interrupts.  Don't even try to enable MSI.
380          */
381         if (xhci->quirks & XHCI_BROKEN_MSI)
382                 goto legacy_irq;
383
384         /* unregister the legacy interrupt */
385         if (hcd->irq)
386                 free_irq(hcd->irq, hcd);
387         hcd->irq = 0;
388
389         ret = xhci_setup_msix(xhci);
390         if (ret)
391                 /* fall back to msi*/
392                 ret = xhci_setup_msi(xhci);
393
394         if (!ret)
395                 /* hcd->irq is 0, we have MSI */
396                 return 0;
397
398         if (!pdev->irq) {
399                 xhci_err(xhci, "No msi-x/msi found and no IRQ in BIOS\n");
400                 return -EINVAL;
401         }
402
403  legacy_irq:
404         if (!strlen(hcd->irq_descr))
405                 snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
406                          hcd->driver->description, hcd->self.busnum);
407
408         /* fall back to legacy interrupt*/
409         ret = request_irq(pdev->irq, &usb_hcd_irq, IRQF_SHARED,
410                         hcd->irq_descr, hcd);
411         if (ret) {
412                 xhci_err(xhci, "request interrupt %d failed\n",
413                                 pdev->irq);
414                 return ret;
415         }
416         hcd->irq = pdev->irq;
417         return 0;
418 }
419
420 #else
421
422 static inline int xhci_try_enable_msi(struct usb_hcd *hcd)
423 {
424         return 0;
425 }
426
427 static inline void xhci_cleanup_msix(struct xhci_hcd *xhci)
428 {
429 }
430
431 static inline void xhci_msix_sync_irqs(struct xhci_hcd *xhci)
432 {
433 }
434
435 #endif
436
437 static void compliance_mode_recovery(unsigned long arg)
438 {
439         struct xhci_hcd *xhci;
440         struct usb_hcd *hcd;
441         u32 temp;
442         int i;
443
444         xhci = (struct xhci_hcd *)arg;
445
446         for (i = 0; i < xhci->num_usb3_ports; i++) {
447                 temp = readl(xhci->usb3_ports[i]);
448                 if ((temp & PORT_PLS_MASK) == USB_SS_PORT_LS_COMP_MOD) {
449                         /*
450                          * Compliance Mode Detected. Letting USB Core
451                          * handle the Warm Reset
452                          */
453                         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
454                                         "Compliance mode detected->port %d",
455                                         i + 1);
456                         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
457                                         "Attempting compliance mode recovery");
458                         hcd = xhci->shared_hcd;
459
460                         if (hcd->state == HC_STATE_SUSPENDED)
461                                 usb_hcd_resume_root_hub(hcd);
462
463                         usb_hcd_poll_rh_status(hcd);
464                 }
465         }
466
467         if (xhci->port_status_u0 != ((1 << xhci->num_usb3_ports)-1))
468                 mod_timer(&xhci->comp_mode_recovery_timer,
469                         jiffies + msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
470 }
471
472 /*
473  * Quirk to work around issue generated by the SN65LVPE502CP USB3.0 re-driver
474  * that causes ports behind that hardware to enter compliance mode sometimes.
475  * The quirk creates a timer that polls every 2 seconds the link state of
476  * each host controller's port and recovers it by issuing a Warm reset
477  * if Compliance mode is detected, otherwise the port will become "dead" (no
478  * device connections or disconnections will be detected anymore). Becasue no
479  * status event is generated when entering compliance mode (per xhci spec),
480  * this quirk is needed on systems that have the failing hardware installed.
481  */
482 static void compliance_mode_recovery_timer_init(struct xhci_hcd *xhci)
483 {
484         xhci->port_status_u0 = 0;
485         setup_timer(&xhci->comp_mode_recovery_timer,
486                     compliance_mode_recovery, (unsigned long)xhci);
487         xhci->comp_mode_recovery_timer.expires = jiffies +
488                         msecs_to_jiffies(COMP_MODE_RCVRY_MSECS);
489
490         set_timer_slack(&xhci->comp_mode_recovery_timer,
491                         msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
492         add_timer(&xhci->comp_mode_recovery_timer);
493         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
494                         "Compliance mode recovery timer initialized");
495 }
496
497 /*
498  * This function identifies the systems that have installed the SN65LVPE502CP
499  * USB3.0 re-driver and that need the Compliance Mode Quirk.
500  * Systems:
501  * Vendor: Hewlett-Packard -> System Models: Z420, Z620 and Z820
502  */
503 static bool xhci_compliance_mode_recovery_timer_quirk_check(void)
504 {
505         const char *dmi_product_name, *dmi_sys_vendor;
506
507         dmi_product_name = dmi_get_system_info(DMI_PRODUCT_NAME);
508         dmi_sys_vendor = dmi_get_system_info(DMI_SYS_VENDOR);
509         if (!dmi_product_name || !dmi_sys_vendor)
510                 return false;
511
512         if (!(strstr(dmi_sys_vendor, "Hewlett-Packard")))
513                 return false;
514
515         if (strstr(dmi_product_name, "Z420") ||
516                         strstr(dmi_product_name, "Z620") ||
517                         strstr(dmi_product_name, "Z820") ||
518                         strstr(dmi_product_name, "Z1 Workstation"))
519                 return true;
520
521         return false;
522 }
523
524 static int xhci_all_ports_seen_u0(struct xhci_hcd *xhci)
525 {
526         return (xhci->port_status_u0 == ((1 << xhci->num_usb3_ports)-1));
527 }
528
529
530 /*
531  * Initialize memory for HCD and xHC (one-time init).
532  *
533  * Program the PAGESIZE register, initialize the device context array, create
534  * device contexts (?), set up a command ring segment (or two?), create event
535  * ring (one for now).
536  */
537 int xhci_init(struct usb_hcd *hcd)
538 {
539         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
540         int retval = 0;
541
542         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_init");
543         spin_lock_init(&xhci->lock);
544         if (xhci->hci_version == 0x95 && link_quirk) {
545                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
546                                 "QUIRK: Not clearing Link TRB chain bits.");
547                 xhci->quirks |= XHCI_LINK_TRB_QUIRK;
548         } else {
549                 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
550                                 "xHCI doesn't need link TRB QUIRK");
551         }
552         retval = xhci_mem_init(xhci, GFP_KERNEL);
553         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Finished xhci_init");
554
555         /* Initializing Compliance Mode Recovery Data If Needed */
556         if (xhci_compliance_mode_recovery_timer_quirk_check()) {
557                 xhci->quirks |= XHCI_COMP_MODE_QUIRK;
558                 compliance_mode_recovery_timer_init(xhci);
559         }
560
561         return retval;
562 }
563
564 /*-------------------------------------------------------------------------*/
565
566
567 static int xhci_run_finished(struct xhci_hcd *xhci)
568 {
569         if (xhci_start(xhci)) {
570                 xhci_halt(xhci);
571                 return -ENODEV;
572         }
573         xhci->shared_hcd->state = HC_STATE_RUNNING;
574         xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
575
576         if (xhci->quirks & XHCI_NEC_HOST)
577                 xhci_ring_cmd_db(xhci);
578
579         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
580                         "Finished xhci_run for USB3 roothub");
581         return 0;
582 }
583
584 /*
585  * Start the HC after it was halted.
586  *
587  * This function is called by the USB core when the HC driver is added.
588  * Its opposite is xhci_stop().
589  *
590  * xhci_init() must be called once before this function can be called.
591  * Reset the HC, enable device slot contexts, program DCBAAP, and
592  * set command ring pointer and event ring pointer.
593  *
594  * Setup MSI-X vectors and enable interrupts.
595  */
596 int xhci_run(struct usb_hcd *hcd)
597 {
598         u32 temp;
599         u64 temp_64;
600         int ret;
601         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
602
603         /* Start the xHCI host controller running only after the USB 2.0 roothub
604          * is setup.
605          */
606
607         hcd->uses_new_polling = 1;
608         if (!usb_hcd_is_primary_hcd(hcd))
609                 return xhci_run_finished(xhci);
610
611         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_run");
612
613         ret = xhci_try_enable_msi(hcd);
614         if (ret)
615                 return ret;
616
617         xhci_dbg(xhci, "Command ring memory map follows:\n");
618         xhci_debug_ring(xhci, xhci->cmd_ring);
619         xhci_dbg_ring_ptrs(xhci, xhci->cmd_ring);
620         xhci_dbg_cmd_ptrs(xhci);
621
622         xhci_dbg(xhci, "ERST memory map follows:\n");
623         xhci_dbg_erst(xhci, &xhci->erst);
624         xhci_dbg(xhci, "Event ring:\n");
625         xhci_debug_ring(xhci, xhci->event_ring);
626         xhci_dbg_ring_ptrs(xhci, xhci->event_ring);
627         temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
628         temp_64 &= ~ERST_PTR_MASK;
629         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
630                         "ERST deq = 64'h%0lx", (long unsigned int) temp_64);
631
632         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
633                         "// Set the interrupt modulation register");
634         temp = readl(&xhci->ir_set->irq_control);
635         temp &= ~ER_IRQ_INTERVAL_MASK;
636         temp |= (u32) 160;
637         writel(temp, &xhci->ir_set->irq_control);
638
639         /* Set the HCD state before we enable the irqs */
640         temp = readl(&xhci->op_regs->command);
641         temp |= (CMD_EIE);
642         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
643                         "// Enable interrupts, cmd = 0x%x.", temp);
644         writel(temp, &xhci->op_regs->command);
645
646         temp = readl(&xhci->ir_set->irq_pending);
647         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
648                         "// Enabling event ring interrupter %p by writing 0x%x to irq_pending",
649                         xhci->ir_set, (unsigned int) ER_IRQ_ENABLE(temp));
650         writel(ER_IRQ_ENABLE(temp), &xhci->ir_set->irq_pending);
651         xhci_print_ir_set(xhci, 0);
652
653         if (xhci->quirks & XHCI_NEC_HOST) {
654                 struct xhci_command *command;
655                 command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
656                 if (!command)
657                         return -ENOMEM;
658                 xhci_queue_vendor_command(xhci, command, 0, 0, 0,
659                                 TRB_TYPE(TRB_NEC_GET_FW));
660         }
661         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
662                         "Finished xhci_run for USB2 roothub");
663         return 0;
664 }
665 EXPORT_SYMBOL_GPL(xhci_run);
666
667 /*
668  * Stop xHCI driver.
669  *
670  * This function is called by the USB core when the HC driver is removed.
671  * Its opposite is xhci_run().
672  *
673  * Disable device contexts, disable IRQs, and quiesce the HC.
674  * Reset the HC, finish any completed transactions, and cleanup memory.
675  */
676 void xhci_stop(struct usb_hcd *hcd)
677 {
678         u32 temp;
679         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
680
681         mutex_lock(&xhci->mutex);
682
683         if (!(xhci->xhc_state & XHCI_STATE_HALTED)) {
684                 spin_lock_irq(&xhci->lock);
685
686                 xhci->xhc_state |= XHCI_STATE_HALTED;
687                 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
688                 xhci_halt(xhci);
689                 xhci_reset(xhci);
690
691                 spin_unlock_irq(&xhci->lock);
692         }
693
694         if (!usb_hcd_is_primary_hcd(hcd)) {
695                 mutex_unlock(&xhci->mutex);
696                 return;
697         }
698
699         xhci_cleanup_msix(xhci);
700
701         /* Deleting Compliance Mode Recovery Timer */
702         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
703                         (!(xhci_all_ports_seen_u0(xhci)))) {
704                 del_timer_sync(&xhci->comp_mode_recovery_timer);
705                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
706                                 "%s: compliance mode recovery timer deleted",
707                                 __func__);
708         }
709
710         if (xhci->quirks & XHCI_AMD_PLL_FIX)
711                 usb_amd_dev_put();
712
713         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
714                         "// Disabling event ring interrupts");
715         temp = readl(&xhci->op_regs->status);
716         writel(temp & ~STS_EINT, &xhci->op_regs->status);
717         temp = readl(&xhci->ir_set->irq_pending);
718         writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
719         xhci_print_ir_set(xhci, 0);
720
721         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "cleaning up memory");
722         xhci_mem_cleanup(xhci);
723         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
724                         "xhci_stop completed - status = %x",
725                         readl(&xhci->op_regs->status));
726         mutex_unlock(&xhci->mutex);
727 }
728
729 /*
730  * Shutdown HC (not bus-specific)
731  *
732  * This is called when the machine is rebooting or halting.  We assume that the
733  * machine will be powered off, and the HC's internal state will be reset.
734  * Don't bother to free memory.
735  *
736  * This will only ever be called with the main usb_hcd (the USB3 roothub).
737  */
738 void xhci_shutdown(struct usb_hcd *hcd)
739 {
740         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
741
742         if (xhci->quirks & XHCI_SPURIOUS_REBOOT)
743                 usb_disable_xhci_ports(to_pci_dev(hcd->self.controller));
744
745         spin_lock_irq(&xhci->lock);
746         xhci_halt(xhci);
747         /* Workaround for spurious wakeups at shutdown with HSW */
748         if (xhci->quirks & XHCI_SPURIOUS_WAKEUP)
749                 xhci_reset(xhci);
750         spin_unlock_irq(&xhci->lock);
751
752         xhci_cleanup_msix(xhci);
753
754         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
755                         "xhci_shutdown completed - status = %x",
756                         readl(&xhci->op_regs->status));
757 }
758 EXPORT_SYMBOL_GPL(xhci_shutdown);
759
760 #ifdef CONFIG_PM
761 static void xhci_save_registers(struct xhci_hcd *xhci)
762 {
763         xhci->s3.command = readl(&xhci->op_regs->command);
764         xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
765         xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
766         xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);
767         xhci->s3.erst_size = readl(&xhci->ir_set->erst_size);
768         xhci->s3.erst_base = xhci_read_64(xhci, &xhci->ir_set->erst_base);
769         xhci->s3.erst_dequeue = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
770         xhci->s3.irq_pending = readl(&xhci->ir_set->irq_pending);
771         xhci->s3.irq_control = readl(&xhci->ir_set->irq_control);
772 }
773
774 static void xhci_restore_registers(struct xhci_hcd *xhci)
775 {
776         writel(xhci->s3.command, &xhci->op_regs->command);
777         writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
778         xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
779         writel(xhci->s3.config_reg, &xhci->op_regs->config_reg);
780         writel(xhci->s3.erst_size, &xhci->ir_set->erst_size);
781         xhci_write_64(xhci, xhci->s3.erst_base, &xhci->ir_set->erst_base);
782         xhci_write_64(xhci, xhci->s3.erst_dequeue, &xhci->ir_set->erst_dequeue);
783         writel(xhci->s3.irq_pending, &xhci->ir_set->irq_pending);
784         writel(xhci->s3.irq_control, &xhci->ir_set->irq_control);
785 }
786
787 static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
788 {
789         u64     val_64;
790
791         /* step 2: initialize command ring buffer */
792         val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
793         val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
794                 (xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
795                                       xhci->cmd_ring->dequeue) &
796                  (u64) ~CMD_RING_RSVD_BITS) |
797                 xhci->cmd_ring->cycle_state;
798         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
799                         "// Setting command ring address to 0x%llx",
800                         (long unsigned long) val_64);
801         xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
802 }
803
804 /*
805  * The whole command ring must be cleared to zero when we suspend the host.
806  *
807  * The host doesn't save the command ring pointer in the suspend well, so we
808  * need to re-program it on resume.  Unfortunately, the pointer must be 64-byte
809  * aligned, because of the reserved bits in the command ring dequeue pointer
810  * register.  Therefore, we can't just set the dequeue pointer back in the
811  * middle of the ring (TRBs are 16-byte aligned).
812  */
813 static void xhci_clear_command_ring(struct xhci_hcd *xhci)
814 {
815         struct xhci_ring *ring;
816         struct xhci_segment *seg;
817
818         ring = xhci->cmd_ring;
819         seg = ring->deq_seg;
820         do {
821                 memset(seg->trbs, 0,
822                         sizeof(union xhci_trb) * (TRBS_PER_SEGMENT - 1));
823                 seg->trbs[TRBS_PER_SEGMENT - 1].link.control &=
824                         cpu_to_le32(~TRB_CYCLE);
825                 seg = seg->next;
826         } while (seg != ring->deq_seg);
827
828         /* Reset the software enqueue and dequeue pointers */
829         ring->deq_seg = ring->first_seg;
830         ring->dequeue = ring->first_seg->trbs;
831         ring->enq_seg = ring->deq_seg;
832         ring->enqueue = ring->dequeue;
833
834         ring->num_trbs_free = ring->num_segs * (TRBS_PER_SEGMENT - 1) - 1;
835         /*
836          * Ring is now zeroed, so the HW should look for change of ownership
837          * when the cycle bit is set to 1.
838          */
839         ring->cycle_state = 1;
840
841         /*
842          * Reset the hardware dequeue pointer.
843          * Yes, this will need to be re-written after resume, but we're paranoid
844          * and want to make sure the hardware doesn't access bogus memory
845          * because, say, the BIOS or an SMI started the host without changing
846          * the command ring pointers.
847          */
848         xhci_set_cmd_ring_deq(xhci);
849 }
850
851 static void xhci_disable_port_wake_on_bits(struct xhci_hcd *xhci)
852 {
853         int port_index;
854         __le32 __iomem **port_array;
855         unsigned long flags;
856         u32 t1, t2;
857
858         spin_lock_irqsave(&xhci->lock, flags);
859
860         /* disble usb3 ports Wake bits*/
861         port_index = xhci->num_usb3_ports;
862         port_array = xhci->usb3_ports;
863         while (port_index--) {
864                 t1 = readl(port_array[port_index]);
865                 t1 = xhci_port_state_to_neutral(t1);
866                 t2 = t1 & ~PORT_WAKE_BITS;
867                 if (t1 != t2)
868                         writel(t2, port_array[port_index]);
869         }
870
871         /* disble usb2 ports Wake bits*/
872         port_index = xhci->num_usb2_ports;
873         port_array = xhci->usb2_ports;
874         while (port_index--) {
875                 t1 = readl(port_array[port_index]);
876                 t1 = xhci_port_state_to_neutral(t1);
877                 t2 = t1 & ~PORT_WAKE_BITS;
878                 if (t1 != t2)
879                         writel(t2, port_array[port_index]);
880         }
881
882         spin_unlock_irqrestore(&xhci->lock, flags);
883 }
884
885 static bool xhci_pending_portevent(struct xhci_hcd *xhci)
886 {
887         __le32 __iomem          **port_array;
888         int                     port_index;
889         u32                     status;
890         u32                     portsc;
891
892         status = readl(&xhci->op_regs->status);
893         if (status & STS_EINT)
894                 return true;
895         /*
896          * Checking STS_EINT is not enough as there is a lag between a change
897          * bit being set and the Port Status Change Event that it generated
898          * being written to the Event Ring. See note in xhci 1.1 section 4.19.2.
899          */
900
901         port_index = xhci->num_usb2_ports;
902         port_array = xhci->usb2_ports;
903         while (port_index--) {
904                 portsc = readl(port_array[port_index]);
905                 if (portsc & PORT_CHANGE_MASK ||
906                     (portsc & PORT_PLS_MASK) == XDEV_RESUME)
907                         return true;
908         }
909         port_index = xhci->num_usb3_ports;
910         port_array = xhci->usb3_ports;
911         while (port_index--) {
912                 portsc = readl(port_array[port_index]);
913                 if (portsc & PORT_CHANGE_MASK ||
914                     (portsc & PORT_PLS_MASK) == XDEV_RESUME)
915                         return true;
916         }
917         return false;
918 }
919
920 /*
921  * Stop HC (not bus-specific)
922  *
923  * This is called when the machine transition into S3/S4 mode.
924  *
925  */
926 int xhci_suspend(struct xhci_hcd *xhci, bool do_wakeup)
927 {
928         int                     rc = 0;
929         unsigned int            delay = XHCI_MAX_HALT_USEC * 2;
930         struct usb_hcd          *hcd = xhci_to_hcd(xhci);
931         u32                     command;
932
933         if (!hcd->state)
934                 return 0;
935
936         if (hcd->state != HC_STATE_SUSPENDED ||
937                         xhci->shared_hcd->state != HC_STATE_SUSPENDED)
938                 return -EINVAL;
939
940         /* Clear root port wake on bits if wakeup not allowed. */
941         if (!do_wakeup)
942                 xhci_disable_port_wake_on_bits(xhci);
943
944         /* Don't poll the roothubs on bus suspend. */
945         xhci_dbg(xhci, "%s: stopping port polling.\n", __func__);
946         clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
947         del_timer_sync(&hcd->rh_timer);
948         clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
949         del_timer_sync(&xhci->shared_hcd->rh_timer);
950
951         spin_lock_irq(&xhci->lock);
952         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
953         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
954         /* step 1: stop endpoint */
955         /* skipped assuming that port suspend has done */
956
957         /* step 2: clear Run/Stop bit */
958         command = readl(&xhci->op_regs->command);
959         command &= ~CMD_RUN;
960         writel(command, &xhci->op_regs->command);
961
962         /* Some chips from Fresco Logic need an extraordinary delay */
963         delay *= (xhci->quirks & XHCI_SLOW_SUSPEND) ? 10 : 1;
964
965         if (xhci_handshake(&xhci->op_regs->status,
966                       STS_HALT, STS_HALT, delay)) {
967                 xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
968                 spin_unlock_irq(&xhci->lock);
969                 return -ETIMEDOUT;
970         }
971         xhci_clear_command_ring(xhci);
972
973         /* step 3: save registers */
974         xhci_save_registers(xhci);
975
976         /* step 4: set CSS flag */
977         command = readl(&xhci->op_regs->command);
978         command |= CMD_CSS;
979         writel(command, &xhci->op_regs->command);
980         if (xhci_handshake(&xhci->op_regs->status,
981                                 STS_SAVE, 0, 20 * 1000)) {
982                 xhci_warn(xhci, "WARN: xHC save state timeout\n");
983                 spin_unlock_irq(&xhci->lock);
984                 return -ETIMEDOUT;
985         }
986         spin_unlock_irq(&xhci->lock);
987
988         /*
989          * Deleting Compliance Mode Recovery Timer because the xHCI Host
990          * is about to be suspended.
991          */
992         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
993                         (!(xhci_all_ports_seen_u0(xhci)))) {
994                 del_timer_sync(&xhci->comp_mode_recovery_timer);
995                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
996                                 "%s: compliance mode recovery timer deleted",
997                                 __func__);
998         }
999
1000         /* step 5: remove core well power */
1001         /* synchronize irq when using MSI-X */
1002         xhci_msix_sync_irqs(xhci);
1003
1004         return rc;
1005 }
1006 EXPORT_SYMBOL_GPL(xhci_suspend);
1007
1008 /*
1009  * start xHC (not bus-specific)
1010  *
1011  * This is called when the machine transition from S3/S4 mode.
1012  *
1013  */
1014 int xhci_resume(struct xhci_hcd *xhci, bool hibernated)
1015 {
1016         u32                     command, temp = 0;
1017         struct usb_hcd          *hcd = xhci_to_hcd(xhci);
1018         struct usb_hcd          *secondary_hcd;
1019         int                     retval = 0;
1020         bool                    comp_timer_running = false;
1021         bool                    pending_portevent = false;
1022
1023         if (!hcd->state)
1024                 return 0;
1025
1026         /* Wait a bit if either of the roothubs need to settle from the
1027          * transition into bus suspend.
1028          */
1029         if (time_before(jiffies, xhci->bus_state[0].next_statechange) ||
1030                         time_before(jiffies,
1031                                 xhci->bus_state[1].next_statechange))
1032                 msleep(100);
1033
1034         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1035         set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
1036
1037         spin_lock_irq(&xhci->lock);
1038         if (xhci->quirks & XHCI_RESET_ON_RESUME)
1039                 hibernated = true;
1040
1041         if (!hibernated) {
1042                 /*
1043                  * Some controllers might lose power during suspend, so wait
1044                  * for controller not ready bit to clear, just as in xHC init.
1045                  */
1046                 retval = xhci_handshake(&xhci->op_regs->status,
1047                                         STS_CNR, 0, 10 * 1000 * 1000);
1048                 if (retval) {
1049                         xhci_warn(xhci, "Controller not ready at resume %d\n",
1050                                   retval);
1051                         spin_unlock_irq(&xhci->lock);
1052                         return retval;
1053                 }
1054                 /* step 1: restore register */
1055                 xhci_restore_registers(xhci);
1056                 /* step 2: initialize command ring buffer */
1057                 xhci_set_cmd_ring_deq(xhci);
1058                 /* step 3: restore state and start state*/
1059                 /* step 3: set CRS flag */
1060                 command = readl(&xhci->op_regs->command);
1061                 command |= CMD_CRS;
1062                 writel(command, &xhci->op_regs->command);
1063                 /*
1064                  * Some controllers take up to 55+ ms to complete the controller
1065                  * restore so setting the timeout to 100ms. Xhci specification
1066                  * doesn't mention any timeout value.
1067                  */
1068                 if (xhci_handshake(&xhci->op_regs->status,
1069                               STS_RESTORE, 0, 100 * 1000)) {
1070                         xhci_warn(xhci, "WARN: xHC restore state timeout\n");
1071                         spin_unlock_irq(&xhci->lock);
1072                         return -ETIMEDOUT;
1073                 }
1074                 temp = readl(&xhci->op_regs->status);
1075         }
1076
1077         /* If restore operation fails, re-initialize the HC during resume */
1078         if ((temp & STS_SRE) || hibernated) {
1079
1080                 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1081                                 !(xhci_all_ports_seen_u0(xhci))) {
1082                         del_timer_sync(&xhci->comp_mode_recovery_timer);
1083                         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1084                                 "Compliance Mode Recovery Timer deleted!");
1085                 }
1086
1087                 /* Let the USB core know _both_ roothubs lost power. */
1088                 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1089                 usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
1090
1091                 xhci_dbg(xhci, "Stop HCD\n");
1092                 xhci_halt(xhci);
1093                 xhci_reset(xhci);
1094                 spin_unlock_irq(&xhci->lock);
1095                 xhci_cleanup_msix(xhci);
1096
1097                 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1098                 temp = readl(&xhci->op_regs->status);
1099                 writel(temp & ~STS_EINT, &xhci->op_regs->status);
1100                 temp = readl(&xhci->ir_set->irq_pending);
1101                 writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
1102                 xhci_print_ir_set(xhci, 0);
1103
1104                 xhci_dbg(xhci, "cleaning up memory\n");
1105                 xhci_mem_cleanup(xhci);
1106                 xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
1107                             readl(&xhci->op_regs->status));
1108
1109                 /* USB core calls the PCI reinit and start functions twice:
1110                  * first with the primary HCD, and then with the secondary HCD.
1111                  * If we don't do the same, the host will never be started.
1112                  */
1113                 if (!usb_hcd_is_primary_hcd(hcd))
1114                         secondary_hcd = hcd;
1115                 else
1116                         secondary_hcd = xhci->shared_hcd;
1117
1118                 xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1119                 retval = xhci_init(hcd->primary_hcd);
1120                 if (retval)
1121                         return retval;
1122                 comp_timer_running = true;
1123
1124                 xhci_dbg(xhci, "Start the primary HCD\n");
1125                 retval = xhci_run(hcd->primary_hcd);
1126                 if (!retval) {
1127                         xhci_dbg(xhci, "Start the secondary HCD\n");
1128                         retval = xhci_run(secondary_hcd);
1129                 }
1130                 hcd->state = HC_STATE_SUSPENDED;
1131                 xhci->shared_hcd->state = HC_STATE_SUSPENDED;
1132                 goto done;
1133         }
1134
1135         /* step 4: set Run/Stop bit */
1136         command = readl(&xhci->op_regs->command);
1137         command |= CMD_RUN;
1138         writel(command, &xhci->op_regs->command);
1139         xhci_handshake(&xhci->op_regs->status, STS_HALT,
1140                   0, 250 * 1000);
1141
1142         /* step 5: walk topology and initialize portsc,
1143          * portpmsc and portli
1144          */
1145         /* this is done in bus_resume */
1146
1147         /* step 6: restart each of the previously
1148          * Running endpoints by ringing their doorbells
1149          */
1150
1151         spin_unlock_irq(&xhci->lock);
1152
1153  done:
1154         if (retval == 0) {
1155                 /*
1156                  * Resume roothubs only if there are pending events.
1157                  * USB 3 devices resend U3 LFPS wake after a 100ms delay if
1158                  * the first wake signalling failed, give it that chance.
1159                  */
1160                 pending_portevent = xhci_pending_portevent(xhci);
1161                 if (!pending_portevent) {
1162                         msleep(120);
1163                         pending_portevent = xhci_pending_portevent(xhci);
1164                 }
1165
1166                 if (pending_portevent) {
1167                         usb_hcd_resume_root_hub(xhci->shared_hcd);
1168                         usb_hcd_resume_root_hub(hcd);
1169                 }
1170         }
1171         /*
1172          * If system is subject to the Quirk, Compliance Mode Timer needs to
1173          * be re-initialized Always after a system resume. Ports are subject
1174          * to suffer the Compliance Mode issue again. It doesn't matter if
1175          * ports have entered previously to U0 before system's suspension.
1176          */
1177         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) && !comp_timer_running)
1178                 compliance_mode_recovery_timer_init(xhci);
1179
1180         /* Re-enable port polling. */
1181         xhci_dbg(xhci, "%s: starting port polling.\n", __func__);
1182         set_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
1183         usb_hcd_poll_rh_status(xhci->shared_hcd);
1184         set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1185         usb_hcd_poll_rh_status(hcd);
1186
1187         return retval;
1188 }
1189 EXPORT_SYMBOL_GPL(xhci_resume);
1190 #endif  /* CONFIG_PM */
1191
1192 /*-------------------------------------------------------------------------*/
1193
1194 /**
1195  * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1196  * HCDs.  Find the index for an endpoint given its descriptor.  Use the return
1197  * value to right shift 1 for the bitmask.
1198  *
1199  * Index  = (epnum * 2) + direction - 1,
1200  * where direction = 0 for OUT, 1 for IN.
1201  * For control endpoints, the IN index is used (OUT index is unused), so
1202  * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1203  */
1204 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1205 {
1206         unsigned int index;
1207         if (usb_endpoint_xfer_control(desc))
1208                 index = (unsigned int) (usb_endpoint_num(desc)*2);
1209         else
1210                 index = (unsigned int) (usb_endpoint_num(desc)*2) +
1211                         (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1212         return index;
1213 }
1214
1215 /* The reverse operation to xhci_get_endpoint_index. Calculate the USB endpoint
1216  * address from the XHCI endpoint index.
1217  */
1218 unsigned int xhci_get_endpoint_address(unsigned int ep_index)
1219 {
1220         unsigned int number = DIV_ROUND_UP(ep_index, 2);
1221         unsigned int direction = ep_index % 2 ? USB_DIR_OUT : USB_DIR_IN;
1222         return direction | number;
1223 }
1224
1225 /* Find the flag for this endpoint (for use in the control context).  Use the
1226  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
1227  * bit 1, etc.
1228  */
1229 unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1230 {
1231         return 1 << (xhci_get_endpoint_index(desc) + 1);
1232 }
1233
1234 /* Find the flag for this endpoint (for use in the control context).  Use the
1235  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
1236  * bit 1, etc.
1237  */
1238 unsigned int xhci_get_endpoint_flag_from_index(unsigned int ep_index)
1239 {
1240         return 1 << (ep_index + 1);
1241 }
1242
1243 /* Compute the last valid endpoint context index.  Basically, this is the
1244  * endpoint index plus one.  For slot contexts with more than valid endpoint,
1245  * we find the most significant bit set in the added contexts flags.
1246  * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1247  * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1248  */
1249 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1250 {
1251         return fls(added_ctxs) - 1;
1252 }
1253
1254 /* Returns 1 if the arguments are OK;
1255  * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1256  */
1257 static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
1258                 struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
1259                 const char *func) {
1260         struct xhci_hcd *xhci;
1261         struct xhci_virt_device *virt_dev;
1262
1263         if (!hcd || (check_ep && !ep) || !udev) {
1264                 pr_debug("xHCI %s called with invalid args\n", func);
1265                 return -EINVAL;
1266         }
1267         if (!udev->parent) {
1268                 pr_debug("xHCI %s called for root hub\n", func);
1269                 return 0;
1270         }
1271
1272         xhci = hcd_to_xhci(hcd);
1273         if (check_virt_dev) {
1274                 if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
1275                         xhci_dbg(xhci, "xHCI %s called with unaddressed device\n",
1276                                         func);
1277                         return -EINVAL;
1278                 }
1279
1280                 virt_dev = xhci->devs[udev->slot_id];
1281                 if (virt_dev->udev != udev) {
1282                         xhci_dbg(xhci, "xHCI %s called with udev and "
1283                                           "virt_dev does not match\n", func);
1284                         return -EINVAL;
1285                 }
1286         }
1287
1288         if (xhci->xhc_state & XHCI_STATE_HALTED)
1289                 return -ENODEV;
1290
1291         return 1;
1292 }
1293
1294 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1295                 struct usb_device *udev, struct xhci_command *command,
1296                 bool ctx_change, bool must_succeed);
1297
1298 /*
1299  * Full speed devices may have a max packet size greater than 8 bytes, but the
1300  * USB core doesn't know that until it reads the first 8 bytes of the
1301  * descriptor.  If the usb_device's max packet size changes after that point,
1302  * we need to issue an evaluate context command and wait on it.
1303  */
1304 static int xhci_check_maxpacket(struct xhci_hcd *xhci, unsigned int slot_id,
1305                 unsigned int ep_index, struct urb *urb, gfp_t mem_flags)
1306 {
1307         struct xhci_container_ctx *out_ctx;
1308         struct xhci_input_control_ctx *ctrl_ctx;
1309         struct xhci_ep_ctx *ep_ctx;
1310         struct xhci_command *command;
1311         int max_packet_size;
1312         int hw_max_packet_size;
1313         int ret = 0;
1314
1315         out_ctx = xhci->devs[slot_id]->out_ctx;
1316         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1317         hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1318         max_packet_size = usb_endpoint_maxp(&urb->dev->ep0.desc);
1319         if (hw_max_packet_size != max_packet_size) {
1320                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1321                                 "Max Packet Size for ep 0 changed.");
1322                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1323                                 "Max packet size in usb_device = %d",
1324                                 max_packet_size);
1325                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1326                                 "Max packet size in xHCI HW = %d",
1327                                 hw_max_packet_size);
1328                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1329                                 "Issuing evaluate context command.");
1330
1331                 /* Set up the input context flags for the command */
1332                 /* FIXME: This won't work if a non-default control endpoint
1333                  * changes max packet sizes.
1334                  */
1335
1336                 command = xhci_alloc_command(xhci, false, true, mem_flags);
1337                 if (!command)
1338                         return -ENOMEM;
1339
1340                 command->in_ctx = xhci->devs[slot_id]->in_ctx;
1341                 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
1342                 if (!ctrl_ctx) {
1343                         xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1344                                         __func__);
1345                         ret = -ENOMEM;
1346                         goto command_cleanup;
1347                 }
1348                 /* Set up the modified control endpoint 0 */
1349                 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
1350                                 xhci->devs[slot_id]->out_ctx, ep_index);
1351
1352                 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
1353                 ep_ctx->ep_info &= cpu_to_le32(~EP_STATE_MASK);/* must clear */
1354                 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1355                 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1356
1357                 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1358                 ctrl_ctx->drop_flags = 0;
1359
1360                 xhci_dbg(xhci, "Slot %d input context\n", slot_id);
1361                 xhci_dbg_ctx(xhci, command->in_ctx, ep_index);
1362                 xhci_dbg(xhci, "Slot %d output context\n", slot_id);
1363                 xhci_dbg_ctx(xhci, out_ctx, ep_index);
1364
1365                 ret = xhci_configure_endpoint(xhci, urb->dev, command,
1366                                 true, false);
1367
1368                 /* Clean up the input context for later use by bandwidth
1369                  * functions.
1370                  */
1371                 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1372 command_cleanup:
1373                 kfree(command->completion);
1374                 kfree(command);
1375         }
1376         return ret;
1377 }
1378
1379 /*
1380  * non-error returns are a promise to giveback() the urb later
1381  * we drop ownership so next owner (or urb unlink) can get it
1382  */
1383 int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1384 {
1385         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1386         struct xhci_td *buffer;
1387         unsigned long flags;
1388         int ret = 0;
1389         unsigned int slot_id, ep_index;
1390         struct urb_priv *urb_priv;
1391         int size, i;
1392
1393         if (!urb || xhci_check_args(hcd, urb->dev, urb->ep,
1394                                         true, true, __func__) <= 0)
1395                 return -EINVAL;
1396
1397         slot_id = urb->dev->slot_id;
1398         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1399
1400         if (!HCD_HW_ACCESSIBLE(hcd)) {
1401                 if (!in_interrupt())
1402                         xhci_dbg(xhci, "urb submitted during PCI suspend\n");
1403                 ret = -ESHUTDOWN;
1404                 goto exit;
1405         }
1406
1407         if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1408                 size = urb->number_of_packets;
1409         else if (usb_endpoint_is_bulk_out(&urb->ep->desc) &&
1410             urb->transfer_buffer_length > 0 &&
1411             urb->transfer_flags & URB_ZERO_PACKET &&
1412             !(urb->transfer_buffer_length % usb_endpoint_maxp(&urb->ep->desc)))
1413                 size = 2;
1414         else
1415                 size = 1;
1416
1417         urb_priv = kzalloc(sizeof(struct urb_priv) +
1418                                   size * sizeof(struct xhci_td *), mem_flags);
1419         if (!urb_priv)
1420                 return -ENOMEM;
1421
1422         buffer = kzalloc(size * sizeof(struct xhci_td), mem_flags);
1423         if (!buffer) {
1424                 kfree(urb_priv);
1425                 return -ENOMEM;
1426         }
1427
1428         for (i = 0; i < size; i++) {
1429                 urb_priv->td[i] = buffer;
1430                 buffer++;
1431         }
1432
1433         urb_priv->length = size;
1434         urb_priv->td_cnt = 0;
1435         urb->hcpriv = urb_priv;
1436
1437         if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1438                 /* Check to see if the max packet size for the default control
1439                  * endpoint changed during FS device enumeration
1440                  */
1441                 if (urb->dev->speed == USB_SPEED_FULL) {
1442                         ret = xhci_check_maxpacket(xhci, slot_id,
1443                                         ep_index, urb, mem_flags);
1444                         if (ret < 0) {
1445                                 xhci_urb_free_priv(urb_priv);
1446                                 urb->hcpriv = NULL;
1447                                 return ret;
1448                         }
1449                 }
1450
1451                 /* We have a spinlock and interrupts disabled, so we must pass
1452                  * atomic context to this function, which may allocate memory.
1453                  */
1454                 spin_lock_irqsave(&xhci->lock, flags);
1455                 if (xhci->xhc_state & XHCI_STATE_DYING)
1456                         goto dying;
1457                 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1458                                 slot_id, ep_index);
1459                 if (ret)
1460                         goto free_priv;
1461                 spin_unlock_irqrestore(&xhci->lock, flags);
1462         } else if (usb_endpoint_xfer_bulk(&urb->ep->desc)) {
1463                 spin_lock_irqsave(&xhci->lock, flags);
1464                 if (xhci->xhc_state & XHCI_STATE_DYING)
1465                         goto dying;
1466                 if (xhci->devs[slot_id]->eps[ep_index].ep_state &
1467                                 EP_GETTING_STREAMS) {
1468                         xhci_warn(xhci, "WARN: Can't enqueue URB while bulk ep "
1469                                         "is transitioning to using streams.\n");
1470                         ret = -EINVAL;
1471                 } else if (xhci->devs[slot_id]->eps[ep_index].ep_state &
1472                                 EP_GETTING_NO_STREAMS) {
1473                         xhci_warn(xhci, "WARN: Can't enqueue URB while bulk ep "
1474                                         "is transitioning to "
1475                                         "not having streams.\n");
1476                         ret = -EINVAL;
1477                 } else {
1478                         ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1479                                         slot_id, ep_index);
1480                 }
1481                 if (ret)
1482                         goto free_priv;
1483                 spin_unlock_irqrestore(&xhci->lock, flags);
1484         } else if (usb_endpoint_xfer_int(&urb->ep->desc)) {
1485                 spin_lock_irqsave(&xhci->lock, flags);
1486                 if (xhci->xhc_state & XHCI_STATE_DYING)
1487                         goto dying;
1488                 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1489                                 slot_id, ep_index);
1490                 if (ret)
1491                         goto free_priv;
1492                 spin_unlock_irqrestore(&xhci->lock, flags);
1493         } else {
1494                 spin_lock_irqsave(&xhci->lock, flags);
1495                 if (xhci->xhc_state & XHCI_STATE_DYING)
1496                         goto dying;
1497                 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1498                                 slot_id, ep_index);
1499                 if (ret)
1500                         goto free_priv;
1501                 spin_unlock_irqrestore(&xhci->lock, flags);
1502         }
1503 exit:
1504         return ret;
1505 dying:
1506         xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for "
1507                         "non-responsive xHCI host.\n",
1508                         urb->ep->desc.bEndpointAddress, urb);
1509         ret = -ESHUTDOWN;
1510 free_priv:
1511         xhci_urb_free_priv(urb_priv);
1512         urb->hcpriv = NULL;
1513         spin_unlock_irqrestore(&xhci->lock, flags);
1514         return ret;
1515 }
1516
1517 /* Get the right ring for the given URB.
1518  * If the endpoint supports streams, boundary check the URB's stream ID.
1519  * If the endpoint doesn't support streams, return the singular endpoint ring.
1520  */
1521 static struct xhci_ring *xhci_urb_to_transfer_ring(struct xhci_hcd *xhci,
1522                 struct urb *urb)
1523 {
1524         unsigned int slot_id;
1525         unsigned int ep_index;
1526         unsigned int stream_id;
1527         struct xhci_virt_ep *ep;
1528
1529         slot_id = urb->dev->slot_id;
1530         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1531         stream_id = urb->stream_id;
1532         ep = &xhci->devs[slot_id]->eps[ep_index];
1533         /* Common case: no streams */
1534         if (!(ep->ep_state & EP_HAS_STREAMS))
1535                 return ep->ring;
1536
1537         if (stream_id == 0) {
1538                 xhci_warn(xhci,
1539                                 "WARN: Slot ID %u, ep index %u has streams, "
1540                                 "but URB has no stream ID.\n",
1541                                 slot_id, ep_index);
1542                 return NULL;
1543         }
1544
1545         if (stream_id < ep->stream_info->num_streams)
1546                 return ep->stream_info->stream_rings[stream_id];
1547
1548         xhci_warn(xhci,
1549                         "WARN: Slot ID %u, ep index %u has "
1550                         "stream IDs 1 to %u allocated, "
1551                         "but stream ID %u is requested.\n",
1552                         slot_id, ep_index,
1553                         ep->stream_info->num_streams - 1,
1554                         stream_id);
1555         return NULL;
1556 }
1557
1558 /*
1559  * Remove the URB's TD from the endpoint ring.  This may cause the HC to stop
1560  * USB transfers, potentially stopping in the middle of a TRB buffer.  The HC
1561  * should pick up where it left off in the TD, unless a Set Transfer Ring
1562  * Dequeue Pointer is issued.
1563  *
1564  * The TRBs that make up the buffers for the canceled URB will be "removed" from
1565  * the ring.  Since the ring is a contiguous structure, they can't be physically
1566  * removed.  Instead, there are two options:
1567  *
1568  *  1) If the HC is in the middle of processing the URB to be canceled, we
1569  *     simply move the ring's dequeue pointer past those TRBs using the Set
1570  *     Transfer Ring Dequeue Pointer command.  This will be the common case,
1571  *     when drivers timeout on the last submitted URB and attempt to cancel.
1572  *
1573  *  2) If the HC is in the middle of a different TD, we turn the TRBs into a
1574  *     series of 1-TRB transfer no-op TDs.  (No-ops shouldn't be chained.)  The
1575  *     HC will need to invalidate the any TRBs it has cached after the stop
1576  *     endpoint command, as noted in the xHCI 0.95 errata.
1577  *
1578  *  3) The TD may have completed by the time the Stop Endpoint Command
1579  *     completes, so software needs to handle that case too.
1580  *
1581  * This function should protect against the TD enqueueing code ringing the
1582  * doorbell while this code is waiting for a Stop Endpoint command to complete.
1583  * It also needs to account for multiple cancellations on happening at the same
1584  * time for the same endpoint.
1585  *
1586  * Note that this function can be called in any context, or so says
1587  * usb_hcd_unlink_urb()
1588  */
1589 int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1590 {
1591         unsigned long flags;
1592         int ret, i;
1593         u32 temp;
1594         struct xhci_hcd *xhci;
1595         struct urb_priv *urb_priv;
1596         struct xhci_td *td;
1597         unsigned int ep_index;
1598         struct xhci_ring *ep_ring;
1599         struct xhci_virt_ep *ep;
1600         struct xhci_command *command;
1601
1602         xhci = hcd_to_xhci(hcd);
1603         spin_lock_irqsave(&xhci->lock, flags);
1604         /* Make sure the URB hasn't completed or been unlinked already */
1605         ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1606         if (ret || !urb->hcpriv)
1607                 goto done;
1608         temp = readl(&xhci->op_regs->status);
1609         if (temp == 0xffffffff || (xhci->xhc_state & XHCI_STATE_HALTED)) {
1610                 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1611                                 "HW died, freeing TD.");
1612                 urb_priv = urb->hcpriv;
1613                 for (i = urb_priv->td_cnt;
1614                      i < urb_priv->length && xhci->devs[urb->dev->slot_id];
1615                      i++) {
1616                         td = urb_priv->td[i];
1617                         if (!list_empty(&td->td_list))
1618                                 list_del_init(&td->td_list);
1619                         if (!list_empty(&td->cancelled_td_list))
1620                                 list_del_init(&td->cancelled_td_list);
1621                 }
1622
1623                 usb_hcd_unlink_urb_from_ep(hcd, urb);
1624                 spin_unlock_irqrestore(&xhci->lock, flags);
1625                 usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1626                 xhci_urb_free_priv(urb_priv);
1627                 return ret;
1628         }
1629
1630         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1631         ep = &xhci->devs[urb->dev->slot_id]->eps[ep_index];
1632         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1633         if (!ep_ring) {
1634                 ret = -EINVAL;
1635                 goto done;
1636         }
1637
1638         urb_priv = urb->hcpriv;
1639         i = urb_priv->td_cnt;
1640         if (i < urb_priv->length)
1641                 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1642                                 "Cancel URB %p, dev %s, ep 0x%x, "
1643                                 "starting at offset 0x%llx",
1644                                 urb, urb->dev->devpath,
1645                                 urb->ep->desc.bEndpointAddress,
1646                                 (unsigned long long) xhci_trb_virt_to_dma(
1647                                         urb_priv->td[i]->start_seg,
1648                                         urb_priv->td[i]->first_trb));
1649
1650         for (; i < urb_priv->length; i++) {
1651                 td = urb_priv->td[i];
1652                 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
1653         }
1654
1655         /* Queue a stop endpoint command, but only if this is
1656          * the first cancellation to be handled.
1657          */
1658         if (!(ep->ep_state & EP_HALT_PENDING)) {
1659                 command = xhci_alloc_command(xhci, false, false, GFP_ATOMIC);
1660                 if (!command) {
1661                         ret = -ENOMEM;
1662                         goto done;
1663                 }
1664                 ep->ep_state |= EP_HALT_PENDING;
1665                 ep->stop_cmds_pending++;
1666                 ep->stop_cmd_timer.expires = jiffies +
1667                         XHCI_STOP_EP_CMD_TIMEOUT * HZ;
1668                 add_timer(&ep->stop_cmd_timer);
1669                 xhci_queue_stop_endpoint(xhci, command, urb->dev->slot_id,
1670                                          ep_index, 0);
1671                 xhci_ring_cmd_db(xhci);
1672         }
1673 done:
1674         spin_unlock_irqrestore(&xhci->lock, flags);
1675         return ret;
1676 }
1677
1678 /* Drop an endpoint from a new bandwidth configuration for this device.
1679  * Only one call to this function is allowed per endpoint before
1680  * check_bandwidth() or reset_bandwidth() must be called.
1681  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1682  * add the endpoint to the schedule with possibly new parameters denoted by a
1683  * different endpoint descriptor in usb_host_endpoint.
1684  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1685  * not allowed.
1686  *
1687  * The USB core will not allow URBs to be queued to an endpoint that is being
1688  * disabled, so there's no need for mutual exclusion to protect
1689  * the xhci->devs[slot_id] structure.
1690  */
1691 int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1692                 struct usb_host_endpoint *ep)
1693 {
1694         struct xhci_hcd *xhci;
1695         struct xhci_container_ctx *in_ctx, *out_ctx;
1696         struct xhci_input_control_ctx *ctrl_ctx;
1697         unsigned int ep_index;
1698         struct xhci_ep_ctx *ep_ctx;
1699         u32 drop_flag;
1700         u32 new_add_flags, new_drop_flags;
1701         int ret;
1702
1703         ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1704         if (ret <= 0)
1705                 return ret;
1706         xhci = hcd_to_xhci(hcd);
1707         if (xhci->xhc_state & XHCI_STATE_DYING)
1708                 return -ENODEV;
1709
1710         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1711         drop_flag = xhci_get_endpoint_flag(&ep->desc);
1712         if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1713                 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1714                                 __func__, drop_flag);
1715                 return 0;
1716         }
1717
1718         in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1719         out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1720         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1721         if (!ctrl_ctx) {
1722                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1723                                 __func__);
1724                 return 0;
1725         }
1726
1727         ep_index = xhci_get_endpoint_index(&ep->desc);
1728         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1729         /* If the HC already knows the endpoint is disabled,
1730          * or the HCD has noted it is disabled, ignore this request
1731          */
1732         if (((ep_ctx->ep_info & cpu_to_le32(EP_STATE_MASK)) ==
1733              cpu_to_le32(EP_STATE_DISABLED)) ||
1734             le32_to_cpu(ctrl_ctx->drop_flags) &
1735             xhci_get_endpoint_flag(&ep->desc)) {
1736                 /* Do not warn when called after a usb_device_reset */
1737                 if (xhci->devs[udev->slot_id]->eps[ep_index].ring != NULL)
1738                         xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1739                                   __func__, ep);
1740                 return 0;
1741         }
1742
1743         ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1744         new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1745
1746         ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1747         new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1748
1749         xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1750
1751         xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1752                         (unsigned int) ep->desc.bEndpointAddress,
1753                         udev->slot_id,
1754                         (unsigned int) new_drop_flags,
1755                         (unsigned int) new_add_flags);
1756         return 0;
1757 }
1758
1759 /* Add an endpoint to a new possible bandwidth configuration for this device.
1760  * Only one call to this function is allowed per endpoint before
1761  * check_bandwidth() or reset_bandwidth() must be called.
1762  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1763  * add the endpoint to the schedule with possibly new parameters denoted by a
1764  * different endpoint descriptor in usb_host_endpoint.
1765  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1766  * not allowed.
1767  *
1768  * The USB core will not allow URBs to be queued to an endpoint until the
1769  * configuration or alt setting is installed in the device, so there's no need
1770  * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1771  */
1772 int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1773                 struct usb_host_endpoint *ep)
1774 {
1775         struct xhci_hcd *xhci;
1776         struct xhci_container_ctx *in_ctx;
1777         unsigned int ep_index;
1778         struct xhci_input_control_ctx *ctrl_ctx;
1779         u32 added_ctxs;
1780         u32 new_add_flags, new_drop_flags;
1781         struct xhci_virt_device *virt_dev;
1782         int ret = 0;
1783
1784         ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1785         if (ret <= 0) {
1786                 /* So we won't queue a reset ep command for a root hub */
1787                 ep->hcpriv = NULL;
1788                 return ret;
1789         }
1790         xhci = hcd_to_xhci(hcd);
1791         if (xhci->xhc_state & XHCI_STATE_DYING)
1792                 return -ENODEV;
1793
1794         added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1795         if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1796                 /* FIXME when we have to issue an evaluate endpoint command to
1797                  * deal with ep0 max packet size changing once we get the
1798                  * descriptors
1799                  */
1800                 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1801                                 __func__, added_ctxs);
1802                 return 0;
1803         }
1804
1805         virt_dev = xhci->devs[udev->slot_id];
1806         in_ctx = virt_dev->in_ctx;
1807         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1808         if (!ctrl_ctx) {
1809                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1810                                 __func__);
1811                 return 0;
1812         }
1813
1814         ep_index = xhci_get_endpoint_index(&ep->desc);
1815         /* If this endpoint is already in use, and the upper layers are trying
1816          * to add it again without dropping it, reject the addition.
1817          */
1818         if (virt_dev->eps[ep_index].ring &&
1819                         !(le32_to_cpu(ctrl_ctx->drop_flags) & added_ctxs)) {
1820                 xhci_warn(xhci, "Trying to add endpoint 0x%x "
1821                                 "without dropping it.\n",
1822                                 (unsigned int) ep->desc.bEndpointAddress);
1823                 return -EINVAL;
1824         }
1825
1826         /* If the HCD has already noted the endpoint is enabled,
1827          * ignore this request.
1828          */
1829         if (le32_to_cpu(ctrl_ctx->add_flags) & added_ctxs) {
1830                 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1831                                 __func__, ep);
1832                 return 0;
1833         }
1834
1835         /*
1836          * Configuration and alternate setting changes must be done in
1837          * process context, not interrupt context (or so documenation
1838          * for usb_set_interface() and usb_set_configuration() claim).
1839          */
1840         if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1841                 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1842                                 __func__, ep->desc.bEndpointAddress);
1843                 return -ENOMEM;
1844         }
1845
1846         ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
1847         new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1848
1849         /* If xhci_endpoint_disable() was called for this endpoint, but the
1850          * xHC hasn't been notified yet through the check_bandwidth() call,
1851          * this re-adds a new state for the endpoint from the new endpoint
1852          * descriptors.  We must drop and re-add this endpoint, so we leave the
1853          * drop flags alone.
1854          */
1855         new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1856
1857         /* Store the usb_device pointer for later use */
1858         ep->hcpriv = udev;
1859
1860         xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1861                         (unsigned int) ep->desc.bEndpointAddress,
1862                         udev->slot_id,
1863                         (unsigned int) new_drop_flags,
1864                         (unsigned int) new_add_flags);
1865         return 0;
1866 }
1867
1868 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1869 {
1870         struct xhci_input_control_ctx *ctrl_ctx;
1871         struct xhci_ep_ctx *ep_ctx;
1872         struct xhci_slot_ctx *slot_ctx;
1873         int i;
1874
1875         ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1876         if (!ctrl_ctx) {
1877                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1878                                 __func__);
1879                 return;
1880         }
1881
1882         /* When a device's add flag and drop flag are zero, any subsequent
1883          * configure endpoint command will leave that endpoint's state
1884          * untouched.  Make sure we don't leave any old state in the input
1885          * endpoint contexts.
1886          */
1887         ctrl_ctx->drop_flags = 0;
1888         ctrl_ctx->add_flags = 0;
1889         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1890         slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1891         /* Endpoint 0 is always valid */
1892         slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
1893         for (i = 1; i < 31; ++i) {
1894                 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
1895                 ep_ctx->ep_info = 0;
1896                 ep_ctx->ep_info2 = 0;
1897                 ep_ctx->deq = 0;
1898                 ep_ctx->tx_info = 0;
1899         }
1900 }
1901
1902 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
1903                 struct usb_device *udev, u32 *cmd_status)
1904 {
1905         int ret;
1906
1907         switch (*cmd_status) {
1908         case COMP_CMD_ABORT:
1909         case COMP_CMD_STOP:
1910                 xhci_warn(xhci, "Timeout while waiting for configure endpoint command\n");
1911                 ret = -ETIME;
1912                 break;
1913         case COMP_ENOMEM:
1914                 dev_warn(&udev->dev,
1915                          "Not enough host controller resources for new device state.\n");
1916                 ret = -ENOMEM;
1917                 /* FIXME: can we allocate more resources for the HC? */
1918                 break;
1919         case COMP_BW_ERR:
1920         case COMP_2ND_BW_ERR:
1921                 dev_warn(&udev->dev,
1922                          "Not enough bandwidth for new device state.\n");
1923                 ret = -ENOSPC;
1924                 /* FIXME: can we go back to the old state? */
1925                 break;
1926         case COMP_TRB_ERR:
1927                 /* the HCD set up something wrong */
1928                 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
1929                                 "add flag = 1, "
1930                                 "and endpoint is not disabled.\n");
1931                 ret = -EINVAL;
1932                 break;
1933         case COMP_DEV_ERR:
1934                 dev_warn(&udev->dev,
1935                          "ERROR: Incompatible device for endpoint configure command.\n");
1936                 ret = -ENODEV;
1937                 break;
1938         case COMP_SUCCESS:
1939                 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1940                                 "Successful Endpoint Configure command");
1941                 ret = 0;
1942                 break;
1943         default:
1944                 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
1945                                 *cmd_status);
1946                 ret = -EINVAL;
1947                 break;
1948         }
1949         return ret;
1950 }
1951
1952 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
1953                 struct usb_device *udev, u32 *cmd_status)
1954 {
1955         int ret;
1956         struct xhci_virt_device *virt_dev = xhci->devs[udev->slot_id];
1957
1958         switch (*cmd_status) {
1959         case COMP_CMD_ABORT:
1960         case COMP_CMD_STOP:
1961                 xhci_warn(xhci, "Timeout while waiting for evaluate context command\n");
1962                 ret = -ETIME;
1963                 break;
1964         case COMP_EINVAL:
1965                 dev_warn(&udev->dev,
1966                          "WARN: xHCI driver setup invalid evaluate context command.\n");
1967                 ret = -EINVAL;
1968                 break;
1969         case COMP_EBADSLT:
1970                 dev_warn(&udev->dev,
1971                         "WARN: slot not enabled for evaluate context command.\n");
1972                 ret = -EINVAL;
1973                 break;
1974         case COMP_CTX_STATE:
1975                 dev_warn(&udev->dev,
1976                         "WARN: invalid context state for evaluate context command.\n");
1977                 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 1);
1978                 ret = -EINVAL;
1979                 break;
1980         case COMP_DEV_ERR:
1981                 dev_warn(&udev->dev,
1982                         "ERROR: Incompatible device for evaluate context command.\n");
1983                 ret = -ENODEV;
1984                 break;
1985         case COMP_MEL_ERR:
1986                 /* Max Exit Latency too large error */
1987                 dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
1988                 ret = -EINVAL;
1989                 break;
1990         case COMP_SUCCESS:
1991                 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1992                                 "Successful evaluate context command");
1993                 ret = 0;
1994                 break;
1995         default:
1996                 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
1997                         *cmd_status);
1998                 ret = -EINVAL;
1999                 break;
2000         }
2001         return ret;
2002 }
2003
2004 static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
2005                 struct xhci_input_control_ctx *ctrl_ctx)
2006 {
2007         u32 valid_add_flags;
2008         u32 valid_drop_flags;
2009
2010         /* Ignore the slot flag (bit 0), and the default control endpoint flag
2011          * (bit 1).  The default control endpoint is added during the Address
2012          * Device command and is never removed until the slot is disabled.
2013          */
2014         valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2015         valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2016
2017         /* Use hweight32 to count the number of ones in the add flags, or
2018          * number of endpoints added.  Don't count endpoints that are changed
2019          * (both added and dropped).
2020          */
2021         return hweight32(valid_add_flags) -
2022                 hweight32(valid_add_flags & valid_drop_flags);
2023 }
2024
2025 static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
2026                 struct xhci_input_control_ctx *ctrl_ctx)
2027 {
2028         u32 valid_add_flags;
2029         u32 valid_drop_flags;
2030
2031         valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2032         valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2033
2034         return hweight32(valid_drop_flags) -
2035                 hweight32(valid_add_flags & valid_drop_flags);
2036 }
2037
2038 /*
2039  * We need to reserve the new number of endpoints before the configure endpoint
2040  * command completes.  We can't subtract the dropped endpoints from the number
2041  * of active endpoints until the command completes because we can oversubscribe
2042  * the host in this case:
2043  *
2044  *  - the first configure endpoint command drops more endpoints than it adds
2045  *  - a second configure endpoint command that adds more endpoints is queued
2046  *  - the first configure endpoint command fails, so the config is unchanged
2047  *  - the second command may succeed, even though there isn't enough resources
2048  *
2049  * Must be called with xhci->lock held.
2050  */
2051 static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
2052                 struct xhci_input_control_ctx *ctrl_ctx)
2053 {
2054         u32 added_eps;
2055
2056         added_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2057         if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
2058                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2059                                 "Not enough ep ctxs: "
2060                                 "%u active, need to add %u, limit is %u.",
2061                                 xhci->num_active_eps, added_eps,
2062                                 xhci->limit_active_eps);
2063                 return -ENOMEM;
2064         }
2065         xhci->num_active_eps += added_eps;
2066         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2067                         "Adding %u ep ctxs, %u now active.", added_eps,
2068                         xhci->num_active_eps);
2069         return 0;
2070 }
2071
2072 /*
2073  * The configure endpoint was failed by the xHC for some other reason, so we
2074  * need to revert the resources that failed configuration would have used.
2075  *
2076  * Must be called with xhci->lock held.
2077  */
2078 static void xhci_free_host_resources(struct xhci_hcd *xhci,
2079                 struct xhci_input_control_ctx *ctrl_ctx)
2080 {
2081         u32 num_failed_eps;
2082
2083         num_failed_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2084         xhci->num_active_eps -= num_failed_eps;
2085         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2086                         "Removing %u failed ep ctxs, %u now active.",
2087                         num_failed_eps,
2088                         xhci->num_active_eps);
2089 }
2090
2091 /*
2092  * Now that the command has completed, clean up the active endpoint count by
2093  * subtracting out the endpoints that were dropped (but not changed).
2094  *
2095  * Must be called with xhci->lock held.
2096  */
2097 static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
2098                 struct xhci_input_control_ctx *ctrl_ctx)
2099 {
2100         u32 num_dropped_eps;
2101
2102         num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, ctrl_ctx);
2103         xhci->num_active_eps -= num_dropped_eps;
2104         if (num_dropped_eps)
2105                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2106                                 "Removing %u dropped ep ctxs, %u now active.",
2107                                 num_dropped_eps,
2108                                 xhci->num_active_eps);
2109 }
2110
2111 static unsigned int xhci_get_block_size(struct usb_device *udev)
2112 {
2113         switch (udev->speed) {
2114         case USB_SPEED_LOW:
2115         case USB_SPEED_FULL:
2116                 return FS_BLOCK;
2117         case USB_SPEED_HIGH:
2118                 return HS_BLOCK;
2119         case USB_SPEED_SUPER:
2120         case USB_SPEED_SUPER_PLUS:
2121                 return SS_BLOCK;
2122         case USB_SPEED_UNKNOWN:
2123         case USB_SPEED_WIRELESS:
2124         default:
2125                 /* Should never happen */
2126                 return 1;
2127         }
2128 }
2129
2130 static unsigned int
2131 xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
2132 {
2133         if (interval_bw->overhead[LS_OVERHEAD_TYPE])
2134                 return LS_OVERHEAD;
2135         if (interval_bw->overhead[FS_OVERHEAD_TYPE])
2136                 return FS_OVERHEAD;
2137         return HS_OVERHEAD;
2138 }
2139
2140 /* If we are changing a LS/FS device under a HS hub,
2141  * make sure (if we are activating a new TT) that the HS bus has enough
2142  * bandwidth for this new TT.
2143  */
2144 static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
2145                 struct xhci_virt_device *virt_dev,
2146                 int old_active_eps)
2147 {
2148         struct xhci_interval_bw_table *bw_table;
2149         struct xhci_tt_bw_info *tt_info;
2150
2151         /* Find the bandwidth table for the root port this TT is attached to. */
2152         bw_table = &xhci->rh_bw[virt_dev->real_port - 1].bw_table;
2153         tt_info = virt_dev->tt_info;
2154         /* If this TT already had active endpoints, the bandwidth for this TT
2155          * has already been added.  Removing all periodic endpoints (and thus
2156          * making the TT enactive) will only decrease the bandwidth used.
2157          */
2158         if (old_active_eps)
2159                 return 0;
2160         if (old_active_eps == 0 && tt_info->active_eps != 0) {
2161                 if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
2162                         return -ENOMEM;
2163                 return 0;
2164         }
2165         /* Not sure why we would have no new active endpoints...
2166          *
2167          * Maybe because of an Evaluate Context change for a hub update or a
2168          * control endpoint 0 max packet size change?
2169          * FIXME: skip the bandwidth calculation in that case.
2170          */
2171         return 0;
2172 }
2173
2174 static int xhci_check_ss_bw(struct xhci_hcd *xhci,
2175                 struct xhci_virt_device *virt_dev)
2176 {
2177         unsigned int bw_reserved;
2178
2179         bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
2180         if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
2181                 return -ENOMEM;
2182
2183         bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
2184         if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
2185                 return -ENOMEM;
2186
2187         return 0;
2188 }
2189
2190 /*
2191  * This algorithm is a very conservative estimate of the worst-case scheduling
2192  * scenario for any one interval.  The hardware dynamically schedules the
2193  * packets, so we can't tell which microframe could be the limiting factor in
2194  * the bandwidth scheduling.  This only takes into account periodic endpoints.
2195  *
2196  * Obviously, we can't solve an NP complete problem to find the minimum worst
2197  * case scenario.  Instead, we come up with an estimate that is no less than
2198  * the worst case bandwidth used for any one microframe, but may be an
2199  * over-estimate.
2200  *
2201  * We walk the requirements for each endpoint by interval, starting with the
2202  * smallest interval, and place packets in the schedule where there is only one
2203  * possible way to schedule packets for that interval.  In order to simplify
2204  * this algorithm, we record the largest max packet size for each interval, and
2205  * assume all packets will be that size.
2206  *
2207  * For interval 0, we obviously must schedule all packets for each interval.
2208  * The bandwidth for interval 0 is just the amount of data to be transmitted
2209  * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2210  * the number of packets).
2211  *
2212  * For interval 1, we have two possible microframes to schedule those packets
2213  * in.  For this algorithm, if we can schedule the same number of packets for
2214  * each possible scheduling opportunity (each microframe), we will do so.  The
2215  * remaining number of packets will be saved to be transmitted in the gaps in
2216  * the next interval's scheduling sequence.
2217  *
2218  * As we move those remaining packets to be scheduled with interval 2 packets,
2219  * we have to double the number of remaining packets to transmit.  This is
2220  * because the intervals are actually powers of 2, and we would be transmitting
2221  * the previous interval's packets twice in this interval.  We also have to be
2222  * sure that when we look at the largest max packet size for this interval, we
2223  * also look at the largest max packet size for the remaining packets and take
2224  * the greater of the two.
2225  *
2226  * The algorithm continues to evenly distribute packets in each scheduling
2227  * opportunity, and push the remaining packets out, until we get to the last
2228  * interval.  Then those packets and their associated overhead are just added
2229  * to the bandwidth used.
2230  */
2231 static int xhci_check_bw_table(struct xhci_hcd *xhci,
2232                 struct xhci_virt_device *virt_dev,
2233                 int old_active_eps)
2234 {
2235         unsigned int bw_reserved;
2236         unsigned int max_bandwidth;
2237         unsigned int bw_used;
2238         unsigned int block_size;
2239         struct xhci_interval_bw_table *bw_table;
2240         unsigned int packet_size = 0;
2241         unsigned int overhead = 0;
2242         unsigned int packets_transmitted = 0;
2243         unsigned int packets_remaining = 0;
2244         unsigned int i;
2245
2246         if (virt_dev->udev->speed >= USB_SPEED_SUPER)
2247                 return xhci_check_ss_bw(xhci, virt_dev);
2248
2249         if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2250                 max_bandwidth = HS_BW_LIMIT;
2251                 /* Convert percent of bus BW reserved to blocks reserved */
2252                 bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2253         } else {
2254                 max_bandwidth = FS_BW_LIMIT;
2255                 bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2256         }
2257
2258         bw_table = virt_dev->bw_table;
2259         /* We need to translate the max packet size and max ESIT payloads into
2260          * the units the hardware uses.
2261          */
2262         block_size = xhci_get_block_size(virt_dev->udev);
2263
2264         /* If we are manipulating a LS/FS device under a HS hub, double check
2265          * that the HS bus has enough bandwidth if we are activing a new TT.
2266          */
2267         if (virt_dev->tt_info) {
2268                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2269                                 "Recalculating BW for rootport %u",
2270                                 virt_dev->real_port);
2271                 if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2272                         xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2273                                         "newly activated TT.\n");
2274                         return -ENOMEM;
2275                 }
2276                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2277                                 "Recalculating BW for TT slot %u port %u",
2278                                 virt_dev->tt_info->slot_id,
2279                                 virt_dev->tt_info->ttport);
2280         } else {
2281                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2282                                 "Recalculating BW for rootport %u",
2283                                 virt_dev->real_port);
2284         }
2285
2286         /* Add in how much bandwidth will be used for interval zero, or the
2287          * rounded max ESIT payload + number of packets * largest overhead.
2288          */
2289         bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2290                 bw_table->interval_bw[0].num_packets *
2291                 xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2292
2293         for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2294                 unsigned int bw_added;
2295                 unsigned int largest_mps;
2296                 unsigned int interval_overhead;
2297
2298                 /*
2299                  * How many packets could we transmit in this interval?
2300                  * If packets didn't fit in the previous interval, we will need
2301                  * to transmit that many packets twice within this interval.
2302                  */
2303                 packets_remaining = 2 * packets_remaining +
2304                         bw_table->interval_bw[i].num_packets;
2305
2306                 /* Find the largest max packet size of this or the previous
2307                  * interval.
2308                  */
2309                 if (list_empty(&bw_table->interval_bw[i].endpoints))
2310                         largest_mps = 0;
2311                 else {
2312                         struct xhci_virt_ep *virt_ep;
2313                         struct list_head *ep_entry;
2314
2315                         ep_entry = bw_table->interval_bw[i].endpoints.next;
2316                         virt_ep = list_entry(ep_entry,
2317                                         struct xhci_virt_ep, bw_endpoint_list);
2318                         /* Convert to blocks, rounding up */
2319                         largest_mps = DIV_ROUND_UP(
2320                                         virt_ep->bw_info.max_packet_size,
2321                                         block_size);
2322                 }
2323                 if (largest_mps > packet_size)
2324                         packet_size = largest_mps;
2325
2326                 /* Use the larger overhead of this or the previous interval. */
2327                 interval_overhead = xhci_get_largest_overhead(
2328                                 &bw_table->interval_bw[i]);
2329                 if (interval_overhead > overhead)
2330                         overhead = interval_overhead;
2331
2332                 /* How many packets can we evenly distribute across
2333                  * (1 << (i + 1)) possible scheduling opportunities?
2334                  */
2335                 packets_transmitted = packets_remaining >> (i + 1);
2336
2337                 /* Add in the bandwidth used for those scheduled packets */
2338                 bw_added = packets_transmitted * (overhead + packet_size);
2339
2340                 /* How many packets do we have remaining to transmit? */
2341                 packets_remaining = packets_remaining % (1 << (i + 1));
2342
2343                 /* What largest max packet size should those packets have? */
2344                 /* If we've transmitted all packets, don't carry over the
2345                  * largest packet size.
2346                  */
2347                 if (packets_remaining == 0) {
2348                         packet_size = 0;
2349                         overhead = 0;
2350                 } else if (packets_transmitted > 0) {
2351                         /* Otherwise if we do have remaining packets, and we've
2352                          * scheduled some packets in this interval, take the
2353                          * largest max packet size from endpoints with this
2354                          * interval.
2355                          */
2356                         packet_size = largest_mps;
2357                         overhead = interval_overhead;
2358                 }
2359                 /* Otherwise carry over packet_size and overhead from the last
2360                  * time we had a remainder.
2361                  */
2362                 bw_used += bw_added;
2363                 if (bw_used > max_bandwidth) {
2364                         xhci_warn(xhci, "Not enough bandwidth. "
2365                                         "Proposed: %u, Max: %u\n",
2366                                 bw_used, max_bandwidth);
2367                         return -ENOMEM;
2368                 }
2369         }
2370         /*
2371          * Ok, we know we have some packets left over after even-handedly
2372          * scheduling interval 15.  We don't know which microframes they will
2373          * fit into, so we over-schedule and say they will be scheduled every
2374          * microframe.
2375          */
2376         if (packets_remaining > 0)
2377                 bw_used += overhead + packet_size;
2378
2379         if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2380                 unsigned int port_index = virt_dev->real_port - 1;
2381
2382                 /* OK, we're manipulating a HS device attached to a
2383                  * root port bandwidth domain.  Include the number of active TTs
2384                  * in the bandwidth used.
2385                  */
2386                 bw_used += TT_HS_OVERHEAD *
2387                         xhci->rh_bw[port_index].num_active_tts;
2388         }
2389
2390         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2391                 "Final bandwidth: %u, Limit: %u, Reserved: %u, "
2392                 "Available: %u " "percent",
2393                 bw_used, max_bandwidth, bw_reserved,
2394                 (max_bandwidth - bw_used - bw_reserved) * 100 /
2395                 max_bandwidth);
2396
2397         bw_used += bw_reserved;
2398         if (bw_used > max_bandwidth) {
2399                 xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2400                                 bw_used, max_bandwidth);
2401                 return -ENOMEM;
2402         }
2403
2404         bw_table->bw_used = bw_used;
2405         return 0;
2406 }
2407
2408 static bool xhci_is_async_ep(unsigned int ep_type)
2409 {
2410         return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2411                                         ep_type != ISOC_IN_EP &&
2412                                         ep_type != INT_IN_EP);
2413 }
2414
2415 static bool xhci_is_sync_in_ep(unsigned int ep_type)
2416 {
2417         return (ep_type == ISOC_IN_EP || ep_type == INT_IN_EP);
2418 }
2419
2420 static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2421 {
2422         unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2423
2424         if (ep_bw->ep_interval == 0)
2425                 return SS_OVERHEAD_BURST +
2426                         (ep_bw->mult * ep_bw->num_packets *
2427                                         (SS_OVERHEAD + mps));
2428         return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2429                                 (SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2430                                 1 << ep_bw->ep_interval);
2431
2432 }
2433
2434 void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2435                 struct xhci_bw_info *ep_bw,
2436                 struct xhci_interval_bw_table *bw_table,
2437                 struct usb_device *udev,
2438                 struct xhci_virt_ep *virt_ep,
2439                 struct xhci_tt_bw_info *tt_info)
2440 {
2441         struct xhci_interval_bw *interval_bw;
2442         int normalized_interval;
2443
2444         if (xhci_is_async_ep(ep_bw->type))
2445                 return;
2446
2447         if (udev->speed >= USB_SPEED_SUPER) {
2448                 if (xhci_is_sync_in_ep(ep_bw->type))
2449                         xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2450                                 xhci_get_ss_bw_consumed(ep_bw);
2451                 else
2452                         xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2453                                 xhci_get_ss_bw_consumed(ep_bw);
2454                 return;
2455         }
2456
2457         /* SuperSpeed endpoints never get added to intervals in the table, so
2458          * this check is only valid for HS/FS/LS devices.
2459          */
2460         if (list_empty(&virt_ep->bw_endpoint_list))
2461                 return;
2462         /* For LS/FS devices, we need to translate the interval expressed in
2463          * microframes to frames.
2464          */
2465         if (udev->speed == USB_SPEED_HIGH)
2466                 normalized_interval = ep_bw->ep_interval;
2467         else
2468                 normalized_interval = ep_bw->ep_interval - 3;
2469
2470         if (normalized_interval == 0)
2471                 bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2472         interval_bw = &bw_table->interval_bw[normalized_interval];
2473         interval_bw->num_packets -= ep_bw->num_packets;
2474         switch (udev->speed) {
2475         case USB_SPEED_LOW:
2476                 interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2477                 break;
2478         case USB_SPEED_FULL:
2479                 interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2480                 break;
2481         case USB_SPEED_HIGH:
2482                 interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2483                 break;
2484         case USB_SPEED_SUPER:
2485         case USB_SPEED_SUPER_PLUS:
2486         case USB_SPEED_UNKNOWN:
2487         case USB_SPEED_WIRELESS:
2488                 /* Should never happen because only LS/FS/HS endpoints will get
2489                  * added to the endpoint list.
2490                  */
2491                 return;
2492         }
2493         if (tt_info)
2494                 tt_info->active_eps -= 1;
2495         list_del_init(&virt_ep->bw_endpoint_list);
2496 }
2497
2498 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2499                 struct xhci_bw_info *ep_bw,
2500                 struct xhci_interval_bw_table *bw_table,
2501                 struct usb_device *udev,
2502                 struct xhci_virt_ep *virt_ep,
2503                 struct xhci_tt_bw_info *tt_info)
2504 {
2505         struct xhci_interval_bw *interval_bw;
2506         struct xhci_virt_ep *smaller_ep;
2507         int normalized_interval;
2508
2509         if (xhci_is_async_ep(ep_bw->type))
2510                 return;
2511
2512         if (udev->speed == USB_SPEED_SUPER) {
2513                 if (xhci_is_sync_in_ep(ep_bw->type))
2514                         xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2515                                 xhci_get_ss_bw_consumed(ep_bw);
2516                 else
2517                         xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2518                                 xhci_get_ss_bw_consumed(ep_bw);
2519                 return;
2520         }
2521
2522         /* For LS/FS devices, we need to translate the interval expressed in
2523          * microframes to frames.
2524          */
2525         if (udev->speed == USB_SPEED_HIGH)
2526                 normalized_interval = ep_bw->ep_interval;
2527         else
2528                 normalized_interval = ep_bw->ep_interval - 3;
2529
2530         if (normalized_interval == 0)
2531                 bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2532         interval_bw = &bw_table->interval_bw[normalized_interval];
2533         interval_bw->num_packets += ep_bw->num_packets;
2534         switch (udev->speed) {
2535         case USB_SPEED_LOW:
2536                 interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2537                 break;
2538         case USB_SPEED_FULL:
2539                 interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2540                 break;
2541         case USB_SPEED_HIGH:
2542                 interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2543                 break;
2544         case USB_SPEED_SUPER:
2545         case USB_SPEED_SUPER_PLUS:
2546         case USB_SPEED_UNKNOWN:
2547         case USB_SPEED_WIRELESS:
2548                 /* Should never happen because only LS/FS/HS endpoints will get
2549                  * added to the endpoint list.
2550                  */
2551                 return;
2552         }
2553
2554         if (tt_info)
2555                 tt_info->active_eps += 1;
2556         /* Insert the endpoint into the list, largest max packet size first. */
2557         list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2558                         bw_endpoint_list) {
2559                 if (ep_bw->max_packet_size >=
2560                                 smaller_ep->bw_info.max_packet_size) {
2561                         /* Add the new ep before the smaller endpoint */
2562                         list_add_tail(&virt_ep->bw_endpoint_list,
2563                                         &smaller_ep->bw_endpoint_list);
2564                         return;
2565                 }
2566         }
2567         /* Add the new endpoint at the end of the list. */
2568         list_add_tail(&virt_ep->bw_endpoint_list,
2569                         &interval_bw->endpoints);
2570 }
2571
2572 void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2573                 struct xhci_virt_device *virt_dev,
2574                 int old_active_eps)
2575 {
2576         struct xhci_root_port_bw_info *rh_bw_info;
2577         if (!virt_dev->tt_info)
2578                 return;
2579
2580         rh_bw_info = &xhci->rh_bw[virt_dev->real_port - 1];
2581         if (old_active_eps == 0 &&
2582                                 virt_dev->tt_info->active_eps != 0) {
2583                 rh_bw_info->num_active_tts += 1;
2584                 rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2585         } else if (old_active_eps != 0 &&
2586                                 virt_dev->tt_info->active_eps == 0) {
2587                 rh_bw_info->num_active_tts -= 1;
2588                 rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2589         }
2590 }
2591
2592 static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2593                 struct xhci_virt_device *virt_dev,
2594                 struct xhci_container_ctx *in_ctx)
2595 {
2596         struct xhci_bw_info ep_bw_info[31];
2597         int i;
2598         struct xhci_input_control_ctx *ctrl_ctx;
2599         int old_active_eps = 0;
2600
2601         if (virt_dev->tt_info)
2602                 old_active_eps = virt_dev->tt_info->active_eps;
2603
2604         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2605         if (!ctrl_ctx) {
2606                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2607                                 __func__);
2608                 return -ENOMEM;
2609         }
2610
2611         for (i = 0; i < 31; i++) {
2612                 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2613                         continue;
2614
2615                 /* Make a copy of the BW info in case we need to revert this */
2616                 memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2617                                 sizeof(ep_bw_info[i]));
2618                 /* Drop the endpoint from the interval table if the endpoint is
2619                  * being dropped or changed.
2620                  */
2621                 if (EP_IS_DROPPED(ctrl_ctx, i))
2622                         xhci_drop_ep_from_interval_table(xhci,
2623                                         &virt_dev->eps[i].bw_info,
2624                                         virt_dev->bw_table,
2625                                         virt_dev->udev,
2626                                         &virt_dev->eps[i],
2627                                         virt_dev->tt_info);
2628         }
2629         /* Overwrite the information stored in the endpoints' bw_info */
2630         xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2631         for (i = 0; i < 31; i++) {
2632                 /* Add any changed or added endpoints to the interval table */
2633                 if (EP_IS_ADDED(ctrl_ctx, i))
2634                         xhci_add_ep_to_interval_table(xhci,
2635                                         &virt_dev->eps[i].bw_info,
2636                                         virt_dev->bw_table,
2637                                         virt_dev->udev,
2638                                         &virt_dev->eps[i],
2639                                         virt_dev->tt_info);
2640         }
2641
2642         if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2643                 /* Ok, this fits in the bandwidth we have.
2644                  * Update the number of active TTs.
2645                  */
2646                 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2647                 return 0;
2648         }
2649
2650         /* We don't have enough bandwidth for this, revert the stored info. */
2651         for (i = 0; i < 31; i++) {
2652                 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2653                         continue;
2654
2655                 /* Drop the new copies of any added or changed endpoints from
2656                  * the interval table.
2657                  */
2658                 if (EP_IS_ADDED(ctrl_ctx, i)) {
2659                         xhci_drop_ep_from_interval_table(xhci,
2660                                         &virt_dev->eps[i].bw_info,
2661                                         virt_dev->bw_table,
2662                                         virt_dev->udev,
2663                                         &virt_dev->eps[i],
2664                                         virt_dev->tt_info);
2665                 }
2666                 /* Revert the endpoint back to its old information */
2667                 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2668                                 sizeof(ep_bw_info[i]));
2669                 /* Add any changed or dropped endpoints back into the table */
2670                 if (EP_IS_DROPPED(ctrl_ctx, i))
2671                         xhci_add_ep_to_interval_table(xhci,
2672                                         &virt_dev->eps[i].bw_info,
2673                                         virt_dev->bw_table,
2674                                         virt_dev->udev,
2675                                         &virt_dev->eps[i],
2676                                         virt_dev->tt_info);
2677         }
2678         return -ENOMEM;
2679 }
2680
2681
2682 /* Issue a configure endpoint command or evaluate context command
2683  * and wait for it to finish.
2684  */
2685 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2686                 struct usb_device *udev,
2687                 struct xhci_command *command,
2688                 bool ctx_change, bool must_succeed)
2689 {
2690         int ret;
2691         unsigned long flags;
2692         struct xhci_input_control_ctx *ctrl_ctx;
2693         struct xhci_virt_device *virt_dev;
2694
2695         if (!command)
2696                 return -EINVAL;
2697
2698         spin_lock_irqsave(&xhci->lock, flags);
2699         virt_dev = xhci->devs[udev->slot_id];
2700
2701         ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2702         if (!ctrl_ctx) {
2703                 spin_unlock_irqrestore(&xhci->lock, flags);
2704                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2705                                 __func__);
2706                 return -ENOMEM;
2707         }
2708
2709         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
2710                         xhci_reserve_host_resources(xhci, ctrl_ctx)) {
2711                 spin_unlock_irqrestore(&xhci->lock, flags);
2712                 xhci_warn(xhci, "Not enough host resources, "
2713                                 "active endpoint contexts = %u\n",
2714                                 xhci->num_active_eps);
2715                 return -ENOMEM;
2716         }
2717         if ((xhci->quirks & XHCI_SW_BW_CHECKING) &&
2718             xhci_reserve_bandwidth(xhci, virt_dev, command->in_ctx)) {
2719                 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2720                         xhci_free_host_resources(xhci, ctrl_ctx);
2721                 spin_unlock_irqrestore(&xhci->lock, flags);
2722                 xhci_warn(xhci, "Not enough bandwidth\n");
2723                 return -ENOMEM;
2724         }
2725
2726         if (!ctx_change)
2727                 ret = xhci_queue_configure_endpoint(xhci, command,
2728                                 command->in_ctx->dma,
2729                                 udev->slot_id, must_succeed);
2730         else
2731                 ret = xhci_queue_evaluate_context(xhci, command,
2732                                 command->in_ctx->dma,
2733                                 udev->slot_id, must_succeed);
2734         if (ret < 0) {
2735                 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2736                         xhci_free_host_resources(xhci, ctrl_ctx);
2737                 spin_unlock_irqrestore(&xhci->lock, flags);
2738                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
2739                                 "FIXME allocate a new ring segment");
2740                 return -ENOMEM;
2741         }
2742         xhci_ring_cmd_db(xhci);
2743         spin_unlock_irqrestore(&xhci->lock, flags);
2744
2745         /* Wait for the configure endpoint command to complete */
2746         wait_for_completion(command->completion);
2747
2748         if (!ctx_change)
2749                 ret = xhci_configure_endpoint_result(xhci, udev,
2750                                                      &command->status);
2751         else
2752                 ret = xhci_evaluate_context_result(xhci, udev,
2753                                                    &command->status);
2754
2755         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
2756                 spin_lock_irqsave(&xhci->lock, flags);
2757                 /* If the command failed, remove the reserved resources.
2758                  * Otherwise, clean up the estimate to include dropped eps.
2759                  */
2760                 if (ret)
2761                         xhci_free_host_resources(xhci, ctrl_ctx);
2762                 else
2763                         xhci_finish_resource_reservation(xhci, ctrl_ctx);
2764                 spin_unlock_irqrestore(&xhci->lock, flags);
2765         }
2766         return ret;
2767 }
2768
2769 static void xhci_check_bw_drop_ep_streams(struct xhci_hcd *xhci,
2770         struct xhci_virt_device *vdev, int i)
2771 {
2772         struct xhci_virt_ep *ep = &vdev->eps[i];
2773
2774         if (ep->ep_state & EP_HAS_STREAMS) {
2775                 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on set_interface, freeing streams.\n",
2776                                 xhci_get_endpoint_address(i));
2777                 xhci_free_stream_info(xhci, ep->stream_info);
2778                 ep->stream_info = NULL;
2779                 ep->ep_state &= ~EP_HAS_STREAMS;
2780         }
2781 }
2782
2783 /* Called after one or more calls to xhci_add_endpoint() or
2784  * xhci_drop_endpoint().  If this call fails, the USB core is expected
2785  * to call xhci_reset_bandwidth().
2786  *
2787  * Since we are in the middle of changing either configuration or
2788  * installing a new alt setting, the USB core won't allow URBs to be
2789  * enqueued for any endpoint on the old config or interface.  Nothing
2790  * else should be touching the xhci->devs[slot_id] structure, so we
2791  * don't need to take the xhci->lock for manipulating that.
2792  */
2793 int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2794 {
2795         int i;
2796         int ret = 0;
2797         struct xhci_hcd *xhci;
2798         struct xhci_virt_device *virt_dev;
2799         struct xhci_input_control_ctx *ctrl_ctx;
2800         struct xhci_slot_ctx *slot_ctx;
2801         struct xhci_command *command;
2802
2803         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2804         if (ret <= 0)
2805                 return ret;
2806         xhci = hcd_to_xhci(hcd);
2807         if ((xhci->xhc_state & XHCI_STATE_DYING) ||
2808                 (xhci->xhc_state & XHCI_STATE_REMOVING))
2809                 return -ENODEV;
2810
2811         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2812         virt_dev = xhci->devs[udev->slot_id];
2813
2814         command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
2815         if (!command)
2816                 return -ENOMEM;
2817
2818         command->in_ctx = virt_dev->in_ctx;
2819
2820         /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
2821         ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2822         if (!ctrl_ctx) {
2823                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2824                                 __func__);
2825                 ret = -ENOMEM;
2826                 goto command_cleanup;
2827         }
2828         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2829         ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
2830         ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
2831
2832         /* Don't issue the command if there's no endpoints to update. */
2833         if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
2834             ctrl_ctx->drop_flags == 0) {
2835                 ret = 0;
2836                 goto command_cleanup;
2837         }
2838         /* Fix up Context Entries field. Minimum value is EP0 == BIT(1). */
2839         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2840         for (i = 31; i >= 1; i--) {
2841                 __le32 le32 = cpu_to_le32(BIT(i));
2842
2843                 if ((virt_dev->eps[i-1].ring && !(ctrl_ctx->drop_flags & le32))
2844                     || (ctrl_ctx->add_flags & le32) || i == 1) {
2845                         slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2846                         slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(i));
2847                         break;
2848                 }
2849         }
2850         xhci_dbg(xhci, "New Input Control Context:\n");
2851         xhci_dbg_ctx(xhci, virt_dev->in_ctx,
2852                      LAST_CTX_TO_EP_NUM(le32_to_cpu(slot_ctx->dev_info)));
2853
2854         ret = xhci_configure_endpoint(xhci, udev, command,
2855                         false, false);
2856         if (ret)
2857                 /* Callee should call reset_bandwidth() */
2858                 goto command_cleanup;
2859
2860         xhci_dbg(xhci, "Output context after successful config ep cmd:\n");
2861         xhci_dbg_ctx(xhci, virt_dev->out_ctx,
2862                      LAST_CTX_TO_EP_NUM(le32_to_cpu(slot_ctx->dev_info)));
2863
2864         /* Free any rings that were dropped, but not changed. */
2865         for (i = 1; i < 31; ++i) {
2866                 if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
2867                     !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1)))) {
2868                         xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
2869                         xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2870                 }
2871         }
2872         xhci_zero_in_ctx(xhci, virt_dev);
2873         /*
2874          * Install any rings for completely new endpoints or changed endpoints,
2875          * and free or cache any old rings from changed endpoints.
2876          */
2877         for (i = 1; i < 31; ++i) {
2878                 if (!virt_dev->eps[i].new_ring)
2879                         continue;
2880                 /* Only cache or free the old ring if it exists.
2881                  * It may not if this is the first add of an endpoint.
2882                  */
2883                 if (virt_dev->eps[i].ring) {
2884                         xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
2885                 }
2886                 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2887                 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
2888                 virt_dev->eps[i].new_ring = NULL;
2889         }
2890 command_cleanup:
2891         kfree(command->completion);
2892         kfree(command);
2893
2894         return ret;
2895 }
2896
2897 void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2898 {
2899         struct xhci_hcd *xhci;
2900         struct xhci_virt_device *virt_dev;
2901         int i, ret;
2902
2903         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2904         if (ret <= 0)
2905                 return;
2906         xhci = hcd_to_xhci(hcd);
2907
2908         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2909         virt_dev = xhci->devs[udev->slot_id];
2910         /* Free any rings allocated for added endpoints */
2911         for (i = 0; i < 31; ++i) {
2912                 if (virt_dev->eps[i].new_ring) {
2913                         xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
2914                         virt_dev->eps[i].new_ring = NULL;
2915                 }
2916         }
2917         xhci_zero_in_ctx(xhci, virt_dev);
2918 }
2919
2920 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
2921                 struct xhci_container_ctx *in_ctx,
2922                 struct xhci_container_ctx *out_ctx,
2923                 struct xhci_input_control_ctx *ctrl_ctx,
2924                 u32 add_flags, u32 drop_flags)
2925 {
2926         ctrl_ctx->add_flags = cpu_to_le32(add_flags);
2927         ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
2928         xhci_slot_copy(xhci, in_ctx, out_ctx);
2929         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2930
2931         xhci_dbg(xhci, "Input Context:\n");
2932         xhci_dbg_ctx(xhci, in_ctx, xhci_last_valid_endpoint(add_flags));
2933 }
2934
2935 static void xhci_setup_input_ctx_for_quirk(struct xhci_hcd *xhci,
2936                 unsigned int slot_id, unsigned int ep_index,
2937                 struct xhci_dequeue_state *deq_state)
2938 {
2939         struct xhci_input_control_ctx *ctrl_ctx;
2940         struct xhci_container_ctx *in_ctx;
2941         struct xhci_ep_ctx *ep_ctx;
2942         u32 added_ctxs;
2943         dma_addr_t addr;
2944
2945         in_ctx = xhci->devs[slot_id]->in_ctx;
2946         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2947         if (!ctrl_ctx) {
2948                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2949                                 __func__);
2950                 return;
2951         }
2952
2953         xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
2954                         xhci->devs[slot_id]->out_ctx, ep_index);
2955         ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
2956         addr = xhci_trb_virt_to_dma(deq_state->new_deq_seg,
2957                         deq_state->new_deq_ptr);
2958         if (addr == 0) {
2959                 xhci_warn(xhci, "WARN Cannot submit config ep after "
2960                                 "reset ep command\n");
2961                 xhci_warn(xhci, "WARN deq seg = %p, deq ptr = %p\n",
2962                                 deq_state->new_deq_seg,
2963                                 deq_state->new_deq_ptr);
2964                 return;
2965         }
2966         ep_ctx->deq = cpu_to_le64(addr | deq_state->new_cycle_state);
2967
2968         added_ctxs = xhci_get_endpoint_flag_from_index(ep_index);
2969         xhci_setup_input_ctx_for_config_ep(xhci, xhci->devs[slot_id]->in_ctx,
2970                         xhci->devs[slot_id]->out_ctx, ctrl_ctx,
2971                         added_ctxs, added_ctxs);
2972 }
2973
2974 void xhci_cleanup_stalled_ring(struct xhci_hcd *xhci,
2975                         unsigned int ep_index, struct xhci_td *td)
2976 {
2977         struct xhci_dequeue_state deq_state;
2978         struct xhci_virt_ep *ep;
2979         struct usb_device *udev = td->urb->dev;
2980
2981         xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
2982                         "Cleaning up stalled endpoint ring");
2983         ep = &xhci->devs[udev->slot_id]->eps[ep_index];
2984         /* We need to move the HW's dequeue pointer past this TD,
2985          * or it will attempt to resend it on the next doorbell ring.
2986          */
2987         xhci_find_new_dequeue_state(xhci, udev->slot_id,
2988                         ep_index, ep->stopped_stream, td, &deq_state);
2989
2990         if (!deq_state.new_deq_ptr || !deq_state.new_deq_seg)
2991                 return;
2992
2993         /* HW with the reset endpoint quirk will use the saved dequeue state to
2994          * issue a configure endpoint command later.
2995          */
2996         if (!(xhci->quirks & XHCI_RESET_EP_QUIRK)) {
2997                 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
2998                                 "Queueing new dequeue state");
2999                 xhci_queue_new_dequeue_state(xhci, udev->slot_id,
3000                                 ep_index, ep->stopped_stream, &deq_state);
3001         } else {
3002                 /* Better hope no one uses the input context between now and the
3003                  * reset endpoint completion!
3004                  * XXX: No idea how this hardware will react when stream rings
3005                  * are enabled.
3006                  */
3007                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3008                                 "Setting up input context for "
3009                                 "configure endpoint command");
3010                 xhci_setup_input_ctx_for_quirk(xhci, udev->slot_id,
3011                                 ep_index, &deq_state);
3012         }
3013 }
3014
3015 /* Called when clearing halted device. The core should have sent the control
3016  * message to clear the device halt condition. The host side of the halt should
3017  * already be cleared with a reset endpoint command issued when the STALL tx
3018  * event was received.
3019  *
3020  * Context: in_interrupt
3021  */
3022
3023 void xhci_endpoint_reset(struct usb_hcd *hcd,
3024                 struct usb_host_endpoint *ep)
3025 {
3026         struct xhci_hcd *xhci;
3027
3028         xhci = hcd_to_xhci(hcd);
3029
3030         /*
3031          * We might need to implement the config ep cmd in xhci 4.8.1 note:
3032          * The Reset Endpoint Command may only be issued to endpoints in the
3033          * Halted state. If software wishes reset the Data Toggle or Sequence
3034          * Number of an endpoint that isn't in the Halted state, then software
3035          * may issue a Configure Endpoint Command with the Drop and Add bits set
3036          * for the target endpoint. that is in the Stopped state.
3037          */
3038
3039         /* For now just print debug to follow the situation */
3040         xhci_dbg(xhci, "Endpoint 0x%x ep reset callback called\n",
3041                  ep->desc.bEndpointAddress);
3042 }
3043
3044 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
3045                 struct usb_device *udev, struct usb_host_endpoint *ep,
3046                 unsigned int slot_id)
3047 {
3048         int ret;
3049         unsigned int ep_index;
3050         unsigned int ep_state;
3051
3052         if (!ep)
3053                 return -EINVAL;
3054         ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
3055         if (ret <= 0)
3056                 return -EINVAL;
3057         if (usb_ss_max_streams(&ep->ss_ep_comp) == 0) {
3058                 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
3059                                 " descriptor for ep 0x%x does not support streams\n",
3060                                 ep->desc.bEndpointAddress);
3061                 return -EINVAL;
3062         }
3063
3064         ep_index = xhci_get_endpoint_index(&ep->desc);
3065         ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3066         if (ep_state & EP_HAS_STREAMS ||
3067                         ep_state & EP_GETTING_STREAMS) {
3068                 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
3069                                 "already has streams set up.\n",
3070                                 ep->desc.bEndpointAddress);
3071                 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
3072                                 "dynamic stream context array reallocation.\n");
3073                 return -EINVAL;
3074         }
3075         if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
3076                 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
3077                                 "endpoint 0x%x; URBs are pending.\n",
3078                                 ep->desc.bEndpointAddress);
3079                 return -EINVAL;
3080         }
3081         return 0;
3082 }
3083
3084 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
3085                 unsigned int *num_streams, unsigned int *num_stream_ctxs)
3086 {
3087         unsigned int max_streams;
3088
3089         /* The stream context array size must be a power of two */
3090         *num_stream_ctxs = roundup_pow_of_two(*num_streams);
3091         /*
3092          * Find out how many primary stream array entries the host controller
3093          * supports.  Later we may use secondary stream arrays (similar to 2nd
3094          * level page entries), but that's an optional feature for xHCI host
3095          * controllers. xHCs must support at least 4 stream IDs.
3096          */
3097         max_streams = HCC_MAX_PSA(xhci->hcc_params);
3098         if (*num_stream_ctxs > max_streams) {
3099                 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
3100                                 max_streams);
3101                 *num_stream_ctxs = max_streams;
3102                 *num_streams = max_streams;
3103         }
3104 }
3105
3106 /* Returns an error code if one of the endpoint already has streams.
3107  * This does not change any data structures, it only checks and gathers
3108  * information.
3109  */
3110 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
3111                 struct usb_device *udev,
3112                 struct usb_host_endpoint **eps, unsigned int num_eps,
3113                 unsigned int *num_streams, u32 *changed_ep_bitmask)
3114 {
3115         unsigned int max_streams;
3116         unsigned int endpoint_flag;
3117         int i;
3118         int ret;
3119
3120         for (i = 0; i < num_eps; i++) {
3121                 ret = xhci_check_streams_endpoint(xhci, udev,
3122                                 eps[i], udev->slot_id);
3123                 if (ret < 0)
3124                         return ret;
3125
3126                 max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
3127                 if (max_streams < (*num_streams - 1)) {
3128                         xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
3129                                         eps[i]->desc.bEndpointAddress,
3130                                         max_streams);
3131                         *num_streams = max_streams+1;
3132                 }
3133
3134                 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
3135                 if (*changed_ep_bitmask & endpoint_flag)
3136                         return -EINVAL;
3137                 *changed_ep_bitmask |= endpoint_flag;
3138         }
3139         return 0;
3140 }
3141
3142 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
3143                 struct usb_device *udev,
3144                 struct usb_host_endpoint **eps, unsigned int num_eps)
3145 {
3146         u32 changed_ep_bitmask = 0;
3147         unsigned int slot_id;
3148         unsigned int ep_index;
3149         unsigned int ep_state;
3150         int i;
3151
3152         slot_id = udev->slot_id;
3153         if (!xhci->devs[slot_id])
3154                 return 0;
3155
3156         for (i = 0; i < num_eps; i++) {
3157                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3158                 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3159                 /* Are streams already being freed for the endpoint? */
3160                 if (ep_state & EP_GETTING_NO_STREAMS) {
3161                         xhci_warn(xhci, "WARN Can't disable streams for "
3162                                         "endpoint 0x%x, "
3163                                         "streams are being disabled already\n",
3164                                         eps[i]->desc.bEndpointAddress);
3165                         return 0;
3166                 }
3167                 /* Are there actually any streams to free? */
3168                 if (!(ep_state & EP_HAS_STREAMS) &&
3169                                 !(ep_state & EP_GETTING_STREAMS)) {
3170                         xhci_warn(xhci, "WARN Can't disable streams for "
3171                                         "endpoint 0x%x, "
3172                                         "streams are already disabled!\n",
3173                                         eps[i]->desc.bEndpointAddress);
3174                         xhci_warn(xhci, "WARN xhci_free_streams() called "
3175                                         "with non-streams endpoint\n");
3176                         return 0;
3177                 }
3178                 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
3179         }
3180         return changed_ep_bitmask;
3181 }
3182
3183 /*
3184  * The USB device drivers use this function (through the HCD interface in USB
3185  * core) to prepare a set of bulk endpoints to use streams.  Streams are used to
3186  * coordinate mass storage command queueing across multiple endpoints (basically
3187  * a stream ID == a task ID).
3188  *
3189  * Setting up streams involves allocating the same size stream context array
3190  * for each endpoint and issuing a configure endpoint command for all endpoints.
3191  *
3192  * Don't allow the call to succeed if one endpoint only supports one stream
3193  * (which means it doesn't support streams at all).
3194  *
3195  * Drivers may get less stream IDs than they asked for, if the host controller
3196  * hardware or endpoints claim they can't support the number of requested
3197  * stream IDs.
3198  */
3199 int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
3200                 struct usb_host_endpoint **eps, unsigned int num_eps,
3201                 unsigned int num_streams, gfp_t mem_flags)
3202 {
3203         int i, ret;
3204         struct xhci_hcd *xhci;
3205         struct xhci_virt_device *vdev;
3206         struct xhci_command *config_cmd;
3207         struct xhci_input_control_ctx *ctrl_ctx;
3208         unsigned int ep_index;
3209         unsigned int num_stream_ctxs;
3210         unsigned long flags;
3211         u32 changed_ep_bitmask = 0;
3212
3213         if (!eps)
3214                 return -EINVAL;
3215
3216         /* Add one to the number of streams requested to account for
3217          * stream 0 that is reserved for xHCI usage.
3218          */
3219         num_streams += 1;
3220         xhci = hcd_to_xhci(hcd);
3221         xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
3222                         num_streams);
3223
3224         /* MaxPSASize value 0 (2 streams) means streams are not supported */
3225         if ((xhci->quirks & XHCI_BROKEN_STREAMS) ||
3226                         HCC_MAX_PSA(xhci->hcc_params) < 4) {
3227                 xhci_dbg(xhci, "xHCI controller does not support streams.\n");
3228                 return -ENOSYS;
3229         }
3230
3231         config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
3232         if (!config_cmd) {
3233                 xhci_dbg(xhci, "Could not allocate xHCI command structure.\n");
3234                 return -ENOMEM;
3235         }
3236         ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
3237         if (!ctrl_ctx) {
3238                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3239                                 __func__);
3240                 xhci_free_command(xhci, config_cmd);
3241                 return -ENOMEM;
3242         }
3243
3244         /* Check to make sure all endpoints are not already configured for
3245          * streams.  While we're at it, find the maximum number of streams that
3246          * all the endpoints will support and check for duplicate endpoints.
3247          */
3248         spin_lock_irqsave(&xhci->lock, flags);
3249         ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
3250                         num_eps, &num_streams, &changed_ep_bitmask);
3251         if (ret < 0) {
3252                 xhci_free_command(xhci, config_cmd);
3253                 spin_unlock_irqrestore(&xhci->lock, flags);
3254                 return ret;
3255         }
3256         if (num_streams <= 1) {
3257                 xhci_warn(xhci, "WARN: endpoints can't handle "
3258                                 "more than one stream.\n");
3259                 xhci_free_command(xhci, config_cmd);
3260                 spin_unlock_irqrestore(&xhci->lock, flags);
3261                 return -EINVAL;
3262         }
3263         vdev = xhci->devs[udev->slot_id];
3264         /* Mark each endpoint as being in transition, so
3265          * xhci_urb_enqueue() will reject all URBs.
3266          */
3267         for (i = 0; i < num_eps; i++) {
3268                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3269                 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
3270         }
3271         spin_unlock_irqrestore(&xhci->lock, flags);
3272
3273         /* Setup internal data structures and allocate HW data structures for
3274          * streams (but don't install the HW structures in the input context
3275          * until we're sure all memory allocation succeeded).
3276          */
3277         xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
3278         xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
3279                         num_stream_ctxs, num_streams);
3280
3281         for (i = 0; i < num_eps; i++) {
3282                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3283                 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
3284                                 num_stream_ctxs,
3285                                 num_streams, mem_flags);
3286                 if (!vdev->eps[ep_index].stream_info)
3287                         goto cleanup;
3288                 /* Set maxPstreams in endpoint context and update deq ptr to
3289                  * point to stream context array. FIXME
3290                  */
3291         }
3292
3293         /* Set up the input context for a configure endpoint command. */
3294         for (i = 0; i < num_eps; i++) {
3295                 struct xhci_ep_ctx *ep_ctx;
3296
3297                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3298                 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
3299
3300                 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3301                                 vdev->out_ctx, ep_index);
3302                 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3303                                 vdev->eps[ep_index].stream_info);
3304         }
3305         /* Tell the HW to drop its old copy of the endpoint context info
3306          * and add the updated copy from the input context.
3307          */
3308         xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
3309                         vdev->out_ctx, ctrl_ctx,
3310                         changed_ep_bitmask, changed_ep_bitmask);
3311
3312         /* Issue and wait for the configure endpoint command */
3313         ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3314                         false, false);
3315
3316         /* xHC rejected the configure endpoint command for some reason, so we
3317          * leave the old ring intact and free our internal streams data
3318          * structure.
3319          */
3320         if (ret < 0)
3321                 goto cleanup;
3322
3323         spin_lock_irqsave(&xhci->lock, flags);
3324         for (i = 0; i < num_eps; i++) {
3325                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3326                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3327                 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
3328                          udev->slot_id, ep_index);
3329                 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
3330         }
3331         xhci_free_command(xhci, config_cmd);
3332         spin_unlock_irqrestore(&xhci->lock, flags);
3333
3334         /* Subtract 1 for stream 0, which drivers can't use */
3335         return num_streams - 1;
3336
3337 cleanup:
3338         /* If it didn't work, free the streams! */
3339         for (i = 0; i < num_eps; i++) {
3340                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3341                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3342                 vdev->eps[ep_index].stream_info = NULL;
3343                 /* FIXME Unset maxPstreams in endpoint context and
3344                  * update deq ptr to point to normal string ring.
3345                  */
3346                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3347                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3348                 xhci_endpoint_zero(xhci, vdev, eps[i]);
3349         }
3350         xhci_free_command(xhci, config_cmd);
3351         return -ENOMEM;
3352 }
3353
3354 /* Transition the endpoint from using streams to being a "normal" endpoint
3355  * without streams.
3356  *
3357  * Modify the endpoint context state, submit a configure endpoint command,
3358  * and free all endpoint rings for streams if that completes successfully.
3359  */
3360 int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3361                 struct usb_host_endpoint **eps, unsigned int num_eps,
3362                 gfp_t mem_flags)
3363 {
3364         int i, ret;
3365         struct xhci_hcd *xhci;
3366         struct xhci_virt_device *vdev;
3367         struct xhci_command *command;
3368         struct xhci_input_control_ctx *ctrl_ctx;
3369         unsigned int ep_index;
3370         unsigned long flags;
3371         u32 changed_ep_bitmask;
3372
3373         xhci = hcd_to_xhci(hcd);
3374         vdev = xhci->devs[udev->slot_id];
3375
3376         /* Set up a configure endpoint command to remove the streams rings */
3377         spin_lock_irqsave(&xhci->lock, flags);
3378         changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3379                         udev, eps, num_eps);
3380         if (changed_ep_bitmask == 0) {
3381                 spin_unlock_irqrestore(&xhci->lock, flags);
3382                 return -EINVAL;
3383         }
3384
3385         /* Use the xhci_command structure from the first endpoint.  We may have
3386          * allocated too many, but the driver may call xhci_free_streams() for
3387          * each endpoint it grouped into one call to xhci_alloc_streams().
3388          */
3389         ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3390         command = vdev->eps[ep_index].stream_info->free_streams_command;
3391         ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3392         if (!ctrl_ctx) {
3393                 spin_unlock_irqrestore(&xhci->lock, flags);
3394                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3395                                 __func__);
3396                 return -EINVAL;
3397         }
3398
3399         for (i = 0; i < num_eps; i++) {
3400                 struct xhci_ep_ctx *ep_ctx;
3401
3402                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3403                 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3404                 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3405                         EP_GETTING_NO_STREAMS;
3406
3407                 xhci_endpoint_copy(xhci, command->in_ctx,
3408                                 vdev->out_ctx, ep_index);
3409                 xhci_setup_no_streams_ep_input_ctx(ep_ctx,
3410                                 &vdev->eps[ep_index]);
3411         }
3412         xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3413                         vdev->out_ctx, ctrl_ctx,
3414                         changed_ep_bitmask, changed_ep_bitmask);
3415         spin_unlock_irqrestore(&xhci->lock, flags);
3416
3417         /* Issue and wait for the configure endpoint command,
3418          * which must succeed.
3419          */
3420         ret = xhci_configure_endpoint(xhci, udev, command,
3421                         false, true);
3422
3423         /* xHC rejected the configure endpoint command for some reason, so we
3424          * leave the streams rings intact.
3425          */
3426         if (ret < 0)
3427                 return ret;
3428
3429         spin_lock_irqsave(&xhci->lock, flags);
3430         for (i = 0; i < num_eps; i++) {
3431                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3432                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3433                 vdev->eps[ep_index].stream_info = NULL;
3434                 /* FIXME Unset maxPstreams in endpoint context and
3435                  * update deq ptr to point to normal string ring.
3436                  */
3437                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
3438                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3439         }
3440         spin_unlock_irqrestore(&xhci->lock, flags);
3441
3442         return 0;
3443 }
3444
3445 /*
3446  * Deletes endpoint resources for endpoints that were active before a Reset
3447  * Device command, or a Disable Slot command.  The Reset Device command leaves
3448  * the control endpoint intact, whereas the Disable Slot command deletes it.
3449  *
3450  * Must be called with xhci->lock held.
3451  */
3452 void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
3453         struct xhci_virt_device *virt_dev, bool drop_control_ep)
3454 {
3455         int i;
3456         unsigned int num_dropped_eps = 0;
3457         unsigned int drop_flags = 0;
3458
3459         for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
3460                 if (virt_dev->eps[i].ring) {
3461                         drop_flags |= 1 << i;
3462                         num_dropped_eps++;
3463                 }
3464         }
3465         xhci->num_active_eps -= num_dropped_eps;
3466         if (num_dropped_eps)
3467                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3468                                 "Dropped %u ep ctxs, flags = 0x%x, "
3469                                 "%u now active.",
3470                                 num_dropped_eps, drop_flags,
3471                                 xhci->num_active_eps);
3472 }
3473
3474 /*
3475  * This submits a Reset Device Command, which will set the device state to 0,
3476  * set the device address to 0, and disable all the endpoints except the default
3477  * control endpoint.  The USB core should come back and call
3478  * xhci_address_device(), and then re-set up the configuration.  If this is
3479  * called because of a usb_reset_and_verify_device(), then the old alternate
3480  * settings will be re-installed through the normal bandwidth allocation
3481  * functions.
3482  *
3483  * Wait for the Reset Device command to finish.  Remove all structures
3484  * associated with the endpoints that were disabled.  Clear the input device
3485  * structure?  Cache the rings?  Reset the control endpoint 0 max packet size?
3486  *
3487  * If the virt_dev to be reset does not exist or does not match the udev,
3488  * it means the device is lost, possibly due to the xHC restore error and
3489  * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3490  * re-allocate the device.
3491  */
3492 int xhci_discover_or_reset_device(struct usb_hcd *hcd, struct usb_device *udev)
3493 {
3494         int ret, i;
3495         unsigned long flags;
3496         struct xhci_hcd *xhci;
3497         unsigned int slot_id;
3498         struct xhci_virt_device *virt_dev;
3499         struct xhci_command *reset_device_cmd;
3500         int last_freed_endpoint;
3501         struct xhci_slot_ctx *slot_ctx;
3502         int old_active_eps = 0;
3503
3504         ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3505         if (ret <= 0)
3506                 return ret;
3507         xhci = hcd_to_xhci(hcd);
3508         slot_id = udev->slot_id;
3509         virt_dev = xhci->devs[slot_id];
3510         if (!virt_dev) {
3511                 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3512                                 "not exist. Re-allocate the device\n", slot_id);
3513                 ret = xhci_alloc_dev(hcd, udev);
3514                 if (ret == 1)
3515                         return 0;
3516                 else
3517                         return -EINVAL;
3518         }
3519
3520         if (virt_dev->tt_info)
3521                 old_active_eps = virt_dev->tt_info->active_eps;
3522
3523         if (virt_dev->udev != udev) {
3524                 /* If the virt_dev and the udev does not match, this virt_dev
3525                  * may belong to another udev.
3526                  * Re-allocate the device.
3527                  */
3528                 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3529                                 "not match the udev. Re-allocate the device\n",
3530                                 slot_id);
3531                 ret = xhci_alloc_dev(hcd, udev);
3532                 if (ret == 1)
3533                         return 0;
3534                 else
3535                         return -EINVAL;
3536         }
3537
3538         /* If device is not setup, there is no point in resetting it */
3539         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3540         if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3541                                                 SLOT_STATE_DISABLED)
3542                 return 0;
3543
3544         xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3545         /* Allocate the command structure that holds the struct completion.
3546          * Assume we're in process context, since the normal device reset
3547          * process has to wait for the device anyway.  Storage devices are
3548          * reset as part of error handling, so use GFP_NOIO instead of
3549          * GFP_KERNEL.
3550          */
3551         reset_device_cmd = xhci_alloc_command(xhci, false, true, GFP_NOIO);
3552         if (!reset_device_cmd) {
3553                 xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3554                 return -ENOMEM;
3555         }
3556
3557         /* Attempt to submit the Reset Device command to the command ring */
3558         spin_lock_irqsave(&xhci->lock, flags);
3559
3560         ret = xhci_queue_reset_device(xhci, reset_device_cmd, slot_id);
3561         if (ret) {
3562                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3563                 spin_unlock_irqrestore(&xhci->lock, flags);
3564                 goto command_cleanup;
3565         }
3566         xhci_ring_cmd_db(xhci);
3567         spin_unlock_irqrestore(&xhci->lock, flags);
3568
3569         /* Wait for the Reset Device command to finish */
3570         wait_for_completion(reset_device_cmd->completion);
3571
3572         /* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3573          * unless we tried to reset a slot ID that wasn't enabled,
3574          * or the device wasn't in the addressed or configured state.
3575          */
3576         ret = reset_device_cmd->status;
3577         switch (ret) {
3578         case COMP_CMD_ABORT:
3579         case COMP_CMD_STOP:
3580                 xhci_warn(xhci, "Timeout waiting for reset device command\n");
3581                 ret = -ETIME;
3582                 goto command_cleanup;
3583         case COMP_EBADSLT: /* 0.95 completion code for bad slot ID */
3584         case COMP_CTX_STATE: /* 0.96 completion code for same thing */
3585                 xhci_dbg(xhci, "Can't reset device (slot ID %u) in %s state\n",
3586                                 slot_id,
3587                                 xhci_get_slot_state(xhci, virt_dev->out_ctx));
3588                 xhci_dbg(xhci, "Not freeing device rings.\n");
3589                 /* Don't treat this as an error.  May change my mind later. */
3590                 ret = 0;
3591                 goto command_cleanup;
3592         case COMP_SUCCESS:
3593                 xhci_dbg(xhci, "Successful reset device command.\n");
3594                 break;
3595         default:
3596                 if (xhci_is_vendor_info_code(xhci, ret))
3597                         break;
3598                 xhci_warn(xhci, "Unknown completion code %u for "
3599                                 "reset device command.\n", ret);
3600                 ret = -EINVAL;
3601                 goto command_cleanup;
3602         }
3603
3604         /* Free up host controller endpoint resources */
3605         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3606                 spin_lock_irqsave(&xhci->lock, flags);
3607                 /* Don't delete the default control endpoint resources */
3608                 xhci_free_device_endpoint_resources(xhci, virt_dev, false);
3609                 spin_unlock_irqrestore(&xhci->lock, flags);
3610         }
3611
3612         /* Everything but endpoint 0 is disabled, so free or cache the rings. */
3613         last_freed_endpoint = 1;
3614         for (i = 1; i < 31; ++i) {
3615                 struct xhci_virt_ep *ep = &virt_dev->eps[i];
3616
3617                 if (ep->ep_state & EP_HAS_STREAMS) {
3618                         xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on device reset, freeing streams.\n",
3619                                         xhci_get_endpoint_address(i));
3620                         xhci_free_stream_info(xhci, ep->stream_info);
3621                         ep->stream_info = NULL;
3622                         ep->ep_state &= ~EP_HAS_STREAMS;
3623                 }
3624
3625                 if (ep->ring) {
3626                         xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
3627                         last_freed_endpoint = i;
3628                 }
3629                 if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
3630                         xhci_drop_ep_from_interval_table(xhci,
3631                                         &virt_dev->eps[i].bw_info,
3632                                         virt_dev->bw_table,
3633                                         udev,
3634                                         &virt_dev->eps[i],
3635                                         virt_dev->tt_info);
3636                 xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
3637         }
3638         /* If necessary, update the number of active TTs on this root port */
3639         xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
3640
3641         xhci_dbg(xhci, "Output context after successful reset device cmd:\n");
3642         xhci_dbg_ctx(xhci, virt_dev->out_ctx, last_freed_endpoint);
3643         ret = 0;
3644
3645 command_cleanup:
3646         xhci_free_command(xhci, reset_device_cmd);
3647         return ret;
3648 }
3649
3650 /*
3651  * At this point, the struct usb_device is about to go away, the device has
3652  * disconnected, and all traffic has been stopped and the endpoints have been
3653  * disabled.  Free any HC data structures associated with that device.
3654  */
3655 void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
3656 {
3657         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3658         struct xhci_virt_device *virt_dev;
3659         unsigned long flags;
3660         u32 state;
3661         int i, ret;
3662         struct xhci_command *command;
3663
3664         command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
3665         if (!command)
3666                 return;
3667
3668 #ifndef CONFIG_USB_DEFAULT_PERSIST
3669         /*
3670          * We called pm_runtime_get_noresume when the device was attached.
3671          * Decrement the counter here to allow controller to runtime suspend
3672          * if no devices remain.
3673          */
3674         if (xhci->quirks & XHCI_RESET_ON_RESUME)
3675                 pm_runtime_put_noidle(hcd->self.controller);
3676 #endif
3677
3678         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3679         /* If the host is halted due to driver unload, we still need to free the
3680          * device.
3681          */
3682         if (ret <= 0 && ret != -ENODEV) {
3683                 kfree(command);
3684                 return;
3685         }
3686
3687         virt_dev = xhci->devs[udev->slot_id];
3688
3689         /* Stop any wayward timer functions (which may grab the lock) */
3690         for (i = 0; i < 31; ++i) {
3691                 virt_dev->eps[i].ep_state &= ~EP_HALT_PENDING;
3692                 del_timer_sync(&virt_dev->eps[i].stop_cmd_timer);
3693         }
3694
3695         spin_lock_irqsave(&xhci->lock, flags);
3696
3697         virt_dev->udev = NULL;
3698
3699         /* Don't disable the slot if the host controller is dead. */
3700         state = readl(&xhci->op_regs->status);
3701         if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
3702                         (xhci->xhc_state & XHCI_STATE_HALTED)) {
3703                 xhci_free_virt_device(xhci, udev->slot_id);
3704                 spin_unlock_irqrestore(&xhci->lock, flags);
3705                 kfree(command);
3706                 return;
3707         }
3708
3709         if (xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
3710                                     udev->slot_id)) {
3711                 spin_unlock_irqrestore(&xhci->lock, flags);
3712                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3713                 return;
3714         }
3715         xhci_ring_cmd_db(xhci);
3716         spin_unlock_irqrestore(&xhci->lock, flags);
3717
3718         /*
3719          * Event command completion handler will free any data structures
3720          * associated with the slot.  XXX Can free sleep?
3721          */
3722 }
3723
3724 /*
3725  * Checks if we have enough host controller resources for the default control
3726  * endpoint.
3727  *
3728  * Must be called with xhci->lock held.
3729  */
3730 static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
3731 {
3732         if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
3733                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3734                                 "Not enough ep ctxs: "
3735                                 "%u active, need to add 1, limit is %u.",
3736                                 xhci->num_active_eps, xhci->limit_active_eps);
3737                 return -ENOMEM;
3738         }
3739         xhci->num_active_eps += 1;
3740         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3741                         "Adding 1 ep ctx, %u now active.",
3742                         xhci->num_active_eps);
3743         return 0;
3744 }
3745
3746
3747 /*
3748  * Returns 0 if the xHC ran out of device slots, the Enable Slot command
3749  * timed out, or allocating memory failed.  Returns 1 on success.
3750  */
3751 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
3752 {
3753         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3754         unsigned long flags;
3755         int ret, slot_id;
3756         struct xhci_command *command;
3757
3758         command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
3759         if (!command)
3760                 return 0;
3761
3762         /* xhci->slot_id and xhci->addr_dev are not thread-safe */
3763         mutex_lock(&xhci->mutex);
3764         spin_lock_irqsave(&xhci->lock, flags);
3765         command->completion = &xhci->addr_dev;
3766         ret = xhci_queue_slot_control(xhci, command, TRB_ENABLE_SLOT, 0);
3767         if (ret) {
3768                 spin_unlock_irqrestore(&xhci->lock, flags);
3769                 mutex_unlock(&xhci->mutex);
3770                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3771                 kfree(command);
3772                 return 0;
3773         }
3774         xhci_ring_cmd_db(xhci);
3775         spin_unlock_irqrestore(&xhci->lock, flags);
3776
3777         wait_for_completion(command->completion);
3778         slot_id = xhci->slot_id;
3779         mutex_unlock(&xhci->mutex);
3780
3781         if (!slot_id || command->status != COMP_SUCCESS) {
3782                 xhci_err(xhci, "Error while assigning device slot ID\n");
3783                 xhci_err(xhci, "Max number of devices this xHCI host supports is %u.\n",
3784                                 HCS_MAX_SLOTS(
3785                                         readl(&xhci->cap_regs->hcs_params1)));
3786                 kfree(command);
3787                 return 0;
3788         }
3789
3790         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3791                 spin_lock_irqsave(&xhci->lock, flags);
3792                 ret = xhci_reserve_host_control_ep_resources(xhci);
3793                 if (ret) {
3794                         spin_unlock_irqrestore(&xhci->lock, flags);
3795                         xhci_warn(xhci, "Not enough host resources, "
3796                                         "active endpoint contexts = %u\n",
3797                                         xhci->num_active_eps);
3798                         goto disable_slot;
3799                 }
3800                 spin_unlock_irqrestore(&xhci->lock, flags);
3801         }
3802         /* Use GFP_NOIO, since this function can be called from
3803          * xhci_discover_or_reset_device(), which may be called as part of
3804          * mass storage driver error handling.
3805          */
3806         if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) {
3807                 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
3808                 goto disable_slot;
3809         }
3810         udev->slot_id = slot_id;
3811
3812 #ifndef CONFIG_USB_DEFAULT_PERSIST
3813         /*
3814          * If resetting upon resume, we can't put the controller into runtime
3815          * suspend if there is a device attached.
3816          */
3817         if (xhci->quirks & XHCI_RESET_ON_RESUME)
3818                 pm_runtime_get_noresume(hcd->self.controller);
3819 #endif
3820
3821
3822         kfree(command);
3823         /* Is this a LS or FS device under a HS hub? */
3824         /* Hub or peripherial? */
3825         return 1;
3826
3827 disable_slot:
3828         /* Disable slot, if we can do it without mem alloc */
3829         spin_lock_irqsave(&xhci->lock, flags);
3830         command->completion = NULL;
3831         command->status = 0;
3832         if (!xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
3833                                      udev->slot_id))
3834                 xhci_ring_cmd_db(xhci);
3835         spin_unlock_irqrestore(&xhci->lock, flags);
3836         return 0;
3837 }
3838
3839 /*
3840  * Issue an Address Device command and optionally send a corresponding
3841  * SetAddress request to the device.
3842  */
3843 static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
3844                              enum xhci_setup_dev setup)
3845 {
3846         const char *act = setup == SETUP_CONTEXT_ONLY ? "context" : "address";
3847         unsigned long flags;
3848         struct xhci_virt_device *virt_dev;
3849         int ret = 0;
3850         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3851         struct xhci_slot_ctx *slot_ctx;
3852         struct xhci_input_control_ctx *ctrl_ctx;
3853         u64 temp_64;
3854         struct xhci_command *command = NULL;
3855
3856         mutex_lock(&xhci->mutex);
3857
3858         if (xhci->xhc_state) {  /* dying, removing or halted */
3859                 ret = -ESHUTDOWN;
3860                 goto out;
3861         }
3862
3863         if (!udev->slot_id) {
3864                 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3865                                 "Bad Slot ID %d", udev->slot_id);
3866                 ret = -EINVAL;
3867                 goto out;
3868         }
3869
3870         virt_dev = xhci->devs[udev->slot_id];
3871
3872         if (WARN_ON(!virt_dev)) {
3873                 /*
3874                  * In plug/unplug torture test with an NEC controller,
3875                  * a zero-dereference was observed once due to virt_dev = 0.
3876                  * Print useful debug rather than crash if it is observed again!
3877                  */
3878                 xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
3879                         udev->slot_id);
3880                 ret = -EINVAL;
3881                 goto out;
3882         }
3883
3884         if (setup == SETUP_CONTEXT_ONLY) {
3885                 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3886                 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3887                     SLOT_STATE_DEFAULT) {
3888                         xhci_dbg(xhci, "Slot already in default state\n");
3889                         goto out;
3890                 }
3891         }
3892
3893         command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
3894         if (!command) {
3895                 ret = -ENOMEM;
3896                 goto out;
3897         }
3898
3899         command->in_ctx = virt_dev->in_ctx;
3900         command->completion = &xhci->addr_dev;
3901
3902         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
3903         ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
3904         if (!ctrl_ctx) {
3905                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3906                                 __func__);
3907                 ret = -EINVAL;
3908                 goto out;
3909         }
3910         /*
3911          * If this is the first Set Address since device plug-in or
3912          * virt_device realloaction after a resume with an xHCI power loss,
3913          * then set up the slot context.
3914          */
3915         if (!slot_ctx->dev_info)
3916                 xhci_setup_addressable_virt_dev(xhci, udev);
3917         /* Otherwise, update the control endpoint ring enqueue pointer. */
3918         else
3919                 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
3920         ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
3921         ctrl_ctx->drop_flags = 0;
3922
3923         xhci_dbg(xhci, "Slot ID %d Input Context:\n", udev->slot_id);
3924         xhci_dbg_ctx(xhci, virt_dev->in_ctx, 2);
3925         trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
3926                                 le32_to_cpu(slot_ctx->dev_info) >> 27);
3927
3928         spin_lock_irqsave(&xhci->lock, flags);
3929         ret = xhci_queue_address_device(xhci, command, virt_dev->in_ctx->dma,
3930                                         udev->slot_id, setup);
3931         if (ret) {
3932                 spin_unlock_irqrestore(&xhci->lock, flags);
3933                 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3934                                 "FIXME: allocate a command ring segment");
3935                 goto out;
3936         }
3937         xhci_ring_cmd_db(xhci);
3938         spin_unlock_irqrestore(&xhci->lock, flags);
3939
3940         /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
3941         wait_for_completion(command->completion);
3942
3943         /* FIXME: From section 4.3.4: "Software shall be responsible for timing
3944          * the SetAddress() "recovery interval" required by USB and aborting the
3945          * command on a timeout.
3946          */
3947         switch (command->status) {
3948         case COMP_CMD_ABORT:
3949         case COMP_CMD_STOP:
3950                 xhci_warn(xhci, "Timeout while waiting for setup device command\n");
3951                 ret = -ETIME;
3952                 break;
3953         case COMP_CTX_STATE:
3954         case COMP_EBADSLT:
3955                 xhci_err(xhci, "Setup ERROR: setup %s command for slot %d.\n",
3956                          act, udev->slot_id);
3957                 ret = -EINVAL;
3958                 break;
3959         case COMP_TX_ERR:
3960                 dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
3961                 ret = -EPROTO;
3962                 break;
3963         case COMP_DEV_ERR:
3964                 dev_warn(&udev->dev,
3965                          "ERROR: Incompatible device for setup %s command\n", act);
3966                 ret = -ENODEV;
3967                 break;
3968         case COMP_SUCCESS:
3969                 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3970                                "Successful setup %s command", act);
3971                 break;
3972         default:
3973                 xhci_err(xhci,
3974                          "ERROR: unexpected setup %s command completion code 0x%x.\n",
3975                          act, command->status);
3976                 xhci_dbg(xhci, "Slot ID %d Output Context:\n", udev->slot_id);
3977                 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 2);
3978                 trace_xhci_address_ctx(xhci, virt_dev->out_ctx, 1);
3979                 ret = -EINVAL;
3980                 break;
3981         }
3982         if (ret)
3983                 goto out;
3984         temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
3985         xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3986                         "Op regs DCBAA ptr = %#016llx", temp_64);
3987         xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3988                 "Slot ID %d dcbaa entry @%p = %#016llx",
3989                 udev->slot_id,
3990                 &xhci->dcbaa->dev_context_ptrs[udev->slot_id],
3991                 (unsigned long long)
3992                 le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
3993         xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3994                         "Output Context DMA address = %#08llx",
3995                         (unsigned long long)virt_dev->out_ctx->dma);
3996         xhci_dbg(xhci, "Slot ID %d Input Context:\n", udev->slot_id);
3997         xhci_dbg_ctx(xhci, virt_dev->in_ctx, 2);
3998         trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
3999                                 le32_to_cpu(slot_ctx->dev_info) >> 27);
4000         xhci_dbg(xhci, "Slot ID %d Output Context:\n", udev->slot_id);
4001         xhci_dbg_ctx(xhci, virt_dev->out_ctx, 2);
4002         /*
4003          * USB core uses address 1 for the roothubs, so we add one to the
4004          * address given back to us by the HC.
4005          */
4006         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4007         trace_xhci_address_ctx(xhci, virt_dev->out_ctx,
4008                                 le32_to_cpu(slot_ctx->dev_info) >> 27);
4009         /* Zero the input context control for later use */
4010         ctrl_ctx->add_flags = 0;
4011         ctrl_ctx->drop_flags = 0;
4012
4013         xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4014                        "Internal device address = %d",
4015                        le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4016 out:
4017         mutex_unlock(&xhci->mutex);
4018         kfree(command);
4019         return ret;
4020 }
4021
4022 int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev)
4023 {
4024         return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ADDRESS);
4025 }
4026
4027 int xhci_enable_device(struct usb_hcd *hcd, struct usb_device *udev)
4028 {
4029         return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ONLY);
4030 }
4031
4032 /*
4033  * Transfer the port index into real index in the HW port status
4034  * registers. Caculate offset between the port's PORTSC register
4035  * and port status base. Divide the number of per port register
4036  * to get the real index. The raw port number bases 1.
4037  */
4038 int xhci_find_raw_port_number(struct usb_hcd *hcd, int port1)
4039 {
4040         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4041         __le32 __iomem *base_addr = &xhci->op_regs->port_status_base;
4042         __le32 __iomem *addr;
4043         int raw_port;
4044
4045         if (hcd->speed < HCD_USB3)
4046                 addr = xhci->usb2_ports[port1 - 1];
4047         else
4048                 addr = xhci->usb3_ports[port1 - 1];
4049
4050         raw_port = (addr - base_addr)/NUM_PORT_REGS + 1;
4051         return raw_port;
4052 }
4053
4054 /*
4055  * Issue an Evaluate Context command to change the Maximum Exit Latency in the
4056  * slot context.  If that succeeds, store the new MEL in the xhci_virt_device.
4057  */
4058 static int __maybe_unused xhci_change_max_exit_latency(struct xhci_hcd *xhci,
4059                         struct usb_device *udev, u16 max_exit_latency)
4060 {
4061         struct xhci_virt_device *virt_dev;
4062         struct xhci_command *command;
4063         struct xhci_input_control_ctx *ctrl_ctx;
4064         struct xhci_slot_ctx *slot_ctx;
4065         unsigned long flags;
4066         int ret;
4067
4068         spin_lock_irqsave(&xhci->lock, flags);
4069
4070         virt_dev = xhci->devs[udev->slot_id];
4071
4072         /*
4073          * virt_dev might not exists yet if xHC resumed from hibernate (S4) and
4074          * xHC was re-initialized. Exit latency will be set later after
4075          * hub_port_finish_reset() is done and xhci->devs[] are re-allocated
4076          */
4077
4078         if (!virt_dev || max_exit_latency == virt_dev->current_mel) {
4079                 spin_unlock_irqrestore(&xhci->lock, flags);
4080                 return 0;
4081         }
4082
4083         /* Attempt to issue an Evaluate Context command to change the MEL. */
4084         command = xhci->lpm_command;
4085         ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
4086         if (!ctrl_ctx) {
4087                 spin_unlock_irqrestore(&xhci->lock, flags);
4088                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4089                                 __func__);
4090                 return -ENOMEM;
4091         }
4092
4093         xhci_slot_copy(xhci, command->in_ctx, virt_dev->out_ctx);
4094         spin_unlock_irqrestore(&xhci->lock, flags);
4095
4096         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4097         slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
4098         slot_ctx->dev_info2 &= cpu_to_le32(~((u32) MAX_EXIT));
4099         slot_ctx->dev_info2 |= cpu_to_le32(max_exit_latency);
4100         slot_ctx->dev_state = 0;
4101
4102         xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
4103                         "Set up evaluate context for LPM MEL change.");
4104         xhci_dbg(xhci, "Slot %u Input Context:\n", udev->slot_id);
4105         xhci_dbg_ctx(xhci, command->in_ctx, 0);
4106
4107         /* Issue and wait for the evaluate context command. */
4108         ret = xhci_configure_endpoint(xhci, udev, command,
4109                         true, true);
4110         xhci_dbg(xhci, "Slot %u Output Context:\n", udev->slot_id);
4111         xhci_dbg_ctx(xhci, virt_dev->out_ctx, 0);
4112
4113         if (!ret) {
4114                 spin_lock_irqsave(&xhci->lock, flags);
4115                 virt_dev->current_mel = max_exit_latency;
4116                 spin_unlock_irqrestore(&xhci->lock, flags);
4117         }
4118         return ret;
4119 }
4120
4121 #ifdef CONFIG_PM
4122
4123 /* BESL to HIRD Encoding array for USB2 LPM */
4124 static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
4125         3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
4126
4127 /* Calculate HIRD/BESL for USB2 PORTPMSC*/
4128 static int xhci_calculate_hird_besl(struct xhci_hcd *xhci,
4129                                         struct usb_device *udev)
4130 {
4131         int u2del, besl, besl_host;
4132         int besl_device = 0;
4133         u32 field;
4134
4135         u2del = HCS_U2_LATENCY(xhci->hcs_params3);
4136         field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4137
4138         if (field & USB_BESL_SUPPORT) {
4139                 for (besl_host = 0; besl_host < 16; besl_host++) {
4140                         if (xhci_besl_encoding[besl_host] >= u2del)
4141                                 break;
4142                 }
4143                 /* Use baseline BESL value as default */
4144                 if (field & USB_BESL_BASELINE_VALID)
4145                         besl_device = USB_GET_BESL_BASELINE(field);
4146                 else if (field & USB_BESL_DEEP_VALID)
4147                         besl_device = USB_GET_BESL_DEEP(field);
4148         } else {
4149                 if (u2del <= 50)
4150                         besl_host = 0;
4151                 else
4152                         besl_host = (u2del - 51) / 75 + 1;
4153         }
4154
4155         besl = besl_host + besl_device;
4156         if (besl > 15)
4157                 besl = 15;
4158
4159         return besl;
4160 }
4161
4162 /* Calculate BESLD, L1 timeout and HIRDM for USB2 PORTHLPMC */
4163 static int xhci_calculate_usb2_hw_lpm_params(struct usb_device *udev)
4164 {
4165         u32 field;
4166         int l1;
4167         int besld = 0;
4168         int hirdm = 0;
4169
4170         field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4171
4172         /* xHCI l1 is set in steps of 256us, xHCI 1.0 section 5.4.11.2 */
4173         l1 = udev->l1_params.timeout / 256;
4174
4175         /* device has preferred BESLD */
4176         if (field & USB_BESL_DEEP_VALID) {
4177                 besld = USB_GET_BESL_DEEP(field);
4178                 hirdm = 1;
4179         }
4180
4181         return PORT_BESLD(besld) | PORT_L1_TIMEOUT(l1) | PORT_HIRDM(hirdm);
4182 }
4183
4184 int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4185                         struct usb_device *udev, int enable)
4186 {
4187         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4188         __le32 __iomem  **port_array;
4189         __le32 __iomem  *pm_addr, *hlpm_addr;
4190         u32             pm_val, hlpm_val, field;
4191         unsigned int    port_num;
4192         unsigned long   flags;
4193         int             hird, exit_latency;
4194         int             ret;
4195
4196         if (hcd->speed >= HCD_USB3 || !xhci->hw_lpm_support ||
4197                         !udev->lpm_capable)
4198                 return -EPERM;
4199
4200         if (!udev->parent || udev->parent->parent ||
4201                         udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4202                 return -EPERM;
4203
4204         if (udev->usb2_hw_lpm_capable != 1)
4205                 return -EPERM;
4206
4207         spin_lock_irqsave(&xhci->lock, flags);
4208
4209         port_array = xhci->usb2_ports;
4210         port_num = udev->portnum - 1;
4211         pm_addr = port_array[port_num] + PORTPMSC;
4212         pm_val = readl(pm_addr);
4213         hlpm_addr = port_array[port_num] + PORTHLPMC;
4214
4215         xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
4216                         enable ? "enable" : "disable", port_num + 1);
4217
4218         if (enable) {
4219                 /* Host supports BESL timeout instead of HIRD */
4220                 if (udev->usb2_hw_lpm_besl_capable) {
4221                         /* if device doesn't have a preferred BESL value use a
4222                          * default one which works with mixed HIRD and BESL
4223                          * systems. See XHCI_DEFAULT_BESL definition in xhci.h
4224                          */
4225                         field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4226                         if ((field & USB_BESL_SUPPORT) &&
4227                             (field & USB_BESL_BASELINE_VALID))
4228                                 hird = USB_GET_BESL_BASELINE(field);
4229                         else
4230                                 hird = udev->l1_params.besl;
4231
4232                         exit_latency = xhci_besl_encoding[hird];
4233                         spin_unlock_irqrestore(&xhci->lock, flags);
4234
4235                         /* USB 3.0 code dedicate one xhci->lpm_command->in_ctx
4236                          * input context for link powermanagement evaluate
4237                          * context commands. It is protected by hcd->bandwidth
4238                          * mutex and is shared by all devices. We need to set
4239                          * the max ext latency in USB 2 BESL LPM as well, so
4240                          * use the same mutex and xhci_change_max_exit_latency()
4241                          */
4242                         mutex_lock(hcd->bandwidth_mutex);
4243                         ret = xhci_change_max_exit_latency(xhci, udev,
4244                                                            exit_latency);
4245                         mutex_unlock(hcd->bandwidth_mutex);
4246
4247                         if (ret < 0)
4248                                 return ret;
4249                         spin_lock_irqsave(&xhci->lock, flags);
4250
4251                         hlpm_val = xhci_calculate_usb2_hw_lpm_params(udev);
4252                         writel(hlpm_val, hlpm_addr);
4253                         /* flush write */
4254                         readl(hlpm_addr);
4255                 } else {
4256                         hird = xhci_calculate_hird_besl(xhci, udev);
4257                 }
4258
4259                 pm_val &= ~PORT_HIRD_MASK;
4260                 pm_val |= PORT_HIRD(hird) | PORT_RWE | PORT_L1DS(udev->slot_id);
4261                 writel(pm_val, pm_addr);
4262                 pm_val = readl(pm_addr);
4263                 pm_val |= PORT_HLE;
4264                 writel(pm_val, pm_addr);
4265                 /* flush write */
4266                 readl(pm_addr);
4267         } else {
4268                 pm_val &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK | PORT_L1DS_MASK);
4269                 writel(pm_val, pm_addr);
4270                 /* flush write */
4271                 readl(pm_addr);
4272                 if (udev->usb2_hw_lpm_besl_capable) {
4273                         spin_unlock_irqrestore(&xhci->lock, flags);
4274                         mutex_lock(hcd->bandwidth_mutex);
4275                         xhci_change_max_exit_latency(xhci, udev, 0);
4276                         mutex_unlock(hcd->bandwidth_mutex);
4277                         readl_poll_timeout(port_array[port_num], pm_val,
4278                                            (pm_val & PORT_PLS_MASK) == XDEV_U0,
4279                                            100, 10000);
4280                         return 0;
4281                 }
4282         }
4283
4284         spin_unlock_irqrestore(&xhci->lock, flags);
4285         return 0;
4286 }
4287
4288 /* check if a usb2 port supports a given extened capability protocol
4289  * only USB2 ports extended protocol capability values are cached.
4290  * Return 1 if capability is supported
4291  */
4292 static int xhci_check_usb2_port_capability(struct xhci_hcd *xhci, int port,
4293                                            unsigned capability)
4294 {
4295         u32 port_offset, port_count;
4296         int i;
4297
4298         for (i = 0; i < xhci->num_ext_caps; i++) {
4299                 if (xhci->ext_caps[i] & capability) {
4300                         /* port offsets starts at 1 */
4301                         port_offset = XHCI_EXT_PORT_OFF(xhci->ext_caps[i]) - 1;
4302                         port_count = XHCI_EXT_PORT_COUNT(xhci->ext_caps[i]);
4303                         if (port >= port_offset &&
4304                             port < port_offset + port_count)
4305                                 return 1;
4306                 }
4307         }
4308         return 0;
4309 }
4310
4311 int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4312 {
4313         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4314         int             portnum = udev->portnum - 1;
4315
4316         if (hcd->speed >= HCD_USB3 || !xhci->sw_lpm_support ||
4317                         !udev->lpm_capable)
4318                 return 0;
4319
4320         /* we only support lpm for non-hub device connected to root hub yet */
4321         if (!udev->parent || udev->parent->parent ||
4322                         udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4323                 return 0;
4324
4325         if (xhci->hw_lpm_support == 1 &&
4326                         xhci_check_usb2_port_capability(
4327                                 xhci, portnum, XHCI_HLC)) {
4328                 udev->usb2_hw_lpm_capable = 1;
4329                 udev->l1_params.timeout = XHCI_L1_TIMEOUT;
4330                 udev->l1_params.besl = XHCI_DEFAULT_BESL;
4331                 if (xhci_check_usb2_port_capability(xhci, portnum,
4332                                         XHCI_BLC))
4333                         udev->usb2_hw_lpm_besl_capable = 1;
4334         }
4335
4336         return 0;
4337 }
4338
4339 /*---------------------- USB 3.0 Link PM functions ------------------------*/
4340
4341 /* Service interval in nanoseconds = 2^(bInterval - 1) * 125us * 1000ns / 1us */
4342 static unsigned long long xhci_service_interval_to_ns(
4343                 struct usb_endpoint_descriptor *desc)
4344 {
4345         return (1ULL << (desc->bInterval - 1)) * 125 * 1000;
4346 }
4347
4348 static u16 xhci_get_timeout_no_hub_lpm(struct usb_device *udev,
4349                 enum usb3_link_state state)
4350 {
4351         unsigned long long sel;
4352         unsigned long long pel;
4353         unsigned int max_sel_pel;
4354         char *state_name;
4355
4356         switch (state) {
4357         case USB3_LPM_U1:
4358                 /* Convert SEL and PEL stored in nanoseconds to microseconds */
4359                 sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4360                 pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4361                 max_sel_pel = USB3_LPM_MAX_U1_SEL_PEL;
4362                 state_name = "U1";
4363                 break;
4364         case USB3_LPM_U2:
4365                 sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4366                 pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4367                 max_sel_pel = USB3_LPM_MAX_U2_SEL_PEL;
4368                 state_name = "U2";
4369                 break;
4370         default:
4371                 dev_warn(&udev->dev, "%s: Can't get timeout for non-U1 or U2 state.\n",
4372                                 __func__);
4373                 return USB3_LPM_DISABLED;
4374         }
4375
4376         if (sel <= max_sel_pel && pel <= max_sel_pel)
4377                 return USB3_LPM_DEVICE_INITIATED;
4378
4379         if (sel > max_sel_pel)
4380                 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4381                                 "due to long SEL %llu ms\n",
4382                                 state_name, sel);
4383         else
4384                 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4385                                 "due to long PEL %llu ms\n",
4386                                 state_name, pel);
4387         return USB3_LPM_DISABLED;
4388 }
4389
4390 /* The U1 timeout should be the maximum of the following values:
4391  *  - For control endpoints, U1 system exit latency (SEL) * 3
4392  *  - For bulk endpoints, U1 SEL * 5
4393  *  - For interrupt endpoints:
4394  *    - Notification EPs, U1 SEL * 3
4395  *    - Periodic EPs, max(105% of bInterval, U1 SEL * 2)
4396  *  - For isochronous endpoints, max(105% of bInterval, U1 SEL * 2)
4397  */
4398 static unsigned long long xhci_calculate_intel_u1_timeout(
4399                 struct usb_device *udev,
4400                 struct usb_endpoint_descriptor *desc)
4401 {
4402         unsigned long long timeout_ns;
4403         int ep_type;
4404         int intr_type;
4405
4406         ep_type = usb_endpoint_type(desc);
4407         switch (ep_type) {
4408         case USB_ENDPOINT_XFER_CONTROL:
4409                 timeout_ns = udev->u1_params.sel * 3;
4410                 break;
4411         case USB_ENDPOINT_XFER_BULK:
4412                 timeout_ns = udev->u1_params.sel * 5;
4413                 break;
4414         case USB_ENDPOINT_XFER_INT:
4415                 intr_type = usb_endpoint_interrupt_type(desc);
4416                 if (intr_type == USB_ENDPOINT_INTR_NOTIFICATION) {
4417                         timeout_ns = udev->u1_params.sel * 3;
4418                         break;
4419                 }
4420                 /* Otherwise the calculation is the same as isoc eps */
4421         case USB_ENDPOINT_XFER_ISOC:
4422                 timeout_ns = xhci_service_interval_to_ns(desc);
4423                 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns * 105, 100);
4424                 if (timeout_ns < udev->u1_params.sel * 2)
4425                         timeout_ns = udev->u1_params.sel * 2;
4426                 break;
4427         default:
4428                 return 0;
4429         }
4430
4431         return timeout_ns;
4432 }
4433
4434 /* Returns the hub-encoded U1 timeout value. */
4435 static u16 xhci_calculate_u1_timeout(struct xhci_hcd *xhci,
4436                 struct usb_device *udev,
4437                 struct usb_endpoint_descriptor *desc)
4438 {
4439         unsigned long long timeout_ns;
4440
4441         if (xhci->quirks & XHCI_INTEL_HOST)
4442                 timeout_ns = xhci_calculate_intel_u1_timeout(udev, desc);
4443         else
4444                 timeout_ns = udev->u1_params.sel;
4445
4446         /* Prevent U1 if service interval is shorter than U1 exit latency */
4447         if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4448                 if (xhci_service_interval_to_ns(desc) <= timeout_ns) {
4449                         dev_dbg(&udev->dev, "Disable U1, ESIT shorter than exit latency\n");
4450                         return USB3_LPM_DISABLED;
4451                 }
4452         }
4453
4454         /* The U1 timeout is encoded in 1us intervals.
4455          * Don't return a timeout of zero, because that's USB3_LPM_DISABLED.
4456          */
4457         if (timeout_ns == USB3_LPM_DISABLED)
4458                 timeout_ns = 1;
4459         else
4460                 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 1000);
4461
4462         /* If the necessary timeout value is bigger than what we can set in the
4463          * USB 3.0 hub, we have to disable hub-initiated U1.
4464          */
4465         if (timeout_ns <= USB3_LPM_U1_MAX_TIMEOUT)
4466                 return timeout_ns;
4467         dev_dbg(&udev->dev, "Hub-initiated U1 disabled "
4468                         "due to long timeout %llu ms\n", timeout_ns);
4469         return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U1);
4470 }
4471
4472 /* The U2 timeout should be the maximum of:
4473  *  - 10 ms (to avoid the bandwidth impact on the scheduler)
4474  *  - largest bInterval of any active periodic endpoint (to avoid going
4475  *    into lower power link states between intervals).
4476  *  - the U2 Exit Latency of the device
4477  */
4478 static unsigned long long xhci_calculate_intel_u2_timeout(
4479                 struct usb_device *udev,
4480                 struct usb_endpoint_descriptor *desc)
4481 {
4482         unsigned long long timeout_ns;
4483         unsigned long long u2_del_ns;
4484
4485         timeout_ns = 10 * 1000 * 1000;
4486
4487         if ((usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) &&
4488                         (xhci_service_interval_to_ns(desc) > timeout_ns))
4489                 timeout_ns = xhci_service_interval_to_ns(desc);
4490
4491         u2_del_ns = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat) * 1000ULL;
4492         if (u2_del_ns > timeout_ns)
4493                 timeout_ns = u2_del_ns;
4494
4495         return timeout_ns;
4496 }
4497
4498 /* Returns the hub-encoded U2 timeout value. */
4499 static u16 xhci_calculate_u2_timeout(struct xhci_hcd *xhci,
4500                 struct usb_device *udev,
4501                 struct usb_endpoint_descriptor *desc)
4502 {
4503         unsigned long long timeout_ns;
4504
4505         if (xhci->quirks & XHCI_INTEL_HOST)
4506                 timeout_ns = xhci_calculate_intel_u2_timeout(udev, desc);
4507         else
4508                 timeout_ns = udev->u2_params.sel;
4509
4510         /* Prevent U2 if service interval is shorter than U2 exit latency */
4511         if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4512                 if (xhci_service_interval_to_ns(desc) <= timeout_ns) {
4513                         dev_dbg(&udev->dev, "Disable U2, ESIT shorter than exit latency\n");
4514                         return USB3_LPM_DISABLED;
4515                 }
4516         }
4517
4518         /* The U2 timeout is encoded in 256us intervals */
4519         timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 256 * 1000);
4520         /* If the necessary timeout value is bigger than what we can set in the
4521          * USB 3.0 hub, we have to disable hub-initiated U2.
4522          */
4523         if (timeout_ns <= USB3_LPM_U2_MAX_TIMEOUT)
4524                 return timeout_ns;
4525         dev_dbg(&udev->dev, "Hub-initiated U2 disabled "
4526                         "due to long timeout %llu ms\n", timeout_ns);
4527         return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U2);
4528 }
4529
4530 static u16 xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4531                 struct usb_device *udev,
4532                 struct usb_endpoint_descriptor *desc,
4533                 enum usb3_link_state state,
4534                 u16 *timeout)
4535 {
4536         if (state == USB3_LPM_U1)
4537                 return xhci_calculate_u1_timeout(xhci, udev, desc);
4538         else if (state == USB3_LPM_U2)
4539                 return xhci_calculate_u2_timeout(xhci, udev, desc);
4540
4541         return USB3_LPM_DISABLED;
4542 }
4543
4544 static int xhci_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4545                 struct usb_device *udev,
4546                 struct usb_endpoint_descriptor *desc,
4547                 enum usb3_link_state state,
4548                 u16 *timeout)
4549 {
4550         u16 alt_timeout;
4551
4552         alt_timeout = xhci_call_host_update_timeout_for_endpoint(xhci, udev,
4553                 desc, state, timeout);
4554
4555         /* If we found we can't enable hub-initiated LPM, and
4556          * the U1 or U2 exit latency was too high to allow
4557          * device-initiated LPM as well, then we will disable LPM
4558          * for this device, so stop searching any further.
4559          */
4560         if (alt_timeout == USB3_LPM_DISABLED) {
4561                 *timeout = alt_timeout;
4562                 return -E2BIG;
4563         }
4564         if (alt_timeout > *timeout)
4565                 *timeout = alt_timeout;
4566         return 0;
4567 }
4568
4569 static int xhci_update_timeout_for_interface(struct xhci_hcd *xhci,
4570                 struct usb_device *udev,
4571                 struct usb_host_interface *alt,
4572                 enum usb3_link_state state,
4573                 u16 *timeout)
4574 {
4575         int j;
4576
4577         for (j = 0; j < alt->desc.bNumEndpoints; j++) {
4578                 if (xhci_update_timeout_for_endpoint(xhci, udev,
4579                                         &alt->endpoint[j].desc, state, timeout))
4580                         return -E2BIG;
4581                 continue;
4582         }
4583         return 0;
4584 }
4585
4586 static int xhci_check_intel_tier_policy(struct usb_device *udev,
4587                 enum usb3_link_state state)
4588 {
4589         struct usb_device *parent;
4590         unsigned int num_hubs;
4591
4592         if (state == USB3_LPM_U2)
4593                 return 0;
4594
4595         /* Don't enable U1 if the device is on a 2nd tier hub or lower. */
4596         for (parent = udev->parent, num_hubs = 0; parent->parent;
4597                         parent = parent->parent)
4598                 num_hubs++;
4599
4600         if (num_hubs < 2)
4601                 return 0;
4602
4603         dev_dbg(&udev->dev, "Disabling U1 link state for device"
4604                         " below second-tier hub.\n");
4605         dev_dbg(&udev->dev, "Plug device into first-tier hub "
4606                         "to decrease power consumption.\n");
4607         return -E2BIG;
4608 }
4609
4610 static int xhci_check_tier_policy(struct xhci_hcd *xhci,
4611                 struct usb_device *udev,
4612                 enum usb3_link_state state)
4613 {
4614         if (xhci->quirks & XHCI_INTEL_HOST)
4615                 return xhci_check_intel_tier_policy(udev, state);
4616         else
4617                 return 0;
4618 }
4619
4620 /* Returns the U1 or U2 timeout that should be enabled.
4621  * If the tier check or timeout setting functions return with a non-zero exit
4622  * code, that means the timeout value has been finalized and we shouldn't look
4623  * at any more endpoints.
4624  */
4625 static u16 xhci_calculate_lpm_timeout(struct usb_hcd *hcd,
4626                         struct usb_device *udev, enum usb3_link_state state)
4627 {
4628         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4629         struct usb_host_config *config;
4630         char *state_name;
4631         int i;
4632         u16 timeout = USB3_LPM_DISABLED;
4633
4634         if (state == USB3_LPM_U1)
4635                 state_name = "U1";
4636         else if (state == USB3_LPM_U2)
4637                 state_name = "U2";
4638         else {
4639                 dev_warn(&udev->dev, "Can't enable unknown link state %i\n",
4640                                 state);
4641                 return timeout;
4642         }
4643
4644         if (xhci_check_tier_policy(xhci, udev, state) < 0)
4645                 return timeout;
4646
4647         /* Gather some information about the currently installed configuration
4648          * and alternate interface settings.
4649          */
4650         if (xhci_update_timeout_for_endpoint(xhci, udev, &udev->ep0.desc,
4651                         state, &timeout))
4652                 return timeout;
4653
4654         config = udev->actconfig;
4655         if (!config)
4656                 return timeout;
4657
4658         for (i = 0; i < config->desc.bNumInterfaces; i++) {
4659                 struct usb_driver *driver;
4660                 struct usb_interface *intf = config->interface[i];
4661
4662                 if (!intf)
4663                         continue;
4664
4665                 /* Check if any currently bound drivers want hub-initiated LPM
4666                  * disabled.
4667                  */
4668                 if (intf->dev.driver) {
4669                         driver = to_usb_driver(intf->dev.driver);
4670                         if (driver && driver->disable_hub_initiated_lpm) {
4671                                 dev_dbg(&udev->dev, "Hub-initiated %s disabled at request of driver %s\n",
4672                                         state_name, driver->name);
4673                                 timeout = xhci_get_timeout_no_hub_lpm(udev,
4674                                                                       state);
4675                                 if (timeout == USB3_LPM_DISABLED)
4676                                         return timeout;
4677                         }
4678                 }
4679
4680                 /* Not sure how this could happen... */
4681                 if (!intf->cur_altsetting)
4682                         continue;
4683
4684                 if (xhci_update_timeout_for_interface(xhci, udev,
4685                                         intf->cur_altsetting,
4686                                         state, &timeout))
4687                         return timeout;
4688         }
4689         return timeout;
4690 }
4691
4692 static int calculate_max_exit_latency(struct usb_device *udev,
4693                 enum usb3_link_state state_changed,
4694                 u16 hub_encoded_timeout)
4695 {
4696         unsigned long long u1_mel_us = 0;
4697         unsigned long long u2_mel_us = 0;
4698         unsigned long long mel_us = 0;
4699         bool disabling_u1;
4700         bool disabling_u2;
4701         bool enabling_u1;
4702         bool enabling_u2;
4703
4704         disabling_u1 = (state_changed == USB3_LPM_U1 &&
4705                         hub_encoded_timeout == USB3_LPM_DISABLED);
4706         disabling_u2 = (state_changed == USB3_LPM_U2 &&
4707                         hub_encoded_timeout == USB3_LPM_DISABLED);
4708
4709         enabling_u1 = (state_changed == USB3_LPM_U1 &&
4710                         hub_encoded_timeout != USB3_LPM_DISABLED);
4711         enabling_u2 = (state_changed == USB3_LPM_U2 &&
4712                         hub_encoded_timeout != USB3_LPM_DISABLED);
4713
4714         /* If U1 was already enabled and we're not disabling it,
4715          * or we're going to enable U1, account for the U1 max exit latency.
4716          */
4717         if ((udev->u1_params.timeout != USB3_LPM_DISABLED && !disabling_u1) ||
4718                         enabling_u1)
4719                 u1_mel_us = DIV_ROUND_UP(udev->u1_params.mel, 1000);
4720         if ((udev->u2_params.timeout != USB3_LPM_DISABLED && !disabling_u2) ||
4721                         enabling_u2)
4722                 u2_mel_us = DIV_ROUND_UP(udev->u2_params.mel, 1000);
4723
4724         if (u1_mel_us > u2_mel_us)
4725                 mel_us = u1_mel_us;
4726         else
4727                 mel_us = u2_mel_us;
4728         /* xHCI host controller max exit latency field is only 16 bits wide. */
4729         if (mel_us > MAX_EXIT) {
4730                 dev_warn(&udev->dev, "Link PM max exit latency of %lluus "
4731                                 "is too big.\n", mel_us);
4732                 return -E2BIG;
4733         }
4734         return mel_us;
4735 }
4736
4737 /* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
4738 int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
4739                         struct usb_device *udev, enum usb3_link_state state)
4740 {
4741         struct xhci_hcd *xhci;
4742         u16 hub_encoded_timeout;
4743         int mel;
4744         int ret;
4745
4746         xhci = hcd_to_xhci(hcd);
4747         /* The LPM timeout values are pretty host-controller specific, so don't
4748          * enable hub-initiated timeouts unless the vendor has provided
4749          * information about their timeout algorithm.
4750          */
4751         if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
4752                         !xhci->devs[udev->slot_id])
4753                 return USB3_LPM_DISABLED;
4754
4755         hub_encoded_timeout = xhci_calculate_lpm_timeout(hcd, udev, state);
4756         mel = calculate_max_exit_latency(udev, state, hub_encoded_timeout);
4757         if (mel < 0) {
4758                 /* Max Exit Latency is too big, disable LPM. */
4759                 hub_encoded_timeout = USB3_LPM_DISABLED;
4760                 mel = 0;
4761         }
4762
4763         ret = xhci_change_max_exit_latency(xhci, udev, mel);
4764         if (ret)
4765                 return ret;
4766         return hub_encoded_timeout;
4767 }
4768
4769 int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
4770                         struct usb_device *udev, enum usb3_link_state state)
4771 {
4772         struct xhci_hcd *xhci;
4773         u16 mel;
4774
4775         xhci = hcd_to_xhci(hcd);
4776         if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
4777                         !xhci->devs[udev->slot_id])
4778                 return 0;
4779
4780         mel = calculate_max_exit_latency(udev, state, USB3_LPM_DISABLED);
4781         return xhci_change_max_exit_latency(xhci, udev, mel);
4782 }
4783 #else /* CONFIG_PM */
4784
4785 int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4786                                 struct usb_device *udev, int enable)
4787 {
4788         return 0;
4789 }
4790
4791 int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4792 {
4793         return 0;
4794 }
4795
4796 int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
4797                         struct usb_device *udev, enum usb3_link_state state)
4798 {
4799         return USB3_LPM_DISABLED;
4800 }
4801
4802 int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
4803                         struct usb_device *udev, enum usb3_link_state state)
4804 {
4805         return 0;
4806 }
4807 #endif  /* CONFIG_PM */
4808
4809 /*-------------------------------------------------------------------------*/
4810
4811 /* Once a hub descriptor is fetched for a device, we need to update the xHC's
4812  * internal data structures for the device.
4813  */
4814 int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
4815                         struct usb_tt *tt, gfp_t mem_flags)
4816 {
4817         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4818         struct xhci_virt_device *vdev;
4819         struct xhci_command *config_cmd;
4820         struct xhci_input_control_ctx *ctrl_ctx;
4821         struct xhci_slot_ctx *slot_ctx;
4822         unsigned long flags;
4823         unsigned think_time;
4824         int ret;
4825
4826         /* Ignore root hubs */
4827         if (!hdev->parent)
4828                 return 0;
4829
4830         vdev = xhci->devs[hdev->slot_id];
4831         if (!vdev) {
4832                 xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
4833                 return -EINVAL;
4834         }
4835         config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
4836         if (!config_cmd) {
4837                 xhci_dbg(xhci, "Could not allocate xHCI command structure.\n");
4838                 return -ENOMEM;
4839         }
4840         ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
4841         if (!ctrl_ctx) {
4842                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4843                                 __func__);
4844                 xhci_free_command(xhci, config_cmd);
4845                 return -ENOMEM;
4846         }
4847
4848         spin_lock_irqsave(&xhci->lock, flags);
4849         if (hdev->speed == USB_SPEED_HIGH &&
4850                         xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
4851                 xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
4852                 xhci_free_command(xhci, config_cmd);
4853                 spin_unlock_irqrestore(&xhci->lock, flags);
4854                 return -ENOMEM;
4855         }
4856
4857         xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
4858         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4859         slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
4860         slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
4861         /*
4862          * refer to section 6.2.2: MTT should be 0 for full speed hub,
4863          * but it may be already set to 1 when setup an xHCI virtual
4864          * device, so clear it anyway.
4865          */
4866         if (tt->multi)
4867                 slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
4868         else if (hdev->speed == USB_SPEED_FULL)
4869                 slot_ctx->dev_info &= cpu_to_le32(~DEV_MTT);
4870
4871         if (xhci->hci_version > 0x95) {
4872                 xhci_dbg(xhci, "xHCI version %x needs hub "
4873                                 "TT think time and number of ports\n",
4874                                 (unsigned int) xhci->hci_version);
4875                 slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
4876                 /* Set TT think time - convert from ns to FS bit times.
4877                  * 0 = 8 FS bit times, 1 = 16 FS bit times,
4878                  * 2 = 24 FS bit times, 3 = 32 FS bit times.
4879                  *
4880                  * xHCI 1.0: this field shall be 0 if the device is not a
4881                  * High-spped hub.
4882                  */
4883                 think_time = tt->think_time;
4884                 if (think_time != 0)
4885                         think_time = (think_time / 666) - 1;
4886                 if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
4887                         slot_ctx->tt_info |=
4888                                 cpu_to_le32(TT_THINK_TIME(think_time));
4889         } else {
4890                 xhci_dbg(xhci, "xHCI version %x doesn't need hub "
4891                                 "TT think time or number of ports\n",
4892                                 (unsigned int) xhci->hci_version);
4893         }
4894         slot_ctx->dev_state = 0;
4895         spin_unlock_irqrestore(&xhci->lock, flags);
4896
4897         xhci_dbg(xhci, "Set up %s for hub device.\n",
4898                         (xhci->hci_version > 0x95) ?
4899                         "configure endpoint" : "evaluate context");
4900         xhci_dbg(xhci, "Slot %u Input Context:\n", hdev->slot_id);
4901         xhci_dbg_ctx(xhci, config_cmd->in_ctx, 0);
4902
4903         /* Issue and wait for the configure endpoint or
4904          * evaluate context command.
4905          */
4906         if (xhci->hci_version > 0x95)
4907                 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
4908                                 false, false);
4909         else
4910                 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
4911                                 true, false);
4912
4913         xhci_dbg(xhci, "Slot %u Output Context:\n", hdev->slot_id);
4914         xhci_dbg_ctx(xhci, vdev->out_ctx, 0);
4915
4916         xhci_free_command(xhci, config_cmd);
4917         return ret;
4918 }
4919
4920 int xhci_get_frame(struct usb_hcd *hcd)
4921 {
4922         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4923         /* EHCI mods by the periodic size.  Why? */
4924         return readl(&xhci->run_regs->microframe_index) >> 3;
4925 }
4926
4927 int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks)
4928 {
4929         struct xhci_hcd         *xhci;
4930         struct device           *dev = hcd->self.controller;
4931         int                     retval;
4932
4933         /* Accept arbitrarily long scatter-gather lists */
4934         hcd->self.sg_tablesize = ~0;
4935
4936         /* support to build packet from discontinuous buffers */
4937         hcd->self.no_sg_constraint = 1;
4938
4939         /* XHCI controllers don't stop the ep queue on short packets :| */
4940         hcd->self.no_stop_on_short = 1;
4941
4942         xhci = hcd_to_xhci(hcd);
4943
4944         if (usb_hcd_is_primary_hcd(hcd)) {
4945                 xhci->main_hcd = hcd;
4946                 /* Mark the first roothub as being USB 2.0.
4947                  * The xHCI driver will register the USB 3.0 roothub.
4948                  */
4949                 hcd->speed = HCD_USB2;
4950                 hcd->self.root_hub->speed = USB_SPEED_HIGH;
4951                 /*
4952                  * USB 2.0 roothub under xHCI has an integrated TT,
4953                  * (rate matching hub) as opposed to having an OHCI/UHCI
4954                  * companion controller.
4955                  */
4956                 hcd->has_tt = 1;
4957         } else {
4958                 if (xhci->sbrn == 0x31) {
4959                         xhci_info(xhci, "Host supports USB 3.1 Enhanced SuperSpeed\n");
4960                         hcd->speed = HCD_USB31;
4961                 }
4962                 /* xHCI private pointer was set in xhci_pci_probe for the second
4963                  * registered roothub.
4964                  */
4965                 return 0;
4966         }
4967
4968         mutex_init(&xhci->mutex);
4969         xhci->cap_regs = hcd->regs;
4970         xhci->op_regs = hcd->regs +
4971                 HC_LENGTH(readl(&xhci->cap_regs->hc_capbase));
4972         xhci->run_regs = hcd->regs +
4973                 (readl(&xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
4974         /* Cache read-only capability registers */
4975         xhci->hcs_params1 = readl(&xhci->cap_regs->hcs_params1);
4976         xhci->hcs_params2 = readl(&xhci->cap_regs->hcs_params2);
4977         xhci->hcs_params3 = readl(&xhci->cap_regs->hcs_params3);
4978         xhci->hcc_params = readl(&xhci->cap_regs->hc_capbase);
4979         xhci->hci_version = HC_VERSION(xhci->hcc_params);
4980         xhci->hcc_params = readl(&xhci->cap_regs->hcc_params);
4981         if (xhci->hci_version > 0x100)
4982                 xhci->hcc_params2 = readl(&xhci->cap_regs->hcc_params2);
4983         xhci_print_registers(xhci);
4984
4985         xhci->quirks = quirks;
4986
4987         get_quirks(dev, xhci);
4988
4989         /* In xhci controllers which follow xhci 1.0 spec gives a spurious
4990          * success event after a short transfer. This quirk will ignore such
4991          * spurious event.
4992          */
4993         if (xhci->hci_version > 0x96)
4994                 xhci->quirks |= XHCI_SPURIOUS_SUCCESS;
4995
4996         /* Make sure the HC is halted. */
4997         retval = xhci_halt(xhci);
4998         if (retval)
4999                 return retval;
5000
5001         xhci_dbg(xhci, "Resetting HCD\n");
5002         /* Reset the internal HC memory state and registers. */
5003         retval = xhci_reset(xhci);
5004         if (retval)
5005                 return retval;
5006         xhci_dbg(xhci, "Reset complete\n");
5007
5008         /* Set dma_mask and coherent_dma_mask to 64-bits,
5009          * if xHC supports 64-bit addressing */
5010         if (HCC_64BIT_ADDR(xhci->hcc_params) &&
5011                         !dma_set_mask(dev, DMA_BIT_MASK(64))) {
5012                 xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
5013                 dma_set_coherent_mask(dev, DMA_BIT_MASK(64));
5014         } else {
5015                 /*
5016                  * This is to avoid error in cases where a 32-bit USB
5017                  * controller is used on a 64-bit capable system.
5018                  */
5019                 retval = dma_set_mask(dev, DMA_BIT_MASK(32));
5020                 if (retval)
5021                         return retval;
5022                 xhci_dbg(xhci, "Enabling 32-bit DMA addresses.\n");
5023                 dma_set_coherent_mask(dev, DMA_BIT_MASK(32));
5024         }
5025
5026         xhci_dbg(xhci, "Calling HCD init\n");
5027         /* Initialize HCD and host controller data structures. */
5028         retval = xhci_init(hcd);
5029         if (retval)
5030                 return retval;
5031         xhci_dbg(xhci, "Called HCD init\n");
5032
5033         xhci_info(xhci, "hcc params 0x%08x hci version 0x%x quirks 0x%08x\n",
5034                   xhci->hcc_params, xhci->hci_version, xhci->quirks);
5035
5036         return 0;
5037 }
5038 EXPORT_SYMBOL_GPL(xhci_gen_setup);
5039
5040 static const struct hc_driver xhci_hc_driver = {
5041         .description =          "xhci-hcd",
5042         .product_desc =         "xHCI Host Controller",
5043         .hcd_priv_size =        sizeof(struct xhci_hcd *),
5044
5045         /*
5046          * generic hardware linkage
5047          */
5048         .irq =                  xhci_irq,
5049         .flags =                HCD_MEMORY | HCD_USB3 | HCD_SHARED,
5050
5051         /*
5052          * basic lifecycle operations
5053          */
5054         .reset =                NULL, /* set in xhci_init_driver() */
5055         .start =                xhci_run,
5056         .stop =                 xhci_stop,
5057         .shutdown =             xhci_shutdown,
5058
5059         /*
5060          * managing i/o requests and associated device resources
5061          */
5062         .urb_enqueue =          xhci_urb_enqueue,
5063         .urb_dequeue =          xhci_urb_dequeue,
5064         .alloc_dev =            xhci_alloc_dev,
5065         .free_dev =             xhci_free_dev,
5066         .alloc_streams =        xhci_alloc_streams,
5067         .free_streams =         xhci_free_streams,
5068         .add_endpoint =         xhci_add_endpoint,
5069         .drop_endpoint =        xhci_drop_endpoint,
5070         .endpoint_reset =       xhci_endpoint_reset,
5071         .check_bandwidth =      xhci_check_bandwidth,
5072         .reset_bandwidth =      xhci_reset_bandwidth,
5073         .address_device =       xhci_address_device,
5074         .enable_device =        xhci_enable_device,
5075         .update_hub_device =    xhci_update_hub_device,
5076         .reset_device =         xhci_discover_or_reset_device,
5077
5078         /*
5079          * scheduling support
5080          */
5081         .get_frame_number =     xhci_get_frame,
5082
5083         /*
5084          * root hub support
5085          */
5086         .hub_control =          xhci_hub_control,
5087         .hub_status_data =      xhci_hub_status_data,
5088         .bus_suspend =          xhci_bus_suspend,
5089         .bus_resume =           xhci_bus_resume,
5090
5091         /*
5092          * call back when device connected and addressed
5093          */
5094         .update_device =        xhci_update_device,
5095         .set_usb2_hw_lpm =      xhci_set_usb2_hardware_lpm,
5096         .enable_usb3_lpm_timeout =      xhci_enable_usb3_lpm_timeout,
5097         .disable_usb3_lpm_timeout =     xhci_disable_usb3_lpm_timeout,
5098         .find_raw_port_number = xhci_find_raw_port_number,
5099 };
5100
5101 void xhci_init_driver(struct hc_driver *drv,
5102                       const struct xhci_driver_overrides *over)
5103 {
5104         BUG_ON(!over);
5105
5106         /* Copy the generic table to drv then apply the overrides */
5107         *drv = xhci_hc_driver;
5108
5109         if (over) {
5110                 drv->hcd_priv_size += over->extra_priv_size;
5111                 if (over->reset)
5112                         drv->reset = over->reset;
5113                 if (over->start)
5114                         drv->start = over->start;
5115         }
5116 }
5117 EXPORT_SYMBOL_GPL(xhci_init_driver);
5118
5119 MODULE_DESCRIPTION(DRIVER_DESC);
5120 MODULE_AUTHOR(DRIVER_AUTHOR);
5121 MODULE_LICENSE("GPL");
5122
5123 static int __init xhci_hcd_init(void)
5124 {
5125         /*
5126          * Check the compiler generated sizes of structures that must be laid
5127          * out in specific ways for hardware access.
5128          */
5129         BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
5130         BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
5131         BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
5132         /* xhci_device_control has eight fields, and also
5133          * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
5134          */
5135         BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
5136         BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
5137         BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
5138         BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 8*32/8);
5139         BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
5140         /* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
5141         BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
5142
5143         if (usb_disabled())
5144                 return -ENODEV;
5145
5146         return 0;
5147 }
5148
5149 /*
5150  * If an init function is provided, an exit function must also be provided
5151  * to allow module unload.
5152  */
5153 static void __exit xhci_hcd_fini(void) { }
5154
5155 module_init(xhci_hcd_init);
5156 module_exit(xhci_hcd_fini);