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