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