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