xhci: fix memleak in xhci_run()
[muen/linux.git] / drivers / usb / host / xhci.c
1 /*
2  * xHCI host controller driver
3  *
4  * Copyright (C) 2008 Intel Corp.
5  *
6  * Author: Sarah Sharp
7  * Some code borrowed from the Linux EHCI driver.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16  * for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22
23 #include <linux/pci.h>
24 #include <linux/irq.h>
25 #include <linux/log2.h>
26 #include <linux/module.h>
27 #include <linux/moduleparam.h>
28 #include <linux/slab.h>
29 #include <linux/dmi.h>
30 #include <linux/dma-mapping.h>
31
32 #include "xhci.h"
33 #include "xhci-trace.h"
34 #include "xhci-mtk.h"
35
36 #define DRIVER_AUTHOR "Sarah Sharp"
37 #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
38
39 #define PORT_WAKE_BITS  (PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E)
40
41 /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
42 static int link_quirk;
43 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
44 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
45
46 static unsigned int quirks;
47 module_param(quirks, uint, S_IRUGO);
48 MODULE_PARM_DESC(quirks, "Bit flags for quirks to be enabled as default");
49
50 /* TODO: copied from ehci-hcd.c - can this be refactored? */
51 /*
52  * xhci_handshake - spin reading hc until handshake completes or fails
53  * @ptr: address of hc register to be read
54  * @mask: bits to look at in result of read
55  * @done: value of those bits when handshake succeeds
56  * @usec: timeout in microseconds
57  *
58  * Returns negative errno, or zero on success
59  *
60  * Success happens when the "mask" bits have the specified value (hardware
61  * handshake done).  There are two failure modes:  "usec" have passed (major
62  * hardware flakeout), or the register reads as all-ones (hardware removed).
63  */
64 int xhci_handshake(void __iomem *ptr, u32 mask, u32 done, int usec)
65 {
66         u32     result;
67
68         do {
69                 result = readl(ptr);
70                 if (result == ~(u32)0)          /* card removed */
71                         return -ENODEV;
72                 result &= mask;
73                 if (result == done)
74                         return 0;
75                 udelay(1);
76                 usec--;
77         } while (usec > 0);
78         return -ETIMEDOUT;
79 }
80
81 /*
82  * Disable interrupts and begin the xHCI halting process.
83  */
84 void xhci_quiesce(struct xhci_hcd *xhci)
85 {
86         u32 halted;
87         u32 cmd;
88         u32 mask;
89
90         mask = ~(XHCI_IRQS);
91         halted = readl(&xhci->op_regs->status) & STS_HALT;
92         if (!halted)
93                 mask &= ~CMD_RUN;
94
95         cmd = readl(&xhci->op_regs->command);
96         cmd &= mask;
97         writel(cmd, &xhci->op_regs->command);
98 }
99
100 /*
101  * Force HC into halt state.
102  *
103  * Disable any IRQs and clear the run/stop bit.
104  * HC will complete any current and actively pipelined transactions, and
105  * should halt within 16 ms of the run/stop bit being cleared.
106  * Read HC Halted bit in the status register to see when the HC is finished.
107  */
108 int xhci_halt(struct xhci_hcd *xhci)
109 {
110         int ret;
111         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Halt the HC");
112         xhci_quiesce(xhci);
113
114         ret = xhci_handshake(&xhci->op_regs->status,
115                         STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
116         if (ret) {
117                 xhci_warn(xhci, "Host halt failed, %d\n", ret);
118                 return ret;
119         }
120         xhci->xhc_state |= XHCI_STATE_HALTED;
121         xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
122         return ret;
123 }
124
125 /*
126  * Set the run bit and wait for the host to be running.
127  */
128 int xhci_start(struct xhci_hcd *xhci)
129 {
130         u32 temp;
131         int ret;
132
133         temp = readl(&xhci->op_regs->command);
134         temp |= (CMD_RUN);
135         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Turn on HC, cmd = 0x%x.",
136                         temp);
137         writel(temp, &xhci->op_regs->command);
138
139         /*
140          * Wait for the HCHalted Status bit to be 0 to indicate the host is
141          * running.
142          */
143         ret = xhci_handshake(&xhci->op_regs->status,
144                         STS_HALT, 0, XHCI_MAX_HALT_USEC);
145         if (ret == -ETIMEDOUT)
146                 xhci_err(xhci, "Host took too long to start, "
147                                 "waited %u microseconds.\n",
148                                 XHCI_MAX_HALT_USEC);
149         if (!ret)
150                 /* clear state flags. Including dying, halted or removing */
151                 xhci->xhc_state = 0;
152
153         return ret;
154 }
155
156 /*
157  * Reset a halted HC.
158  *
159  * This resets pipelines, timers, counters, state machines, etc.
160  * Transactions will be terminated immediately, and operational registers
161  * will be set to their defaults.
162  */
163 int xhci_reset(struct xhci_hcd *xhci)
164 {
165         u32 command;
166         u32 state;
167         int ret, i;
168
169         state = readl(&xhci->op_regs->status);
170
171         if (state == ~(u32)0) {
172                 xhci_warn(xhci, "Host not accessible, reset failed.\n");
173                 return -ENODEV;
174         }
175
176         if ((state & STS_HALT) == 0) {
177                 xhci_warn(xhci, "Host controller not halted, aborting reset.\n");
178                 return 0;
179         }
180
181         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Reset the HC");
182         command = readl(&xhci->op_regs->command);
183         command |= CMD_RESET;
184         writel(command, &xhci->op_regs->command);
185
186         /* Existing Intel xHCI controllers require a delay of 1 mS,
187          * after setting the CMD_RESET bit, and before accessing any
188          * HC registers. This allows the HC to complete the
189          * reset operation and be ready for HC register access.
190          * Without this delay, the subsequent HC register access,
191          * may result in a system hang very rarely.
192          */
193         if (xhci->quirks & XHCI_INTEL_HOST)
194                 udelay(1000);
195
196         ret = xhci_handshake(&xhci->op_regs->command,
197                         CMD_RESET, 0, 10 * 1000 * 1000);
198         if (ret)
199                 return ret;
200
201         if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
202                 usb_asmedia_modifyflowcontrol(to_pci_dev(xhci_to_hcd(xhci)->self.controller));
203
204         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
205                          "Wait for controller to be ready for doorbell rings");
206         /*
207          * xHCI cannot write to any doorbells or operational registers other
208          * than status until the "Controller Not Ready" flag is cleared.
209          */
210         ret = xhci_handshake(&xhci->op_regs->status,
211                         STS_CNR, 0, 10 * 1000 * 1000);
212
213         for (i = 0; i < 2; i++) {
214                 xhci->bus_state[i].port_c_suspend = 0;
215                 xhci->bus_state[i].suspended_ports = 0;
216                 xhci->bus_state[i].resuming_ports = 0;
217         }
218
219         return ret;
220 }
221
222
223 #ifdef CONFIG_USB_PCI
224 /*
225  * Set up MSI
226  */
227 static int xhci_setup_msi(struct xhci_hcd *xhci)
228 {
229         int ret;
230         /*
231          * TODO:Check with MSI Soc for sysdev
232          */
233         struct pci_dev  *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
234
235         ret = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_MSI);
236         if (ret < 0) {
237                 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
238                                 "failed to allocate MSI entry");
239                 return ret;
240         }
241
242         ret = request_irq(pdev->irq, xhci_msi_irq,
243                                 0, "xhci_hcd", xhci_to_hcd(xhci));
244         if (ret) {
245                 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
246                                 "disable MSI interrupt");
247                 pci_free_irq_vectors(pdev);
248         }
249
250         return ret;
251 }
252
253 /*
254  * Set up MSI-X
255  */
256 static int xhci_setup_msix(struct xhci_hcd *xhci)
257 {
258         int i, ret = 0;
259         struct usb_hcd *hcd = xhci_to_hcd(xhci);
260         struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
261
262         /*
263          * calculate number of msi-x vectors supported.
264          * - HCS_MAX_INTRS: the max number of interrupts the host can handle,
265          *   with max number of interrupters based on the xhci HCSPARAMS1.
266          * - num_online_cpus: maximum msi-x vectors per CPUs core.
267          *   Add additional 1 vector to ensure always available interrupt.
268          */
269         xhci->msix_count = min(num_online_cpus() + 1,
270                                 HCS_MAX_INTRS(xhci->hcs_params1));
271
272         ret = pci_alloc_irq_vectors(pdev, xhci->msix_count, xhci->msix_count,
273                         PCI_IRQ_MSIX);
274         if (ret < 0) {
275                 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
276                                 "Failed to enable MSI-X");
277                 return ret;
278         }
279
280         for (i = 0; i < xhci->msix_count; i++) {
281                 ret = request_irq(pci_irq_vector(pdev, i), xhci_msi_irq, 0,
282                                 "xhci_hcd", xhci_to_hcd(xhci));
283                 if (ret)
284                         goto disable_msix;
285         }
286
287         hcd->msix_enabled = 1;
288         return ret;
289
290 disable_msix:
291         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "disable MSI-X interrupt");
292         while (--i >= 0)
293                 free_irq(pci_irq_vector(pdev, i), xhci_to_hcd(xhci));
294         pci_free_irq_vectors(pdev);
295         return ret;
296 }
297
298 /* Free any IRQs and disable MSI-X */
299 static void xhci_cleanup_msix(struct xhci_hcd *xhci)
300 {
301         struct usb_hcd *hcd = xhci_to_hcd(xhci);
302         struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
303
304         if (xhci->quirks & XHCI_PLAT)
305                 return;
306
307         /* return if using legacy interrupt */
308         if (hcd->irq > 0)
309                 return;
310
311         if (hcd->msix_enabled) {
312                 int i;
313
314                 for (i = 0; i < xhci->msix_count; i++)
315                         free_irq(pci_irq_vector(pdev, i), xhci_to_hcd(xhci));
316         } else {
317                 free_irq(pci_irq_vector(pdev, 0), xhci_to_hcd(xhci));
318         }
319
320         pci_free_irq_vectors(pdev);
321         hcd->msix_enabled = 0;
322 }
323
324 static void __maybe_unused xhci_msix_sync_irqs(struct xhci_hcd *xhci)
325 {
326         struct usb_hcd *hcd = xhci_to_hcd(xhci);
327
328         if (hcd->msix_enabled) {
329                 struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
330                 int i;
331
332                 for (i = 0; i < xhci->msix_count; i++)
333                         synchronize_irq(pci_irq_vector(pdev, i));
334         }
335 }
336
337 static int xhci_try_enable_msi(struct usb_hcd *hcd)
338 {
339         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
340         struct pci_dev  *pdev;
341         int ret;
342
343         /* The xhci platform device has set up IRQs through usb_add_hcd. */
344         if (xhci->quirks & XHCI_PLAT)
345                 return 0;
346
347         pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
348         /*
349          * Some Fresco Logic host controllers advertise MSI, but fail to
350          * generate interrupts.  Don't even try to enable MSI.
351          */
352         if (xhci->quirks & XHCI_BROKEN_MSI)
353                 goto legacy_irq;
354
355         /* unregister the legacy interrupt */
356         if (hcd->irq)
357                 free_irq(hcd->irq, hcd);
358         hcd->irq = 0;
359
360         ret = xhci_setup_msix(xhci);
361         if (ret)
362                 /* fall back to msi*/
363                 ret = xhci_setup_msi(xhci);
364
365         if (!ret) {
366                 hcd->msi_enabled = 1;
367                 return 0;
368         }
369
370         if (!pdev->irq) {
371                 xhci_err(xhci, "No msi-x/msi found and no IRQ in BIOS\n");
372                 return -EINVAL;
373         }
374
375  legacy_irq:
376         if (!strlen(hcd->irq_descr))
377                 snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
378                          hcd->driver->description, hcd->self.busnum);
379
380         /* fall back to legacy interrupt*/
381         ret = request_irq(pdev->irq, &usb_hcd_irq, IRQF_SHARED,
382                         hcd->irq_descr, hcd);
383         if (ret) {
384                 xhci_err(xhci, "request interrupt %d failed\n",
385                                 pdev->irq);
386                 return ret;
387         }
388         hcd->irq = pdev->irq;
389         return 0;
390 }
391
392 #else
393
394 static inline int xhci_try_enable_msi(struct usb_hcd *hcd)
395 {
396         return 0;
397 }
398
399 static inline void xhci_cleanup_msix(struct xhci_hcd *xhci)
400 {
401 }
402
403 static inline void xhci_msix_sync_irqs(struct xhci_hcd *xhci)
404 {
405 }
406
407 #endif
408
409 static void compliance_mode_recovery(unsigned long arg)
410 {
411         struct xhci_hcd *xhci;
412         struct usb_hcd *hcd;
413         u32 temp;
414         int i;
415
416         xhci = (struct xhci_hcd *)arg;
417
418         for (i = 0; i < xhci->num_usb3_ports; i++) {
419                 temp = readl(xhci->usb3_ports[i]);
420                 if ((temp & PORT_PLS_MASK) == USB_SS_PORT_LS_COMP_MOD) {
421                         /*
422                          * Compliance Mode Detected. Letting USB Core
423                          * handle the Warm Reset
424                          */
425                         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
426                                         "Compliance mode detected->port %d",
427                                         i + 1);
428                         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
429                                         "Attempting compliance mode recovery");
430                         hcd = xhci->shared_hcd;
431
432                         if (hcd->state == HC_STATE_SUSPENDED)
433                                 usb_hcd_resume_root_hub(hcd);
434
435                         usb_hcd_poll_rh_status(hcd);
436                 }
437         }
438
439         if (xhci->port_status_u0 != ((1 << xhci->num_usb3_ports)-1))
440                 mod_timer(&xhci->comp_mode_recovery_timer,
441                         jiffies + msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
442 }
443
444 /*
445  * Quirk to work around issue generated by the SN65LVPE502CP USB3.0 re-driver
446  * that causes ports behind that hardware to enter compliance mode sometimes.
447  * The quirk creates a timer that polls every 2 seconds the link state of
448  * each host controller's port and recovers it by issuing a Warm reset
449  * if Compliance mode is detected, otherwise the port will become "dead" (no
450  * device connections or disconnections will be detected anymore). Becasue no
451  * status event is generated when entering compliance mode (per xhci spec),
452  * this quirk is needed on systems that have the failing hardware installed.
453  */
454 static void compliance_mode_recovery_timer_init(struct xhci_hcd *xhci)
455 {
456         xhci->port_status_u0 = 0;
457         setup_timer(&xhci->comp_mode_recovery_timer,
458                     compliance_mode_recovery, (unsigned long)xhci);
459         xhci->comp_mode_recovery_timer.expires = jiffies +
460                         msecs_to_jiffies(COMP_MODE_RCVRY_MSECS);
461
462         add_timer(&xhci->comp_mode_recovery_timer);
463         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
464                         "Compliance mode recovery timer initialized");
465 }
466
467 /*
468  * This function identifies the systems that have installed the SN65LVPE502CP
469  * USB3.0 re-driver and that need the Compliance Mode Quirk.
470  * Systems:
471  * Vendor: Hewlett-Packard -> System Models: Z420, Z620 and Z820
472  */
473 static bool xhci_compliance_mode_recovery_timer_quirk_check(void)
474 {
475         const char *dmi_product_name, *dmi_sys_vendor;
476
477         dmi_product_name = dmi_get_system_info(DMI_PRODUCT_NAME);
478         dmi_sys_vendor = dmi_get_system_info(DMI_SYS_VENDOR);
479         if (!dmi_product_name || !dmi_sys_vendor)
480                 return false;
481
482         if (!(strstr(dmi_sys_vendor, "Hewlett-Packard")))
483                 return false;
484
485         if (strstr(dmi_product_name, "Z420") ||
486                         strstr(dmi_product_name, "Z620") ||
487                         strstr(dmi_product_name, "Z820") ||
488                         strstr(dmi_product_name, "Z1 Workstation"))
489                 return true;
490
491         return false;
492 }
493
494 static int xhci_all_ports_seen_u0(struct xhci_hcd *xhci)
495 {
496         return (xhci->port_status_u0 == ((1 << xhci->num_usb3_ports)-1));
497 }
498
499
500 /*
501  * Initialize memory for HCD and xHC (one-time init).
502  *
503  * Program the PAGESIZE register, initialize the device context array, create
504  * device contexts (?), set up a command ring segment (or two?), create event
505  * ring (one for now).
506  */
507 static int xhci_init(struct usb_hcd *hcd)
508 {
509         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
510         int retval = 0;
511
512         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_init");
513         spin_lock_init(&xhci->lock);
514         if (xhci->hci_version == 0x95 && link_quirk) {
515                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
516                                 "QUIRK: Not clearing Link TRB chain bits.");
517                 xhci->quirks |= XHCI_LINK_TRB_QUIRK;
518         } else {
519                 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
520                                 "xHCI doesn't need link TRB QUIRK");
521         }
522         retval = xhci_mem_init(xhci, GFP_KERNEL);
523         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Finished xhci_init");
524
525         /* Initializing Compliance Mode Recovery Data If Needed */
526         if (xhci_compliance_mode_recovery_timer_quirk_check()) {
527                 xhci->quirks |= XHCI_COMP_MODE_QUIRK;
528                 compliance_mode_recovery_timer_init(xhci);
529         }
530
531         return retval;
532 }
533
534 /*-------------------------------------------------------------------------*/
535
536
537 static int xhci_run_finished(struct xhci_hcd *xhci)
538 {
539         if (xhci_start(xhci)) {
540                 xhci_halt(xhci);
541                 return -ENODEV;
542         }
543         xhci->shared_hcd->state = HC_STATE_RUNNING;
544         xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
545
546         if (xhci->quirks & XHCI_NEC_HOST)
547                 xhci_ring_cmd_db(xhci);
548
549         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
550                         "Finished xhci_run for USB3 roothub");
551         return 0;
552 }
553
554 /*
555  * Start the HC after it was halted.
556  *
557  * This function is called by the USB core when the HC driver is added.
558  * Its opposite is xhci_stop().
559  *
560  * xhci_init() must be called once before this function can be called.
561  * Reset the HC, enable device slot contexts, program DCBAAP, and
562  * set command ring pointer and event ring pointer.
563  *
564  * Setup MSI-X vectors and enable interrupts.
565  */
566 int xhci_run(struct usb_hcd *hcd)
567 {
568         u32 temp;
569         u64 temp_64;
570         int ret;
571         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
572
573         /* Start the xHCI host controller running only after the USB 2.0 roothub
574          * is setup.
575          */
576
577         hcd->uses_new_polling = 1;
578         if (!usb_hcd_is_primary_hcd(hcd))
579                 return xhci_run_finished(xhci);
580
581         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_run");
582
583         ret = xhci_try_enable_msi(hcd);
584         if (ret)
585                 return ret;
586
587         xhci_dbg_cmd_ptrs(xhci);
588
589         xhci_dbg(xhci, "ERST memory map follows:\n");
590         xhci_dbg_erst(xhci, &xhci->erst);
591         temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
592         temp_64 &= ~ERST_PTR_MASK;
593         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
594                         "ERST deq = 64'h%0lx", (long unsigned int) temp_64);
595
596         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
597                         "// Set the interrupt modulation register");
598         temp = readl(&xhci->ir_set->irq_control);
599         temp &= ~ER_IRQ_INTERVAL_MASK;
600         /*
601          * the increment interval is 8 times as much as that defined
602          * in xHCI spec on MTK's controller
603          */
604         temp |= (u32) ((xhci->quirks & XHCI_MTK_HOST) ? 20 : 160);
605         writel(temp, &xhci->ir_set->irq_control);
606
607         /* Set the HCD state before we enable the irqs */
608         temp = readl(&xhci->op_regs->command);
609         temp |= (CMD_EIE);
610         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
611                         "// Enable interrupts, cmd = 0x%x.", temp);
612         writel(temp, &xhci->op_regs->command);
613
614         temp = readl(&xhci->ir_set->irq_pending);
615         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
616                         "// Enabling event ring interrupter %p by writing 0x%x to irq_pending",
617                         xhci->ir_set, (unsigned int) ER_IRQ_ENABLE(temp));
618         writel(ER_IRQ_ENABLE(temp), &xhci->ir_set->irq_pending);
619         xhci_print_ir_set(xhci, 0);
620
621         if (xhci->quirks & XHCI_NEC_HOST) {
622                 struct xhci_command *command;
623
624                 command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
625                 if (!command)
626                         return -ENOMEM;
627
628                 ret = xhci_queue_vendor_command(xhci, command, 0, 0, 0,
629                                 TRB_TYPE(TRB_NEC_GET_FW));
630                 if (ret)
631                         xhci_free_command(xhci, command);
632         }
633         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
634                         "Finished xhci_run for USB2 roothub");
635         return 0;
636 }
637 EXPORT_SYMBOL_GPL(xhci_run);
638
639 /*
640  * Stop xHCI driver.
641  *
642  * This function is called by the USB core when the HC driver is removed.
643  * Its opposite is xhci_run().
644  *
645  * Disable device contexts, disable IRQs, and quiesce the HC.
646  * Reset the HC, finish any completed transactions, and cleanup memory.
647  */
648 static void xhci_stop(struct usb_hcd *hcd)
649 {
650         u32 temp;
651         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
652
653         mutex_lock(&xhci->mutex);
654
655         /* Only halt host and free memory after both hcds are removed */
656         if (!usb_hcd_is_primary_hcd(hcd)) {
657                 /* usb core will free this hcd shortly, unset pointer */
658                 xhci->shared_hcd = NULL;
659                 mutex_unlock(&xhci->mutex);
660                 return;
661         }
662
663         spin_lock_irq(&xhci->lock);
664         xhci->xhc_state |= XHCI_STATE_HALTED;
665         xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
666         xhci_halt(xhci);
667         xhci_reset(xhci);
668         spin_unlock_irq(&xhci->lock);
669
670         xhci_cleanup_msix(xhci);
671
672         /* Deleting Compliance Mode Recovery Timer */
673         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
674                         (!(xhci_all_ports_seen_u0(xhci)))) {
675                 del_timer_sync(&xhci->comp_mode_recovery_timer);
676                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
677                                 "%s: compliance mode recovery timer deleted",
678                                 __func__);
679         }
680
681         if (xhci->quirks & XHCI_AMD_PLL_FIX)
682                 usb_amd_dev_put();
683
684         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
685                         "// Disabling event ring interrupts");
686         temp = readl(&xhci->op_regs->status);
687         writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
688         temp = readl(&xhci->ir_set->irq_pending);
689         writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
690         xhci_print_ir_set(xhci, 0);
691
692         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "cleaning up memory");
693         xhci_mem_cleanup(xhci);
694         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
695                         "xhci_stop completed - status = %x",
696                         readl(&xhci->op_regs->status));
697         mutex_unlock(&xhci->mutex);
698 }
699
700 /*
701  * Shutdown HC (not bus-specific)
702  *
703  * This is called when the machine is rebooting or halting.  We assume that the
704  * machine will be powered off, and the HC's internal state will be reset.
705  * Don't bother to free memory.
706  *
707  * This will only ever be called with the main usb_hcd (the USB3 roothub).
708  */
709 static void xhci_shutdown(struct usb_hcd *hcd)
710 {
711         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
712
713         if (xhci->quirks & XHCI_SPURIOUS_REBOOT)
714                 usb_disable_xhci_ports(to_pci_dev(hcd->self.sysdev));
715
716         spin_lock_irq(&xhci->lock);
717         xhci_halt(xhci);
718         /* Workaround for spurious wakeups at shutdown with HSW */
719         if (xhci->quirks & XHCI_SPURIOUS_WAKEUP)
720                 xhci_reset(xhci);
721         spin_unlock_irq(&xhci->lock);
722
723         xhci_cleanup_msix(xhci);
724
725         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
726                         "xhci_shutdown completed - status = %x",
727                         readl(&xhci->op_regs->status));
728
729         /* Yet another workaround for spurious wakeups at shutdown with HSW */
730         if (xhci->quirks & XHCI_SPURIOUS_WAKEUP)
731                 pci_set_power_state(to_pci_dev(hcd->self.sysdev), PCI_D3hot);
732 }
733
734 #ifdef CONFIG_PM
735 static void xhci_save_registers(struct xhci_hcd *xhci)
736 {
737         xhci->s3.command = readl(&xhci->op_regs->command);
738         xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
739         xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
740         xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);
741         xhci->s3.erst_size = readl(&xhci->ir_set->erst_size);
742         xhci->s3.erst_base = xhci_read_64(xhci, &xhci->ir_set->erst_base);
743         xhci->s3.erst_dequeue = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
744         xhci->s3.irq_pending = readl(&xhci->ir_set->irq_pending);
745         xhci->s3.irq_control = readl(&xhci->ir_set->irq_control);
746 }
747
748 static void xhci_restore_registers(struct xhci_hcd *xhci)
749 {
750         writel(xhci->s3.command, &xhci->op_regs->command);
751         writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
752         xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
753         writel(xhci->s3.config_reg, &xhci->op_regs->config_reg);
754         writel(xhci->s3.erst_size, &xhci->ir_set->erst_size);
755         xhci_write_64(xhci, xhci->s3.erst_base, &xhci->ir_set->erst_base);
756         xhci_write_64(xhci, xhci->s3.erst_dequeue, &xhci->ir_set->erst_dequeue);
757         writel(xhci->s3.irq_pending, &xhci->ir_set->irq_pending);
758         writel(xhci->s3.irq_control, &xhci->ir_set->irq_control);
759 }
760
761 static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
762 {
763         u64     val_64;
764
765         /* step 2: initialize command ring buffer */
766         val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
767         val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
768                 (xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
769                                       xhci->cmd_ring->dequeue) &
770                  (u64) ~CMD_RING_RSVD_BITS) |
771                 xhci->cmd_ring->cycle_state;
772         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
773                         "// Setting command ring address to 0x%llx",
774                         (long unsigned long) val_64);
775         xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
776 }
777
778 /*
779  * The whole command ring must be cleared to zero when we suspend the host.
780  *
781  * The host doesn't save the command ring pointer in the suspend well, so we
782  * need to re-program it on resume.  Unfortunately, the pointer must be 64-byte
783  * aligned, because of the reserved bits in the command ring dequeue pointer
784  * register.  Therefore, we can't just set the dequeue pointer back in the
785  * middle of the ring (TRBs are 16-byte aligned).
786  */
787 static void xhci_clear_command_ring(struct xhci_hcd *xhci)
788 {
789         struct xhci_ring *ring;
790         struct xhci_segment *seg;
791
792         ring = xhci->cmd_ring;
793         seg = ring->deq_seg;
794         do {
795                 memset(seg->trbs, 0,
796                         sizeof(union xhci_trb) * (TRBS_PER_SEGMENT - 1));
797                 seg->trbs[TRBS_PER_SEGMENT - 1].link.control &=
798                         cpu_to_le32(~TRB_CYCLE);
799                 seg = seg->next;
800         } while (seg != ring->deq_seg);
801
802         /* Reset the software enqueue and dequeue pointers */
803         ring->deq_seg = ring->first_seg;
804         ring->dequeue = ring->first_seg->trbs;
805         ring->enq_seg = ring->deq_seg;
806         ring->enqueue = ring->dequeue;
807
808         ring->num_trbs_free = ring->num_segs * (TRBS_PER_SEGMENT - 1) - 1;
809         /*
810          * Ring is now zeroed, so the HW should look for change of ownership
811          * when the cycle bit is set to 1.
812          */
813         ring->cycle_state = 1;
814
815         /*
816          * Reset the hardware dequeue pointer.
817          * Yes, this will need to be re-written after resume, but we're paranoid
818          * and want to make sure the hardware doesn't access bogus memory
819          * because, say, the BIOS or an SMI started the host without changing
820          * the command ring pointers.
821          */
822         xhci_set_cmd_ring_deq(xhci);
823 }
824
825 static void xhci_disable_port_wake_on_bits(struct xhci_hcd *xhci)
826 {
827         int port_index;
828         __le32 __iomem **port_array;
829         unsigned long flags;
830         u32 t1, t2;
831
832         spin_lock_irqsave(&xhci->lock, flags);
833
834         /* disable usb3 ports Wake bits */
835         port_index = xhci->num_usb3_ports;
836         port_array = xhci->usb3_ports;
837         while (port_index--) {
838                 t1 = readl(port_array[port_index]);
839                 t1 = xhci_port_state_to_neutral(t1);
840                 t2 = t1 & ~PORT_WAKE_BITS;
841                 if (t1 != t2)
842                         writel(t2, port_array[port_index]);
843         }
844
845         /* disable usb2 ports Wake bits */
846         port_index = xhci->num_usb2_ports;
847         port_array = xhci->usb2_ports;
848         while (port_index--) {
849                 t1 = readl(port_array[port_index]);
850                 t1 = xhci_port_state_to_neutral(t1);
851                 t2 = t1 & ~PORT_WAKE_BITS;
852                 if (t1 != t2)
853                         writel(t2, port_array[port_index]);
854         }
855
856         spin_unlock_irqrestore(&xhci->lock, flags);
857 }
858
859 /*
860  * Stop HC (not bus-specific)
861  *
862  * This is called when the machine transition into S3/S4 mode.
863  *
864  */
865 int xhci_suspend(struct xhci_hcd *xhci, bool do_wakeup)
866 {
867         int                     rc = 0;
868         unsigned int            delay = XHCI_MAX_HALT_USEC;
869         struct usb_hcd          *hcd = xhci_to_hcd(xhci);
870         u32                     command;
871
872         if (!hcd->state)
873                 return 0;
874
875         if (hcd->state != HC_STATE_SUSPENDED ||
876                         xhci->shared_hcd->state != HC_STATE_SUSPENDED)
877                 return -EINVAL;
878
879         /* Clear root port wake on bits if wakeup not allowed. */
880         if (!do_wakeup)
881                 xhci_disable_port_wake_on_bits(xhci);
882
883         /* Don't poll the roothubs on bus suspend. */
884         xhci_dbg(xhci, "%s: stopping port polling.\n", __func__);
885         clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
886         del_timer_sync(&hcd->rh_timer);
887         clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
888         del_timer_sync(&xhci->shared_hcd->rh_timer);
889
890         spin_lock_irq(&xhci->lock);
891         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
892         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
893         /* step 1: stop endpoint */
894         /* skipped assuming that port suspend has done */
895
896         /* step 2: clear Run/Stop bit */
897         command = readl(&xhci->op_regs->command);
898         command &= ~CMD_RUN;
899         writel(command, &xhci->op_regs->command);
900
901         /* Some chips from Fresco Logic need an extraordinary delay */
902         delay *= (xhci->quirks & XHCI_SLOW_SUSPEND) ? 10 : 1;
903
904         if (xhci_handshake(&xhci->op_regs->status,
905                       STS_HALT, STS_HALT, delay)) {
906                 xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
907                 spin_unlock_irq(&xhci->lock);
908                 return -ETIMEDOUT;
909         }
910         xhci_clear_command_ring(xhci);
911
912         /* step 3: save registers */
913         xhci_save_registers(xhci);
914
915         /* step 4: set CSS flag */
916         command = readl(&xhci->op_regs->command);
917         command |= CMD_CSS;
918         writel(command, &xhci->op_regs->command);
919         if (xhci_handshake(&xhci->op_regs->status,
920                                 STS_SAVE, 0, 10 * 1000)) {
921                 xhci_warn(xhci, "WARN: xHC save state timeout\n");
922                 spin_unlock_irq(&xhci->lock);
923                 return -ETIMEDOUT;
924         }
925         spin_unlock_irq(&xhci->lock);
926
927         /*
928          * Deleting Compliance Mode Recovery Timer because the xHCI Host
929          * is about to be suspended.
930          */
931         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
932                         (!(xhci_all_ports_seen_u0(xhci)))) {
933                 del_timer_sync(&xhci->comp_mode_recovery_timer);
934                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
935                                 "%s: compliance mode recovery timer deleted",
936                                 __func__);
937         }
938
939         /* step 5: remove core well power */
940         /* synchronize irq when using MSI-X */
941         xhci_msix_sync_irqs(xhci);
942
943         return rc;
944 }
945 EXPORT_SYMBOL_GPL(xhci_suspend);
946
947 /*
948  * start xHC (not bus-specific)
949  *
950  * This is called when the machine transition from S3/S4 mode.
951  *
952  */
953 int xhci_resume(struct xhci_hcd *xhci, bool hibernated)
954 {
955         u32                     command, temp = 0, status;
956         struct usb_hcd          *hcd = xhci_to_hcd(xhci);
957         struct usb_hcd          *secondary_hcd;
958         int                     retval = 0;
959         bool                    comp_timer_running = false;
960
961         if (!hcd->state)
962                 return 0;
963
964         /* Wait a bit if either of the roothubs need to settle from the
965          * transition into bus suspend.
966          */
967         if (time_before(jiffies, xhci->bus_state[0].next_statechange) ||
968                         time_before(jiffies,
969                                 xhci->bus_state[1].next_statechange))
970                 msleep(100);
971
972         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
973         set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
974
975         spin_lock_irq(&xhci->lock);
976         if (xhci->quirks & XHCI_RESET_ON_RESUME)
977                 hibernated = true;
978
979         if (!hibernated) {
980                 /* step 1: restore register */
981                 xhci_restore_registers(xhci);
982                 /* step 2: initialize command ring buffer */
983                 xhci_set_cmd_ring_deq(xhci);
984                 /* step 3: restore state and start state*/
985                 /* step 3: set CRS flag */
986                 command = readl(&xhci->op_regs->command);
987                 command |= CMD_CRS;
988                 writel(command, &xhci->op_regs->command);
989                 if (xhci_handshake(&xhci->op_regs->status,
990                               STS_RESTORE, 0, 10 * 1000)) {
991                         xhci_warn(xhci, "WARN: xHC restore state timeout\n");
992                         spin_unlock_irq(&xhci->lock);
993                         return -ETIMEDOUT;
994                 }
995                 temp = readl(&xhci->op_regs->status);
996         }
997
998         /* If restore operation fails, re-initialize the HC during resume */
999         if ((temp & STS_SRE) || hibernated) {
1000
1001                 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1002                                 !(xhci_all_ports_seen_u0(xhci))) {
1003                         del_timer_sync(&xhci->comp_mode_recovery_timer);
1004                         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1005                                 "Compliance Mode Recovery Timer deleted!");
1006                 }
1007
1008                 /* Let the USB core know _both_ roothubs lost power. */
1009                 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1010                 usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
1011
1012                 xhci_dbg(xhci, "Stop HCD\n");
1013                 xhci_halt(xhci);
1014                 xhci_reset(xhci);
1015                 spin_unlock_irq(&xhci->lock);
1016                 xhci_cleanup_msix(xhci);
1017
1018                 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1019                 temp = readl(&xhci->op_regs->status);
1020                 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
1021                 temp = readl(&xhci->ir_set->irq_pending);
1022                 writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
1023                 xhci_print_ir_set(xhci, 0);
1024
1025                 xhci_dbg(xhci, "cleaning up memory\n");
1026                 xhci_mem_cleanup(xhci);
1027                 xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
1028                             readl(&xhci->op_regs->status));
1029
1030                 /* USB core calls the PCI reinit and start functions twice:
1031                  * first with the primary HCD, and then with the secondary HCD.
1032                  * If we don't do the same, the host will never be started.
1033                  */
1034                 if (!usb_hcd_is_primary_hcd(hcd))
1035                         secondary_hcd = hcd;
1036                 else
1037                         secondary_hcd = xhci->shared_hcd;
1038
1039                 xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1040                 retval = xhci_init(hcd->primary_hcd);
1041                 if (retval)
1042                         return retval;
1043                 comp_timer_running = true;
1044
1045                 xhci_dbg(xhci, "Start the primary HCD\n");
1046                 retval = xhci_run(hcd->primary_hcd);
1047                 if (!retval) {
1048                         xhci_dbg(xhci, "Start the secondary HCD\n");
1049                         retval = xhci_run(secondary_hcd);
1050                 }
1051                 hcd->state = HC_STATE_SUSPENDED;
1052                 xhci->shared_hcd->state = HC_STATE_SUSPENDED;
1053                 goto done;
1054         }
1055
1056         /* step 4: set Run/Stop bit */
1057         command = readl(&xhci->op_regs->command);
1058         command |= CMD_RUN;
1059         writel(command, &xhci->op_regs->command);
1060         xhci_handshake(&xhci->op_regs->status, STS_HALT,
1061                   0, 250 * 1000);
1062
1063         /* step 5: walk topology and initialize portsc,
1064          * portpmsc and portli
1065          */
1066         /* this is done in bus_resume */
1067
1068         /* step 6: restart each of the previously
1069          * Running endpoints by ringing their doorbells
1070          */
1071
1072         spin_unlock_irq(&xhci->lock);
1073
1074  done:
1075         if (retval == 0) {
1076                 /* Resume root hubs only when have pending events. */
1077                 status = readl(&xhci->op_regs->status);
1078                 if (status & STS_EINT) {
1079                         usb_hcd_resume_root_hub(xhci->shared_hcd);
1080                         usb_hcd_resume_root_hub(hcd);
1081                 }
1082         }
1083
1084         /*
1085          * If system is subject to the Quirk, Compliance Mode Timer needs to
1086          * be re-initialized Always after a system resume. Ports are subject
1087          * to suffer the Compliance Mode issue again. It doesn't matter if
1088          * ports have entered previously to U0 before system's suspension.
1089          */
1090         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) && !comp_timer_running)
1091                 compliance_mode_recovery_timer_init(xhci);
1092
1093         if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
1094                 usb_asmedia_modifyflowcontrol(to_pci_dev(hcd->self.controller));
1095
1096         /* Re-enable port polling. */
1097         xhci_dbg(xhci, "%s: starting port polling.\n", __func__);
1098         set_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
1099         usb_hcd_poll_rh_status(xhci->shared_hcd);
1100         set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1101         usb_hcd_poll_rh_status(hcd);
1102
1103         return retval;
1104 }
1105 EXPORT_SYMBOL_GPL(xhci_resume);
1106 #endif  /* CONFIG_PM */
1107
1108 /*-------------------------------------------------------------------------*/
1109
1110 /**
1111  * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1112  * HCDs.  Find the index for an endpoint given its descriptor.  Use the return
1113  * value to right shift 1 for the bitmask.
1114  *
1115  * Index  = (epnum * 2) + direction - 1,
1116  * where direction = 0 for OUT, 1 for IN.
1117  * For control endpoints, the IN index is used (OUT index is unused), so
1118  * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1119  */
1120 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1121 {
1122         unsigned int index;
1123         if (usb_endpoint_xfer_control(desc))
1124                 index = (unsigned int) (usb_endpoint_num(desc)*2);
1125         else
1126                 index = (unsigned int) (usb_endpoint_num(desc)*2) +
1127                         (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1128         return index;
1129 }
1130
1131 /* The reverse operation to xhci_get_endpoint_index. Calculate the USB endpoint
1132  * address from the XHCI endpoint index.
1133  */
1134 unsigned int xhci_get_endpoint_address(unsigned int ep_index)
1135 {
1136         unsigned int number = DIV_ROUND_UP(ep_index, 2);
1137         unsigned int direction = ep_index % 2 ? USB_DIR_OUT : USB_DIR_IN;
1138         return direction | number;
1139 }
1140
1141 /* Find the flag for this endpoint (for use in the control context).  Use the
1142  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
1143  * bit 1, etc.
1144  */
1145 static unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1146 {
1147         return 1 << (xhci_get_endpoint_index(desc) + 1);
1148 }
1149
1150 /* Find the flag for this endpoint (for use in the control context).  Use the
1151  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
1152  * bit 1, etc.
1153  */
1154 static unsigned int xhci_get_endpoint_flag_from_index(unsigned int ep_index)
1155 {
1156         return 1 << (ep_index + 1);
1157 }
1158
1159 /* Compute the last valid endpoint context index.  Basically, this is the
1160  * endpoint index plus one.  For slot contexts with more than valid endpoint,
1161  * we find the most significant bit set in the added contexts flags.
1162  * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1163  * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1164  */
1165 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1166 {
1167         return fls(added_ctxs) - 1;
1168 }
1169
1170 /* Returns 1 if the arguments are OK;
1171  * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1172  */
1173 static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
1174                 struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
1175                 const char *func) {
1176         struct xhci_hcd *xhci;
1177         struct xhci_virt_device *virt_dev;
1178
1179         if (!hcd || (check_ep && !ep) || !udev) {
1180                 pr_debug("xHCI %s called with invalid args\n", func);
1181                 return -EINVAL;
1182         }
1183         if (!udev->parent) {
1184                 pr_debug("xHCI %s called for root hub\n", func);
1185                 return 0;
1186         }
1187
1188         xhci = hcd_to_xhci(hcd);
1189         if (check_virt_dev) {
1190                 if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
1191                         xhci_dbg(xhci, "xHCI %s called with unaddressed device\n",
1192                                         func);
1193                         return -EINVAL;
1194                 }
1195
1196                 virt_dev = xhci->devs[udev->slot_id];
1197                 if (virt_dev->udev != udev) {
1198                         xhci_dbg(xhci, "xHCI %s called with udev and "
1199                                           "virt_dev does not match\n", func);
1200                         return -EINVAL;
1201                 }
1202         }
1203
1204         if (xhci->xhc_state & XHCI_STATE_HALTED)
1205                 return -ENODEV;
1206
1207         return 1;
1208 }
1209
1210 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1211                 struct usb_device *udev, struct xhci_command *command,
1212                 bool ctx_change, bool must_succeed);
1213
1214 /*
1215  * Full speed devices may have a max packet size greater than 8 bytes, but the
1216  * USB core doesn't know that until it reads the first 8 bytes of the
1217  * descriptor.  If the usb_device's max packet size changes after that point,
1218  * we need to issue an evaluate context command and wait on it.
1219  */
1220 static int xhci_check_maxpacket(struct xhci_hcd *xhci, unsigned int slot_id,
1221                 unsigned int ep_index, struct urb *urb)
1222 {
1223         struct xhci_container_ctx *out_ctx;
1224         struct xhci_input_control_ctx *ctrl_ctx;
1225         struct xhci_ep_ctx *ep_ctx;
1226         struct xhci_command *command;
1227         int max_packet_size;
1228         int hw_max_packet_size;
1229         int ret = 0;
1230
1231         out_ctx = xhci->devs[slot_id]->out_ctx;
1232         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1233         hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1234         max_packet_size = usb_endpoint_maxp(&urb->dev->ep0.desc);
1235         if (hw_max_packet_size != max_packet_size) {
1236                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1237                                 "Max Packet Size for ep 0 changed.");
1238                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1239                                 "Max packet size in usb_device = %d",
1240                                 max_packet_size);
1241                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1242                                 "Max packet size in xHCI HW = %d",
1243                                 hw_max_packet_size);
1244                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1245                                 "Issuing evaluate context command.");
1246
1247                 /* Set up the input context flags for the command */
1248                 /* FIXME: This won't work if a non-default control endpoint
1249                  * changes max packet sizes.
1250                  */
1251
1252                 command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
1253                 if (!command)
1254                         return -ENOMEM;
1255
1256                 command->in_ctx = xhci->devs[slot_id]->in_ctx;
1257                 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
1258                 if (!ctrl_ctx) {
1259                         xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1260                                         __func__);
1261                         ret = -ENOMEM;
1262                         goto command_cleanup;
1263                 }
1264                 /* Set up the modified control endpoint 0 */
1265                 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
1266                                 xhci->devs[slot_id]->out_ctx, ep_index);
1267
1268                 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
1269                 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1270                 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1271
1272                 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1273                 ctrl_ctx->drop_flags = 0;
1274
1275                 ret = xhci_configure_endpoint(xhci, urb->dev, command,
1276                                 true, false);
1277
1278                 /* Clean up the input context for later use by bandwidth
1279                  * functions.
1280                  */
1281                 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1282 command_cleanup:
1283                 kfree(command->completion);
1284                 kfree(command);
1285         }
1286         return ret;
1287 }
1288
1289 /*
1290  * non-error returns are a promise to giveback() the urb later
1291  * we drop ownership so next owner (or urb unlink) can get it
1292  */
1293 static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1294 {
1295         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1296         unsigned long flags;
1297         int ret = 0;
1298         unsigned int slot_id, ep_index, ep_state;
1299         struct urb_priv *urb_priv;
1300         int num_tds;
1301
1302         if (!urb || xhci_check_args(hcd, urb->dev, urb->ep,
1303                                         true, true, __func__) <= 0)
1304                 return -EINVAL;
1305
1306         slot_id = urb->dev->slot_id;
1307         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1308
1309         if (!HCD_HW_ACCESSIBLE(hcd)) {
1310                 if (!in_interrupt())
1311                         xhci_dbg(xhci, "urb submitted during PCI suspend\n");
1312                 return -ESHUTDOWN;
1313         }
1314
1315         if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1316                 num_tds = urb->number_of_packets;
1317         else if (usb_endpoint_is_bulk_out(&urb->ep->desc) &&
1318             urb->transfer_buffer_length > 0 &&
1319             urb->transfer_flags & URB_ZERO_PACKET &&
1320             !(urb->transfer_buffer_length % usb_endpoint_maxp(&urb->ep->desc)))
1321                 num_tds = 2;
1322         else
1323                 num_tds = 1;
1324
1325         urb_priv = kzalloc(sizeof(struct urb_priv) +
1326                            num_tds * sizeof(struct xhci_td), mem_flags);
1327         if (!urb_priv)
1328                 return -ENOMEM;
1329
1330         urb_priv->num_tds = num_tds;
1331         urb_priv->num_tds_done = 0;
1332         urb->hcpriv = urb_priv;
1333
1334         trace_xhci_urb_enqueue(urb);
1335
1336         if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1337                 /* Check to see if the max packet size for the default control
1338                  * endpoint changed during FS device enumeration
1339                  */
1340                 if (urb->dev->speed == USB_SPEED_FULL) {
1341                         ret = xhci_check_maxpacket(xhci, slot_id,
1342                                         ep_index, urb);
1343                         if (ret < 0) {
1344                                 xhci_urb_free_priv(urb_priv);
1345                                 urb->hcpriv = NULL;
1346                                 return ret;
1347                         }
1348                 }
1349         }
1350
1351         spin_lock_irqsave(&xhci->lock, flags);
1352
1353         if (xhci->xhc_state & XHCI_STATE_DYING) {
1354                 xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for non-responsive xHCI host.\n",
1355                          urb->ep->desc.bEndpointAddress, urb);
1356                 ret = -ESHUTDOWN;
1357                 goto free_priv;
1358         }
1359
1360         switch (usb_endpoint_type(&urb->ep->desc)) {
1361
1362         case USB_ENDPOINT_XFER_CONTROL:
1363                 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1364                                          slot_id, ep_index);
1365                 break;
1366         case USB_ENDPOINT_XFER_BULK:
1367                 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
1368                 if (ep_state & (EP_GETTING_STREAMS | EP_GETTING_NO_STREAMS)) {
1369                         xhci_warn(xhci, "WARN: Can't enqueue URB, ep in streams transition state %x\n",
1370                                   ep_state);
1371                         ret = -EINVAL;
1372                         break;
1373                 }
1374                 ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1375                                          slot_id, ep_index);
1376                 break;
1377
1378
1379         case USB_ENDPOINT_XFER_INT:
1380                 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1381                                 slot_id, ep_index);
1382                 break;
1383
1384         case USB_ENDPOINT_XFER_ISOC:
1385                 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1386                                 slot_id, ep_index);
1387         }
1388
1389         if (ret) {
1390 free_priv:
1391                 xhci_urb_free_priv(urb_priv);
1392                 urb->hcpriv = NULL;
1393         }
1394         spin_unlock_irqrestore(&xhci->lock, flags);
1395         return ret;
1396 }
1397
1398 /*
1399  * Remove the URB's TD from the endpoint ring.  This may cause the HC to stop
1400  * USB transfers, potentially stopping in the middle of a TRB buffer.  The HC
1401  * should pick up where it left off in the TD, unless a Set Transfer Ring
1402  * Dequeue Pointer is issued.
1403  *
1404  * The TRBs that make up the buffers for the canceled URB will be "removed" from
1405  * the ring.  Since the ring is a contiguous structure, they can't be physically
1406  * removed.  Instead, there are two options:
1407  *
1408  *  1) If the HC is in the middle of processing the URB to be canceled, we
1409  *     simply move the ring's dequeue pointer past those TRBs using the Set
1410  *     Transfer Ring Dequeue Pointer command.  This will be the common case,
1411  *     when drivers timeout on the last submitted URB and attempt to cancel.
1412  *
1413  *  2) If the HC is in the middle of a different TD, we turn the TRBs into a
1414  *     series of 1-TRB transfer no-op TDs.  (No-ops shouldn't be chained.)  The
1415  *     HC will need to invalidate the any TRBs it has cached after the stop
1416  *     endpoint command, as noted in the xHCI 0.95 errata.
1417  *
1418  *  3) The TD may have completed by the time the Stop Endpoint Command
1419  *     completes, so software needs to handle that case too.
1420  *
1421  * This function should protect against the TD enqueueing code ringing the
1422  * doorbell while this code is waiting for a Stop Endpoint command to complete.
1423  * It also needs to account for multiple cancellations on happening at the same
1424  * time for the same endpoint.
1425  *
1426  * Note that this function can be called in any context, or so says
1427  * usb_hcd_unlink_urb()
1428  */
1429 static int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1430 {
1431         unsigned long flags;
1432         int ret, i;
1433         u32 temp;
1434         struct xhci_hcd *xhci;
1435         struct urb_priv *urb_priv;
1436         struct xhci_td *td;
1437         unsigned int ep_index;
1438         struct xhci_ring *ep_ring;
1439         struct xhci_virt_ep *ep;
1440         struct xhci_command *command;
1441         struct xhci_virt_device *vdev;
1442
1443         xhci = hcd_to_xhci(hcd);
1444         spin_lock_irqsave(&xhci->lock, flags);
1445
1446         trace_xhci_urb_dequeue(urb);
1447
1448         /* Make sure the URB hasn't completed or been unlinked already */
1449         ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1450         if (ret)
1451                 goto done;
1452
1453         /* give back URB now if we can't queue it for cancel */
1454         vdev = xhci->devs[urb->dev->slot_id];
1455         urb_priv = urb->hcpriv;
1456         if (!vdev || !urb_priv)
1457                 goto err_giveback;
1458
1459         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1460         ep = &vdev->eps[ep_index];
1461         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1462         if (!ep || !ep_ring)
1463                 goto err_giveback;
1464
1465         /* If xHC is dead take it down and return ALL URBs in xhci_hc_died() */
1466         temp = readl(&xhci->op_regs->status);
1467         if (temp == ~(u32)0 || xhci->xhc_state & XHCI_STATE_DYING) {
1468                 xhci_hc_died(xhci);
1469                 goto done;
1470         }
1471
1472         if (xhci->xhc_state & XHCI_STATE_HALTED) {
1473                 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1474                                 "HC halted, freeing TD manually.");
1475                 for (i = urb_priv->num_tds_done;
1476                      i < urb_priv->num_tds;
1477                      i++) {
1478                         td = &urb_priv->td[i];
1479                         if (!list_empty(&td->td_list))
1480                                 list_del_init(&td->td_list);
1481                         if (!list_empty(&td->cancelled_td_list))
1482                                 list_del_init(&td->cancelled_td_list);
1483                 }
1484                 goto err_giveback;
1485         }
1486
1487         i = urb_priv->num_tds_done;
1488         if (i < urb_priv->num_tds)
1489                 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1490                                 "Cancel URB %p, dev %s, ep 0x%x, "
1491                                 "starting at offset 0x%llx",
1492                                 urb, urb->dev->devpath,
1493                                 urb->ep->desc.bEndpointAddress,
1494                                 (unsigned long long) xhci_trb_virt_to_dma(
1495                                         urb_priv->td[i].start_seg,
1496                                         urb_priv->td[i].first_trb));
1497
1498         for (; i < urb_priv->num_tds; i++) {
1499                 td = &urb_priv->td[i];
1500                 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
1501         }
1502
1503         /* Queue a stop endpoint command, but only if this is
1504          * the first cancellation to be handled.
1505          */
1506         if (!(ep->ep_state & EP_STOP_CMD_PENDING)) {
1507                 command = xhci_alloc_command(xhci, false, false, GFP_ATOMIC);
1508                 if (!command) {
1509                         ret = -ENOMEM;
1510                         goto done;
1511                 }
1512                 ep->ep_state |= EP_STOP_CMD_PENDING;
1513                 ep->stop_cmd_timer.expires = jiffies +
1514                         XHCI_STOP_EP_CMD_TIMEOUT * HZ;
1515                 add_timer(&ep->stop_cmd_timer);
1516                 xhci_queue_stop_endpoint(xhci, command, urb->dev->slot_id,
1517                                          ep_index, 0);
1518                 xhci_ring_cmd_db(xhci);
1519         }
1520 done:
1521         spin_unlock_irqrestore(&xhci->lock, flags);
1522         return ret;
1523
1524 err_giveback:
1525         if (urb_priv)
1526                 xhci_urb_free_priv(urb_priv);
1527         usb_hcd_unlink_urb_from_ep(hcd, urb);
1528         spin_unlock_irqrestore(&xhci->lock, flags);
1529         usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1530         return ret;
1531 }
1532
1533 /* Drop an endpoint from a new bandwidth configuration for this device.
1534  * Only one call to this function is allowed per endpoint before
1535  * check_bandwidth() or reset_bandwidth() must be called.
1536  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1537  * add the endpoint to the schedule with possibly new parameters denoted by a
1538  * different endpoint descriptor in usb_host_endpoint.
1539  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1540  * not allowed.
1541  *
1542  * The USB core will not allow URBs to be queued to an endpoint that is being
1543  * disabled, so there's no need for mutual exclusion to protect
1544  * the xhci->devs[slot_id] structure.
1545  */
1546 static int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1547                 struct usb_host_endpoint *ep)
1548 {
1549         struct xhci_hcd *xhci;
1550         struct xhci_container_ctx *in_ctx, *out_ctx;
1551         struct xhci_input_control_ctx *ctrl_ctx;
1552         unsigned int ep_index;
1553         struct xhci_ep_ctx *ep_ctx;
1554         u32 drop_flag;
1555         u32 new_add_flags, new_drop_flags;
1556         int ret;
1557
1558         ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1559         if (ret <= 0)
1560                 return ret;
1561         xhci = hcd_to_xhci(hcd);
1562         if (xhci->xhc_state & XHCI_STATE_DYING)
1563                 return -ENODEV;
1564
1565         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1566         drop_flag = xhci_get_endpoint_flag(&ep->desc);
1567         if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1568                 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1569                                 __func__, drop_flag);
1570                 return 0;
1571         }
1572
1573         in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1574         out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1575         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1576         if (!ctrl_ctx) {
1577                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1578                                 __func__);
1579                 return 0;
1580         }
1581
1582         ep_index = xhci_get_endpoint_index(&ep->desc);
1583         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1584         /* If the HC already knows the endpoint is disabled,
1585          * or the HCD has noted it is disabled, ignore this request
1586          */
1587         if ((GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) ||
1588             le32_to_cpu(ctrl_ctx->drop_flags) &
1589             xhci_get_endpoint_flag(&ep->desc)) {
1590                 /* Do not warn when called after a usb_device_reset */
1591                 if (xhci->devs[udev->slot_id]->eps[ep_index].ring != NULL)
1592                         xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1593                                   __func__, ep);
1594                 return 0;
1595         }
1596
1597         ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1598         new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1599
1600         ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1601         new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1602
1603         xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1604
1605         if (xhci->quirks & XHCI_MTK_HOST)
1606                 xhci_mtk_drop_ep_quirk(hcd, udev, ep);
1607
1608         xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1609                         (unsigned int) ep->desc.bEndpointAddress,
1610                         udev->slot_id,
1611                         (unsigned int) new_drop_flags,
1612                         (unsigned int) new_add_flags);
1613         return 0;
1614 }
1615
1616 /* Add an endpoint to a new possible bandwidth configuration for this device.
1617  * Only one call to this function is allowed per endpoint before
1618  * check_bandwidth() or reset_bandwidth() must be called.
1619  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1620  * add the endpoint to the schedule with possibly new parameters denoted by a
1621  * different endpoint descriptor in usb_host_endpoint.
1622  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1623  * not allowed.
1624  *
1625  * The USB core will not allow URBs to be queued to an endpoint until the
1626  * configuration or alt setting is installed in the device, so there's no need
1627  * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1628  */
1629 static int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1630                 struct usb_host_endpoint *ep)
1631 {
1632         struct xhci_hcd *xhci;
1633         struct xhci_container_ctx *in_ctx;
1634         unsigned int ep_index;
1635         struct xhci_input_control_ctx *ctrl_ctx;
1636         u32 added_ctxs;
1637         u32 new_add_flags, new_drop_flags;
1638         struct xhci_virt_device *virt_dev;
1639         int ret = 0;
1640
1641         ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1642         if (ret <= 0) {
1643                 /* So we won't queue a reset ep command for a root hub */
1644                 ep->hcpriv = NULL;
1645                 return ret;
1646         }
1647         xhci = hcd_to_xhci(hcd);
1648         if (xhci->xhc_state & XHCI_STATE_DYING)
1649                 return -ENODEV;
1650
1651         added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1652         if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1653                 /* FIXME when we have to issue an evaluate endpoint command to
1654                  * deal with ep0 max packet size changing once we get the
1655                  * descriptors
1656                  */
1657                 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1658                                 __func__, added_ctxs);
1659                 return 0;
1660         }
1661
1662         virt_dev = xhci->devs[udev->slot_id];
1663         in_ctx = virt_dev->in_ctx;
1664         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1665         if (!ctrl_ctx) {
1666                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1667                                 __func__);
1668                 return 0;
1669         }
1670
1671         ep_index = xhci_get_endpoint_index(&ep->desc);
1672         /* If this endpoint is already in use, and the upper layers are trying
1673          * to add it again without dropping it, reject the addition.
1674          */
1675         if (virt_dev->eps[ep_index].ring &&
1676                         !(le32_to_cpu(ctrl_ctx->drop_flags) & added_ctxs)) {
1677                 xhci_warn(xhci, "Trying to add endpoint 0x%x "
1678                                 "without dropping it.\n",
1679                                 (unsigned int) ep->desc.bEndpointAddress);
1680                 return -EINVAL;
1681         }
1682
1683         /* If the HCD has already noted the endpoint is enabled,
1684          * ignore this request.
1685          */
1686         if (le32_to_cpu(ctrl_ctx->add_flags) & added_ctxs) {
1687                 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1688                                 __func__, ep);
1689                 return 0;
1690         }
1691
1692         /*
1693          * Configuration and alternate setting changes must be done in
1694          * process context, not interrupt context (or so documenation
1695          * for usb_set_interface() and usb_set_configuration() claim).
1696          */
1697         if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1698                 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1699                                 __func__, ep->desc.bEndpointAddress);
1700                 return -ENOMEM;
1701         }
1702
1703         if (xhci->quirks & XHCI_MTK_HOST) {
1704                 ret = xhci_mtk_add_ep_quirk(hcd, udev, ep);
1705                 if (ret < 0) {
1706                         xhci_free_endpoint_ring(xhci, virt_dev, ep_index);
1707                         return ret;
1708                 }
1709         }
1710
1711         ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
1712         new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1713
1714         /* If xhci_endpoint_disable() was called for this endpoint, but the
1715          * xHC hasn't been notified yet through the check_bandwidth() call,
1716          * this re-adds a new state for the endpoint from the new endpoint
1717          * descriptors.  We must drop and re-add this endpoint, so we leave the
1718          * drop flags alone.
1719          */
1720         new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1721
1722         /* Store the usb_device pointer for later use */
1723         ep->hcpriv = udev;
1724
1725         xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1726                         (unsigned int) ep->desc.bEndpointAddress,
1727                         udev->slot_id,
1728                         (unsigned int) new_drop_flags,
1729                         (unsigned int) new_add_flags);
1730         return 0;
1731 }
1732
1733 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1734 {
1735         struct xhci_input_control_ctx *ctrl_ctx;
1736         struct xhci_ep_ctx *ep_ctx;
1737         struct xhci_slot_ctx *slot_ctx;
1738         int i;
1739
1740         ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1741         if (!ctrl_ctx) {
1742                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1743                                 __func__);
1744                 return;
1745         }
1746
1747         /* When a device's add flag and drop flag are zero, any subsequent
1748          * configure endpoint command will leave that endpoint's state
1749          * untouched.  Make sure we don't leave any old state in the input
1750          * endpoint contexts.
1751          */
1752         ctrl_ctx->drop_flags = 0;
1753         ctrl_ctx->add_flags = 0;
1754         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1755         slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1756         /* Endpoint 0 is always valid */
1757         slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
1758         for (i = 1; i < 31; i++) {
1759                 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
1760                 ep_ctx->ep_info = 0;
1761                 ep_ctx->ep_info2 = 0;
1762                 ep_ctx->deq = 0;
1763                 ep_ctx->tx_info = 0;
1764         }
1765 }
1766
1767 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
1768                 struct usb_device *udev, u32 *cmd_status)
1769 {
1770         int ret;
1771
1772         switch (*cmd_status) {
1773         case COMP_COMMAND_ABORTED:
1774         case COMP_COMMAND_RING_STOPPED:
1775                 xhci_warn(xhci, "Timeout while waiting for configure endpoint command\n");
1776                 ret = -ETIME;
1777                 break;
1778         case COMP_RESOURCE_ERROR:
1779                 dev_warn(&udev->dev,
1780                          "Not enough host controller resources for new device state.\n");
1781                 ret = -ENOMEM;
1782                 /* FIXME: can we allocate more resources for the HC? */
1783                 break;
1784         case COMP_BANDWIDTH_ERROR:
1785         case COMP_SECONDARY_BANDWIDTH_ERROR:
1786                 dev_warn(&udev->dev,
1787                          "Not enough bandwidth for new device state.\n");
1788                 ret = -ENOSPC;
1789                 /* FIXME: can we go back to the old state? */
1790                 break;
1791         case COMP_TRB_ERROR:
1792                 /* the HCD set up something wrong */
1793                 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
1794                                 "add flag = 1, "
1795                                 "and endpoint is not disabled.\n");
1796                 ret = -EINVAL;
1797                 break;
1798         case COMP_INCOMPATIBLE_DEVICE_ERROR:
1799                 dev_warn(&udev->dev,
1800                          "ERROR: Incompatible device for endpoint configure command.\n");
1801                 ret = -ENODEV;
1802                 break;
1803         case COMP_SUCCESS:
1804                 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1805                                 "Successful Endpoint Configure command");
1806                 ret = 0;
1807                 break;
1808         default:
1809                 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
1810                                 *cmd_status);
1811                 ret = -EINVAL;
1812                 break;
1813         }
1814         return ret;
1815 }
1816
1817 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
1818                 struct usb_device *udev, u32 *cmd_status)
1819 {
1820         int ret;
1821
1822         switch (*cmd_status) {
1823         case COMP_COMMAND_ABORTED:
1824         case COMP_COMMAND_RING_STOPPED:
1825                 xhci_warn(xhci, "Timeout while waiting for evaluate context command\n");
1826                 ret = -ETIME;
1827                 break;
1828         case COMP_PARAMETER_ERROR:
1829                 dev_warn(&udev->dev,
1830                          "WARN: xHCI driver setup invalid evaluate context command.\n");
1831                 ret = -EINVAL;
1832                 break;
1833         case COMP_SLOT_NOT_ENABLED_ERROR:
1834                 dev_warn(&udev->dev,
1835                         "WARN: slot not enabled for evaluate context command.\n");
1836                 ret = -EINVAL;
1837                 break;
1838         case COMP_CONTEXT_STATE_ERROR:
1839                 dev_warn(&udev->dev,
1840                         "WARN: invalid context state for evaluate context command.\n");
1841                 ret = -EINVAL;
1842                 break;
1843         case COMP_INCOMPATIBLE_DEVICE_ERROR:
1844                 dev_warn(&udev->dev,
1845                         "ERROR: Incompatible device for evaluate context command.\n");
1846                 ret = -ENODEV;
1847                 break;
1848         case COMP_MAX_EXIT_LATENCY_TOO_LARGE_ERROR:
1849                 /* Max Exit Latency too large error */
1850                 dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
1851                 ret = -EINVAL;
1852                 break;
1853         case COMP_SUCCESS:
1854                 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1855                                 "Successful evaluate context command");
1856                 ret = 0;
1857                 break;
1858         default:
1859                 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
1860                         *cmd_status);
1861                 ret = -EINVAL;
1862                 break;
1863         }
1864         return ret;
1865 }
1866
1867 static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
1868                 struct xhci_input_control_ctx *ctrl_ctx)
1869 {
1870         u32 valid_add_flags;
1871         u32 valid_drop_flags;
1872
1873         /* Ignore the slot flag (bit 0), and the default control endpoint flag
1874          * (bit 1).  The default control endpoint is added during the Address
1875          * Device command and is never removed until the slot is disabled.
1876          */
1877         valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
1878         valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
1879
1880         /* Use hweight32 to count the number of ones in the add flags, or
1881          * number of endpoints added.  Don't count endpoints that are changed
1882          * (both added and dropped).
1883          */
1884         return hweight32(valid_add_flags) -
1885                 hweight32(valid_add_flags & valid_drop_flags);
1886 }
1887
1888 static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
1889                 struct xhci_input_control_ctx *ctrl_ctx)
1890 {
1891         u32 valid_add_flags;
1892         u32 valid_drop_flags;
1893
1894         valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
1895         valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
1896
1897         return hweight32(valid_drop_flags) -
1898                 hweight32(valid_add_flags & valid_drop_flags);
1899 }
1900
1901 /*
1902  * We need to reserve the new number of endpoints before the configure endpoint
1903  * command completes.  We can't subtract the dropped endpoints from the number
1904  * of active endpoints until the command completes because we can oversubscribe
1905  * the host in this case:
1906  *
1907  *  - the first configure endpoint command drops more endpoints than it adds
1908  *  - a second configure endpoint command that adds more endpoints is queued
1909  *  - the first configure endpoint command fails, so the config is unchanged
1910  *  - the second command may succeed, even though there isn't enough resources
1911  *
1912  * Must be called with xhci->lock held.
1913  */
1914 static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
1915                 struct xhci_input_control_ctx *ctrl_ctx)
1916 {
1917         u32 added_eps;
1918
1919         added_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
1920         if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
1921                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1922                                 "Not enough ep ctxs: "
1923                                 "%u active, need to add %u, limit is %u.",
1924                                 xhci->num_active_eps, added_eps,
1925                                 xhci->limit_active_eps);
1926                 return -ENOMEM;
1927         }
1928         xhci->num_active_eps += added_eps;
1929         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1930                         "Adding %u ep ctxs, %u now active.", added_eps,
1931                         xhci->num_active_eps);
1932         return 0;
1933 }
1934
1935 /*
1936  * The configure endpoint was failed by the xHC for some other reason, so we
1937  * need to revert the resources that failed configuration would have used.
1938  *
1939  * Must be called with xhci->lock held.
1940  */
1941 static void xhci_free_host_resources(struct xhci_hcd *xhci,
1942                 struct xhci_input_control_ctx *ctrl_ctx)
1943 {
1944         u32 num_failed_eps;
1945
1946         num_failed_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
1947         xhci->num_active_eps -= num_failed_eps;
1948         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1949                         "Removing %u failed ep ctxs, %u now active.",
1950                         num_failed_eps,
1951                         xhci->num_active_eps);
1952 }
1953
1954 /*
1955  * Now that the command has completed, clean up the active endpoint count by
1956  * subtracting out the endpoints that were dropped (but not changed).
1957  *
1958  * Must be called with xhci->lock held.
1959  */
1960 static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
1961                 struct xhci_input_control_ctx *ctrl_ctx)
1962 {
1963         u32 num_dropped_eps;
1964
1965         num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, ctrl_ctx);
1966         xhci->num_active_eps -= num_dropped_eps;
1967         if (num_dropped_eps)
1968                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1969                                 "Removing %u dropped ep ctxs, %u now active.",
1970                                 num_dropped_eps,
1971                                 xhci->num_active_eps);
1972 }
1973
1974 static unsigned int xhci_get_block_size(struct usb_device *udev)
1975 {
1976         switch (udev->speed) {
1977         case USB_SPEED_LOW:
1978         case USB_SPEED_FULL:
1979                 return FS_BLOCK;
1980         case USB_SPEED_HIGH:
1981                 return HS_BLOCK;
1982         case USB_SPEED_SUPER:
1983         case USB_SPEED_SUPER_PLUS:
1984                 return SS_BLOCK;
1985         case USB_SPEED_UNKNOWN:
1986         case USB_SPEED_WIRELESS:
1987         default:
1988                 /* Should never happen */
1989                 return 1;
1990         }
1991 }
1992
1993 static unsigned int
1994 xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
1995 {
1996         if (interval_bw->overhead[LS_OVERHEAD_TYPE])
1997                 return LS_OVERHEAD;
1998         if (interval_bw->overhead[FS_OVERHEAD_TYPE])
1999                 return FS_OVERHEAD;
2000         return HS_OVERHEAD;
2001 }
2002
2003 /* If we are changing a LS/FS device under a HS hub,
2004  * make sure (if we are activating a new TT) that the HS bus has enough
2005  * bandwidth for this new TT.
2006  */
2007 static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
2008                 struct xhci_virt_device *virt_dev,
2009                 int old_active_eps)
2010 {
2011         struct xhci_interval_bw_table *bw_table;
2012         struct xhci_tt_bw_info *tt_info;
2013
2014         /* Find the bandwidth table for the root port this TT is attached to. */
2015         bw_table = &xhci->rh_bw[virt_dev->real_port - 1].bw_table;
2016         tt_info = virt_dev->tt_info;
2017         /* If this TT already had active endpoints, the bandwidth for this TT
2018          * has already been added.  Removing all periodic endpoints (and thus
2019          * making the TT enactive) will only decrease the bandwidth used.
2020          */
2021         if (old_active_eps)
2022                 return 0;
2023         if (old_active_eps == 0 && tt_info->active_eps != 0) {
2024                 if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
2025                         return -ENOMEM;
2026                 return 0;
2027         }
2028         /* Not sure why we would have no new active endpoints...
2029          *
2030          * Maybe because of an Evaluate Context change for a hub update or a
2031          * control endpoint 0 max packet size change?
2032          * FIXME: skip the bandwidth calculation in that case.
2033          */
2034         return 0;
2035 }
2036
2037 static int xhci_check_ss_bw(struct xhci_hcd *xhci,
2038                 struct xhci_virt_device *virt_dev)
2039 {
2040         unsigned int bw_reserved;
2041
2042         bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
2043         if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
2044                 return -ENOMEM;
2045
2046         bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
2047         if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
2048                 return -ENOMEM;
2049
2050         return 0;
2051 }
2052
2053 /*
2054  * This algorithm is a very conservative estimate of the worst-case scheduling
2055  * scenario for any one interval.  The hardware dynamically schedules the
2056  * packets, so we can't tell which microframe could be the limiting factor in
2057  * the bandwidth scheduling.  This only takes into account periodic endpoints.
2058  *
2059  * Obviously, we can't solve an NP complete problem to find the minimum worst
2060  * case scenario.  Instead, we come up with an estimate that is no less than
2061  * the worst case bandwidth used for any one microframe, but may be an
2062  * over-estimate.
2063  *
2064  * We walk the requirements for each endpoint by interval, starting with the
2065  * smallest interval, and place packets in the schedule where there is only one
2066  * possible way to schedule packets for that interval.  In order to simplify
2067  * this algorithm, we record the largest max packet size for each interval, and
2068  * assume all packets will be that size.
2069  *
2070  * For interval 0, we obviously must schedule all packets for each interval.
2071  * The bandwidth for interval 0 is just the amount of data to be transmitted
2072  * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2073  * the number of packets).
2074  *
2075  * For interval 1, we have two possible microframes to schedule those packets
2076  * in.  For this algorithm, if we can schedule the same number of packets for
2077  * each possible scheduling opportunity (each microframe), we will do so.  The
2078  * remaining number of packets will be saved to be transmitted in the gaps in
2079  * the next interval's scheduling sequence.
2080  *
2081  * As we move those remaining packets to be scheduled with interval 2 packets,
2082  * we have to double the number of remaining packets to transmit.  This is
2083  * because the intervals are actually powers of 2, and we would be transmitting
2084  * the previous interval's packets twice in this interval.  We also have to be
2085  * sure that when we look at the largest max packet size for this interval, we
2086  * also look at the largest max packet size for the remaining packets and take
2087  * the greater of the two.
2088  *
2089  * The algorithm continues to evenly distribute packets in each scheduling
2090  * opportunity, and push the remaining packets out, until we get to the last
2091  * interval.  Then those packets and their associated overhead are just added
2092  * to the bandwidth used.
2093  */
2094 static int xhci_check_bw_table(struct xhci_hcd *xhci,
2095                 struct xhci_virt_device *virt_dev,
2096                 int old_active_eps)
2097 {
2098         unsigned int bw_reserved;
2099         unsigned int max_bandwidth;
2100         unsigned int bw_used;
2101         unsigned int block_size;
2102         struct xhci_interval_bw_table *bw_table;
2103         unsigned int packet_size = 0;
2104         unsigned int overhead = 0;
2105         unsigned int packets_transmitted = 0;
2106         unsigned int packets_remaining = 0;
2107         unsigned int i;
2108
2109         if (virt_dev->udev->speed >= USB_SPEED_SUPER)
2110                 return xhci_check_ss_bw(xhci, virt_dev);
2111
2112         if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2113                 max_bandwidth = HS_BW_LIMIT;
2114                 /* Convert percent of bus BW reserved to blocks reserved */
2115                 bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2116         } else {
2117                 max_bandwidth = FS_BW_LIMIT;
2118                 bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2119         }
2120
2121         bw_table = virt_dev->bw_table;
2122         /* We need to translate the max packet size and max ESIT payloads into
2123          * the units the hardware uses.
2124          */
2125         block_size = xhci_get_block_size(virt_dev->udev);
2126
2127         /* If we are manipulating a LS/FS device under a HS hub, double check
2128          * that the HS bus has enough bandwidth if we are activing a new TT.
2129          */
2130         if (virt_dev->tt_info) {
2131                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2132                                 "Recalculating BW for rootport %u",
2133                                 virt_dev->real_port);
2134                 if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2135                         xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2136                                         "newly activated TT.\n");
2137                         return -ENOMEM;
2138                 }
2139                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2140                                 "Recalculating BW for TT slot %u port %u",
2141                                 virt_dev->tt_info->slot_id,
2142                                 virt_dev->tt_info->ttport);
2143         } else {
2144                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2145                                 "Recalculating BW for rootport %u",
2146                                 virt_dev->real_port);
2147         }
2148
2149         /* Add in how much bandwidth will be used for interval zero, or the
2150          * rounded max ESIT payload + number of packets * largest overhead.
2151          */
2152         bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2153                 bw_table->interval_bw[0].num_packets *
2154                 xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2155
2156         for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2157                 unsigned int bw_added;
2158                 unsigned int largest_mps;
2159                 unsigned int interval_overhead;
2160
2161                 /*
2162                  * How many packets could we transmit in this interval?
2163                  * If packets didn't fit in the previous interval, we will need
2164                  * to transmit that many packets twice within this interval.
2165                  */
2166                 packets_remaining = 2 * packets_remaining +
2167                         bw_table->interval_bw[i].num_packets;
2168
2169                 /* Find the largest max packet size of this or the previous
2170                  * interval.
2171                  */
2172                 if (list_empty(&bw_table->interval_bw[i].endpoints))
2173                         largest_mps = 0;
2174                 else {
2175                         struct xhci_virt_ep *virt_ep;
2176                         struct list_head *ep_entry;
2177
2178                         ep_entry = bw_table->interval_bw[i].endpoints.next;
2179                         virt_ep = list_entry(ep_entry,
2180                                         struct xhci_virt_ep, bw_endpoint_list);
2181                         /* Convert to blocks, rounding up */
2182                         largest_mps = DIV_ROUND_UP(
2183                                         virt_ep->bw_info.max_packet_size,
2184                                         block_size);
2185                 }
2186                 if (largest_mps > packet_size)
2187                         packet_size = largest_mps;
2188
2189                 /* Use the larger overhead of this or the previous interval. */
2190                 interval_overhead = xhci_get_largest_overhead(
2191                                 &bw_table->interval_bw[i]);
2192                 if (interval_overhead > overhead)
2193                         overhead = interval_overhead;
2194
2195                 /* How many packets can we evenly distribute across
2196                  * (1 << (i + 1)) possible scheduling opportunities?
2197                  */
2198                 packets_transmitted = packets_remaining >> (i + 1);
2199
2200                 /* Add in the bandwidth used for those scheduled packets */
2201                 bw_added = packets_transmitted * (overhead + packet_size);
2202
2203                 /* How many packets do we have remaining to transmit? */
2204                 packets_remaining = packets_remaining % (1 << (i + 1));
2205
2206                 /* What largest max packet size should those packets have? */
2207                 /* If we've transmitted all packets, don't carry over the
2208                  * largest packet size.
2209                  */
2210                 if (packets_remaining == 0) {
2211                         packet_size = 0;
2212                         overhead = 0;
2213                 } else if (packets_transmitted > 0) {
2214                         /* Otherwise if we do have remaining packets, and we've
2215                          * scheduled some packets in this interval, take the
2216                          * largest max packet size from endpoints with this
2217                          * interval.
2218                          */
2219                         packet_size = largest_mps;
2220                         overhead = interval_overhead;
2221                 }
2222                 /* Otherwise carry over packet_size and overhead from the last
2223                  * time we had a remainder.
2224                  */
2225                 bw_used += bw_added;
2226                 if (bw_used > max_bandwidth) {
2227                         xhci_warn(xhci, "Not enough bandwidth. "
2228                                         "Proposed: %u, Max: %u\n",
2229                                 bw_used, max_bandwidth);
2230                         return -ENOMEM;
2231                 }
2232         }
2233         /*
2234          * Ok, we know we have some packets left over after even-handedly
2235          * scheduling interval 15.  We don't know which microframes they will
2236          * fit into, so we over-schedule and say they will be scheduled every
2237          * microframe.
2238          */
2239         if (packets_remaining > 0)
2240                 bw_used += overhead + packet_size;
2241
2242         if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2243                 unsigned int port_index = virt_dev->real_port - 1;
2244
2245                 /* OK, we're manipulating a HS device attached to a
2246                  * root port bandwidth domain.  Include the number of active TTs
2247                  * in the bandwidth used.
2248                  */
2249                 bw_used += TT_HS_OVERHEAD *
2250                         xhci->rh_bw[port_index].num_active_tts;
2251         }
2252
2253         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2254                 "Final bandwidth: %u, Limit: %u, Reserved: %u, "
2255                 "Available: %u " "percent",
2256                 bw_used, max_bandwidth, bw_reserved,
2257                 (max_bandwidth - bw_used - bw_reserved) * 100 /
2258                 max_bandwidth);
2259
2260         bw_used += bw_reserved;
2261         if (bw_used > max_bandwidth) {
2262                 xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2263                                 bw_used, max_bandwidth);
2264                 return -ENOMEM;
2265         }
2266
2267         bw_table->bw_used = bw_used;
2268         return 0;
2269 }
2270
2271 static bool xhci_is_async_ep(unsigned int ep_type)
2272 {
2273         return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2274                                         ep_type != ISOC_IN_EP &&
2275                                         ep_type != INT_IN_EP);
2276 }
2277
2278 static bool xhci_is_sync_in_ep(unsigned int ep_type)
2279 {
2280         return (ep_type == ISOC_IN_EP || ep_type == INT_IN_EP);
2281 }
2282
2283 static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2284 {
2285         unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2286
2287         if (ep_bw->ep_interval == 0)
2288                 return SS_OVERHEAD_BURST +
2289                         (ep_bw->mult * ep_bw->num_packets *
2290                                         (SS_OVERHEAD + mps));
2291         return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2292                                 (SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2293                                 1 << ep_bw->ep_interval);
2294
2295 }
2296
2297 static void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2298                 struct xhci_bw_info *ep_bw,
2299                 struct xhci_interval_bw_table *bw_table,
2300                 struct usb_device *udev,
2301                 struct xhci_virt_ep *virt_ep,
2302                 struct xhci_tt_bw_info *tt_info)
2303 {
2304         struct xhci_interval_bw *interval_bw;
2305         int normalized_interval;
2306
2307         if (xhci_is_async_ep(ep_bw->type))
2308                 return;
2309
2310         if (udev->speed >= USB_SPEED_SUPER) {
2311                 if (xhci_is_sync_in_ep(ep_bw->type))
2312                         xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2313                                 xhci_get_ss_bw_consumed(ep_bw);
2314                 else
2315                         xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2316                                 xhci_get_ss_bw_consumed(ep_bw);
2317                 return;
2318         }
2319
2320         /* SuperSpeed endpoints never get added to intervals in the table, so
2321          * this check is only valid for HS/FS/LS devices.
2322          */
2323         if (list_empty(&virt_ep->bw_endpoint_list))
2324                 return;
2325         /* For LS/FS devices, we need to translate the interval expressed in
2326          * microframes to frames.
2327          */
2328         if (udev->speed == USB_SPEED_HIGH)
2329                 normalized_interval = ep_bw->ep_interval;
2330         else
2331                 normalized_interval = ep_bw->ep_interval - 3;
2332
2333         if (normalized_interval == 0)
2334                 bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2335         interval_bw = &bw_table->interval_bw[normalized_interval];
2336         interval_bw->num_packets -= ep_bw->num_packets;
2337         switch (udev->speed) {
2338         case USB_SPEED_LOW:
2339                 interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2340                 break;
2341         case USB_SPEED_FULL:
2342                 interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2343                 break;
2344         case USB_SPEED_HIGH:
2345                 interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2346                 break;
2347         case USB_SPEED_SUPER:
2348         case USB_SPEED_SUPER_PLUS:
2349         case USB_SPEED_UNKNOWN:
2350         case USB_SPEED_WIRELESS:
2351                 /* Should never happen because only LS/FS/HS endpoints will get
2352                  * added to the endpoint list.
2353                  */
2354                 return;
2355         }
2356         if (tt_info)
2357                 tt_info->active_eps -= 1;
2358         list_del_init(&virt_ep->bw_endpoint_list);
2359 }
2360
2361 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2362                 struct xhci_bw_info *ep_bw,
2363                 struct xhci_interval_bw_table *bw_table,
2364                 struct usb_device *udev,
2365                 struct xhci_virt_ep *virt_ep,
2366                 struct xhci_tt_bw_info *tt_info)
2367 {
2368         struct xhci_interval_bw *interval_bw;
2369         struct xhci_virt_ep *smaller_ep;
2370         int normalized_interval;
2371
2372         if (xhci_is_async_ep(ep_bw->type))
2373                 return;
2374
2375         if (udev->speed == USB_SPEED_SUPER) {
2376                 if (xhci_is_sync_in_ep(ep_bw->type))
2377                         xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2378                                 xhci_get_ss_bw_consumed(ep_bw);
2379                 else
2380                         xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2381                                 xhci_get_ss_bw_consumed(ep_bw);
2382                 return;
2383         }
2384
2385         /* For LS/FS devices, we need to translate the interval expressed in
2386          * microframes to frames.
2387          */
2388         if (udev->speed == USB_SPEED_HIGH)
2389                 normalized_interval = ep_bw->ep_interval;
2390         else
2391                 normalized_interval = ep_bw->ep_interval - 3;
2392
2393         if (normalized_interval == 0)
2394                 bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2395         interval_bw = &bw_table->interval_bw[normalized_interval];
2396         interval_bw->num_packets += ep_bw->num_packets;
2397         switch (udev->speed) {
2398         case USB_SPEED_LOW:
2399                 interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2400                 break;
2401         case USB_SPEED_FULL:
2402                 interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2403                 break;
2404         case USB_SPEED_HIGH:
2405                 interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2406                 break;
2407         case USB_SPEED_SUPER:
2408         case USB_SPEED_SUPER_PLUS:
2409         case USB_SPEED_UNKNOWN:
2410         case USB_SPEED_WIRELESS:
2411                 /* Should never happen because only LS/FS/HS endpoints will get
2412                  * added to the endpoint list.
2413                  */
2414                 return;
2415         }
2416
2417         if (tt_info)
2418                 tt_info->active_eps += 1;
2419         /* Insert the endpoint into the list, largest max packet size first. */
2420         list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2421                         bw_endpoint_list) {
2422                 if (ep_bw->max_packet_size >=
2423                                 smaller_ep->bw_info.max_packet_size) {
2424                         /* Add the new ep before the smaller endpoint */
2425                         list_add_tail(&virt_ep->bw_endpoint_list,
2426                                         &smaller_ep->bw_endpoint_list);
2427                         return;
2428                 }
2429         }
2430         /* Add the new endpoint at the end of the list. */
2431         list_add_tail(&virt_ep->bw_endpoint_list,
2432                         &interval_bw->endpoints);
2433 }
2434
2435 void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2436                 struct xhci_virt_device *virt_dev,
2437                 int old_active_eps)
2438 {
2439         struct xhci_root_port_bw_info *rh_bw_info;
2440         if (!virt_dev->tt_info)
2441                 return;
2442
2443         rh_bw_info = &xhci->rh_bw[virt_dev->real_port - 1];
2444         if (old_active_eps == 0 &&
2445                                 virt_dev->tt_info->active_eps != 0) {
2446                 rh_bw_info->num_active_tts += 1;
2447                 rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2448         } else if (old_active_eps != 0 &&
2449                                 virt_dev->tt_info->active_eps == 0) {
2450                 rh_bw_info->num_active_tts -= 1;
2451                 rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2452         }
2453 }
2454
2455 static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2456                 struct xhci_virt_device *virt_dev,
2457                 struct xhci_container_ctx *in_ctx)
2458 {
2459         struct xhci_bw_info ep_bw_info[31];
2460         int i;
2461         struct xhci_input_control_ctx *ctrl_ctx;
2462         int old_active_eps = 0;
2463
2464         if (virt_dev->tt_info)
2465                 old_active_eps = virt_dev->tt_info->active_eps;
2466
2467         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2468         if (!ctrl_ctx) {
2469                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2470                                 __func__);
2471                 return -ENOMEM;
2472         }
2473
2474         for (i = 0; i < 31; i++) {
2475                 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2476                         continue;
2477
2478                 /* Make a copy of the BW info in case we need to revert this */
2479                 memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2480                                 sizeof(ep_bw_info[i]));
2481                 /* Drop the endpoint from the interval table if the endpoint is
2482                  * being dropped or changed.
2483                  */
2484                 if (EP_IS_DROPPED(ctrl_ctx, i))
2485                         xhci_drop_ep_from_interval_table(xhci,
2486                                         &virt_dev->eps[i].bw_info,
2487                                         virt_dev->bw_table,
2488                                         virt_dev->udev,
2489                                         &virt_dev->eps[i],
2490                                         virt_dev->tt_info);
2491         }
2492         /* Overwrite the information stored in the endpoints' bw_info */
2493         xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2494         for (i = 0; i < 31; i++) {
2495                 /* Add any changed or added endpoints to the interval table */
2496                 if (EP_IS_ADDED(ctrl_ctx, i))
2497                         xhci_add_ep_to_interval_table(xhci,
2498                                         &virt_dev->eps[i].bw_info,
2499                                         virt_dev->bw_table,
2500                                         virt_dev->udev,
2501                                         &virt_dev->eps[i],
2502                                         virt_dev->tt_info);
2503         }
2504
2505         if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2506                 /* Ok, this fits in the bandwidth we have.
2507                  * Update the number of active TTs.
2508                  */
2509                 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2510                 return 0;
2511         }
2512
2513         /* We don't have enough bandwidth for this, revert the stored info. */
2514         for (i = 0; i < 31; i++) {
2515                 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2516                         continue;
2517
2518                 /* Drop the new copies of any added or changed endpoints from
2519                  * the interval table.
2520                  */
2521                 if (EP_IS_ADDED(ctrl_ctx, i)) {
2522                         xhci_drop_ep_from_interval_table(xhci,
2523                                         &virt_dev->eps[i].bw_info,
2524                                         virt_dev->bw_table,
2525                                         virt_dev->udev,
2526                                         &virt_dev->eps[i],
2527                                         virt_dev->tt_info);
2528                 }
2529                 /* Revert the endpoint back to its old information */
2530                 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2531                                 sizeof(ep_bw_info[i]));
2532                 /* Add any changed or dropped endpoints back into the table */
2533                 if (EP_IS_DROPPED(ctrl_ctx, i))
2534                         xhci_add_ep_to_interval_table(xhci,
2535                                         &virt_dev->eps[i].bw_info,
2536                                         virt_dev->bw_table,
2537                                         virt_dev->udev,
2538                                         &virt_dev->eps[i],
2539                                         virt_dev->tt_info);
2540         }
2541         return -ENOMEM;
2542 }
2543
2544
2545 /* Issue a configure endpoint command or evaluate context command
2546  * and wait for it to finish.
2547  */
2548 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2549                 struct usb_device *udev,
2550                 struct xhci_command *command,
2551                 bool ctx_change, bool must_succeed)
2552 {
2553         int ret;
2554         unsigned long flags;
2555         struct xhci_input_control_ctx *ctrl_ctx;
2556         struct xhci_virt_device *virt_dev;
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         if (!ctx_change)
2596                 ret = xhci_queue_configure_endpoint(xhci, command,
2597                                 command->in_ctx->dma,
2598                                 udev->slot_id, must_succeed);
2599         else
2600                 ret = xhci_queue_evaluate_context(xhci, command,
2601                                 command->in_ctx->dma,
2602                                 udev->slot_id, must_succeed);
2603         if (ret < 0) {
2604                 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2605                         xhci_free_host_resources(xhci, ctrl_ctx);
2606                 spin_unlock_irqrestore(&xhci->lock, flags);
2607                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
2608                                 "FIXME allocate a new ring segment");
2609                 return -ENOMEM;
2610         }
2611         xhci_ring_cmd_db(xhci);
2612         spin_unlock_irqrestore(&xhci->lock, flags);
2613
2614         /* Wait for the configure endpoint command to complete */
2615         wait_for_completion(command->completion);
2616
2617         if (!ctx_change)
2618                 ret = xhci_configure_endpoint_result(xhci, udev,
2619                                                      &command->status);
2620         else
2621                 ret = xhci_evaluate_context_result(xhci, udev,
2622                                                    &command->status);
2623
2624         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
2625                 spin_lock_irqsave(&xhci->lock, flags);
2626                 /* If the command failed, remove the reserved resources.
2627                  * Otherwise, clean up the estimate to include dropped eps.
2628                  */
2629                 if (ret)
2630                         xhci_free_host_resources(xhci, ctrl_ctx);
2631                 else
2632                         xhci_finish_resource_reservation(xhci, ctrl_ctx);
2633                 spin_unlock_irqrestore(&xhci->lock, flags);
2634         }
2635         return ret;
2636 }
2637
2638 static void xhci_check_bw_drop_ep_streams(struct xhci_hcd *xhci,
2639         struct xhci_virt_device *vdev, int i)
2640 {
2641         struct xhci_virt_ep *ep = &vdev->eps[i];
2642
2643         if (ep->ep_state & EP_HAS_STREAMS) {
2644                 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on set_interface, freeing streams.\n",
2645                                 xhci_get_endpoint_address(i));
2646                 xhci_free_stream_info(xhci, ep->stream_info);
2647                 ep->stream_info = NULL;
2648                 ep->ep_state &= ~EP_HAS_STREAMS;
2649         }
2650 }
2651
2652 /* Called after one or more calls to xhci_add_endpoint() or
2653  * xhci_drop_endpoint().  If this call fails, the USB core is expected
2654  * to call xhci_reset_bandwidth().
2655  *
2656  * Since we are in the middle of changing either configuration or
2657  * installing a new alt setting, the USB core won't allow URBs to be
2658  * enqueued for any endpoint on the old config or interface.  Nothing
2659  * else should be touching the xhci->devs[slot_id] structure, so we
2660  * don't need to take the xhci->lock for manipulating that.
2661  */
2662 static int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2663 {
2664         int i;
2665         int ret = 0;
2666         struct xhci_hcd *xhci;
2667         struct xhci_virt_device *virt_dev;
2668         struct xhci_input_control_ctx *ctrl_ctx;
2669         struct xhci_slot_ctx *slot_ctx;
2670         struct xhci_command *command;
2671
2672         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2673         if (ret <= 0)
2674                 return ret;
2675         xhci = hcd_to_xhci(hcd);
2676         if ((xhci->xhc_state & XHCI_STATE_DYING) ||
2677                 (xhci->xhc_state & XHCI_STATE_REMOVING))
2678                 return -ENODEV;
2679
2680         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2681         virt_dev = xhci->devs[udev->slot_id];
2682
2683         command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
2684         if (!command)
2685                 return -ENOMEM;
2686
2687         command->in_ctx = virt_dev->in_ctx;
2688
2689         /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
2690         ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2691         if (!ctrl_ctx) {
2692                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2693                                 __func__);
2694                 ret = -ENOMEM;
2695                 goto command_cleanup;
2696         }
2697         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2698         ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
2699         ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
2700
2701         /* Don't issue the command if there's no endpoints to update. */
2702         if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
2703             ctrl_ctx->drop_flags == 0) {
2704                 ret = 0;
2705                 goto command_cleanup;
2706         }
2707         /* Fix up Context Entries field. Minimum value is EP0 == BIT(1). */
2708         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2709         for (i = 31; i >= 1; i--) {
2710                 __le32 le32 = cpu_to_le32(BIT(i));
2711
2712                 if ((virt_dev->eps[i-1].ring && !(ctrl_ctx->drop_flags & le32))
2713                     || (ctrl_ctx->add_flags & le32) || i == 1) {
2714                         slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2715                         slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(i));
2716                         break;
2717                 }
2718         }
2719
2720         ret = xhci_configure_endpoint(xhci, udev, command,
2721                         false, false);
2722         if (ret)
2723                 /* Callee should call reset_bandwidth() */
2724                 goto command_cleanup;
2725
2726         /* Free any rings that were dropped, but not changed. */
2727         for (i = 1; i < 31; i++) {
2728                 if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
2729                     !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1)))) {
2730                         xhci_free_endpoint_ring(xhci, virt_dev, i);
2731                         xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2732                 }
2733         }
2734         xhci_zero_in_ctx(xhci, virt_dev);
2735         /*
2736          * Install any rings for completely new endpoints or changed endpoints,
2737          * and free any old rings from changed endpoints.
2738          */
2739         for (i = 1; i < 31; i++) {
2740                 if (!virt_dev->eps[i].new_ring)
2741                         continue;
2742                 /* Only free the old ring if it exists.
2743                  * It may not if this is the first add of an endpoint.
2744                  */
2745                 if (virt_dev->eps[i].ring) {
2746                         xhci_free_endpoint_ring(xhci, virt_dev, i);
2747                 }
2748                 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2749                 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
2750                 virt_dev->eps[i].new_ring = NULL;
2751         }
2752 command_cleanup:
2753         kfree(command->completion);
2754         kfree(command);
2755
2756         return ret;
2757 }
2758
2759 static void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2760 {
2761         struct xhci_hcd *xhci;
2762         struct xhci_virt_device *virt_dev;
2763         int i, ret;
2764
2765         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2766         if (ret <= 0)
2767                 return;
2768         xhci = hcd_to_xhci(hcd);
2769
2770         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2771         virt_dev = xhci->devs[udev->slot_id];
2772         /* Free any rings allocated for added endpoints */
2773         for (i = 0; i < 31; i++) {
2774                 if (virt_dev->eps[i].new_ring) {
2775                         xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
2776                         virt_dev->eps[i].new_ring = NULL;
2777                 }
2778         }
2779         xhci_zero_in_ctx(xhci, virt_dev);
2780 }
2781
2782 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
2783                 struct xhci_container_ctx *in_ctx,
2784                 struct xhci_container_ctx *out_ctx,
2785                 struct xhci_input_control_ctx *ctrl_ctx,
2786                 u32 add_flags, u32 drop_flags)
2787 {
2788         ctrl_ctx->add_flags = cpu_to_le32(add_flags);
2789         ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
2790         xhci_slot_copy(xhci, in_ctx, out_ctx);
2791         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2792 }
2793
2794 static void xhci_setup_input_ctx_for_quirk(struct xhci_hcd *xhci,
2795                 unsigned int slot_id, unsigned int ep_index,
2796                 struct xhci_dequeue_state *deq_state)
2797 {
2798         struct xhci_input_control_ctx *ctrl_ctx;
2799         struct xhci_container_ctx *in_ctx;
2800         struct xhci_ep_ctx *ep_ctx;
2801         u32 added_ctxs;
2802         dma_addr_t addr;
2803
2804         in_ctx = xhci->devs[slot_id]->in_ctx;
2805         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2806         if (!ctrl_ctx) {
2807                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2808                                 __func__);
2809                 return;
2810         }
2811
2812         xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
2813                         xhci->devs[slot_id]->out_ctx, ep_index);
2814         ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
2815         addr = xhci_trb_virt_to_dma(deq_state->new_deq_seg,
2816                         deq_state->new_deq_ptr);
2817         if (addr == 0) {
2818                 xhci_warn(xhci, "WARN Cannot submit config ep after "
2819                                 "reset ep command\n");
2820                 xhci_warn(xhci, "WARN deq seg = %p, deq ptr = %p\n",
2821                                 deq_state->new_deq_seg,
2822                                 deq_state->new_deq_ptr);
2823                 return;
2824         }
2825         ep_ctx->deq = cpu_to_le64(addr | deq_state->new_cycle_state);
2826
2827         added_ctxs = xhci_get_endpoint_flag_from_index(ep_index);
2828         xhci_setup_input_ctx_for_config_ep(xhci, xhci->devs[slot_id]->in_ctx,
2829                         xhci->devs[slot_id]->out_ctx, ctrl_ctx,
2830                         added_ctxs, added_ctxs);
2831 }
2832
2833 void xhci_cleanup_stalled_ring(struct xhci_hcd *xhci, unsigned int ep_index,
2834                                unsigned int stream_id, struct xhci_td *td)
2835 {
2836         struct xhci_dequeue_state deq_state;
2837         struct xhci_virt_ep *ep;
2838         struct usb_device *udev = td->urb->dev;
2839
2840         xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
2841                         "Cleaning up stalled endpoint ring");
2842         ep = &xhci->devs[udev->slot_id]->eps[ep_index];
2843         /* We need to move the HW's dequeue pointer past this TD,
2844          * or it will attempt to resend it on the next doorbell ring.
2845          */
2846         xhci_find_new_dequeue_state(xhci, udev->slot_id,
2847                         ep_index, stream_id, td, &deq_state);
2848
2849         if (!deq_state.new_deq_ptr || !deq_state.new_deq_seg)
2850                 return;
2851
2852         /* HW with the reset endpoint quirk will use the saved dequeue state to
2853          * issue a configure endpoint command later.
2854          */
2855         if (!(xhci->quirks & XHCI_RESET_EP_QUIRK)) {
2856                 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
2857                                 "Queueing new dequeue state");
2858                 xhci_queue_new_dequeue_state(xhci, udev->slot_id,
2859                                 ep_index, &deq_state);
2860         } else {
2861                 /* Better hope no one uses the input context between now and the
2862                  * reset endpoint completion!
2863                  * XXX: No idea how this hardware will react when stream rings
2864                  * are enabled.
2865                  */
2866                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2867                                 "Setting up input context for "
2868                                 "configure endpoint command");
2869                 xhci_setup_input_ctx_for_quirk(xhci, udev->slot_id,
2870                                 ep_index, &deq_state);
2871         }
2872 }
2873
2874 /* Called when clearing halted device. The core should have sent the control
2875  * message to clear the device halt condition. The host side of the halt should
2876  * already be cleared with a reset endpoint command issued when the STALL tx
2877  * event was received.
2878  *
2879  * Context: in_interrupt
2880  */
2881
2882 static void xhci_endpoint_reset(struct usb_hcd *hcd,
2883                 struct usb_host_endpoint *ep)
2884 {
2885         struct xhci_hcd *xhci;
2886
2887         xhci = hcd_to_xhci(hcd);
2888
2889         /*
2890          * We might need to implement the config ep cmd in xhci 4.8.1 note:
2891          * The Reset Endpoint Command may only be issued to endpoints in the
2892          * Halted state. If software wishes reset the Data Toggle or Sequence
2893          * Number of an endpoint that isn't in the Halted state, then software
2894          * may issue a Configure Endpoint Command with the Drop and Add bits set
2895          * for the target endpoint. that is in the Stopped state.
2896          */
2897
2898         /* For now just print debug to follow the situation */
2899         xhci_dbg(xhci, "Endpoint 0x%x ep reset callback called\n",
2900                  ep->desc.bEndpointAddress);
2901 }
2902
2903 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
2904                 struct usb_device *udev, struct usb_host_endpoint *ep,
2905                 unsigned int slot_id)
2906 {
2907         int ret;
2908         unsigned int ep_index;
2909         unsigned int ep_state;
2910
2911         if (!ep)
2912                 return -EINVAL;
2913         ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
2914         if (ret <= 0)
2915                 return -EINVAL;
2916         if (usb_ss_max_streams(&ep->ss_ep_comp) == 0) {
2917                 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
2918                                 " descriptor for ep 0x%x does not support streams\n",
2919                                 ep->desc.bEndpointAddress);
2920                 return -EINVAL;
2921         }
2922
2923         ep_index = xhci_get_endpoint_index(&ep->desc);
2924         ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
2925         if (ep_state & EP_HAS_STREAMS ||
2926                         ep_state & EP_GETTING_STREAMS) {
2927                 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
2928                                 "already has streams set up.\n",
2929                                 ep->desc.bEndpointAddress);
2930                 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
2931                                 "dynamic stream context array reallocation.\n");
2932                 return -EINVAL;
2933         }
2934         if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
2935                 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
2936                                 "endpoint 0x%x; URBs are pending.\n",
2937                                 ep->desc.bEndpointAddress);
2938                 return -EINVAL;
2939         }
2940         return 0;
2941 }
2942
2943 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
2944                 unsigned int *num_streams, unsigned int *num_stream_ctxs)
2945 {
2946         unsigned int max_streams;
2947
2948         /* The stream context array size must be a power of two */
2949         *num_stream_ctxs = roundup_pow_of_two(*num_streams);
2950         /*
2951          * Find out how many primary stream array entries the host controller
2952          * supports.  Later we may use secondary stream arrays (similar to 2nd
2953          * level page entries), but that's an optional feature for xHCI host
2954          * controllers. xHCs must support at least 4 stream IDs.
2955          */
2956         max_streams = HCC_MAX_PSA(xhci->hcc_params);
2957         if (*num_stream_ctxs > max_streams) {
2958                 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
2959                                 max_streams);
2960                 *num_stream_ctxs = max_streams;
2961                 *num_streams = max_streams;
2962         }
2963 }
2964
2965 /* Returns an error code if one of the endpoint already has streams.
2966  * This does not change any data structures, it only checks and gathers
2967  * information.
2968  */
2969 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
2970                 struct usb_device *udev,
2971                 struct usb_host_endpoint **eps, unsigned int num_eps,
2972                 unsigned int *num_streams, u32 *changed_ep_bitmask)
2973 {
2974         unsigned int max_streams;
2975         unsigned int endpoint_flag;
2976         int i;
2977         int ret;
2978
2979         for (i = 0; i < num_eps; i++) {
2980                 ret = xhci_check_streams_endpoint(xhci, udev,
2981                                 eps[i], udev->slot_id);
2982                 if (ret < 0)
2983                         return ret;
2984
2985                 max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
2986                 if (max_streams < (*num_streams - 1)) {
2987                         xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
2988                                         eps[i]->desc.bEndpointAddress,
2989                                         max_streams);
2990                         *num_streams = max_streams+1;
2991                 }
2992
2993                 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
2994                 if (*changed_ep_bitmask & endpoint_flag)
2995                         return -EINVAL;
2996                 *changed_ep_bitmask |= endpoint_flag;
2997         }
2998         return 0;
2999 }
3000
3001 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
3002                 struct usb_device *udev,
3003                 struct usb_host_endpoint **eps, unsigned int num_eps)
3004 {
3005         u32 changed_ep_bitmask = 0;
3006         unsigned int slot_id;
3007         unsigned int ep_index;
3008         unsigned int ep_state;
3009         int i;
3010
3011         slot_id = udev->slot_id;
3012         if (!xhci->devs[slot_id])
3013                 return 0;
3014
3015         for (i = 0; i < num_eps; i++) {
3016                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3017                 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3018                 /* Are streams already being freed for the endpoint? */
3019                 if (ep_state & EP_GETTING_NO_STREAMS) {
3020                         xhci_warn(xhci, "WARN Can't disable streams for "
3021                                         "endpoint 0x%x, "
3022                                         "streams are being disabled already\n",
3023                                         eps[i]->desc.bEndpointAddress);
3024                         return 0;
3025                 }
3026                 /* Are there actually any streams to free? */
3027                 if (!(ep_state & EP_HAS_STREAMS) &&
3028                                 !(ep_state & EP_GETTING_STREAMS)) {
3029                         xhci_warn(xhci, "WARN Can't disable streams for "
3030                                         "endpoint 0x%x, "
3031                                         "streams are already disabled!\n",
3032                                         eps[i]->desc.bEndpointAddress);
3033                         xhci_warn(xhci, "WARN xhci_free_streams() called "
3034                                         "with non-streams endpoint\n");
3035                         return 0;
3036                 }
3037                 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
3038         }
3039         return changed_ep_bitmask;
3040 }
3041
3042 /*
3043  * The USB device drivers use this function (through the HCD interface in USB
3044  * core) to prepare a set of bulk endpoints to use streams.  Streams are used to
3045  * coordinate mass storage command queueing across multiple endpoints (basically
3046  * a stream ID == a task ID).
3047  *
3048  * Setting up streams involves allocating the same size stream context array
3049  * for each endpoint and issuing a configure endpoint command for all endpoints.
3050  *
3051  * Don't allow the call to succeed if one endpoint only supports one stream
3052  * (which means it doesn't support streams at all).
3053  *
3054  * Drivers may get less stream IDs than they asked for, if the host controller
3055  * hardware or endpoints claim they can't support the number of requested
3056  * stream IDs.
3057  */
3058 static int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
3059                 struct usb_host_endpoint **eps, unsigned int num_eps,
3060                 unsigned int num_streams, gfp_t mem_flags)
3061 {
3062         int i, ret;
3063         struct xhci_hcd *xhci;
3064         struct xhci_virt_device *vdev;
3065         struct xhci_command *config_cmd;
3066         struct xhci_input_control_ctx *ctrl_ctx;
3067         unsigned int ep_index;
3068         unsigned int num_stream_ctxs;
3069         unsigned int max_packet;
3070         unsigned long flags;
3071         u32 changed_ep_bitmask = 0;
3072
3073         if (!eps)
3074                 return -EINVAL;
3075
3076         /* Add one to the number of streams requested to account for
3077          * stream 0 that is reserved for xHCI usage.
3078          */
3079         num_streams += 1;
3080         xhci = hcd_to_xhci(hcd);
3081         xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
3082                         num_streams);
3083
3084         /* MaxPSASize value 0 (2 streams) means streams are not supported */
3085         if ((xhci->quirks & XHCI_BROKEN_STREAMS) ||
3086                         HCC_MAX_PSA(xhci->hcc_params) < 4) {
3087                 xhci_dbg(xhci, "xHCI controller does not support streams.\n");
3088                 return -ENOSYS;
3089         }
3090
3091         config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
3092         if (!config_cmd)
3093                 return -ENOMEM;
3094
3095         ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
3096         if (!ctrl_ctx) {
3097                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3098                                 __func__);
3099                 xhci_free_command(xhci, config_cmd);
3100                 return -ENOMEM;
3101         }
3102
3103         /* Check to make sure all endpoints are not already configured for
3104          * streams.  While we're at it, find the maximum number of streams that
3105          * all the endpoints will support and check for duplicate endpoints.
3106          */
3107         spin_lock_irqsave(&xhci->lock, flags);
3108         ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
3109                         num_eps, &num_streams, &changed_ep_bitmask);
3110         if (ret < 0) {
3111                 xhci_free_command(xhci, config_cmd);
3112                 spin_unlock_irqrestore(&xhci->lock, flags);
3113                 return ret;
3114         }
3115         if (num_streams <= 1) {
3116                 xhci_warn(xhci, "WARN: endpoints can't handle "
3117                                 "more than one stream.\n");
3118                 xhci_free_command(xhci, config_cmd);
3119                 spin_unlock_irqrestore(&xhci->lock, flags);
3120                 return -EINVAL;
3121         }
3122         vdev = xhci->devs[udev->slot_id];
3123         /* Mark each endpoint as being in transition, so
3124          * xhci_urb_enqueue() will reject all URBs.
3125          */
3126         for (i = 0; i < num_eps; i++) {
3127                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3128                 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
3129         }
3130         spin_unlock_irqrestore(&xhci->lock, flags);
3131
3132         /* Setup internal data structures and allocate HW data structures for
3133          * streams (but don't install the HW structures in the input context
3134          * until we're sure all memory allocation succeeded).
3135          */
3136         xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
3137         xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
3138                         num_stream_ctxs, num_streams);
3139
3140         for (i = 0; i < num_eps; i++) {
3141                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3142                 max_packet = usb_endpoint_maxp(&eps[i]->desc);
3143                 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
3144                                 num_stream_ctxs,
3145                                 num_streams,
3146                                 max_packet, mem_flags);
3147                 if (!vdev->eps[ep_index].stream_info)
3148                         goto cleanup;
3149                 /* Set maxPstreams in endpoint context and update deq ptr to
3150                  * point to stream context array. FIXME
3151                  */
3152         }
3153
3154         /* Set up the input context for a configure endpoint command. */
3155         for (i = 0; i < num_eps; i++) {
3156                 struct xhci_ep_ctx *ep_ctx;
3157
3158                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3159                 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
3160
3161                 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3162                                 vdev->out_ctx, ep_index);
3163                 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3164                                 vdev->eps[ep_index].stream_info);
3165         }
3166         /* Tell the HW to drop its old copy of the endpoint context info
3167          * and add the updated copy from the input context.
3168          */
3169         xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
3170                         vdev->out_ctx, ctrl_ctx,
3171                         changed_ep_bitmask, changed_ep_bitmask);
3172
3173         /* Issue and wait for the configure endpoint command */
3174         ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3175                         false, false);
3176
3177         /* xHC rejected the configure endpoint command for some reason, so we
3178          * leave the old ring intact and free our internal streams data
3179          * structure.
3180          */
3181         if (ret < 0)
3182                 goto cleanup;
3183
3184         spin_lock_irqsave(&xhci->lock, flags);
3185         for (i = 0; i < num_eps; i++) {
3186                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3187                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3188                 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
3189                          udev->slot_id, ep_index);
3190                 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
3191         }
3192         xhci_free_command(xhci, config_cmd);
3193         spin_unlock_irqrestore(&xhci->lock, flags);
3194
3195         /* Subtract 1 for stream 0, which drivers can't use */
3196         return num_streams - 1;
3197
3198 cleanup:
3199         /* If it didn't work, free the streams! */
3200         for (i = 0; i < num_eps; i++) {
3201                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3202                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3203                 vdev->eps[ep_index].stream_info = NULL;
3204                 /* FIXME Unset maxPstreams in endpoint context and
3205                  * update deq ptr to point to normal string ring.
3206                  */
3207                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3208                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3209                 xhci_endpoint_zero(xhci, vdev, eps[i]);
3210         }
3211         xhci_free_command(xhci, config_cmd);
3212         return -ENOMEM;
3213 }
3214
3215 /* Transition the endpoint from using streams to being a "normal" endpoint
3216  * without streams.
3217  *
3218  * Modify the endpoint context state, submit a configure endpoint command,
3219  * and free all endpoint rings for streams if that completes successfully.
3220  */
3221 static int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3222                 struct usb_host_endpoint **eps, unsigned int num_eps,
3223                 gfp_t mem_flags)
3224 {
3225         int i, ret;
3226         struct xhci_hcd *xhci;
3227         struct xhci_virt_device *vdev;
3228         struct xhci_command *command;
3229         struct xhci_input_control_ctx *ctrl_ctx;
3230         unsigned int ep_index;
3231         unsigned long flags;
3232         u32 changed_ep_bitmask;
3233
3234         xhci = hcd_to_xhci(hcd);
3235         vdev = xhci->devs[udev->slot_id];
3236
3237         /* Set up a configure endpoint command to remove the streams rings */
3238         spin_lock_irqsave(&xhci->lock, flags);
3239         changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3240                         udev, eps, num_eps);
3241         if (changed_ep_bitmask == 0) {
3242                 spin_unlock_irqrestore(&xhci->lock, flags);
3243                 return -EINVAL;
3244         }
3245
3246         /* Use the xhci_command structure from the first endpoint.  We may have
3247          * allocated too many, but the driver may call xhci_free_streams() for
3248          * each endpoint it grouped into one call to xhci_alloc_streams().
3249          */
3250         ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3251         command = vdev->eps[ep_index].stream_info->free_streams_command;
3252         ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3253         if (!ctrl_ctx) {
3254                 spin_unlock_irqrestore(&xhci->lock, flags);
3255                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3256                                 __func__);
3257                 return -EINVAL;
3258         }
3259
3260         for (i = 0; i < num_eps; i++) {
3261                 struct xhci_ep_ctx *ep_ctx;
3262
3263                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3264                 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3265                 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3266                         EP_GETTING_NO_STREAMS;
3267
3268                 xhci_endpoint_copy(xhci, command->in_ctx,
3269                                 vdev->out_ctx, ep_index);
3270                 xhci_setup_no_streams_ep_input_ctx(ep_ctx,
3271                                 &vdev->eps[ep_index]);
3272         }
3273         xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3274                         vdev->out_ctx, ctrl_ctx,
3275                         changed_ep_bitmask, changed_ep_bitmask);
3276         spin_unlock_irqrestore(&xhci->lock, flags);
3277
3278         /* Issue and wait for the configure endpoint command,
3279          * which must succeed.
3280          */
3281         ret = xhci_configure_endpoint(xhci, udev, command,
3282                         false, true);
3283
3284         /* xHC rejected the configure endpoint command for some reason, so we
3285          * leave the streams rings intact.
3286          */
3287         if (ret < 0)
3288                 return ret;
3289
3290         spin_lock_irqsave(&xhci->lock, flags);
3291         for (i = 0; i < num_eps; i++) {
3292                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3293