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