51326425f9cc799c2d81d910e9d1a7575b4a8bbb
[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                 xhci_queue_vendor_command(xhci, command, 0, 0, 0,
629                                 TRB_TYPE(TRB_NEC_GET_FW));
630         }
631         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
632                         "Finished xhci_run for USB2 roothub");
633         return 0;
634 }
635 EXPORT_SYMBOL_GPL(xhci_run);
636
637 /*
638  * Stop xHCI driver.
639  *
640  * This function is called by the USB core when the HC driver is removed.
641  * Its opposite is xhci_run().
642  *
643  * Disable device contexts, disable IRQs, and quiesce the HC.
644  * Reset the HC, finish any completed transactions, and cleanup memory.
645  */
646 static void xhci_stop(struct usb_hcd *hcd)
647 {
648         u32 temp;
649         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
650
651         mutex_lock(&xhci->mutex);
652
653         /* Only halt host and free memory after both hcds are removed */
654         if (!usb_hcd_is_primary_hcd(hcd)) {
655                 /* usb core will free this hcd shortly, unset pointer */
656                 xhci->shared_hcd = NULL;
657                 mutex_unlock(&xhci->mutex);
658                 return;
659         }
660
661         spin_lock_irq(&xhci->lock);
662         xhci->xhc_state |= XHCI_STATE_HALTED;
663         xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
664         xhci_halt(xhci);
665         xhci_reset(xhci);
666         spin_unlock_irq(&xhci->lock);
667
668         xhci_cleanup_msix(xhci);
669
670         /* Deleting Compliance Mode Recovery Timer */
671         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
672                         (!(xhci_all_ports_seen_u0(xhci)))) {
673                 del_timer_sync(&xhci->comp_mode_recovery_timer);
674                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
675                                 "%s: compliance mode recovery timer deleted",
676                                 __func__);
677         }
678
679         if (xhci->quirks & XHCI_AMD_PLL_FIX)
680                 usb_amd_dev_put();
681
682         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
683                         "// Disabling event ring interrupts");
684         temp = readl(&xhci->op_regs->status);
685         writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
686         temp = readl(&xhci->ir_set->irq_pending);
687         writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
688         xhci_print_ir_set(xhci, 0);
689
690         xhci_dbg_trace(xhci, trace_xhci_dbg_init, "cleaning up memory");
691         xhci_mem_cleanup(xhci);
692         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
693                         "xhci_stop completed - status = %x",
694                         readl(&xhci->op_regs->status));
695         mutex_unlock(&xhci->mutex);
696 }
697
698 /*
699  * Shutdown HC (not bus-specific)
700  *
701  * This is called when the machine is rebooting or halting.  We assume that the
702  * machine will be powered off, and the HC's internal state will be reset.
703  * Don't bother to free memory.
704  *
705  * This will only ever be called with the main usb_hcd (the USB3 roothub).
706  */
707 static void xhci_shutdown(struct usb_hcd *hcd)
708 {
709         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
710
711         if (xhci->quirks & XHCI_SPURIOUS_REBOOT)
712                 usb_disable_xhci_ports(to_pci_dev(hcd->self.sysdev));
713
714         spin_lock_irq(&xhci->lock);
715         xhci_halt(xhci);
716         /* Workaround for spurious wakeups at shutdown with HSW */
717         if (xhci->quirks & XHCI_SPURIOUS_WAKEUP)
718                 xhci_reset(xhci);
719         spin_unlock_irq(&xhci->lock);
720
721         xhci_cleanup_msix(xhci);
722
723         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
724                         "xhci_shutdown completed - status = %x",
725                         readl(&xhci->op_regs->status));
726
727         /* Yet another workaround for spurious wakeups at shutdown with HSW */
728         if (xhci->quirks & XHCI_SPURIOUS_WAKEUP)
729                 pci_set_power_state(to_pci_dev(hcd->self.sysdev), PCI_D3hot);
730 }
731
732 #ifdef CONFIG_PM
733 static void xhci_save_registers(struct xhci_hcd *xhci)
734 {
735         xhci->s3.command = readl(&xhci->op_regs->command);
736         xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
737         xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
738         xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);
739         xhci->s3.erst_size = readl(&xhci->ir_set->erst_size);
740         xhci->s3.erst_base = xhci_read_64(xhci, &xhci->ir_set->erst_base);
741         xhci->s3.erst_dequeue = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
742         xhci->s3.irq_pending = readl(&xhci->ir_set->irq_pending);
743         xhci->s3.irq_control = readl(&xhci->ir_set->irq_control);
744 }
745
746 static void xhci_restore_registers(struct xhci_hcd *xhci)
747 {
748         writel(xhci->s3.command, &xhci->op_regs->command);
749         writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
750         xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
751         writel(xhci->s3.config_reg, &xhci->op_regs->config_reg);
752         writel(xhci->s3.erst_size, &xhci->ir_set->erst_size);
753         xhci_write_64(xhci, xhci->s3.erst_base, &xhci->ir_set->erst_base);
754         xhci_write_64(xhci, xhci->s3.erst_dequeue, &xhci->ir_set->erst_dequeue);
755         writel(xhci->s3.irq_pending, &xhci->ir_set->irq_pending);
756         writel(xhci->s3.irq_control, &xhci->ir_set->irq_control);
757 }
758
759 static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
760 {
761         u64     val_64;
762
763         /* step 2: initialize command ring buffer */
764         val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
765         val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
766                 (xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
767                                       xhci->cmd_ring->dequeue) &
768                  (u64) ~CMD_RING_RSVD_BITS) |
769                 xhci->cmd_ring->cycle_state;
770         xhci_dbg_trace(xhci, trace_xhci_dbg_init,
771                         "// Setting command ring address to 0x%llx",
772                         (long unsigned long) val_64);
773         xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
774 }
775
776 /*
777  * The whole command ring must be cleared to zero when we suspend the host.
778  *
779  * The host doesn't save the command ring pointer in the suspend well, so we
780  * need to re-program it on resume.  Unfortunately, the pointer must be 64-byte
781  * aligned, because of the reserved bits in the command ring dequeue pointer
782  * register.  Therefore, we can't just set the dequeue pointer back in the
783  * middle of the ring (TRBs are 16-byte aligned).
784  */
785 static void xhci_clear_command_ring(struct xhci_hcd *xhci)
786 {
787         struct xhci_ring *ring;
788         struct xhci_segment *seg;
789
790         ring = xhci->cmd_ring;
791         seg = ring->deq_seg;
792         do {
793                 memset(seg->trbs, 0,
794                         sizeof(union xhci_trb) * (TRBS_PER_SEGMENT - 1));
795                 seg->trbs[TRBS_PER_SEGMENT - 1].link.control &=
796                         cpu_to_le32(~TRB_CYCLE);
797                 seg = seg->next;
798         } while (seg != ring->deq_seg);
799
800         /* Reset the software enqueue and dequeue pointers */
801         ring->deq_seg = ring->first_seg;
802         ring->dequeue = ring->first_seg->trbs;
803         ring->enq_seg = ring->deq_seg;
804         ring->enqueue = ring->dequeue;
805
806         ring->num_trbs_free = ring->num_segs * (TRBS_PER_SEGMENT - 1) - 1;
807         /*
808          * Ring is now zeroed, so the HW should look for change of ownership
809          * when the cycle bit is set to 1.
810          */
811         ring->cycle_state = 1;
812
813         /*
814          * Reset the hardware dequeue pointer.
815          * Yes, this will need to be re-written after resume, but we're paranoid
816          * and want to make sure the hardware doesn't access bogus memory
817          * because, say, the BIOS or an SMI started the host without changing
818          * the command ring pointers.
819          */
820         xhci_set_cmd_ring_deq(xhci);
821 }
822
823 static void xhci_disable_port_wake_on_bits(struct xhci_hcd *xhci)
824 {
825         int port_index;
826         __le32 __iomem **port_array;
827         unsigned long flags;
828         u32 t1, t2;
829
830         spin_lock_irqsave(&xhci->lock, flags);
831
832         /* disable usb3 ports Wake bits */
833         port_index = xhci->num_usb3_ports;
834         port_array = xhci->usb3_ports;
835         while (port_index--) {
836                 t1 = readl(port_array[port_index]);
837                 t1 = xhci_port_state_to_neutral(t1);
838                 t2 = t1 & ~PORT_WAKE_BITS;
839                 if (t1 != t2)
840                         writel(t2, port_array[port_index]);
841         }
842
843         /* disable usb2 ports Wake bits */
844         port_index = xhci->num_usb2_ports;
845         port_array = xhci->usb2_ports;
846         while (port_index--) {
847                 t1 = readl(port_array[port_index]);
848                 t1 = xhci_port_state_to_neutral(t1);
849                 t2 = t1 & ~PORT_WAKE_BITS;
850                 if (t1 != t2)
851                         writel(t2, port_array[port_index]);
852         }
853
854         spin_unlock_irqrestore(&xhci->lock, flags);
855 }
856
857 /*
858  * Stop HC (not bus-specific)
859  *
860  * This is called when the machine transition into S3/S4 mode.
861  *
862  */
863 int xhci_suspend(struct xhci_hcd *xhci, bool do_wakeup)
864 {
865         int                     rc = 0;
866         unsigned int            delay = XHCI_MAX_HALT_USEC;
867         struct usb_hcd          *hcd = xhci_to_hcd(xhci);
868         u32                     command;
869
870         if (!hcd->state)
871                 return 0;
872
873         if (hcd->state != HC_STATE_SUSPENDED ||
874                         xhci->shared_hcd->state != HC_STATE_SUSPENDED)
875                 return -EINVAL;
876
877         /* Clear root port wake on bits if wakeup not allowed. */
878         if (!do_wakeup)
879                 xhci_disable_port_wake_on_bits(xhci);
880
881         /* Don't poll the roothubs on bus suspend. */
882         xhci_dbg(xhci, "%s: stopping port polling.\n", __func__);
883         clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
884         del_timer_sync(&hcd->rh_timer);
885         clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
886         del_timer_sync(&xhci->shared_hcd->rh_timer);
887
888         spin_lock_irq(&xhci->lock);
889         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
890         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
891         /* step 1: stop endpoint */
892         /* skipped assuming that port suspend has done */
893
894         /* step 2: clear Run/Stop bit */
895         command = readl(&xhci->op_regs->command);
896         command &= ~CMD_RUN;
897         writel(command, &xhci->op_regs->command);
898
899         /* Some chips from Fresco Logic need an extraordinary delay */
900         delay *= (xhci->quirks & XHCI_SLOW_SUSPEND) ? 10 : 1;
901
902         if (xhci_handshake(&xhci->op_regs->status,
903                       STS_HALT, STS_HALT, delay)) {
904                 xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
905                 spin_unlock_irq(&xhci->lock);
906                 return -ETIMEDOUT;
907         }
908         xhci_clear_command_ring(xhci);
909
910         /* step 3: save registers */
911         xhci_save_registers(xhci);
912
913         /* step 4: set CSS flag */
914         command = readl(&xhci->op_regs->command);
915         command |= CMD_CSS;
916         writel(command, &xhci->op_regs->command);
917         if (xhci_handshake(&xhci->op_regs->status,
918                                 STS_SAVE, 0, 10 * 1000)) {
919                 xhci_warn(xhci, "WARN: xHC save state timeout\n");
920                 spin_unlock_irq(&xhci->lock);
921                 return -ETIMEDOUT;
922         }
923         spin_unlock_irq(&xhci->lock);
924
925         /*
926          * Deleting Compliance Mode Recovery Timer because the xHCI Host
927          * is about to be suspended.
928          */
929         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
930                         (!(xhci_all_ports_seen_u0(xhci)))) {
931                 del_timer_sync(&xhci->comp_mode_recovery_timer);
932                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
933                                 "%s: compliance mode recovery timer deleted",
934                                 __func__);
935         }
936
937         /* step 5: remove core well power */
938         /* synchronize irq when using MSI-X */
939         xhci_msix_sync_irqs(xhci);
940
941         return rc;
942 }
943 EXPORT_SYMBOL_GPL(xhci_suspend);
944
945 /*
946  * start xHC (not bus-specific)
947  *
948  * This is called when the machine transition from S3/S4 mode.
949  *
950  */
951 int xhci_resume(struct xhci_hcd *xhci, bool hibernated)
952 {
953         u32                     command, temp = 0, status;
954         struct usb_hcd          *hcd = xhci_to_hcd(xhci);
955         struct usb_hcd          *secondary_hcd;
956         int                     retval = 0;
957         bool                    comp_timer_running = false;
958
959         if (!hcd->state)
960                 return 0;
961
962         /* Wait a bit if either of the roothubs need to settle from the
963          * transition into bus suspend.
964          */
965         if (time_before(jiffies, xhci->bus_state[0].next_statechange) ||
966                         time_before(jiffies,
967                                 xhci->bus_state[1].next_statechange))
968                 msleep(100);
969
970         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
971         set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
972
973         spin_lock_irq(&xhci->lock);
974         if (xhci->quirks & XHCI_RESET_ON_RESUME)
975                 hibernated = true;
976
977         if (!hibernated) {
978                 /* step 1: restore register */
979                 xhci_restore_registers(xhci);
980                 /* step 2: initialize command ring buffer */
981                 xhci_set_cmd_ring_deq(xhci);
982                 /* step 3: restore state and start state*/
983                 /* step 3: set CRS flag */
984                 command = readl(&xhci->op_regs->command);
985                 command |= CMD_CRS;
986                 writel(command, &xhci->op_regs->command);
987                 if (xhci_handshake(&xhci->op_regs->status,
988                               STS_RESTORE, 0, 10 * 1000)) {
989                         xhci_warn(xhci, "WARN: xHC restore state timeout\n");
990                         spin_unlock_irq(&xhci->lock);
991                         return -ETIMEDOUT;
992                 }
993                 temp = readl(&xhci->op_regs->status);
994         }
995
996         /* If restore operation fails, re-initialize the HC during resume */
997         if ((temp & STS_SRE) || hibernated) {
998
999                 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1000                                 !(xhci_all_ports_seen_u0(xhci))) {
1001                         del_timer_sync(&xhci->comp_mode_recovery_timer);
1002                         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1003                                 "Compliance Mode Recovery Timer deleted!");
1004                 }
1005
1006                 /* Let the USB core know _both_ roothubs lost power. */
1007                 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1008                 usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
1009
1010                 xhci_dbg(xhci, "Stop HCD\n");
1011                 xhci_halt(xhci);
1012                 xhci_reset(xhci);
1013                 spin_unlock_irq(&xhci->lock);
1014                 xhci_cleanup_msix(xhci);
1015
1016                 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1017                 temp = readl(&xhci->op_regs->status);
1018                 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
1019                 temp = readl(&xhci->ir_set->irq_pending);
1020                 writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
1021                 xhci_print_ir_set(xhci, 0);
1022
1023                 xhci_dbg(xhci, "cleaning up memory\n");
1024                 xhci_mem_cleanup(xhci);
1025                 xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
1026                             readl(&xhci->op_regs->status));
1027
1028                 /* USB core calls the PCI reinit and start functions twice:
1029                  * first with the primary HCD, and then with the secondary HCD.
1030                  * If we don't do the same, the host will never be started.
1031                  */
1032                 if (!usb_hcd_is_primary_hcd(hcd))
1033                         secondary_hcd = hcd;
1034                 else
1035                         secondary_hcd = xhci->shared_hcd;
1036
1037                 xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1038                 retval = xhci_init(hcd->primary_hcd);
1039                 if (retval)
1040                         return retval;
1041                 comp_timer_running = true;
1042
1043                 xhci_dbg(xhci, "Start the primary HCD\n");
1044                 retval = xhci_run(hcd->primary_hcd);
1045                 if (!retval) {
1046                         xhci_dbg(xhci, "Start the secondary HCD\n");
1047                         retval = xhci_run(secondary_hcd);
1048                 }
1049                 hcd->state = HC_STATE_SUSPENDED;
1050                 xhci->shared_hcd->state = HC_STATE_SUSPENDED;
1051                 goto done;
1052         }
1053
1054         /* step 4: set Run/Stop bit */
1055         command = readl(&xhci->op_regs->command);
1056         command |= CMD_RUN;
1057         writel(command, &xhci->op_regs->command);
1058         xhci_handshake(&xhci->op_regs->status, STS_HALT,
1059                   0, 250 * 1000);
1060
1061         /* step 5: walk topology and initialize portsc,
1062          * portpmsc and portli
1063          */
1064         /* this is done in bus_resume */
1065
1066         /* step 6: restart each of the previously
1067          * Running endpoints by ringing their doorbells
1068          */
1069
1070         spin_unlock_irq(&xhci->lock);
1071
1072  done:
1073         if (retval == 0) {
1074                 /* Resume root hubs only when have pending events. */
1075                 status = readl(&xhci->op_regs->status);
1076                 if (status & STS_EINT) {
1077                         usb_hcd_resume_root_hub(xhci->shared_hcd);
1078                         usb_hcd_resume_root_hub(hcd);
1079                 }
1080         }
1081
1082         /*
1083          * If system is subject to the Quirk, Compliance Mode Timer needs to
1084          * be re-initialized Always after a system resume. Ports are subject
1085          * to suffer the Compliance Mode issue again. It doesn't matter if
1086          * ports have entered previously to U0 before system's suspension.
1087          */
1088         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) && !comp_timer_running)
1089                 compliance_mode_recovery_timer_init(xhci);
1090
1091         if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
1092                 usb_asmedia_modifyflowcontrol(to_pci_dev(hcd->self.controller));
1093
1094         /* Re-enable port polling. */
1095         xhci_dbg(xhci, "%s: starting port polling.\n", __func__);
1096         set_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
1097         usb_hcd_poll_rh_status(xhci->shared_hcd);
1098         set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1099         usb_hcd_poll_rh_status(hcd);
1100
1101         return retval;
1102 }
1103 EXPORT_SYMBOL_GPL(xhci_resume);
1104 #endif  /* CONFIG_PM */
1105
1106 /*-------------------------------------------------------------------------*/
1107
1108 /**
1109  * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1110  * HCDs.  Find the index for an endpoint given its descriptor.  Use the return
1111  * value to right shift 1 for the bitmask.
1112  *
1113  * Index  = (epnum * 2) + direction - 1,
1114  * where direction = 0 for OUT, 1 for IN.
1115  * For control endpoints, the IN index is used (OUT index is unused), so
1116  * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1117  */
1118 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1119 {
1120         unsigned int index;
1121         if (usb_endpoint_xfer_control(desc))
1122                 index = (unsigned int) (usb_endpoint_num(desc)*2);
1123         else
1124                 index = (unsigned int) (usb_endpoint_num(desc)*2) +
1125                         (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1126         return index;
1127 }
1128
1129 /* The reverse operation to xhci_get_endpoint_index. Calculate the USB endpoint
1130  * address from the XHCI endpoint index.
1131  */
1132 unsigned int xhci_get_endpoint_address(unsigned int ep_index)
1133 {
1134         unsigned int number = DIV_ROUND_UP(ep_index, 2);
1135         unsigned int direction = ep_index % 2 ? USB_DIR_OUT : USB_DIR_IN;
1136         return direction | number;
1137 }
1138
1139 /* Find the flag for this endpoint (for use in the control context).  Use the
1140  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
1141  * bit 1, etc.
1142  */
1143 static unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1144 {
1145         return 1 << (xhci_get_endpoint_index(desc) + 1);
1146 }
1147
1148 /* Find the flag for this endpoint (for use in the control context).  Use the
1149  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
1150  * bit 1, etc.
1151  */
1152 static unsigned int xhci_get_endpoint_flag_from_index(unsigned int ep_index)
1153 {
1154         return 1 << (ep_index + 1);
1155 }
1156
1157 /* Compute the last valid endpoint context index.  Basically, this is the
1158  * endpoint index plus one.  For slot contexts with more than valid endpoint,
1159  * we find the most significant bit set in the added contexts flags.
1160  * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1161  * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1162  */
1163 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1164 {
1165         return fls(added_ctxs) - 1;
1166 }
1167
1168 /* Returns 1 if the arguments are OK;
1169  * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1170  */
1171 static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
1172                 struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
1173                 const char *func) {
1174         struct xhci_hcd *xhci;
1175         struct xhci_virt_device *virt_dev;
1176
1177         if (!hcd || (check_ep && !ep) || !udev) {
1178                 pr_debug("xHCI %s called with invalid args\n", func);
1179                 return -EINVAL;
1180         }
1181         if (!udev->parent) {
1182                 pr_debug("xHCI %s called for root hub\n", func);
1183                 return 0;
1184         }
1185
1186         xhci = hcd_to_xhci(hcd);
1187         if (check_virt_dev) {
1188                 if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
1189                         xhci_dbg(xhci, "xHCI %s called with unaddressed device\n",
1190                                         func);
1191                         return -EINVAL;
1192                 }
1193
1194                 virt_dev = xhci->devs[udev->slot_id];
1195                 if (virt_dev->udev != udev) {
1196                         xhci_dbg(xhci, "xHCI %s called with udev and "
1197                                           "virt_dev does not match\n", func);
1198                         return -EINVAL;
1199                 }
1200         }
1201
1202         if (xhci->xhc_state & XHCI_STATE_HALTED)
1203                 return -ENODEV;
1204
1205         return 1;
1206 }
1207
1208 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1209                 struct usb_device *udev, struct xhci_command *command,
1210                 bool ctx_change, bool must_succeed);
1211
1212 /*
1213  * Full speed devices may have a max packet size greater than 8 bytes, but the
1214  * USB core doesn't know that until it reads the first 8 bytes of the
1215  * descriptor.  If the usb_device's max packet size changes after that point,
1216  * we need to issue an evaluate context command and wait on it.
1217  */
1218 static int xhci_check_maxpacket(struct xhci_hcd *xhci, unsigned int slot_id,
1219                 unsigned int ep_index, struct urb *urb)
1220 {
1221         struct xhci_container_ctx *out_ctx;
1222         struct xhci_input_control_ctx *ctrl_ctx;
1223         struct xhci_ep_ctx *ep_ctx;
1224         struct xhci_command *command;
1225         int max_packet_size;
1226         int hw_max_packet_size;
1227         int ret = 0;
1228
1229         out_ctx = xhci->devs[slot_id]->out_ctx;
1230         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1231         hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1232         max_packet_size = usb_endpoint_maxp(&urb->dev->ep0.desc);
1233         if (hw_max_packet_size != max_packet_size) {
1234                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1235                                 "Max Packet Size for ep 0 changed.");
1236                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1237                                 "Max packet size in usb_device = %d",
1238                                 max_packet_size);
1239                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1240                                 "Max packet size in xHCI HW = %d",
1241                                 hw_max_packet_size);
1242                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1243                                 "Issuing evaluate context command.");
1244
1245                 /* Set up the input context flags for the command */
1246                 /* FIXME: This won't work if a non-default control endpoint
1247                  * changes max packet sizes.
1248                  */
1249
1250                 command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
1251                 if (!command)
1252                         return -ENOMEM;
1253
1254                 command->in_ctx = xhci->devs[slot_id]->in_ctx;
1255                 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
1256                 if (!ctrl_ctx) {
1257                         xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1258                                         __func__);
1259                         ret = -ENOMEM;
1260                         goto command_cleanup;
1261                 }
1262                 /* Set up the modified control endpoint 0 */
1263                 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
1264                                 xhci->devs[slot_id]->out_ctx, ep_index);
1265
1266                 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
1267                 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1268                 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1269
1270                 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1271                 ctrl_ctx->drop_flags = 0;
1272
1273                 ret = xhci_configure_endpoint(xhci, urb->dev, command,
1274                                 true, false);
1275
1276                 /* Clean up the input context for later use by bandwidth
1277                  * functions.
1278                  */
1279                 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1280 command_cleanup:
1281                 kfree(command->completion);
1282                 kfree(command);
1283         }
1284         return ret;
1285 }
1286
1287 /*
1288  * non-error returns are a promise to giveback() the urb later
1289  * we drop ownership so next owner (or urb unlink) can get it
1290  */
1291 static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1292 {
1293         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1294         unsigned long flags;
1295         int ret = 0;
1296         unsigned int slot_id, ep_index, ep_state;
1297         struct urb_priv *urb_priv;
1298         int num_tds;
1299
1300         if (!urb || xhci_check_args(hcd, urb->dev, urb->ep,
1301                                         true, true, __func__) <= 0)
1302                 return -EINVAL;
1303
1304         slot_id = urb->dev->slot_id;
1305         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1306
1307         if (!HCD_HW_ACCESSIBLE(hcd)) {
1308                 if (!in_interrupt())
1309                         xhci_dbg(xhci, "urb submitted during PCI suspend\n");
1310                 return -ESHUTDOWN;
1311         }
1312
1313         if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1314                 num_tds = urb->number_of_packets;
1315         else if (usb_endpoint_is_bulk_out(&urb->ep->desc) &&
1316             urb->transfer_buffer_length > 0 &&
1317             urb->transfer_flags & URB_ZERO_PACKET &&
1318             !(urb->transfer_buffer_length % usb_endpoint_maxp(&urb->ep->desc)))
1319                 num_tds = 2;
1320         else
1321                 num_tds = 1;
1322
1323         urb_priv = kzalloc(sizeof(struct urb_priv) +
1324                            num_tds * sizeof(struct xhci_td), mem_flags);
1325         if (!urb_priv)
1326                 return -ENOMEM;
1327
1328         urb_priv->num_tds = num_tds;
1329         urb_priv->num_tds_done = 0;
1330         urb->hcpriv = urb_priv;
1331
1332         trace_xhci_urb_enqueue(urb);
1333
1334         if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1335                 /* Check to see if the max packet size for the default control
1336                  * endpoint changed during FS device enumeration
1337                  */
1338                 if (urb->dev->speed == USB_SPEED_FULL) {
1339                         ret = xhci_check_maxpacket(xhci, slot_id,
1340                                         ep_index, urb);
1341                         if (ret < 0) {
1342                                 xhci_urb_free_priv(urb_priv);
1343                                 urb->hcpriv = NULL;
1344                                 return ret;
1345                         }
1346                 }
1347         }
1348
1349         spin_lock_irqsave(&xhci->lock, flags);
1350
1351         if (xhci->xhc_state & XHCI_STATE_DYING) {
1352                 xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for non-responsive xHCI host.\n",
1353                          urb->ep->desc.bEndpointAddress, urb);
1354                 ret = -ESHUTDOWN;
1355                 goto free_priv;
1356         }
1357
1358         switch (usb_endpoint_type(&urb->ep->desc)) {
1359
1360         case USB_ENDPOINT_XFER_CONTROL:
1361                 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1362                                          slot_id, ep_index);
1363                 break;
1364         case USB_ENDPOINT_XFER_BULK:
1365                 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
1366                 if (ep_state & (EP_GETTING_STREAMS | EP_GETTING_NO_STREAMS)) {
1367                         xhci_warn(xhci, "WARN: Can't enqueue URB, ep in streams transition state %x\n",
1368                                   ep_state);
1369                         ret = -EINVAL;
1370                         break;
1371                 }
1372                 ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1373                                          slot_id, ep_index);
1374                 break;
1375
1376
1377         case USB_ENDPOINT_XFER_INT:
1378                 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1379                                 slot_id, ep_index);
1380                 break;
1381
1382         case USB_ENDPOINT_XFER_ISOC:
1383                 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1384                                 slot_id, ep_index);
1385         }
1386
1387         if (ret) {
1388 free_priv:
1389                 xhci_urb_free_priv(urb_priv);
1390                 urb->hcpriv = NULL;
1391         }
1392         spin_unlock_irqrestore(&xhci->lock, flags);
1393         return ret;
1394 }
1395
1396 /*
1397  * Remove the URB's TD from the endpoint ring.  This may cause the HC to stop
1398  * USB transfers, potentially stopping in the middle of a TRB buffer.  The HC
1399  * should pick up where it left off in the TD, unless a Set Transfer Ring
1400  * Dequeue Pointer is issued.
1401  *
1402  * The TRBs that make up the buffers for the canceled URB will be "removed" from
1403  * the ring.  Since the ring is a contiguous structure, they can't be physically
1404  * removed.  Instead, there are two options:
1405  *
1406  *  1) If the HC is in the middle of processing the URB to be canceled, we
1407  *     simply move the ring's dequeue pointer past those TRBs using the Set
1408  *     Transfer Ring Dequeue Pointer command.  This will be the common case,
1409  *     when drivers timeout on the last submitted URB and attempt to cancel.
1410  *
1411  *  2) If the HC is in the middle of a different TD, we turn the TRBs into a
1412  *     series of 1-TRB transfer no-op TDs.  (No-ops shouldn't be chained.)  The
1413  *     HC will need to invalidate the any TRBs it has cached after the stop
1414  *     endpoint command, as noted in the xHCI 0.95 errata.
1415  *
1416  *  3) The TD may have completed by the time the Stop Endpoint Command
1417  *     completes, so software needs to handle that case too.
1418  *
1419  * This function should protect against the TD enqueueing code ringing the
1420  * doorbell while this code is waiting for a Stop Endpoint command to complete.
1421  * It also needs to account for multiple cancellations on happening at the same
1422  * time for the same endpoint.
1423  *
1424  * Note that this function can be called in any context, or so says
1425  * usb_hcd_unlink_urb()
1426  */
1427 static int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1428 {
1429         unsigned long flags;
1430         int ret, i;
1431         u32 temp;
1432         struct xhci_hcd *xhci;
1433         struct urb_priv *urb_priv;
1434         struct xhci_td *td;
1435         unsigned int ep_index;
1436         struct xhci_ring *ep_ring;
1437         struct xhci_virt_ep *ep;
1438         struct xhci_command *command;
1439         struct xhci_virt_device *vdev;
1440
1441         xhci = hcd_to_xhci(hcd);
1442         spin_lock_irqsave(&xhci->lock, flags);
1443
1444         trace_xhci_urb_dequeue(urb);
1445
1446         /* Make sure the URB hasn't completed or been unlinked already */
1447         ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1448         if (ret)
1449                 goto done;
1450
1451         /* give back URB now if we can't queue it for cancel */
1452         vdev = xhci->devs[urb->dev->slot_id];
1453         urb_priv = urb->hcpriv;
1454         if (!vdev || !urb_priv)
1455                 goto err_giveback;
1456
1457         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1458         ep = &vdev->eps[ep_index];
1459         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1460         if (!ep || !ep_ring)
1461                 goto err_giveback;
1462
1463         /* If xHC is dead take it down and return ALL URBs in xhci_hc_died() */
1464         temp = readl(&xhci->op_regs->status);
1465         if (temp == ~(u32)0 || xhci->xhc_state & XHCI_STATE_DYING) {
1466                 xhci_hc_died(xhci);
1467                 goto done;
1468         }
1469
1470         if (xhci->xhc_state & XHCI_STATE_HALTED) {
1471                 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1472                                 "HC halted, freeing TD manually.");
1473                 for (i = urb_priv->num_tds_done;
1474                      i < urb_priv->num_tds;
1475                      i++) {
1476                         td = &urb_priv->td[i];
1477                         if (!list_empty(&td->td_list))
1478                                 list_del_init(&td->td_list);
1479                         if (!list_empty(&td->cancelled_td_list))
1480                                 list_del_init(&td->cancelled_td_list);
1481                 }
1482                 goto err_giveback;
1483         }
1484
1485         i = urb_priv->num_tds_done;
1486         if (i < urb_priv->num_tds)
1487                 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1488                                 "Cancel URB %p, dev %s, ep 0x%x, "
1489                                 "starting at offset 0x%llx",
1490                                 urb, urb->dev->devpath,
1491                                 urb->ep->desc.bEndpointAddress,
1492                                 (unsigned long long) xhci_trb_virt_to_dma(
1493                                         urb_priv->td[i].start_seg,
1494                                         urb_priv->td[i].first_trb));
1495
1496         for (; i < urb_priv->num_tds; i++) {
1497                 td = &urb_priv->td[i];
1498                 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
1499         }
1500
1501         /* Queue a stop endpoint command, but only if this is
1502          * the first cancellation to be handled.
1503          */
1504         if (!(ep->ep_state & EP_STOP_CMD_PENDING)) {
1505                 command = xhci_alloc_command(xhci, false, false, GFP_ATOMIC);
1506                 if (!command) {
1507                         ret = -ENOMEM;
1508                         goto done;
1509                 }
1510                 ep->ep_state |= EP_STOP_CMD_PENDING;
1511                 ep->stop_cmd_timer.expires = jiffies +
1512                         XHCI_STOP_EP_CMD_TIMEOUT * HZ;
1513                 add_timer(&ep->stop_cmd_timer);
1514                 xhci_queue_stop_endpoint(xhci, command, urb->dev->slot_id,
1515                                          ep_index, 0);
1516                 xhci_ring_cmd_db(xhci);
1517         }
1518 done:
1519         spin_unlock_irqrestore(&xhci->lock, flags);
1520         return ret;
1521
1522 err_giveback:
1523         if (urb_priv)
1524                 xhci_urb_free_priv(urb_priv);
1525         usb_hcd_unlink_urb_from_ep(hcd, urb);
1526         spin_unlock_irqrestore(&xhci->lock, flags);
1527         usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1528         return ret;
1529 }
1530
1531 /* Drop an endpoint from a new bandwidth configuration for this device.
1532  * Only one call to this function is allowed per endpoint before
1533  * check_bandwidth() or reset_bandwidth() must be called.
1534  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1535  * add the endpoint to the schedule with possibly new parameters denoted by a
1536  * different endpoint descriptor in usb_host_endpoint.
1537  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1538  * not allowed.
1539  *
1540  * The USB core will not allow URBs to be queued to an endpoint that is being
1541  * disabled, so there's no need for mutual exclusion to protect
1542  * the xhci->devs[slot_id] structure.
1543  */
1544 static int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1545                 struct usb_host_endpoint *ep)
1546 {
1547         struct xhci_hcd *xhci;
1548         struct xhci_container_ctx *in_ctx, *out_ctx;
1549         struct xhci_input_control_ctx *ctrl_ctx;
1550         unsigned int ep_index;
1551         struct xhci_ep_ctx *ep_ctx;
1552         u32 drop_flag;
1553         u32 new_add_flags, new_drop_flags;
1554         int ret;
1555
1556         ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1557         if (ret <= 0)
1558                 return ret;
1559         xhci = hcd_to_xhci(hcd);
1560         if (xhci->xhc_state & XHCI_STATE_DYING)
1561                 return -ENODEV;
1562
1563         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1564         drop_flag = xhci_get_endpoint_flag(&ep->desc);
1565         if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1566                 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1567                                 __func__, drop_flag);
1568                 return 0;
1569         }
1570
1571         in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1572         out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1573         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1574         if (!ctrl_ctx) {
1575                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1576                                 __func__);
1577                 return 0;
1578         }
1579
1580         ep_index = xhci_get_endpoint_index(&ep->desc);
1581         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1582         /* If the HC already knows the endpoint is disabled,
1583          * or the HCD has noted it is disabled, ignore this request
1584          */
1585         if ((GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) ||
1586             le32_to_cpu(ctrl_ctx->drop_flags) &
1587             xhci_get_endpoint_flag(&ep->desc)) {
1588                 /* Do not warn when called after a usb_device_reset */
1589                 if (xhci->devs[udev->slot_id]->eps[ep_index].ring != NULL)
1590                         xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1591                                   __func__, ep);
1592                 return 0;
1593         }
1594
1595         ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1596         new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1597
1598         ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1599         new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1600
1601         xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1602
1603         if (xhci->quirks & XHCI_MTK_HOST)
1604                 xhci_mtk_drop_ep_quirk(hcd, udev, ep);
1605
1606         xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1607                         (unsigned int) ep->desc.bEndpointAddress,
1608                         udev->slot_id,
1609                         (unsigned int) new_drop_flags,
1610                         (unsigned int) new_add_flags);
1611         return 0;
1612 }
1613
1614 /* Add an endpoint to a new possible bandwidth configuration for this device.
1615  * Only one call to this function is allowed per endpoint before
1616  * check_bandwidth() or reset_bandwidth() must be called.
1617  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1618  * add the endpoint to the schedule with possibly new parameters denoted by a
1619  * different endpoint descriptor in usb_host_endpoint.
1620  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1621  * not allowed.
1622  *
1623  * The USB core will not allow URBs to be queued to an endpoint until the
1624  * configuration or alt setting is installed in the device, so there's no need
1625  * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1626  */
1627 static int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1628                 struct usb_host_endpoint *ep)
1629 {
1630         struct xhci_hcd *xhci;
1631         struct xhci_container_ctx *in_ctx;
1632         unsigned int ep_index;
1633         struct xhci_input_control_ctx *ctrl_ctx;
1634         u32 added_ctxs;
1635         u32 new_add_flags, new_drop_flags;
1636         struct xhci_virt_device *virt_dev;
1637         int ret = 0;
1638
1639         ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1640         if (ret <= 0) {
1641                 /* So we won't queue a reset ep command for a root hub */
1642                 ep->hcpriv = NULL;
1643                 return ret;
1644         }
1645         xhci = hcd_to_xhci(hcd);
1646         if (xhci->xhc_state & XHCI_STATE_DYING)
1647                 return -ENODEV;
1648
1649         added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1650         if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1651                 /* FIXME when we have to issue an evaluate endpoint command to
1652                  * deal with ep0 max packet size changing once we get the
1653                  * descriptors
1654                  */
1655                 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1656                                 __func__, added_ctxs);
1657                 return 0;
1658         }
1659
1660         virt_dev = xhci->devs[udev->slot_id];
1661         in_ctx = virt_dev->in_ctx;
1662         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1663         if (!ctrl_ctx) {
1664                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1665                                 __func__);
1666                 return 0;
1667         }
1668
1669         ep_index = xhci_get_endpoint_index(&ep->desc);
1670         /* If this endpoint is already in use, and the upper layers are trying
1671          * to add it again without dropping it, reject the addition.
1672          */
1673         if (virt_dev->eps[ep_index].ring &&
1674                         !(le32_to_cpu(ctrl_ctx->drop_flags) & added_ctxs)) {
1675                 xhci_warn(xhci, "Trying to add endpoint 0x%x "
1676                                 "without dropping it.\n",
1677                                 (unsigned int) ep->desc.bEndpointAddress);
1678                 return -EINVAL;
1679         }
1680
1681         /* If the HCD has already noted the endpoint is enabled,
1682          * ignore this request.
1683          */
1684         if (le32_to_cpu(ctrl_ctx->add_flags) & added_ctxs) {
1685                 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1686                                 __func__, ep);
1687                 return 0;
1688         }
1689
1690         /*
1691          * Configuration and alternate setting changes must be done in
1692          * process context, not interrupt context (or so documenation
1693          * for usb_set_interface() and usb_set_configuration() claim).
1694          */
1695         if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1696                 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1697                                 __func__, ep->desc.bEndpointAddress);
1698                 return -ENOMEM;
1699         }
1700
1701         if (xhci->quirks & XHCI_MTK_HOST) {
1702                 ret = xhci_mtk_add_ep_quirk(hcd, udev, ep);
1703                 if (ret < 0) {
1704                         xhci_free_endpoint_ring(xhci, virt_dev, ep_index);
1705                         return ret;
1706                 }
1707         }
1708
1709         ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
1710         new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1711
1712         /* If xhci_endpoint_disable() was called for this endpoint, but the
1713          * xHC hasn't been notified yet through the check_bandwidth() call,
1714          * this re-adds a new state for the endpoint from the new endpoint
1715          * descriptors.  We must drop and re-add this endpoint, so we leave the
1716          * drop flags alone.
1717          */
1718         new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1719
1720         /* Store the usb_device pointer for later use */
1721         ep->hcpriv = udev;
1722
1723         xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1724                         (unsigned int) ep->desc.bEndpointAddress,
1725                         udev->slot_id,
1726                         (unsigned int) new_drop_flags,
1727                         (unsigned int) new_add_flags);
1728         return 0;
1729 }
1730
1731 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1732 {
1733         struct xhci_input_control_ctx *ctrl_ctx;
1734         struct xhci_ep_ctx *ep_ctx;
1735         struct xhci_slot_ctx *slot_ctx;
1736         int i;
1737
1738         ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1739         if (!ctrl_ctx) {
1740                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1741                                 __func__);
1742                 return;
1743         }
1744
1745         /* When a device's add flag and drop flag are zero, any subsequent
1746          * configure endpoint command will leave that endpoint's state
1747          * untouched.  Make sure we don't leave any old state in the input
1748          * endpoint contexts.
1749          */
1750         ctrl_ctx->drop_flags = 0;
1751         ctrl_ctx->add_flags = 0;
1752         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1753         slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1754         /* Endpoint 0 is always valid */
1755         slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
1756         for (i = 1; i < 31; i++) {
1757                 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
1758                 ep_ctx->ep_info = 0;
1759                 ep_ctx->ep_info2 = 0;
1760                 ep_ctx->deq = 0;
1761                 ep_ctx->tx_info = 0;
1762         }
1763 }
1764
1765 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
1766                 struct usb_device *udev, u32 *cmd_status)
1767 {
1768         int ret;
1769
1770         switch (*cmd_status) {
1771         case COMP_COMMAND_ABORTED:
1772         case COMP_COMMAND_RING_STOPPED:
1773                 xhci_warn(xhci, "Timeout while waiting for configure endpoint command\n");
1774                 ret = -ETIME;
1775                 break;
1776         case COMP_RESOURCE_ERROR:
1777                 dev_warn(&udev->dev,
1778                          "Not enough host controller resources for new device state.\n");
1779                 ret = -ENOMEM;
1780                 /* FIXME: can we allocate more resources for the HC? */
1781                 break;
1782         case COMP_BANDWIDTH_ERROR:
1783         case COMP_SECONDARY_BANDWIDTH_ERROR:
1784                 dev_warn(&udev->dev,
1785                          "Not enough bandwidth for new device state.\n");
1786                 ret = -ENOSPC;
1787                 /* FIXME: can we go back to the old state? */
1788                 break;
1789         case COMP_TRB_ERROR:
1790                 /* the HCD set up something wrong */
1791                 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
1792                                 "add flag = 1, "
1793                                 "and endpoint is not disabled.\n");
1794                 ret = -EINVAL;
1795                 break;
1796         case COMP_INCOMPATIBLE_DEVICE_ERROR:
1797                 dev_warn(&udev->dev,
1798                          "ERROR: Incompatible device for endpoint configure command.\n");
1799                 ret = -ENODEV;
1800                 break;
1801         case COMP_SUCCESS:
1802                 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1803                                 "Successful Endpoint Configure command");
1804                 ret = 0;
1805                 break;
1806         default:
1807                 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
1808                                 *cmd_status);
1809                 ret = -EINVAL;
1810                 break;
1811         }
1812         return ret;
1813 }
1814
1815 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
1816                 struct usb_device *udev, u32 *cmd_status)
1817 {
1818         int ret;
1819
1820         switch (*cmd_status) {
1821         case COMP_COMMAND_ABORTED:
1822         case COMP_COMMAND_RING_STOPPED:
1823                 xhci_warn(xhci, "Timeout while waiting for evaluate context command\n");
1824                 ret = -ETIME;
1825                 break;
1826         case COMP_PARAMETER_ERROR:
1827                 dev_warn(&udev->dev,
1828                          "WARN: xHCI driver setup invalid evaluate context command.\n");
1829                 ret = -EINVAL;
1830                 break;
1831         case COMP_SLOT_NOT_ENABLED_ERROR:
1832                 dev_warn(&udev->dev,
1833                         "WARN: slot not enabled for evaluate context command.\n");
1834                 ret = -EINVAL;
1835                 break;
1836         case COMP_CONTEXT_STATE_ERROR:
1837                 dev_warn(&udev->dev,
1838                         "WARN: invalid context state for evaluate context command.\n");
1839                 ret = -EINVAL;
1840                 break;
1841         case COMP_INCOMPATIBLE_DEVICE_ERROR:
1842                 dev_warn(&udev->dev,
1843                         "ERROR: Incompatible device for evaluate context command.\n");
1844                 ret = -ENODEV;
1845                 break;
1846         case COMP_MAX_EXIT_LATENCY_TOO_LARGE_ERROR:
1847                 /* Max Exit Latency too large error */
1848                 dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
1849                 ret = -EINVAL;
1850                 break;
1851         case COMP_SUCCESS:
1852                 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1853                                 "Successful evaluate context command");
1854                 ret = 0;
1855                 break;
1856         default:
1857                 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
1858                         *cmd_status);
1859                 ret = -EINVAL;
1860                 break;
1861         }
1862         return ret;
1863 }
1864
1865 static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
1866                 struct xhci_input_control_ctx *ctrl_ctx)
1867 {
1868         u32 valid_add_flags;
1869         u32 valid_drop_flags;
1870
1871         /* Ignore the slot flag (bit 0), and the default control endpoint flag
1872          * (bit 1).  The default control endpoint is added during the Address
1873          * Device command and is never removed until the slot is disabled.
1874          */
1875         valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
1876         valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
1877
1878         /* Use hweight32 to count the number of ones in the add flags, or
1879          * number of endpoints added.  Don't count endpoints that are changed
1880          * (both added and dropped).
1881          */
1882         return hweight32(valid_add_flags) -
1883                 hweight32(valid_add_flags & valid_drop_flags);
1884 }
1885
1886 static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
1887                 struct xhci_input_control_ctx *ctrl_ctx)
1888 {
1889         u32 valid_add_flags;
1890         u32 valid_drop_flags;
1891
1892         valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
1893         valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
1894
1895         return hweight32(valid_drop_flags) -
1896                 hweight32(valid_add_flags & valid_drop_flags);
1897 }
1898
1899 /*
1900  * We need to reserve the new number of endpoints before the configure endpoint
1901  * command completes.  We can't subtract the dropped endpoints from the number
1902  * of active endpoints until the command completes because we can oversubscribe
1903  * the host in this case:
1904  *
1905  *  - the first configure endpoint command drops more endpoints than it adds
1906  *  - a second configure endpoint command that adds more endpoints is queued
1907  *  - the first configure endpoint command fails, so the config is unchanged
1908  *  - the second command may succeed, even though there isn't enough resources
1909  *
1910  * Must be called with xhci->lock held.
1911  */
1912 static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
1913                 struct xhci_input_control_ctx *ctrl_ctx)
1914 {
1915         u32 added_eps;
1916
1917         added_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
1918         if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
1919                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1920                                 "Not enough ep ctxs: "
1921                                 "%u active, need to add %u, limit is %u.",
1922                                 xhci->num_active_eps, added_eps,
1923                                 xhci->limit_active_eps);
1924                 return -ENOMEM;
1925         }
1926         xhci->num_active_eps += added_eps;
1927         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1928                         "Adding %u ep ctxs, %u now active.", added_eps,
1929                         xhci->num_active_eps);
1930         return 0;
1931 }
1932
1933 /*
1934  * The configure endpoint was failed by the xHC for some other reason, so we
1935  * need to revert the resources that failed configuration would have used.
1936  *
1937  * Must be called with xhci->lock held.
1938  */
1939 static void xhci_free_host_resources(struct xhci_hcd *xhci,
1940                 struct xhci_input_control_ctx *ctrl_ctx)
1941 {
1942         u32 num_failed_eps;
1943
1944         num_failed_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
1945         xhci->num_active_eps -= num_failed_eps;
1946         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1947                         "Removing %u failed ep ctxs, %u now active.",
1948                         num_failed_eps,
1949                         xhci->num_active_eps);
1950 }
1951
1952 /*
1953  * Now that the command has completed, clean up the active endpoint count by
1954  * subtracting out the endpoints that were dropped (but not changed).
1955  *
1956  * Must be called with xhci->lock held.
1957  */
1958 static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
1959                 struct xhci_input_control_ctx *ctrl_ctx)
1960 {
1961         u32 num_dropped_eps;
1962
1963         num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, ctrl_ctx);
1964         xhci->num_active_eps -= num_dropped_eps;
1965         if (num_dropped_eps)
1966                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1967                                 "Removing %u dropped ep ctxs, %u now active.",
1968                                 num_dropped_eps,
1969                                 xhci->num_active_eps);
1970 }
1971
1972 static unsigned int xhci_get_block_size(struct usb_device *udev)
1973 {
1974         switch (udev->speed) {
1975         case USB_SPEED_LOW:
1976         case USB_SPEED_FULL:
1977                 return FS_BLOCK;
1978         case USB_SPEED_HIGH:
1979                 return HS_BLOCK;
1980         case USB_SPEED_SUPER:
1981         case USB_SPEED_SUPER_PLUS:
1982                 return SS_BLOCK;
1983         case USB_SPEED_UNKNOWN:
1984         case USB_SPEED_WIRELESS:
1985         default:
1986                 /* Should never happen */
1987                 return 1;
1988         }
1989 }
1990
1991 static unsigned int
1992 xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
1993 {
1994         if (interval_bw->overhead[LS_OVERHEAD_TYPE])
1995                 return LS_OVERHEAD;
1996         if (interval_bw->overhead[FS_OVERHEAD_TYPE])
1997                 return FS_OVERHEAD;
1998         return HS_OVERHEAD;
1999 }
2000
2001 /* If we are changing a LS/FS device under a HS hub,
2002  * make sure (if we are activating a new TT) that the HS bus has enough
2003  * bandwidth for this new TT.
2004  */
2005 static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
2006                 struct xhci_virt_device *virt_dev,
2007                 int old_active_eps)
2008 {
2009         struct xhci_interval_bw_table *bw_table;
2010         struct xhci_tt_bw_info *tt_info;
2011
2012         /* Find the bandwidth table for the root port this TT is attached to. */
2013         bw_table = &xhci->rh_bw[virt_dev->real_port - 1].bw_table;
2014         tt_info = virt_dev->tt_info;
2015         /* If this TT already had active endpoints, the bandwidth for this TT
2016          * has already been added.  Removing all periodic endpoints (and thus
2017          * making the TT enactive) will only decrease the bandwidth used.
2018          */
2019         if (old_active_eps)
2020                 return 0;
2021         if (old_active_eps == 0 && tt_info->active_eps != 0) {
2022                 if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
2023                         return -ENOMEM;
2024                 return 0;
2025         }
2026         /* Not sure why we would have no new active endpoints...
2027          *
2028          * Maybe because of an Evaluate Context change for a hub update or a
2029          * control endpoint 0 max packet size change?
2030          * FIXME: skip the bandwidth calculation in that case.
2031          */
2032         return 0;
2033 }
2034
2035 static int xhci_check_ss_bw(struct xhci_hcd *xhci,
2036                 struct xhci_virt_device *virt_dev)
2037 {
2038         unsigned int bw_reserved;
2039
2040         bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
2041         if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
2042                 return -ENOMEM;
2043
2044         bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
2045         if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
2046                 return -ENOMEM;
2047
2048         return 0;
2049 }
2050
2051 /*
2052  * This algorithm is a very conservative estimate of the worst-case scheduling
2053  * scenario for any one interval.  The hardware dynamically schedules the
2054  * packets, so we can't tell which microframe could be the limiting factor in
2055  * the bandwidth scheduling.  This only takes into account periodic endpoints.
2056  *
2057  * Obviously, we can't solve an NP complete problem to find the minimum worst
2058  * case scenario.  Instead, we come up with an estimate that is no less than
2059  * the worst case bandwidth used for any one microframe, but may be an
2060  * over-estimate.
2061  *
2062  * We walk the requirements for each endpoint by interval, starting with the
2063  * smallest interval, and place packets in the schedule where there is only one
2064  * possible way to schedule packets for that interval.  In order to simplify
2065  * this algorithm, we record the largest max packet size for each interval, and
2066  * assume all packets will be that size.
2067  *
2068  * For interval 0, we obviously must schedule all packets for each interval.
2069  * The bandwidth for interval 0 is just the amount of data to be transmitted
2070  * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2071  * the number of packets).
2072  *
2073  * For interval 1, we have two possible microframes to schedule those packets
2074  * in.  For this algorithm, if we can schedule the same number of packets for
2075  * each possible scheduling opportunity (each microframe), we will do so.  The
2076  * remaining number of packets will be saved to be transmitted in the gaps in
2077  * the next interval's scheduling sequence.
2078  *
2079  * As we move those remaining packets to be scheduled with interval 2 packets,
2080  * we have to double the number of remaining packets to transmit.  This is
2081  * because the intervals are actually powers of 2, and we would be transmitting
2082  * the previous interval's packets twice in this interval.  We also have to be
2083  * sure that when we look at the largest max packet size for this interval, we
2084  * also look at the largest max packet size for the remaining packets and take
2085  * the greater of the two.
2086  *
2087  * The algorithm continues to evenly distribute packets in each scheduling
2088  * opportunity, and push the remaining packets out, until we get to the last
2089  * interval.  Then those packets and their associated overhead are just added
2090  * to the bandwidth used.
2091  */
2092 static int xhci_check_bw_table(struct xhci_hcd *xhci,
2093                 struct xhci_virt_device *virt_dev,
2094                 int old_active_eps)
2095 {
2096         unsigned int bw_reserved;
2097         unsigned int max_bandwidth;
2098         unsigned int bw_used;
2099         unsigned int block_size;
2100         struct xhci_interval_bw_table *bw_table;
2101         unsigned int packet_size = 0;
2102         unsigned int overhead = 0;
2103         unsigned int packets_transmitted = 0;
2104         unsigned int packets_remaining = 0;
2105         unsigned int i;
2106
2107         if (virt_dev->udev->speed >= USB_SPEED_SUPER)
2108                 return xhci_check_ss_bw(xhci, virt_dev);
2109
2110         if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2111                 max_bandwidth = HS_BW_LIMIT;
2112                 /* Convert percent of bus BW reserved to blocks reserved */
2113                 bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2114         } else {
2115                 max_bandwidth = FS_BW_LIMIT;
2116                 bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2117         }
2118
2119         bw_table = virt_dev->bw_table;
2120         /* We need to translate the max packet size and max ESIT payloads into
2121          * the units the hardware uses.
2122          */
2123         block_size = xhci_get_block_size(virt_dev->udev);
2124
2125         /* If we are manipulating a LS/FS device under a HS hub, double check
2126          * that the HS bus has enough bandwidth if we are activing a new TT.
2127          */
2128         if (virt_dev->tt_info) {
2129                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2130                                 "Recalculating BW for rootport %u",
2131                                 virt_dev->real_port);
2132                 if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2133                         xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2134                                         "newly activated TT.\n");
2135                         return -ENOMEM;
2136                 }
2137                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2138                                 "Recalculating BW for TT slot %u port %u",
2139                                 virt_dev->tt_info->slot_id,
2140                                 virt_dev->tt_info->ttport);
2141         } else {
2142                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2143                                 "Recalculating BW for rootport %u",
2144                                 virt_dev->real_port);
2145         }
2146
2147         /* Add in how much bandwidth will be used for interval zero, or the
2148          * rounded max ESIT payload + number of packets * largest overhead.
2149          */
2150         bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2151                 bw_table->interval_bw[0].num_packets *
2152                 xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2153
2154         for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2155                 unsigned int bw_added;
2156                 unsigned int largest_mps;
2157                 unsigned int interval_overhead;
2158
2159                 /*
2160                  * How many packets could we transmit in this interval?
2161                  * If packets didn't fit in the previous interval, we will need
2162                  * to transmit that many packets twice within this interval.
2163                  */
2164                 packets_remaining = 2 * packets_remaining +
2165                         bw_table->interval_bw[i].num_packets;
2166
2167                 /* Find the largest max packet size of this or the previous
2168                  * interval.
2169                  */
2170                 if (list_empty(&bw_table->interval_bw[i].endpoints))
2171                         largest_mps = 0;
2172                 else {
2173                         struct xhci_virt_ep *virt_ep;
2174                         struct list_head *ep_entry;
2175
2176                         ep_entry = bw_table->interval_bw[i].endpoints.next;
2177                         virt_ep = list_entry(ep_entry,
2178                                         struct xhci_virt_ep, bw_endpoint_list);
2179                         /* Convert to blocks, rounding up */
2180                         largest_mps = DIV_ROUND_UP(
2181                                         virt_ep->bw_info.max_packet_size,
2182                                         block_size);
2183                 }
2184                 if (largest_mps > packet_size)
2185                         packet_size = largest_mps;
2186
2187                 /* Use the larger overhead of this or the previous interval. */
2188                 interval_overhead = xhci_get_largest_overhead(
2189                                 &bw_table->interval_bw[i]);
2190                 if (interval_overhead > overhead)
2191                         overhead = interval_overhead;
2192
2193                 /* How many packets can we evenly distribute across
2194                  * (1 << (i + 1)) possible scheduling opportunities?
2195                  */
2196                 packets_transmitted = packets_remaining >> (i + 1);
2197
2198                 /* Add in the bandwidth used for those scheduled packets */
2199                 bw_added = packets_transmitted * (overhead + packet_size);
2200
2201                 /* How many packets do we have remaining to transmit? */
2202                 packets_remaining = packets_remaining % (1 << (i + 1));
2203
2204                 /* What largest max packet size should those packets have? */
2205                 /* If we've transmitted all packets, don't carry over the
2206                  * largest packet size.
2207                  */
2208                 if (packets_remaining == 0) {
2209                         packet_size = 0;
2210                         overhead = 0;
2211                 } else if (packets_transmitted > 0) {
2212                         /* Otherwise if we do have remaining packets, and we've
2213                          * scheduled some packets in this interval, take the
2214                          * largest max packet size from endpoints with this
2215                          * interval.
2216                          */
2217                         packet_size = largest_mps;
2218                         overhead = interval_overhead;
2219                 }
2220                 /* Otherwise carry over packet_size and overhead from the last
2221                  * time we had a remainder.
2222                  */
2223                 bw_used += bw_added;
2224                 if (bw_used > max_bandwidth) {
2225                         xhci_warn(xhci, "Not enough bandwidth. "
2226                                         "Proposed: %u, Max: %u\n",
2227                                 bw_used, max_bandwidth);
2228                         return -ENOMEM;
2229                 }
2230         }
2231         /*
2232          * Ok, we know we have some packets left over after even-handedly
2233          * scheduling interval 15.  We don't know which microframes they will
2234          * fit into, so we over-schedule and say they will be scheduled every
2235          * microframe.
2236          */
2237         if (packets_remaining > 0)
2238                 bw_used += overhead + packet_size;
2239
2240         if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2241                 unsigned int port_index = virt_dev->real_port - 1;
2242
2243                 /* OK, we're manipulating a HS device attached to a
2244                  * root port bandwidth domain.  Include the number of active TTs
2245                  * in the bandwidth used.
2246                  */
2247                 bw_used += TT_HS_OVERHEAD *
2248                         xhci->rh_bw[port_index].num_active_tts;
2249         }
2250
2251         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2252                 "Final bandwidth: %u, Limit: %u, Reserved: %u, "
2253                 "Available: %u " "percent",
2254                 bw_used, max_bandwidth, bw_reserved,
2255                 (max_bandwidth - bw_used - bw_reserved) * 100 /
2256                 max_bandwidth);
2257
2258         bw_used += bw_reserved;
2259         if (bw_used > max_bandwidth) {
2260                 xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2261                                 bw_used, max_bandwidth);
2262                 return -ENOMEM;
2263         }
2264
2265         bw_table->bw_used = bw_used;
2266         return 0;
2267 }
2268
2269 static bool xhci_is_async_ep(unsigned int ep_type)
2270 {
2271         return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2272                                         ep_type != ISOC_IN_EP &&
2273                                         ep_type != INT_IN_EP);
2274 }
2275
2276 static bool xhci_is_sync_in_ep(unsigned int ep_type)
2277 {
2278         return (ep_type == ISOC_IN_EP || ep_type == INT_IN_EP);
2279 }
2280
2281 static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2282 {
2283         unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2284
2285         if (ep_bw->ep_interval == 0)
2286                 return SS_OVERHEAD_BURST +
2287                         (ep_bw->mult * ep_bw->num_packets *
2288                                         (SS_OVERHEAD + mps));
2289         return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2290                                 (SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2291                                 1 << ep_bw->ep_interval);
2292
2293 }
2294
2295 static void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2296                 struct xhci_bw_info *ep_bw,
2297                 struct xhci_interval_bw_table *bw_table,
2298                 struct usb_device *udev,
2299                 struct xhci_virt_ep *virt_ep,
2300                 struct xhci_tt_bw_info *tt_info)
2301 {
2302         struct xhci_interval_bw *interval_bw;
2303         int normalized_interval;
2304
2305         if (xhci_is_async_ep(ep_bw->type))
2306                 return;
2307
2308         if (udev->speed >= USB_SPEED_SUPER) {
2309                 if (xhci_is_sync_in_ep(ep_bw->type))
2310                         xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2311                                 xhci_get_ss_bw_consumed(ep_bw);
2312                 else
2313                         xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2314                                 xhci_get_ss_bw_consumed(ep_bw);
2315                 return;
2316         }
2317
2318         /* SuperSpeed endpoints never get added to intervals in the table, so
2319          * this check is only valid for HS/FS/LS devices.
2320          */
2321         if (list_empty(&virt_ep->bw_endpoint_list))
2322                 return;
2323         /* For LS/FS devices, we need to translate the interval expressed in
2324          * microframes to frames.
2325          */
2326         if (udev->speed == USB_SPEED_HIGH)
2327                 normalized_interval = ep_bw->ep_interval;
2328         else
2329                 normalized_interval = ep_bw->ep_interval - 3;
2330
2331         if (normalized_interval == 0)
2332                 bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2333         interval_bw = &bw_table->interval_bw[normalized_interval];
2334         interval_bw->num_packets -= ep_bw->num_packets;
2335         switch (udev->speed) {
2336         case USB_SPEED_LOW:
2337                 interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2338                 break;
2339         case USB_SPEED_FULL:
2340                 interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2341                 break;
2342         case USB_SPEED_HIGH:
2343                 interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2344                 break;
2345         case USB_SPEED_SUPER:
2346         case USB_SPEED_SUPER_PLUS:
2347         case USB_SPEED_UNKNOWN:
2348         case USB_SPEED_WIRELESS:
2349                 /* Should never happen because only LS/FS/HS endpoints will get
2350                  * added to the endpoint list.
2351                  */
2352                 return;
2353         }
2354         if (tt_info)
2355                 tt_info->active_eps -= 1;
2356         list_del_init(&virt_ep->bw_endpoint_list);
2357 }
2358
2359 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2360                 struct xhci_bw_info *ep_bw,
2361                 struct xhci_interval_bw_table *bw_table,
2362                 struct usb_device *udev,
2363                 struct xhci_virt_ep *virt_ep,
2364                 struct xhci_tt_bw_info *tt_info)
2365 {
2366         struct xhci_interval_bw *interval_bw;
2367         struct xhci_virt_ep *smaller_ep;
2368         int normalized_interval;
2369
2370         if (xhci_is_async_ep(ep_bw->type))
2371                 return;
2372
2373         if (udev->speed == USB_SPEED_SUPER) {
2374                 if (xhci_is_sync_in_ep(ep_bw->type))
2375                         xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2376                                 xhci_get_ss_bw_consumed(ep_bw);
2377                 else
2378                         xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2379                                 xhci_get_ss_bw_consumed(ep_bw);
2380                 return;
2381         }
2382
2383         /* For LS/FS devices, we need to translate the interval expressed in
2384          * microframes to frames.
2385          */
2386         if (udev->speed == USB_SPEED_HIGH)
2387                 normalized_interval = ep_bw->ep_interval;
2388         else
2389                 normalized_interval = ep_bw->ep_interval - 3;
2390
2391         if (normalized_interval == 0)
2392                 bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2393         interval_bw = &bw_table->interval_bw[normalized_interval];
2394         interval_bw->num_packets += ep_bw->num_packets;
2395         switch (udev->speed) {
2396         case USB_SPEED_LOW:
2397                 interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2398                 break;
2399         case USB_SPEED_FULL:
2400                 interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2401                 break;
2402         case USB_SPEED_HIGH:
2403                 interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2404                 break;
2405         case USB_SPEED_SUPER:
2406         case USB_SPEED_SUPER_PLUS:
2407         case USB_SPEED_UNKNOWN:
2408         case USB_SPEED_WIRELESS:
2409                 /* Should never happen because only LS/FS/HS endpoints will get
2410                  * added to the endpoint list.
2411                  */
2412                 return;
2413         }
2414
2415         if (tt_info)
2416                 tt_info->active_eps += 1;
2417         /* Insert the endpoint into the list, largest max packet size first. */
2418         list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2419                         bw_endpoint_list) {
2420                 if (ep_bw->max_packet_size >=
2421                                 smaller_ep->bw_info.max_packet_size) {
2422                         /* Add the new ep before the smaller endpoint */
2423                         list_add_tail(&virt_ep->bw_endpoint_list,
2424                                         &smaller_ep->bw_endpoint_list);
2425                         return;
2426                 }
2427         }
2428         /* Add the new endpoint at the end of the list. */
2429         list_add_tail(&virt_ep->bw_endpoint_list,
2430                         &interval_bw->endpoints);
2431 }
2432
2433 void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2434                 struct xhci_virt_device *virt_dev,
2435                 int old_active_eps)
2436 {
2437         struct xhci_root_port_bw_info *rh_bw_info;
2438         if (!virt_dev->tt_info)
2439                 return;
2440
2441         rh_bw_info = &xhci->rh_bw[virt_dev->real_port - 1];
2442         if (old_active_eps == 0 &&
2443                                 virt_dev->tt_info->active_eps != 0) {
2444                 rh_bw_info->num_active_tts += 1;
2445                 rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2446         } else if (old_active_eps != 0 &&
2447                                 virt_dev->tt_info->active_eps == 0) {
2448                 rh_bw_info->num_active_tts -= 1;
2449                 rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2450         }
2451 }
2452
2453 static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2454                 struct xhci_virt_device *virt_dev,
2455                 struct xhci_container_ctx *in_ctx)
2456 {
2457         struct xhci_bw_info ep_bw_info[31];
2458         int i;
2459         struct xhci_input_control_ctx *ctrl_ctx;
2460         int old_active_eps = 0;
2461
2462         if (virt_dev->tt_info)
2463                 old_active_eps = virt_dev->tt_info->active_eps;
2464
2465         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2466         if (!ctrl_ctx) {
2467                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2468                                 __func__);
2469                 return -ENOMEM;
2470         }
2471
2472         for (i = 0; i < 31; i++) {
2473                 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2474                         continue;
2475
2476                 /* Make a copy of the BW info in case we need to revert this */
2477                 memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2478                                 sizeof(ep_bw_info[i]));
2479                 /* Drop the endpoint from the interval table if the endpoint is
2480                  * being dropped or changed.
2481                  */
2482                 if (EP_IS_DROPPED(ctrl_ctx, i))
2483                         xhci_drop_ep_from_interval_table(xhci,
2484                                         &virt_dev->eps[i].bw_info,
2485                                         virt_dev->bw_table,
2486                                         virt_dev->udev,
2487                                         &virt_dev->eps[i],
2488                                         virt_dev->tt_info);
2489         }
2490         /* Overwrite the information stored in the endpoints' bw_info */
2491         xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2492         for (i = 0; i < 31; i++) {
2493                 /* Add any changed or added endpoints to the interval table */
2494                 if (EP_IS_ADDED(ctrl_ctx, i))
2495                         xhci_add_ep_to_interval_table(xhci,
2496                                         &virt_dev->eps[i].bw_info,
2497                                         virt_dev->bw_table,
2498                                         virt_dev->udev,
2499                                         &virt_dev->eps[i],
2500                                         virt_dev->tt_info);
2501         }
2502
2503         if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2504                 /* Ok, this fits in the bandwidth we have.
2505                  * Update the number of active TTs.
2506                  */
2507                 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2508                 return 0;
2509         }
2510
2511         /* We don't have enough bandwidth for this, revert the stored info. */
2512         for (i = 0; i < 31; i++) {
2513                 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2514                         continue;
2515
2516                 /* Drop the new copies of any added or changed endpoints from
2517                  * the interval table.
2518                  */
2519                 if (EP_IS_ADDED(ctrl_ctx, i)) {
2520                         xhci_drop_ep_from_interval_table(xhci,
2521                                         &virt_dev->eps[i].bw_info,
2522                                         virt_dev->bw_table,
2523                                         virt_dev->udev,
2524                                         &virt_dev->eps[i],
2525                                         virt_dev->tt_info);
2526                 }
2527                 /* Revert the endpoint back to its old information */
2528                 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2529                                 sizeof(ep_bw_info[i]));
2530                 /* Add any changed or dropped endpoints back into the table */
2531                 if (EP_IS_DROPPED(ctrl_ctx, i))
2532                         xhci_add_ep_to_interval_table(xhci,
2533                                         &virt_dev->eps[i].bw_info,
2534                                         virt_dev->bw_table,
2535                                         virt_dev->udev,
2536                                         &virt_dev->eps[i],
2537                                         virt_dev->tt_info);
2538         }
2539         return -ENOMEM;
2540 }
2541
2542
2543 /* Issue a configure endpoint command or evaluate context command
2544  * and wait for it to finish.
2545  */
2546 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2547                 struct usb_device *udev,
2548                 struct xhci_command *command,
2549                 bool ctx_change, bool must_succeed)
2550 {
2551         int ret;
2552         unsigned long flags;
2553         struct xhci_input_control_ctx *ctrl_ctx;
2554         struct xhci_virt_device *virt_dev;
2555
2556         if (!command)
2557                 return -EINVAL;
2558
2559         spin_lock_irqsave(&xhci->lock, flags);
2560
2561         if (xhci->xhc_state & XHCI_STATE_DYING) {
2562                 spin_unlock_irqrestore(&xhci->lock, flags);
2563                 return -ESHUTDOWN;
2564         }
2565
2566         virt_dev = xhci->devs[udev->slot_id];
2567
2568         ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2569         if (!ctrl_ctx) {
2570                 spin_unlock_irqrestore(&xhci->lock, flags);
2571                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2572                                 __func__);
2573                 return -ENOMEM;
2574         }
2575
2576         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
2577                         xhci_reserve_host_resources(xhci, ctrl_ctx)) {
2578                 spin_unlock_irqrestore(&xhci->lock, flags);
2579                 xhci_warn(xhci, "Not enough host resources, "
2580                                 "active endpoint contexts = %u\n",
2581                                 xhci->num_active_eps);
2582                 return -ENOMEM;
2583         }
2584         if ((xhci->quirks & XHCI_SW_BW_CHECKING) &&
2585             xhci_reserve_bandwidth(xhci, virt_dev, command->in_ctx)) {
2586                 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2587                         xhci_free_host_resources(xhci, ctrl_ctx);
2588                 spin_unlock_irqrestore(&xhci->lock, flags);
2589                 xhci_warn(xhci, "Not enough bandwidth\n");
2590                 return -ENOMEM;
2591         }
2592
2593         if (!ctx_change)
2594                 ret = xhci_queue_configure_endpoint(xhci, command,
2595                                 command->in_ctx->dma,
2596                                 udev->slot_id, must_succeed);
2597         else
2598                 ret = xhci_queue_evaluate_context(xhci, command,
2599                                 command->in_ctx->dma,
2600                                 udev->slot_id, must_succeed);
2601         if (ret < 0) {
2602                 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2603                         xhci_free_host_resources(xhci, ctrl_ctx);
2604                 spin_unlock_irqrestore(&xhci->lock, flags);
2605                 xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
2606                                 "FIXME allocate a new ring segment");
2607                 return -ENOMEM;
2608         }
2609         xhci_ring_cmd_db(xhci);
2610         spin_unlock_irqrestore(&xhci->lock, flags);
2611
2612         /* Wait for the configure endpoint command to complete */
2613         wait_for_completion(command->completion);
2614
2615         if (!ctx_change)
2616                 ret = xhci_configure_endpoint_result(xhci, udev,
2617                                                      &command->status);
2618         else
2619                 ret = xhci_evaluate_context_result(xhci, udev,
2620                                                    &command->status);
2621
2622         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
2623                 spin_lock_irqsave(&xhci->lock, flags);
2624                 /* If the command failed, remove the reserved resources.
2625                  * Otherwise, clean up the estimate to include dropped eps.
2626                  */
2627                 if (ret)
2628                         xhci_free_host_resources(xhci, ctrl_ctx);
2629                 else
2630                         xhci_finish_resource_reservation(xhci, ctrl_ctx);
2631                 spin_unlock_irqrestore(&xhci->lock, flags);
2632         }
2633         return ret;
2634 }
2635
2636 static void xhci_check_bw_drop_ep_streams(struct xhci_hcd *xhci,
2637         struct xhci_virt_device *vdev, int i)
2638 {
2639         struct xhci_virt_ep *ep = &vdev->eps[i];
2640
2641         if (ep->ep_state & EP_HAS_STREAMS) {
2642                 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on set_interface, freeing streams.\n",
2643                                 xhci_get_endpoint_address(i));
2644                 xhci_free_stream_info(xhci, ep->stream_info);
2645                 ep->stream_info = NULL;
2646                 ep->ep_state &= ~EP_HAS_STREAMS;
2647         }
2648 }
2649
2650 /* Called after one or more calls to xhci_add_endpoint() or
2651  * xhci_drop_endpoint().  If this call fails, the USB core is expected
2652  * to call xhci_reset_bandwidth().
2653  *
2654  * Since we are in the middle of changing either configuration or
2655  * installing a new alt setting, the USB core won't allow URBs to be
2656  * enqueued for any endpoint on the old config or interface.  Nothing
2657  * else should be touching the xhci->devs[slot_id] structure, so we
2658  * don't need to take the xhci->lock for manipulating that.
2659  */
2660 static int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2661 {
2662         int i;
2663         int ret = 0;
2664         struct xhci_hcd *xhci;
2665         struct xhci_virt_device *virt_dev;
2666         struct xhci_input_control_ctx *ctrl_ctx;
2667         struct xhci_slot_ctx *slot_ctx;
2668         struct xhci_command *command;
2669
2670         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2671         if (ret <= 0)
2672                 return ret;
2673         xhci = hcd_to_xhci(hcd);
2674         if ((xhci->xhc_state & XHCI_STATE_DYING) ||
2675                 (xhci->xhc_state & XHCI_STATE_REMOVING))
2676                 return -ENODEV;
2677
2678         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2679         virt_dev = xhci->devs[udev->slot_id];
2680
2681         command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
2682         if (!command)
2683                 return -ENOMEM;
2684
2685         command->in_ctx = virt_dev->in_ctx;
2686
2687         /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
2688         ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2689         if (!ctrl_ctx) {
2690                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2691                                 __func__);
2692                 ret = -ENOMEM;
2693                 goto command_cleanup;
2694         }
2695         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2696         ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
2697         ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
2698
2699         /* Don't issue the command if there's no endpoints to update. */
2700         if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
2701             ctrl_ctx->drop_flags == 0) {
2702                 ret = 0;
2703                 goto command_cleanup;
2704         }
2705         /* Fix up Context Entries field. Minimum value is EP0 == BIT(1). */
2706         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2707         for (i = 31; i >= 1; i--) {
2708                 __le32 le32 = cpu_to_le32(BIT(i));
2709
2710                 if ((virt_dev->eps[i-1].ring && !(ctrl_ctx->drop_flags & le32))
2711                     || (ctrl_ctx->add_flags & le32) || i == 1) {
2712                         slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2713                         slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(i));
2714                         break;
2715                 }
2716         }
2717
2718         ret = xhci_configure_endpoint(xhci, udev, command,
2719                         false, false);
2720         if (ret)
2721                 /* Callee should call reset_bandwidth() */
2722                 goto command_cleanup;
2723
2724         /* Free any rings that were dropped, but not changed. */
2725         for (i = 1; i < 31; i++) {
2726                 if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
2727                     !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1)))) {
2728                         xhci_free_endpoint_ring(xhci, virt_dev, i);
2729                         xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2730                 }
2731         }
2732         xhci_zero_in_ctx(xhci, virt_dev);
2733         /*
2734          * Install any rings for completely new endpoints or changed endpoints,
2735          * and free any old rings from changed endpoints.
2736          */
2737         for (i = 1; i < 31; i++) {
2738                 if (!virt_dev->eps[i].new_ring)
2739                         continue;
2740                 /* Only free the old ring if it exists.
2741                  * It may not if this is the first add of an endpoint.
2742                  */
2743                 if (virt_dev->eps[i].ring) {
2744                         xhci_free_endpoint_ring(xhci, virt_dev, i);
2745                 }
2746                 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2747                 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
2748                 virt_dev->eps[i].new_ring = NULL;
2749         }
2750 command_cleanup:
2751         kfree(command->completion);
2752         kfree(command);
2753
2754         return ret;
2755 }
2756
2757 static void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2758 {
2759         struct xhci_hcd *xhci;
2760         struct xhci_virt_device *virt_dev;
2761         int i, ret;
2762
2763         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2764         if (ret <= 0)
2765                 return;
2766         xhci = hcd_to_xhci(hcd);
2767
2768         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2769         virt_dev = xhci->devs[udev->slot_id];
2770         /* Free any rings allocated for added endpoints */
2771         for (i = 0; i < 31; i++) {
2772                 if (virt_dev->eps[i].new_ring) {
2773                         xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
2774                         virt_dev->eps[i].new_ring = NULL;
2775                 }
2776         }
2777         xhci_zero_in_ctx(xhci, virt_dev);
2778 }
2779
2780 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
2781                 struct xhci_container_ctx *in_ctx,
2782                 struct xhci_container_ctx *out_ctx,
2783                 struct xhci_input_control_ctx *ctrl_ctx,
2784                 u32 add_flags, u32 drop_flags)
2785 {
2786         ctrl_ctx->add_flags = cpu_to_le32(add_flags);
2787         ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
2788         xhci_slot_copy(xhci, in_ctx, out_ctx);
2789         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2790 }
2791
2792 static void xhci_setup_input_ctx_for_quirk(struct xhci_hcd *xhci,
2793                 unsigned int slot_id, unsigned int ep_index,
2794                 struct xhci_dequeue_state *deq_state)
2795 {
2796         struct xhci_input_control_ctx *ctrl_ctx;
2797         struct xhci_container_ctx *in_ctx;
2798         struct xhci_ep_ctx *ep_ctx;
2799         u32 added_ctxs;
2800         dma_addr_t addr;
2801
2802         in_ctx = xhci->devs[slot_id]->in_ctx;
2803         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2804         if (!ctrl_ctx) {
2805                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2806                                 __func__);
2807                 return;
2808         }
2809
2810         xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
2811                         xhci->devs[slot_id]->out_ctx, ep_index);
2812         ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
2813         addr = xhci_trb_virt_to_dma(deq_state->new_deq_seg,
2814                         deq_state->new_deq_ptr);
2815         if (addr == 0) {
2816                 xhci_warn(xhci, "WARN Cannot submit config ep after "
2817                                 "reset ep command\n");
2818                 xhci_warn(xhci, "WARN deq seg = %p, deq ptr = %p\n",
2819                                 deq_state->new_deq_seg,
2820                                 deq_state->new_deq_ptr);
2821                 return;
2822         }
2823         ep_ctx->deq = cpu_to_le64(addr | deq_state->new_cycle_state);
2824
2825         added_ctxs = xhci_get_endpoint_flag_from_index(ep_index);
2826         xhci_setup_input_ctx_for_config_ep(xhci, xhci->devs[slot_id]->in_ctx,
2827                         xhci->devs[slot_id]->out_ctx, ctrl_ctx,
2828                         added_ctxs, added_ctxs);
2829 }
2830
2831 void xhci_cleanup_stalled_ring(struct xhci_hcd *xhci, unsigned int ep_index,
2832                                unsigned int stream_id, struct xhci_td *td)
2833 {
2834         struct xhci_dequeue_state deq_state;
2835         struct xhci_virt_ep *ep;
2836         struct usb_device *udev = td->urb->dev;
2837
2838         xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
2839                         "Cleaning up stalled endpoint ring");
2840         ep = &xhci->devs[udev->slot_id]->eps[ep_index];
2841         /* We need to move the HW's dequeue pointer past this TD,
2842          * or it will attempt to resend it on the next doorbell ring.
2843          */
2844         xhci_find_new_dequeue_state(xhci, udev->slot_id,
2845                         ep_index, stream_id, td, &deq_state);
2846
2847         if (!deq_state.new_deq_ptr || !deq_state.new_deq_seg)
2848                 return;
2849
2850         /* HW with the reset endpoint quirk will use the saved dequeue state to
2851          * issue a configure endpoint command later.
2852          */
2853         if (!(xhci->quirks & XHCI_RESET_EP_QUIRK)) {
2854                 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
2855                                 "Queueing new dequeue state");
2856                 xhci_queue_new_dequeue_state(xhci, udev->slot_id,
2857                                 ep_index, &deq_state);
2858         } else {
2859                 /* Better hope no one uses the input context between now and the
2860                  * reset endpoint completion!
2861                  * XXX: No idea how this hardware will react when stream rings
2862                  * are enabled.
2863                  */
2864                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2865                                 "Setting up input context for "
2866                                 "configure endpoint command");
2867                 xhci_setup_input_ctx_for_quirk(xhci, udev->slot_id,
2868                                 ep_index, &deq_state);
2869         }
2870 }
2871
2872 /* Called when clearing halted device. The core should have sent the control
2873  * message to clear the device halt condition. The host side of the halt should
2874  * already be cleared with a reset endpoint command issued when the STALL tx
2875  * event was received.
2876  *
2877  * Context: in_interrupt
2878  */
2879
2880 static void xhci_endpoint_reset(struct usb_hcd *hcd,
2881                 struct usb_host_endpoint *ep)
2882 {
2883         struct xhci_hcd *xhci;
2884
2885         xhci = hcd_to_xhci(hcd);
2886
2887         /*
2888          * We might need to implement the config ep cmd in xhci 4.8.1 note:
2889          * The Reset Endpoint Command may only be issued to endpoints in the
2890          * Halted state. If software wishes reset the Data Toggle or Sequence
2891          * Number of an endpoint that isn't in the Halted state, then software
2892          * may issue a Configure Endpoint Command with the Drop and Add bits set
2893          * for the target endpoint. that is in the Stopped state.
2894          */
2895
2896         /* For now just print debug to follow the situation */
2897         xhci_dbg(xhci, "Endpoint 0x%x ep reset callback called\n",
2898                  ep->desc.bEndpointAddress);
2899 }
2900
2901 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
2902                 struct usb_device *udev, struct usb_host_endpoint *ep,
2903                 unsigned int slot_id)
2904 {
2905         int ret;
2906         unsigned int ep_index;
2907         unsigned int ep_state;
2908
2909         if (!ep)
2910                 return -EINVAL;
2911         ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
2912         if (ret <= 0)
2913                 return -EINVAL;
2914         if (usb_ss_max_streams(&ep->ss_ep_comp) == 0) {
2915                 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
2916                                 " descriptor for ep 0x%x does not support streams\n",
2917                                 ep->desc.bEndpointAddress);
2918                 return -EINVAL;
2919         }
2920
2921         ep_index = xhci_get_endpoint_index(&ep->desc);
2922         ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
2923         if (ep_state & EP_HAS_STREAMS ||
2924                         ep_state & EP_GETTING_STREAMS) {
2925                 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
2926                                 "already has streams set up.\n",
2927                                 ep->desc.bEndpointAddress);
2928                 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
2929                                 "dynamic stream context array reallocation.\n");
2930                 return -EINVAL;
2931         }
2932         if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
2933                 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
2934                                 "endpoint 0x%x; URBs are pending.\n",
2935                                 ep->desc.bEndpointAddress);
2936                 return -EINVAL;
2937         }
2938         return 0;
2939 }
2940
2941 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
2942                 unsigned int *num_streams, unsigned int *num_stream_ctxs)
2943 {
2944         unsigned int max_streams;
2945
2946         /* The stream context array size must be a power of two */
2947         *num_stream_ctxs = roundup_pow_of_two(*num_streams);
2948         /*
2949          * Find out how many primary stream array entries the host controller
2950          * supports.  Later we may use secondary stream arrays (similar to 2nd
2951          * level page entries), but that's an optional feature for xHCI host
2952          * controllers. xHCs must support at least 4 stream IDs.
2953          */
2954         max_streams = HCC_MAX_PSA(xhci->hcc_params);
2955         if (*num_stream_ctxs > max_streams) {
2956                 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
2957                                 max_streams);
2958                 *num_stream_ctxs = max_streams;
2959                 *num_streams = max_streams;
2960         }
2961 }
2962
2963 /* Returns an error code if one of the endpoint already has streams.
2964  * This does not change any data structures, it only checks and gathers
2965  * information.
2966  */
2967 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
2968                 struct usb_device *udev,
2969                 struct usb_host_endpoint **eps, unsigned int num_eps,
2970                 unsigned int *num_streams, u32 *changed_ep_bitmask)
2971 {
2972         unsigned int max_streams;
2973         unsigned int endpoint_flag;
2974         int i;
2975         int ret;
2976
2977         for (i = 0; i < num_eps; i++) {
2978                 ret = xhci_check_streams_endpoint(xhci, udev,
2979                                 eps[i], udev->slot_id);
2980                 if (ret < 0)
2981                         return ret;
2982
2983                 max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
2984                 if (max_streams < (*num_streams - 1)) {
2985                         xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
2986                                         eps[i]->desc.bEndpointAddress,
2987                                         max_streams);
2988                         *num_streams = max_streams+1;
2989                 }
2990
2991                 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
2992                 if (*changed_ep_bitmask & endpoint_flag)
2993                         return -EINVAL;
2994                 *changed_ep_bitmask |= endpoint_flag;
2995         }
2996         return 0;
2997 }
2998
2999 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
3000                 struct usb_device *udev,
3001                 struct usb_host_endpoint **eps, unsigned int num_eps)
3002 {
3003         u32 changed_ep_bitmask = 0;
3004         unsigned int slot_id;
3005         unsigned int ep_index;
3006         unsigned int ep_state;
3007         int i;
3008
3009         slot_id = udev->slot_id;
3010         if (!xhci->devs[slot_id])
3011                 return 0;
3012
3013         for (i = 0; i < num_eps; i++) {
3014                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3015                 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3016                 /* Are streams already being freed for the endpoint? */
3017                 if (ep_state & EP_GETTING_NO_STREAMS) {
3018                         xhci_warn(xhci, "WARN Can't disable streams for "
3019                                         "endpoint 0x%x, "
3020                                         "streams are being disabled already\n",
3021                                         eps[i]->desc.bEndpointAddress);
3022                         return 0;
3023                 }
3024                 /* Are there actually any streams to free? */
3025                 if (!(ep_state & EP_HAS_STREAMS) &&
3026                                 !(ep_state & EP_GETTING_STREAMS)) {
3027                         xhci_warn(xhci, "WARN Can't disable streams for "
3028                                         "endpoint 0x%x, "
3029                                         "streams are already disabled!\n",
3030                                         eps[i]->desc.bEndpointAddress);
3031                         xhci_warn(xhci, "WARN xhci_free_streams() called "
3032                                         "with non-streams endpoint\n");
3033                         return 0;
3034                 }
3035                 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
3036         }
3037         return changed_ep_bitmask;
3038 }
3039
3040 /*
3041  * The USB device drivers use this function (through the HCD interface in USB
3042  * core) to prepare a set of bulk endpoints to use streams.  Streams are used to
3043  * coordinate mass storage command queueing across multiple endpoints (basically
3044  * a stream ID == a task ID).
3045  *
3046  * Setting up streams involves allocating the same size stream context array
3047  * for each endpoint and issuing a configure endpoint command for all endpoints.
3048  *
3049  * Don't allow the call to succeed if one endpoint only supports one stream
3050  * (which means it doesn't support streams at all).
3051  *
3052  * Drivers may get less stream IDs than they asked for, if the host controller
3053  * hardware or endpoints claim they can't support the number of requested
3054  * stream IDs.
3055  */
3056 static int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
3057                 struct usb_host_endpoint **eps, unsigned int num_eps,
3058                 unsigned int num_streams, gfp_t mem_flags)
3059 {
3060         int i, ret;
3061         struct xhci_hcd *xhci;
3062         struct xhci_virt_device *vdev;
3063         struct xhci_command *config_cmd;
3064         struct xhci_input_control_ctx *ctrl_ctx;
3065         unsigned int ep_index;
3066         unsigned int num_stream_ctxs;
3067         unsigned int max_packet;
3068         unsigned long flags;
3069         u32 changed_ep_bitmask = 0;
3070
3071         if (!eps)
3072                 return -EINVAL;
3073
3074         /* Add one to the number of streams requested to account for
3075          * stream 0 that is reserved for xHCI usage.
3076          */
3077         num_streams += 1;
3078         xhci = hcd_to_xhci(hcd);
3079         xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
3080                         num_streams);
3081
3082         /* MaxPSASize value 0 (2 streams) means streams are not supported */
3083         if ((xhci->quirks & XHCI_BROKEN_STREAMS) ||
3084                         HCC_MAX_PSA(xhci->hcc_params) < 4) {
3085                 xhci_dbg(xhci, "xHCI controller does not support streams.\n");
3086                 return -ENOSYS;
3087         }
3088
3089         config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
3090         if (!config_cmd)
3091                 return -ENOMEM;
3092
3093         ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
3094         if (!ctrl_ctx) {
3095                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3096                                 __func__);
3097                 xhci_free_command(xhci, config_cmd);
3098                 return -ENOMEM;
3099         }
3100
3101         /* Check to make sure all endpoints are not already configured for
3102          * streams.  While we're at it, find the maximum number of streams that
3103          * all the endpoints will support and check for duplicate endpoints.
3104          */
3105         spin_lock_irqsave(&xhci->lock, flags);
3106         ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
3107                         num_eps, &num_streams, &changed_ep_bitmask);
3108         if (ret < 0) {
3109                 xhci_free_command(xhci, config_cmd);
3110                 spin_unlock_irqrestore(&xhci->lock, flags);
3111                 return ret;
3112         }
3113         if (num_streams <= 1) {
3114                 xhci_warn(xhci, "WARN: endpoints can't handle "
3115                                 "more than one stream.\n");
3116                 xhci_free_command(xhci, config_cmd);
3117                 spin_unlock_irqrestore(&xhci->lock, flags);
3118                 return -EINVAL;
3119         }
3120         vdev = xhci->devs[udev->slot_id];
3121         /* Mark each endpoint as being in transition, so
3122          * xhci_urb_enqueue() will reject all URBs.
3123          */
3124         for (i = 0; i < num_eps; i++) {
3125                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3126                 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
3127         }
3128         spin_unlock_irqrestore(&xhci->lock, flags);
3129
3130         /* Setup internal data structures and allocate HW data structures for
3131          * streams (but don't install the HW structures in the input context
3132          * until we're sure all memory allocation succeeded).
3133          */
3134         xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
3135         xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
3136                         num_stream_ctxs, num_streams);
3137
3138         for (i = 0; i < num_eps; i++) {
3139                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3140                 max_packet = usb_endpoint_maxp(&eps[i]->desc);
3141                 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
3142                                 num_stream_ctxs,
3143                                 num_streams,
3144                                 max_packet, mem_flags);
3145                 if (!vdev->eps[ep_index].stream_info)
3146                         goto cleanup;
3147                 /* Set maxPstreams in endpoint context and update deq ptr to
3148                  * point to stream context array. FIXME
3149                  */
3150         }
3151
3152         /* Set up the input context for a configure endpoint command. */
3153         for (i = 0; i < num_eps; i++) {
3154                 struct xhci_ep_ctx *ep_ctx;
3155
3156                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3157                 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
3158
3159                 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3160                                 vdev->out_ctx, ep_index);
3161                 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3162                                 vdev->eps[ep_index].stream_info);
3163         }
3164         /* Tell the HW to drop its old copy of the endpoint context info
3165          * and add the updated copy from the input context.
3166          */
3167         xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
3168                         vdev->out_ctx, ctrl_ctx,
3169                         changed_ep_bitmask, changed_ep_bitmask);
3170
3171         /* Issue and wait for the configure endpoint command */
3172         ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3173                         false, false);
3174
3175         /* xHC rejected the configure endpoint command for some reason, so we
3176          * leave the old ring intact and free our internal streams data
3177          * structure.
3178          */
3179         if (ret < 0)
3180                 goto cleanup;
3181
3182         spin_lock_irqsave(&xhci->lock, flags);
3183         for (i = 0; i < num_eps; i++) {
3184                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3185                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3186                 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
3187                          udev->slot_id, ep_index);
3188                 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
3189         }
3190         xhci_free_command(xhci, config_cmd);
3191         spin_unlock_irqrestore(&xhci->lock, flags);
3192
3193         /* Subtract 1 for stream 0, which drivers can't use */
3194         return num_streams - 1;
3195
3196 cleanup:
3197         /* If it didn't work, free the streams! */
3198         for (i = 0; i < num_eps; i++) {
3199                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3200                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3201                 vdev->eps[ep_index].stream_info = NULL;
3202                 /* FIXME Unset maxPstreams in endpoint context and
3203                  * update deq ptr to point to normal string ring.
3204                  */
3205                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3206                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3207                 xhci_endpoint_zero(xhci, vdev, eps[i]);
3208         }
3209         xhci_free_command(xhci, config_cmd);
3210         return -ENOMEM;
3211 }
3212
3213 /* Transition the endpoint from using streams to being a "normal" endpoint
3214  * without streams.
3215  *
3216  * Modify the endpoint context state, submit a configure endpoint command,
3217  * and free all endpoint rings for streams if that completes successfully.
3218  */
3219 static int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3220                 struct usb_host_endpoint **eps, unsigned int num_eps,
3221                 gfp_t mem_flags)
3222 {
3223         int i, ret;
3224         struct xhci_hcd *xhci;
3225         struct xhci_virt_device *vdev;
3226         struct xhci_command *command;
3227         struct xhci_input_control_ctx *ctrl_ctx;
3228         unsigned int ep_index;
3229         unsigned long flags;
3230         u32 changed_ep_bitmask;
3231
3232         xhci = hcd_to_xhci(hcd);
3233         vdev = xhci->devs[udev->slot_id];
3234
3235         /* Set up a configure endpoint command to remove the streams rings */
3236         spin_lock_irqsave(&xhci->lock, flags);
3237         changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3238                         udev, eps, num_eps);
3239         if (changed_ep_bitmask == 0) {
3240                 spin_unlock_irqrestore(&xhci->lock, flags);
3241                 return -EINVAL;
3242         }
3243
3244         /* Use the xhci_command structure from the first endpoint.  We may have
3245          * allocated too many, but the driver may call xhci_free_streams() for
3246          * each endpoint it grouped into one call to xhci_alloc_streams().
3247          */
3248         ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3249         command = vdev->eps[ep_index].stream_info->free_streams_command;
3250         ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3251         if (!ctrl_ctx) {
3252                 spin_unlock_irqrestore(&xhci->lock, flags);
3253                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3254                                 __func__);
3255                 return -EINVAL;
3256         }
3257
3258         for (i = 0; i < num_eps; i++) {
3259                 struct xhci_ep_ctx *ep_ctx;
3260
3261                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3262                 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3263                 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3264                         EP_GETTING_NO_STREAMS;
3265
3266                 xhci_endpoint_copy(xhci, command->in_ctx,
3267                                 vdev->out_ctx, ep_index);
3268                 xhci_setup_no_streams_ep_input_ctx(ep_ctx,
3269                                 &vdev->eps[ep_index]);
3270         }
3271         xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3272                         vdev->out_ctx, ctrl_ctx,
3273                         changed_ep_bitmask, changed_ep_bitmask);
3274         spin_unlock_irqrestore(&xhci->lock, flags);
3275
3276         /* Issue and wait for the configure endpoint command,
3277          * which must succeed.
3278          */
3279         ret = xhci_configure_endpoint(xhci, udev, command,
3280                         false, true);
3281
3282         /* xHC rejected the configure endpoint command for some reason, so we
3283          * leave the streams rings intact.
3284          */
3285         if (ret < 0)
3286                 return ret;
3287
3288         spin_lock_irqsave(&xhci->lock, flags);
3289         for (i = 0; i < num_eps; i++) {
3290                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3291                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3292                 vdev->eps[ep_index].stream_info = NULL;
3293                 /* FIXME Unset maxPstreams in endpoint context and
3294                  * update deq ptr to point to normal string ring.
3295                  */
3296                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
3297                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3298         }
3299         spin_unlock_irqrestore(&xhci->lock, flags);
3300
3301         return 0;
3302 }
3303
3304 /*
3305  * Deletes endpoint resources for endpoints that were active before a Reset
3306  * Device command, or a Disable Slot command.  The Reset Device command leaves
3307  * the control endpoint intact, whereas the Disable Slot command deletes it.
3308  *
3309  * Must be called with xhci->lock held.
3310  */
3311 void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
3312         struct xhci_virt_device *virt_dev, bool drop_control_ep)
3313 {
3314         int i;
3315         unsigned int num_dropped_eps = 0;
3316         unsigned int drop_flags = 0;
3317
3318         for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
3319                 if (virt_dev->eps[i].ring) {
3320                         drop_flags |= 1 << i;
3321                         num_dropped_eps++;
3322                 }
3323         }
3324         xhci->num_active_eps -= num_dropped_eps;
3325         if (num_dropped_eps)
3326                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3327                                 "Dropped %u ep ctxs, flags = 0x%x, "
3328                                 "%u now active.",
3329                                 num_dropped_eps, drop_flags,
3330                                 xhci->num_active_eps);
3331 }
3332
3333 /*
3334  * This submits a Reset Device Command, which will set the device state to 0,
3335  * set the device address to 0, and disable all the endpoints except the default
3336  * control endpoint.  The USB core should come back and call
3337  * xhci_address_device(), and then re-set up the configuration.  If this is
3338  * called because of a usb_reset_and_verify_device(), then the old alternate
3339  * settings will be re-installed through the normal bandwidth allocation
3340  * functions.
3341  *
3342  * Wait for the Reset Device command to finish.  Remove all structures
3343  * associated with the endpoints that were disabled.  Clear the input device
3344  * structure? Reset the control endpoint 0 max packet size?
3345  *
3346  * If the virt_dev to be reset does not exist or does not match the udev,
3347  * it means the device is lost, possibly due to the xHC restore error and
3348  * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3349  * re-allocate the device.
3350  */
3351 static int xhci_discover_or_reset_device(struct usb_hcd *hcd,
3352                 struct usb_device *udev)
3353 {
3354         int ret, i;
3355         unsigned long flags;
3356         struct xhci_hcd *xhci;
3357         unsigned int slot_id;
3358         struct xhci_virt_device *virt_dev;
3359         struct xhci_command *reset_device_cmd;
3360         int last_freed_endpoint;
3361         struct xhci_slot_ctx *slot_ctx;
3362         int old_active_eps = 0;
3363
3364         ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3365         if (ret <= 0)
3366                 return ret;
3367         xhci = hcd_to_xhci(hcd);
3368         slot_id = udev->slot_id;
3369         virt_dev = xhci->devs[slot_id];
3370         if (!virt_dev) {
3371                 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3372                                 "not exist. Re-allocate the device\n", slot_id);
3373                 ret = xhci_alloc_dev(hcd, udev);
3374                 if (ret == 1)
3375                         return 0;
3376                 else
3377                         return -EINVAL;
3378         }
3379
3380         if (virt_dev->tt_info)
3381                 old_active_eps = virt_dev->tt_info->active_eps;
3382
3383         if (virt_dev->udev != udev) {
3384                 /* If the virt_dev and the udev does not match, this virt_dev
3385                  * may belong to another udev.
3386                  * Re-allocate the device.
3387                  */
3388                 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3389                                 "not match the udev. Re-allocate the device\n",
3390                                 slot_id);
3391                 ret = xhci_alloc_dev(hcd, udev);
3392                 if (ret == 1)
3393                         return 0;
3394                 else
3395                         return -EINVAL;
3396         }
3397
3398         /* If device is not setup, there is no point in resetting it */
3399         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3400         if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3401                                                 SLOT_STATE_DISABLED)
3402                 return 0;
3403
3404         trace_xhci_discover_or_reset_device(slot_ctx);
3405
3406         xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3407         /* Allocate the command structure that holds the struct completion.
3408          * Assume we're in process context, since the normal device reset
3409          * process has to wait for the device anyway.  Storage devices are
3410          * reset as part of error handling, so use GFP_NOIO instead of
3411          * GFP_KERNEL.
3412          */
3413         reset_device_cmd = xhci_alloc_command(xhci, false, true, GFP_NOIO);
3414         if (!reset_device_cmd) {
3415                 xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3416                 return -ENOMEM;
3417         }
3418
3419         /* Attempt to submit the Reset Device command to the command ring */
3420         spin_lock_irqsave(&xhci->lock, flags);
3421
3422         ret = xhci_queue_reset_device(xhci, reset_device_cmd, slot_id);
3423         if (ret) {
3424                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3425                 spin_unlock_irqrestore(&xhci->lock, flags);
3426                 goto command_cleanup;
3427         }
3428         xhci_ring_cmd_db(xhci);
3429         spin_unlock_irqrestore(&xhci->lock, flags);
3430
3431         /* Wait for the Reset Device command to finish */
3432         wait_for_completion(reset_device_cmd->completion);
3433
3434         /* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3435          * unless we tried to reset a slot ID that wasn't enabled,
3436          * or the device wasn't in the addressed or configured state.
3437          */
3438         ret = reset_device_cmd->status;
3439         switch (ret) {
3440         case COMP_COMMAND_ABORTED:
3441         case COMP_COMMAND_RING_STOPPED:
3442                 xhci_warn(xhci, "Timeout waiting for reset device command\n");
3443                 ret = -ETIME;
3444                 goto command_cleanup;
3445         case COMP_SLOT_NOT_ENABLED_ERROR: /* 0.95 completion for bad slot ID */
3446         case COMP_CONTEXT_STATE_ERROR: /* 0.96 completion code for same thing */
3447                 xhci_dbg(xhci, "Can't reset device (slot ID %u) in %s state\n",
3448                                 slot_id,
3449                                 xhci_get_slot_state(xhci, virt_dev->out_ctx));
3450                 xhci_dbg(xhci, "Not freeing device rings.\n");
3451                 /* Don't treat this as an error.  May change my mind later. */
3452                 ret = 0;
3453                 goto command_cleanup;
3454         case COMP_SUCCESS:
3455                 xhci_dbg(xhci, "Successful reset device command.\n");
3456                 break;
3457         default:
3458                 if (xhci_is_vendor_info_code(xhci, ret))
3459                         break;
3460                 xhci_warn(xhci, "Unknown completion code %u for "
3461                                 "reset device command.\n", ret);
3462                 ret = -EINVAL;
3463                 goto command_cleanup;
3464         }
3465
3466         /* Free up host controller endpoint resources */
3467         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3468                 spin_lock_irqsave(&xhci->lock, flags);
3469                 /* Don't delete the default control endpoint resources */
3470                 xhci_free_device_endpoint_resources(xhci, virt_dev, false);
3471                 spin_unlock_irqrestore(&xhci->lock, flags);
3472         }
3473
3474         /* Everything but endpoint 0 is disabled, so free the rings. */
3475         last_freed_endpoint = 1;
3476         for (i = 1; i < 31; i++) {
3477                 struct xhci_virt_ep *ep = &virt_dev->eps[i];
3478
3479                 if (ep->ep_state & EP_HAS_STREAMS) {
3480                         xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on device reset, freeing streams.\n",
3481                                         xhci_get_endpoint_address(i));
3482                         xhci_free_stream_info(xhci, ep->stream_info);
3483                         ep->stream_info = NULL;
3484                         ep->ep_state &= ~EP_HAS_STREAMS;
3485                 }
3486
3487                 if (ep->ring) {
3488                         xhci_free_endpoint_ring(xhci, virt_dev, i);
3489                         last_freed_endpoint = i;
3490                 }
3491                 if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
3492                         xhci_drop_ep_from_interval_table(xhci,
3493                                         &virt_dev->eps[i].bw_info,
3494                                         virt_dev->bw_table,
3495                                         udev,
3496                                         &virt_dev->eps[i],
3497                                         virt_dev->tt_info);
3498                 xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
3499         }
3500         /* If necessary, update the number of active TTs on this root port */
3501         xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
3502         ret = 0;
3503
3504 command_cleanup:
3505         xhci_free_command(xhci, reset_device_cmd);
3506         return ret;
3507 }
3508
3509 /*
3510  * At this point, the struct usb_device is about to go away, the device has
3511  * disconnected, and all traffic has been stopped and the endpoints have been
3512  * disabled.  Free any HC data structures associated with that device.
3513  */
3514 static void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
3515 {
3516         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3517         struct xhci_virt_device *virt_dev;
3518         struct xhci_slot_ctx *slot_ctx;
3519         int i, ret;
3520         struct xhci_command *command;
3521
3522         command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
3523         if (!command)
3524                 return;
3525
3526 #ifndef CONFIG_USB_DEFAULT_PERSIST
3527         /*
3528          * We called pm_runtime_get_noresume when the device was attached.
3529          * Decrement the counter here to allow controller to runtime suspend
3530          * if no devices remain.
3531          */
3532         if (xhci->quirks & XHCI_RESET_ON_RESUME)
3533                 pm_runtime_put_noidle(hcd->self.controller);
3534 #endif
3535
3536         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3537         /* If the host is halted due to driver unload, we still need to free the
3538          * device.
3539          */
3540         if (ret <= 0 && ret != -ENODEV) {
3541                 kfree(command);
3542                 return;
3543         }
3544
3545         virt_dev = xhci->devs[udev->slot_id];
3546         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3547         trace_xhci_free_dev(slot_ctx);
3548
3549         /* Stop any wayward timer functions (which may grab the lock) */
3550         for (i = 0; i < 31; i++) {
3551                 virt_dev->eps[i].ep_state &= ~EP_STOP_CMD_PENDING;
3552                 del_timer_sync(&virt_dev->eps[i].stop_cmd_timer);
3553         }
3554
3555         xhci_disable_slot(xhci, command, udev->slot_id);
3556         /*
3557          * Event command completion handler will free any data structures
3558          * associated with the slot.  XXX Can free sleep?
3559          */
3560 }
3561
3562 int xhci_disable_slot(struct xhci_hcd *xhci, struct xhci_command *command,
3563                         u32 slot_id)
3564 {
3565         unsigned long flags;
3566         u32 state;
3567         int ret = 0;
3568         struct xhci_virt_device *virt_dev;
3569
3570         virt_dev = xhci->devs[slot_id];
3571         if (!virt_dev)
3572                 return -EINVAL;
3573         if (!command)
3574                 command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
3575         if (!command)
3576                 return -ENOMEM;
3577
3578         spin_lock_irqsave(&xhci->lock, flags);
3579         /* Don't disable the slot if the host controller is dead. */
3580         state = readl(&xhci->op_regs->status);
3581         if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
3582                         (xhci->xhc_state & XHCI_STATE_HALTED)) {
3583                 xhci_free_virt_device(xhci, slot_id);
3584                 spin_unlock_irqrestore(&xhci->lock, flags);
3585                 kfree(command);
3586                 return ret;
3587         }
3588
3589         ret = xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
3590                                 slot_id);
3591         if (ret) {
3592                 spin_unlock_irqrestore(&xhci->lock, flags);
3593                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3594                 return ret;
3595         }
3596         xhci_ring_cmd_db(xhci);
3597         spin_unlock_irqrestore(&xhci->lock, flags);
3598         return ret;
3599 }
3600
3601 /*
3602  * Checks if we have enough host controller resources for the default control
3603  * endpoint.
3604  *
3605  * Must be called with xhci->lock held.
3606  */
3607 static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
3608 {
3609         if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
3610                 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3611                                 "Not enough ep ctxs: "
3612                                 "%u active, need to add 1, limit is %u.",
3613                                 xhci->num_active_eps, xhci->limit_active_eps);
3614                 return -ENOMEM;
3615         }
3616         xhci->num_active_eps += 1;
3617         xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3618                         "Adding 1 ep ctx, %u now active.",
3619                         xhci->num_active_eps);
3620         return 0;
3621 }
3622
3623
3624 /*
3625  * Returns 0 if the xHC ran out of device slots, the Enable Slot command
3626  * timed out, or allocating memory failed.  Returns 1 on success.
3627  */
3628 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
3629 {
3630         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3631         struct xhci_virt_device *vdev;
3632         struct xhci_slot_ctx *slot_ctx;
3633         unsigned long flags;
3634         int ret, slot_id;
3635         struct xhci_command *command;
3636
3637         command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
3638         if (!command)
3639                 return 0;
3640
3641         /* xhci->slot_id and xhci->addr_dev are not thread-safe */
3642         mutex_lock(&xhci->mutex);
3643         spin_lock_irqsave(&xhci->lock, flags);
3644         ret = xhci_queue_slot_control(xhci, command, TRB_ENABLE_SLOT, 0);
3645         if (ret) {
3646                 spin_unlock_irqrestore(&xhci->lock, flags);
3647                 mutex_unlock(&xhci->mutex);
3648                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3649                 xhci_free_command(xhci, command);
3650                 return 0;
3651         }
3652         xhci_ring_cmd_db(xhci);
3653         spin_unlock_irqrestore(&xhci->lock, flags);
3654
3655         wait_for_completion(command->completion);
3656         slot_id = command->slot_id;
3657         mutex_unlock(&xhci->mutex);
3658
3659         if (!slot_id || command->status != COMP_SUCCESS) {
3660                 xhci_err(xhci, "Error while assigning device slot ID\n");
3661                 xhci_err(xhci, "Max number of devices this xHCI host supports is %u.\n",
3662                                 HCS_MAX_SLOTS(
3663                                         readl(&xhci->cap_regs->hcs_params1)));
3664                 xhci_free_command(xhci, command);
3665                 return 0;
3666         }
3667
3668         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3669                 spin_lock_irqsave(&xhci->lock, flags);
3670                 ret = xhci_reserve_host_control_ep_resources(xhci);
3671                 if (ret) {
3672                         spin_unlock_irqrestore(&xhci->lock, flags);
3673                         xhci_warn(xhci, "Not enough host resources, "
3674                                         "active endpoint contexts = %u\n",
3675                                         xhci->num_active_eps);
3676                         goto disable_slot;
3677                 }
3678                 spin_unlock_irqrestore(&xhci->lock, flags);
3679         }
3680         /* Use GFP_NOIO, since this function can be called from
3681          * xhci_discover_or_reset_device(), which may be called as part of
3682          * mass storage driver error handling.
3683          */
3684         if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) {
3685                 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
3686                 goto disable_slot;
3687         }
3688         vdev = xhci->devs[slot_id];
3689         slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
3690         trace_xhci_alloc_dev(slot_ctx);
3691
3692         udev->slot_id = slot_id;
3693
3694 #ifndef CONFIG_USB_DEFAULT_PERSIST
3695         /*
3696          * If resetting upon resume, we can't put the controller into runtime
3697          * suspend if there is a device attached.
3698          */
3699         if (xhci->quirks & XHCI_RESET_ON_RESUME)
3700                 pm_runtime_get_noresume(hcd->self.controller);
3701 #endif
3702
3703
3704         xhci_free_command(xhci, command);
3705         /* Is this a LS or FS device under a HS hub? */
3706         /* Hub or peripherial? */
3707         return 1;
3708
3709 disable_slot:
3710         /* Disable slot, if we can do it without mem alloc */
3711         kfree(command->completion);
3712         command->completion = NULL;
3713         command->status = 0;
3714         return xhci_disable_slot(xhci, command, udev->slot_id);
3715 }
3716
3717 /*
3718  * Issue an Address Device command and optionally send a corresponding
3719  * SetAddress request to the device.
3720  */
3721 static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
3722                              enum xhci_setup_dev setup)
3723 {
3724         const char *act = setup == SETUP_CONTEXT_ONLY ? "context" : "address";
3725         unsigned long flags;
3726         struct xhci_virt_device *virt_dev;
3727         int ret = 0;
3728         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3729         struct xhci_slot_ctx *slot_ctx;
3730         struct xhci_input_control_ctx *ctrl_ctx;
3731         u64 temp_64;
3732         struct xhci_command *command = NULL;
3733
3734         mutex_lock(&xhci->mutex);
3735
3736         if (xhci->xhc_state) {  /* dying, removing or halted */
3737                 ret = -ESHUTDOWN;
3738                 goto out;
3739         }
3740
3741         if (!udev->slot_id) {
3742                 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3743                                 "Bad Slot ID %d", udev->slot_id);
3744                 ret = -EINVAL;
3745                 goto out;
3746         }
3747
3748         virt_dev = xhci->devs[udev->slot_id];
3749
3750         if (WARN_ON(!virt_dev)) {
3751                 /*
3752                  * In plug/unplug torture test with an NEC controller,
3753                  * a zero-dereference was observed once due to virt_dev = 0.
3754                  * Print useful debug rather than crash if it is observed again!
3755                  */
3756                 xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
3757                         udev->slot_id);
3758                 ret = -EINVAL;
3759                 goto out;
3760         }
3761         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3762         trace_xhci_setup_device_slot(slot_ctx);
3763
3764         if (setup == SETUP_CONTEXT_ONLY) {
3765                 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3766                     SLOT_STATE_DEFAULT) {
3767                         xhci_dbg(xhci, "Slot already in default state\n");
3768                         goto out;
3769                 }
3770         }
3771
3772         command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
3773         if (!command) {
3774                 ret = -ENOMEM;
3775                 goto out;
3776         }
3777
3778         command->in_ctx = virt_dev->in_ctx;
3779
3780         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
3781         ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
3782         if (!ctrl_ctx) {
3783                 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3784                                 __func__);
3785                 ret = -EINVAL;
3786                 goto out;
3787         }
3788         /*
3789          * If this is the first Set Address since device plug-in or
3790          * virt_device realloaction after a resume with an xHCI power loss,
3791          * then set up the slot context.
3792          */
3793         if (!slot_ctx->dev_info)
3794                 xhci_setup_addressable_virt_dev(xhci, udev);
3795         /* Otherwise, update the control endpoint ring enqueue pointer. */
3796         else
3797                 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
3798         ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
3799         ctrl_ctx->drop_flags = 0;
3800
3801         trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
3802                                 le32_to_cpu(slot_ctx->dev_info) >> 27);
3803
3804         spin_lock_irqsave(&xhci->lock, flags);
3805         trace_xhci_setup_device(virt_dev);
3806         ret = xhci_queue_address_device(xhci, command, virt_dev->in_ctx->dma,
3807                                         udev->slot_id, setup);
3808         if (ret) {
3809                 spin_unlock_irqrestore(&xhci->lock, flags);
3810                 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3811                                 "FIXME: allocate a command ring segment");
3812                 goto out;
3813         }
3814         xhci_ring_cmd_db(xhci);
3815         spin_unlock_irqrestore(&xhci->lock, flags);
3816
3817         /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
3818         wait_for_completion(command->completion);
3819
3820         /* FIXME: From section 4.3.4: "Software shall be responsible for timing
3821          * the SetAddress() "recovery interval" required by USB and aborting the
3822          * command on a timeout.
3823          */