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