1 // SPDX-License-Identifier: GPL-2.0
3 * xHCI host controller driver
5 * Copyright (C) 2008 Intel Corp.
8 * Some code borrowed from the Linux EHCI driver.
11 #include <linux/pci.h>
12 #include <linux/iopoll.h>
13 #include <linux/irq.h>
14 #include <linux/log2.h>
15 #include <linux/module.h>
16 #include <linux/moduleparam.h>
17 #include <linux/slab.h>
18 #include <linux/dmi.h>
19 #include <linux/dma-mapping.h>
22 #include "xhci-trace.h"
24 #include "xhci-debugfs.h"
25 #include "xhci-dbgcap.h"
27 #define DRIVER_AUTHOR "Sarah Sharp"
28 #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
30 #define PORT_WAKE_BITS (PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E)
32 /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
33 static int link_quirk;
34 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
35 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
37 static unsigned long long quirks;
38 module_param(quirks, ullong, S_IRUGO);
39 MODULE_PARM_DESC(quirks, "Bit flags for quirks to be enabled as default");
41 static bool td_on_ring(struct xhci_td *td, struct xhci_ring *ring)
43 struct xhci_segment *seg = ring->first_seg;
45 if (!td || !td->start_seg)
48 if (seg == td->start_seg)
51 } while (seg && seg != ring->first_seg);
57 * xhci_handshake - spin reading hc until handshake completes or fails
58 * @ptr: address of hc register to be read
59 * @mask: bits to look at in result of read
60 * @done: value of those bits when handshake succeeds
61 * @usec: timeout in microseconds
63 * Returns negative errno, or zero on success
65 * Success happens when the "mask" bits have the specified value (hardware
66 * handshake done). There are two failure modes: "usec" have passed (major
67 * hardware flakeout), or the register reads as all-ones (hardware removed).
69 int xhci_handshake(void __iomem *ptr, u32 mask, u32 done, int usec)
74 ret = readl_poll_timeout_atomic(ptr, result,
75 (result & mask) == done ||
78 if (result == U32_MAX) /* card removed */
85 * Disable interrupts and begin the xHCI halting process.
87 void xhci_quiesce(struct xhci_hcd *xhci)
94 halted = readl(&xhci->op_regs->status) & STS_HALT;
98 cmd = readl(&xhci->op_regs->command);
100 writel(cmd, &xhci->op_regs->command);
104 * Force HC into halt state.
106 * Disable any IRQs and clear the run/stop bit.
107 * HC will complete any current and actively pipelined transactions, and
108 * should halt within 16 ms of the run/stop bit being cleared.
109 * Read HC Halted bit in the status register to see when the HC is finished.
111 int xhci_halt(struct xhci_hcd *xhci)
114 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Halt the HC");
117 ret = xhci_handshake(&xhci->op_regs->status,
118 STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
120 xhci_warn(xhci, "Host halt failed, %d\n", ret);
123 xhci->xhc_state |= XHCI_STATE_HALTED;
124 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
129 * Set the run bit and wait for the host to be running.
131 int xhci_start(struct xhci_hcd *xhci)
136 temp = readl(&xhci->op_regs->command);
138 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Turn on HC, cmd = 0x%x.",
140 writel(temp, &xhci->op_regs->command);
143 * Wait for the HCHalted Status bit to be 0 to indicate the host is
146 ret = xhci_handshake(&xhci->op_regs->status,
147 STS_HALT, 0, XHCI_MAX_HALT_USEC);
148 if (ret == -ETIMEDOUT)
149 xhci_err(xhci, "Host took too long to start, "
150 "waited %u microseconds.\n",
153 /* clear state flags. Including dying, halted or removing */
162 * This resets pipelines, timers, counters, state machines, etc.
163 * Transactions will be terminated immediately, and operational registers
164 * will be set to their defaults.
166 int xhci_reset(struct xhci_hcd *xhci)
172 state = readl(&xhci->op_regs->status);
174 if (state == ~(u32)0) {
175 xhci_warn(xhci, "Host not accessible, reset failed.\n");
179 if ((state & STS_HALT) == 0) {
180 xhci_warn(xhci, "Host controller not halted, aborting reset.\n");
184 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Reset the HC");
185 command = readl(&xhci->op_regs->command);
186 command |= CMD_RESET;
187 writel(command, &xhci->op_regs->command);
189 /* Existing Intel xHCI controllers require a delay of 1 mS,
190 * after setting the CMD_RESET bit, and before accessing any
191 * HC registers. This allows the HC to complete the
192 * reset operation and be ready for HC register access.
193 * Without this delay, the subsequent HC register access,
194 * may result in a system hang very rarely.
196 if (xhci->quirks & XHCI_INTEL_HOST)
199 ret = xhci_handshake(&xhci->op_regs->command,
200 CMD_RESET, 0, 10 * 1000 * 1000);
204 if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
205 usb_asmedia_modifyflowcontrol(to_pci_dev(xhci_to_hcd(xhci)->self.controller));
207 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
208 "Wait for controller to be ready for doorbell rings");
210 * xHCI cannot write to any doorbells or operational registers other
211 * than status until the "Controller Not Ready" flag is cleared.
213 ret = xhci_handshake(&xhci->op_regs->status,
214 STS_CNR, 0, 10 * 1000 * 1000);
216 for (i = 0; i < 2; i++) {
217 xhci->bus_state[i].port_c_suspend = 0;
218 xhci->bus_state[i].suspended_ports = 0;
219 xhci->bus_state[i].resuming_ports = 0;
225 static void xhci_zero_64b_regs(struct xhci_hcd *xhci)
227 struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
233 * Some Renesas controllers get into a weird state if they are
234 * reset while programmed with 64bit addresses (they will preserve
235 * the top half of the address in internal, non visible
236 * registers). You end up with half the address coming from the
237 * kernel, and the other half coming from the firmware. Also,
238 * changing the programming leads to extra accesses even if the
239 * controller is supposed to be halted. The controller ends up with
240 * a fatal fault, and is then ripe for being properly reset.
242 * Special care is taken to only apply this if the device is behind
243 * an iommu. Doing anything when there is no iommu is definitely
246 if (!(xhci->quirks & XHCI_ZERO_64B_REGS) || !dev->iommu_group)
249 xhci_info(xhci, "Zeroing 64bit base registers, expecting fault\n");
251 /* Clear HSEIE so that faults do not get signaled */
252 val = readl(&xhci->op_regs->command);
254 writel(val, &xhci->op_regs->command);
256 /* Clear HSE (aka FATAL) */
257 val = readl(&xhci->op_regs->status);
259 writel(val, &xhci->op_regs->status);
261 /* Now zero the registers, and brace for impact */
262 val = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
263 if (upper_32_bits(val))
264 xhci_write_64(xhci, 0, &xhci->op_regs->dcbaa_ptr);
265 val = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
266 if (upper_32_bits(val))
267 xhci_write_64(xhci, 0, &xhci->op_regs->cmd_ring);
269 intrs = min_t(u32, HCS_MAX_INTRS(xhci->hcs_params1),
270 ARRAY_SIZE(xhci->run_regs->ir_set));
272 for (i = 0; i < intrs; i++) {
273 struct xhci_intr_reg __iomem *ir;
275 ir = &xhci->run_regs->ir_set[i];
276 val = xhci_read_64(xhci, &ir->erst_base);
277 if (upper_32_bits(val))
278 xhci_write_64(xhci, 0, &ir->erst_base);
279 val= xhci_read_64(xhci, &ir->erst_dequeue);
280 if (upper_32_bits(val))
281 xhci_write_64(xhci, 0, &ir->erst_dequeue);
284 /* Wait for the fault to appear. It will be cleared on reset */
285 err = xhci_handshake(&xhci->op_regs->status,
286 STS_FATAL, STS_FATAL,
289 xhci_info(xhci, "Fault detected\n");
292 #ifdef CONFIG_USB_PCI
296 static int xhci_setup_msi(struct xhci_hcd *xhci)
300 * TODO:Check with MSI Soc for sysdev
302 struct pci_dev *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
304 ret = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_MSI);
306 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
307 "failed to allocate MSI entry");
311 ret = request_irq(pdev->irq, xhci_msi_irq,
312 0, "xhci_hcd", xhci_to_hcd(xhci));
314 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
315 "disable MSI interrupt");
316 pci_free_irq_vectors(pdev);
325 static int xhci_setup_msix(struct xhci_hcd *xhci)
328 struct usb_hcd *hcd = xhci_to_hcd(xhci);
329 struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
332 * calculate number of msi-x vectors supported.
333 * - HCS_MAX_INTRS: the max number of interrupts the host can handle,
334 * with max number of interrupters based on the xhci HCSPARAMS1.
335 * - num_online_cpus: maximum msi-x vectors per CPUs core.
336 * Add additional 1 vector to ensure always available interrupt.
338 xhci->msix_count = min(num_online_cpus() + 1,
339 HCS_MAX_INTRS(xhci->hcs_params1));
341 ret = pci_alloc_irq_vectors(pdev, xhci->msix_count, xhci->msix_count,
344 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
345 "Failed to enable MSI-X");
349 for (i = 0; i < xhci->msix_count; i++) {
350 ret = request_irq(pci_irq_vector(pdev, i), xhci_msi_irq, 0,
351 "xhci_hcd", xhci_to_hcd(xhci));
356 hcd->msix_enabled = 1;
360 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "disable MSI-X interrupt");
362 free_irq(pci_irq_vector(pdev, i), xhci_to_hcd(xhci));
363 pci_free_irq_vectors(pdev);
367 /* Free any IRQs and disable MSI-X */
368 static void xhci_cleanup_msix(struct xhci_hcd *xhci)
370 struct usb_hcd *hcd = xhci_to_hcd(xhci);
371 struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
373 if (xhci->quirks & XHCI_PLAT)
376 /* return if using legacy interrupt */
380 if (hcd->msix_enabled) {
383 for (i = 0; i < xhci->msix_count; i++)
384 free_irq(pci_irq_vector(pdev, i), xhci_to_hcd(xhci));
386 free_irq(pci_irq_vector(pdev, 0), xhci_to_hcd(xhci));
389 pci_free_irq_vectors(pdev);
390 hcd->msix_enabled = 0;
393 static void __maybe_unused xhci_msix_sync_irqs(struct xhci_hcd *xhci)
395 struct usb_hcd *hcd = xhci_to_hcd(xhci);
397 if (hcd->msix_enabled) {
398 struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
401 for (i = 0; i < xhci->msix_count; i++)
402 synchronize_irq(pci_irq_vector(pdev, i));
406 static int xhci_try_enable_msi(struct usb_hcd *hcd)
408 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
409 struct pci_dev *pdev;
412 /* The xhci platform device has set up IRQs through usb_add_hcd. */
413 if (xhci->quirks & XHCI_PLAT)
416 pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
418 * Some Fresco Logic host controllers advertise MSI, but fail to
419 * generate interrupts. Don't even try to enable MSI.
421 if (xhci->quirks & XHCI_BROKEN_MSI)
424 /* unregister the legacy interrupt */
426 free_irq(hcd->irq, hcd);
429 ret = xhci_setup_msix(xhci);
431 /* fall back to msi*/
432 ret = xhci_setup_msi(xhci);
435 hcd->msi_enabled = 1;
440 xhci_err(xhci, "No msi-x/msi found and no IRQ in BIOS\n");
445 if (!strlen(hcd->irq_descr))
446 snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
447 hcd->driver->description, hcd->self.busnum);
449 /* fall back to legacy interrupt*/
450 ret = request_irq(pdev->irq, &usb_hcd_irq, IRQF_SHARED,
451 hcd->irq_descr, hcd);
453 xhci_err(xhci, "request interrupt %d failed\n",
457 hcd->irq = pdev->irq;
463 static inline int xhci_try_enable_msi(struct usb_hcd *hcd)
468 static inline void xhci_cleanup_msix(struct xhci_hcd *xhci)
472 static inline void xhci_msix_sync_irqs(struct xhci_hcd *xhci)
478 static void compliance_mode_recovery(struct timer_list *t)
480 struct xhci_hcd *xhci;
482 struct xhci_hub *rhub;
486 xhci = from_timer(xhci, t, comp_mode_recovery_timer);
487 rhub = &xhci->usb3_rhub;
489 for (i = 0; i < rhub->num_ports; i++) {
490 temp = readl(rhub->ports[i]->addr);
491 if ((temp & PORT_PLS_MASK) == USB_SS_PORT_LS_COMP_MOD) {
493 * Compliance Mode Detected. Letting USB Core
494 * handle the Warm Reset
496 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
497 "Compliance mode detected->port %d",
499 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
500 "Attempting compliance mode recovery");
501 hcd = xhci->shared_hcd;
503 if (hcd->state == HC_STATE_SUSPENDED)
504 usb_hcd_resume_root_hub(hcd);
506 usb_hcd_poll_rh_status(hcd);
510 if (xhci->port_status_u0 != ((1 << rhub->num_ports) - 1))
511 mod_timer(&xhci->comp_mode_recovery_timer,
512 jiffies + msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
516 * Quirk to work around issue generated by the SN65LVPE502CP USB3.0 re-driver
517 * that causes ports behind that hardware to enter compliance mode sometimes.
518 * The quirk creates a timer that polls every 2 seconds the link state of
519 * each host controller's port and recovers it by issuing a Warm reset
520 * if Compliance mode is detected, otherwise the port will become "dead" (no
521 * device connections or disconnections will be detected anymore). Becasue no
522 * status event is generated when entering compliance mode (per xhci spec),
523 * this quirk is needed on systems that have the failing hardware installed.
525 static void compliance_mode_recovery_timer_init(struct xhci_hcd *xhci)
527 xhci->port_status_u0 = 0;
528 timer_setup(&xhci->comp_mode_recovery_timer, compliance_mode_recovery,
530 xhci->comp_mode_recovery_timer.expires = jiffies +
531 msecs_to_jiffies(COMP_MODE_RCVRY_MSECS);
533 add_timer(&xhci->comp_mode_recovery_timer);
534 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
535 "Compliance mode recovery timer initialized");
539 * This function identifies the systems that have installed the SN65LVPE502CP
540 * USB3.0 re-driver and that need the Compliance Mode Quirk.
542 * Vendor: Hewlett-Packard -> System Models: Z420, Z620 and Z820
544 static bool xhci_compliance_mode_recovery_timer_quirk_check(void)
546 const char *dmi_product_name, *dmi_sys_vendor;
548 dmi_product_name = dmi_get_system_info(DMI_PRODUCT_NAME);
549 dmi_sys_vendor = dmi_get_system_info(DMI_SYS_VENDOR);
550 if (!dmi_product_name || !dmi_sys_vendor)
553 if (!(strstr(dmi_sys_vendor, "Hewlett-Packard")))
556 if (strstr(dmi_product_name, "Z420") ||
557 strstr(dmi_product_name, "Z620") ||
558 strstr(dmi_product_name, "Z820") ||
559 strstr(dmi_product_name, "Z1 Workstation"))
565 static int xhci_all_ports_seen_u0(struct xhci_hcd *xhci)
567 return (xhci->port_status_u0 == ((1 << xhci->usb3_rhub.num_ports) - 1));
572 * Initialize memory for HCD and xHC (one-time init).
574 * Program the PAGESIZE register, initialize the device context array, create
575 * device contexts (?), set up a command ring segment (or two?), create event
576 * ring (one for now).
578 static int xhci_init(struct usb_hcd *hcd)
580 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
583 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_init");
584 spin_lock_init(&xhci->lock);
585 if (xhci->hci_version == 0x95 && link_quirk) {
586 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
587 "QUIRK: Not clearing Link TRB chain bits.");
588 xhci->quirks |= XHCI_LINK_TRB_QUIRK;
590 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
591 "xHCI doesn't need link TRB QUIRK");
593 retval = xhci_mem_init(xhci, GFP_KERNEL);
594 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Finished xhci_init");
596 /* Initializing Compliance Mode Recovery Data If Needed */
597 if (xhci_compliance_mode_recovery_timer_quirk_check()) {
598 xhci->quirks |= XHCI_COMP_MODE_QUIRK;
599 compliance_mode_recovery_timer_init(xhci);
605 /*-------------------------------------------------------------------------*/
608 static int xhci_run_finished(struct xhci_hcd *xhci)
610 if (xhci_start(xhci)) {
614 xhci->shared_hcd->state = HC_STATE_RUNNING;
615 xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
617 if (xhci->quirks & XHCI_NEC_HOST)
618 xhci_ring_cmd_db(xhci);
620 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
621 "Finished xhci_run for USB3 roothub");
626 * Start the HC after it was halted.
628 * This function is called by the USB core when the HC driver is added.
629 * Its opposite is xhci_stop().
631 * xhci_init() must be called once before this function can be called.
632 * Reset the HC, enable device slot contexts, program DCBAAP, and
633 * set command ring pointer and event ring pointer.
635 * Setup MSI-X vectors and enable interrupts.
637 int xhci_run(struct usb_hcd *hcd)
642 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
644 /* Start the xHCI host controller running only after the USB 2.0 roothub
648 hcd->uses_new_polling = 1;
649 if (!usb_hcd_is_primary_hcd(hcd))
650 return xhci_run_finished(xhci);
652 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_run");
654 ret = xhci_try_enable_msi(hcd);
658 temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
659 temp_64 &= ~ERST_PTR_MASK;
660 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
661 "ERST deq = 64'h%0lx", (long unsigned int) temp_64);
663 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
664 "// Set the interrupt modulation register");
665 temp = readl(&xhci->ir_set->irq_control);
666 temp &= ~ER_IRQ_INTERVAL_MASK;
667 temp |= (xhci->imod_interval / 250) & ER_IRQ_INTERVAL_MASK;
668 writel(temp, &xhci->ir_set->irq_control);
670 /* Set the HCD state before we enable the irqs */
671 temp = readl(&xhci->op_regs->command);
673 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
674 "// Enable interrupts, cmd = 0x%x.", temp);
675 writel(temp, &xhci->op_regs->command);
677 temp = readl(&xhci->ir_set->irq_pending);
678 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
679 "// Enabling event ring interrupter %p by writing 0x%x to irq_pending",
680 xhci->ir_set, (unsigned int) ER_IRQ_ENABLE(temp));
681 writel(ER_IRQ_ENABLE(temp), &xhci->ir_set->irq_pending);
683 if (xhci->quirks & XHCI_NEC_HOST) {
684 struct xhci_command *command;
686 command = xhci_alloc_command(xhci, false, GFP_KERNEL);
690 ret = xhci_queue_vendor_command(xhci, command, 0, 0, 0,
691 TRB_TYPE(TRB_NEC_GET_FW));
693 xhci_free_command(xhci, command);
695 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
696 "Finished xhci_run for USB2 roothub");
700 xhci_debugfs_init(xhci);
704 EXPORT_SYMBOL_GPL(xhci_run);
709 * This function is called by the USB core when the HC driver is removed.
710 * Its opposite is xhci_run().
712 * Disable device contexts, disable IRQs, and quiesce the HC.
713 * Reset the HC, finish any completed transactions, and cleanup memory.
715 static void xhci_stop(struct usb_hcd *hcd)
718 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
720 mutex_lock(&xhci->mutex);
722 /* Only halt host and free memory after both hcds are removed */
723 if (!usb_hcd_is_primary_hcd(hcd)) {
724 mutex_unlock(&xhci->mutex);
730 spin_lock_irq(&xhci->lock);
731 xhci->xhc_state |= XHCI_STATE_HALTED;
732 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
735 spin_unlock_irq(&xhci->lock);
737 xhci_cleanup_msix(xhci);
739 /* Deleting Compliance Mode Recovery Timer */
740 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
741 (!(xhci_all_ports_seen_u0(xhci)))) {
742 del_timer_sync(&xhci->comp_mode_recovery_timer);
743 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
744 "%s: compliance mode recovery timer deleted",
748 if (xhci->quirks & XHCI_AMD_PLL_FIX)
751 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
752 "// Disabling event ring interrupts");
753 temp = readl(&xhci->op_regs->status);
754 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
755 temp = readl(&xhci->ir_set->irq_pending);
756 writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
758 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "cleaning up memory");
759 xhci_mem_cleanup(xhci);
760 xhci_debugfs_exit(xhci);
761 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
762 "xhci_stop completed - status = %x",
763 readl(&xhci->op_regs->status));
764 mutex_unlock(&xhci->mutex);
768 * Shutdown HC (not bus-specific)
770 * This is called when the machine is rebooting or halting. We assume that the
771 * machine will be powered off, and the HC's internal state will be reset.
772 * Don't bother to free memory.
774 * This will only ever be called with the main usb_hcd (the USB3 roothub).
776 void xhci_shutdown(struct usb_hcd *hcd)
778 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
780 if (xhci->quirks & XHCI_SPURIOUS_REBOOT)
781 usb_disable_xhci_ports(to_pci_dev(hcd->self.sysdev));
783 spin_lock_irq(&xhci->lock);
785 /* Workaround for spurious wakeups at shutdown with HSW */
786 if (xhci->quirks & XHCI_SPURIOUS_WAKEUP)
788 spin_unlock_irq(&xhci->lock);
790 xhci_cleanup_msix(xhci);
792 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
793 "xhci_shutdown completed - status = %x",
794 readl(&xhci->op_regs->status));
796 EXPORT_SYMBOL_GPL(xhci_shutdown);
799 static void xhci_save_registers(struct xhci_hcd *xhci)
801 xhci->s3.command = readl(&xhci->op_regs->command);
802 xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
803 xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
804 xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);
805 xhci->s3.erst_size = readl(&xhci->ir_set->erst_size);
806 xhci->s3.erst_base = xhci_read_64(xhci, &xhci->ir_set->erst_base);
807 xhci->s3.erst_dequeue = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
808 xhci->s3.irq_pending = readl(&xhci->ir_set->irq_pending);
809 xhci->s3.irq_control = readl(&xhci->ir_set->irq_control);
812 static void xhci_restore_registers(struct xhci_hcd *xhci)
814 writel(xhci->s3.command, &xhci->op_regs->command);
815 writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
816 xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
817 writel(xhci->s3.config_reg, &xhci->op_regs->config_reg);
818 writel(xhci->s3.erst_size, &xhci->ir_set->erst_size);
819 xhci_write_64(xhci, xhci->s3.erst_base, &xhci->ir_set->erst_base);
820 xhci_write_64(xhci, xhci->s3.erst_dequeue, &xhci->ir_set->erst_dequeue);
821 writel(xhci->s3.irq_pending, &xhci->ir_set->irq_pending);
822 writel(xhci->s3.irq_control, &xhci->ir_set->irq_control);
825 static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
829 /* step 2: initialize command ring buffer */
830 val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
831 val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
832 (xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
833 xhci->cmd_ring->dequeue) &
834 (u64) ~CMD_RING_RSVD_BITS) |
835 xhci->cmd_ring->cycle_state;
836 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
837 "// Setting command ring address to 0x%llx",
838 (long unsigned long) val_64);
839 xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
843 * The whole command ring must be cleared to zero when we suspend the host.
845 * The host doesn't save the command ring pointer in the suspend well, so we
846 * need to re-program it on resume. Unfortunately, the pointer must be 64-byte
847 * aligned, because of the reserved bits in the command ring dequeue pointer
848 * register. Therefore, we can't just set the dequeue pointer back in the
849 * middle of the ring (TRBs are 16-byte aligned).
851 static void xhci_clear_command_ring(struct xhci_hcd *xhci)
853 struct xhci_ring *ring;
854 struct xhci_segment *seg;
856 ring = xhci->cmd_ring;
860 sizeof(union xhci_trb) * (TRBS_PER_SEGMENT - 1));
861 seg->trbs[TRBS_PER_SEGMENT - 1].link.control &=
862 cpu_to_le32(~TRB_CYCLE);
864 } while (seg != ring->deq_seg);
866 /* Reset the software enqueue and dequeue pointers */
867 ring->deq_seg = ring->first_seg;
868 ring->dequeue = ring->first_seg->trbs;
869 ring->enq_seg = ring->deq_seg;
870 ring->enqueue = ring->dequeue;
872 ring->num_trbs_free = ring->num_segs * (TRBS_PER_SEGMENT - 1) - 1;
874 * Ring is now zeroed, so the HW should look for change of ownership
875 * when the cycle bit is set to 1.
877 ring->cycle_state = 1;
880 * Reset the hardware dequeue pointer.
881 * Yes, this will need to be re-written after resume, but we're paranoid
882 * and want to make sure the hardware doesn't access bogus memory
883 * because, say, the BIOS or an SMI started the host without changing
884 * the command ring pointers.
886 xhci_set_cmd_ring_deq(xhci);
889 static void xhci_disable_port_wake_on_bits(struct xhci_hcd *xhci)
891 struct xhci_port **ports;
896 spin_lock_irqsave(&xhci->lock, flags);
898 /* disable usb3 ports Wake bits */
899 port_index = xhci->usb3_rhub.num_ports;
900 ports = xhci->usb3_rhub.ports;
901 while (port_index--) {
902 t1 = readl(ports[port_index]->addr);
903 t1 = xhci_port_state_to_neutral(t1);
904 t2 = t1 & ~PORT_WAKE_BITS;
906 writel(t2, ports[port_index]->addr);
909 /* disable usb2 ports Wake bits */
910 port_index = xhci->usb2_rhub.num_ports;
911 ports = xhci->usb2_rhub.ports;
912 while (port_index--) {
913 t1 = readl(ports[port_index]->addr);
914 t1 = xhci_port_state_to_neutral(t1);
915 t2 = t1 & ~PORT_WAKE_BITS;
917 writel(t2, ports[port_index]->addr);
920 spin_unlock_irqrestore(&xhci->lock, flags);
923 static bool xhci_pending_portevent(struct xhci_hcd *xhci)
925 struct xhci_port **ports;
930 status = readl(&xhci->op_regs->status);
931 if (status & STS_EINT)
934 * Checking STS_EINT is not enough as there is a lag between a change
935 * bit being set and the Port Status Change Event that it generated
936 * being written to the Event Ring. See note in xhci 1.1 section 4.19.2.
939 port_index = xhci->usb2_rhub.num_ports;
940 ports = xhci->usb2_rhub.ports;
941 while (port_index--) {
942 portsc = readl(ports[port_index]->addr);
943 if (portsc & PORT_CHANGE_MASK ||
944 (portsc & PORT_PLS_MASK) == XDEV_RESUME)
947 port_index = xhci->usb3_rhub.num_ports;
948 ports = xhci->usb3_rhub.ports;
949 while (port_index--) {
950 portsc = readl(ports[port_index]->addr);
951 if (portsc & PORT_CHANGE_MASK ||
952 (portsc & PORT_PLS_MASK) == XDEV_RESUME)
959 * Stop HC (not bus-specific)
961 * This is called when the machine transition into S3/S4 mode.
964 int xhci_suspend(struct xhci_hcd *xhci, bool do_wakeup)
967 unsigned int delay = XHCI_MAX_HALT_USEC * 2;
968 struct usb_hcd *hcd = xhci_to_hcd(xhci);
975 if (hcd->state != HC_STATE_SUSPENDED ||
976 xhci->shared_hcd->state != HC_STATE_SUSPENDED)
979 /* Clear root port wake on bits if wakeup not allowed. */
981 xhci_disable_port_wake_on_bits(xhci);
983 if (!HCD_HW_ACCESSIBLE(hcd))
986 xhci_dbc_suspend(xhci);
988 /* Don't poll the roothubs on bus suspend. */
989 xhci_dbg(xhci, "%s: stopping port polling.\n", __func__);
990 clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
991 del_timer_sync(&hcd->rh_timer);
992 clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
993 del_timer_sync(&xhci->shared_hcd->rh_timer);
995 if (xhci->quirks & XHCI_SUSPEND_DELAY)
996 usleep_range(1000, 1500);
998 spin_lock_irq(&xhci->lock);
999 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1000 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
1001 /* step 1: stop endpoint */
1002 /* skipped assuming that port suspend has done */
1004 /* step 2: clear Run/Stop bit */
1005 command = readl(&xhci->op_regs->command);
1006 command &= ~CMD_RUN;
1007 writel(command, &xhci->op_regs->command);
1009 /* Some chips from Fresco Logic need an extraordinary delay */
1010 delay *= (xhci->quirks & XHCI_SLOW_SUSPEND) ? 10 : 1;
1012 if (xhci_handshake(&xhci->op_regs->status,
1013 STS_HALT, STS_HALT, delay)) {
1014 xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
1015 spin_unlock_irq(&xhci->lock);
1018 xhci_clear_command_ring(xhci);
1020 /* step 3: save registers */
1021 xhci_save_registers(xhci);
1023 /* step 4: set CSS flag */
1024 command = readl(&xhci->op_regs->command);
1026 writel(command, &xhci->op_regs->command);
1027 xhci->broken_suspend = 0;
1028 if (xhci_handshake(&xhci->op_regs->status,
1029 STS_SAVE, 0, 20 * 1000)) {
1031 * AMD SNPS xHC 3.0 occasionally does not clear the
1032 * SSS bit of USBSTS and when driver tries to poll
1033 * to see if the xHC clears BIT(8) which never happens
1034 * and driver assumes that controller is not responding
1035 * and times out. To workaround this, its good to check
1036 * if SRE and HCE bits are not set (as per xhci
1037 * Section 5.4.2) and bypass the timeout.
1039 res = readl(&xhci->op_regs->status);
1040 if ((xhci->quirks & XHCI_SNPS_BROKEN_SUSPEND) &&
1041 (((res & STS_SRE) == 0) &&
1042 ((res & STS_HCE) == 0))) {
1043 xhci->broken_suspend = 1;
1045 xhci_warn(xhci, "WARN: xHC save state timeout\n");
1046 spin_unlock_irq(&xhci->lock);
1050 spin_unlock_irq(&xhci->lock);
1053 * Deleting Compliance Mode Recovery Timer because the xHCI Host
1054 * is about to be suspended.
1056 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1057 (!(xhci_all_ports_seen_u0(xhci)))) {
1058 del_timer_sync(&xhci->comp_mode_recovery_timer);
1059 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1060 "%s: compliance mode recovery timer deleted",
1064 /* step 5: remove core well power */
1065 /* synchronize irq when using MSI-X */
1066 xhci_msix_sync_irqs(xhci);
1070 EXPORT_SYMBOL_GPL(xhci_suspend);
1073 * start xHC (not bus-specific)
1075 * This is called when the machine transition from S3/S4 mode.
1078 int xhci_resume(struct xhci_hcd *xhci, bool hibernated)
1080 u32 command, temp = 0;
1081 struct usb_hcd *hcd = xhci_to_hcd(xhci);
1082 struct usb_hcd *secondary_hcd;
1084 bool comp_timer_running = false;
1085 bool pending_portevent = false;
1090 /* Wait a bit if either of the roothubs need to settle from the
1091 * transition into bus suspend.
1093 if (time_before(jiffies, xhci->bus_state[0].next_statechange) ||
1094 time_before(jiffies,
1095 xhci->bus_state[1].next_statechange))
1098 set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1099 set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
1101 spin_lock_irq(&xhci->lock);
1102 if ((xhci->quirks & XHCI_RESET_ON_RESUME) || xhci->broken_suspend)
1107 * Some controllers might lose power during suspend, so wait
1108 * for controller not ready bit to clear, just as in xHC init.
1110 retval = xhci_handshake(&xhci->op_regs->status,
1111 STS_CNR, 0, 10 * 1000 * 1000);
1113 xhci_warn(xhci, "Controller not ready at resume %d\n",
1115 spin_unlock_irq(&xhci->lock);
1118 /* step 1: restore register */
1119 xhci_restore_registers(xhci);
1120 /* step 2: initialize command ring buffer */
1121 xhci_set_cmd_ring_deq(xhci);
1122 /* step 3: restore state and start state*/
1123 /* step 3: set CRS flag */
1124 command = readl(&xhci->op_regs->command);
1126 writel(command, &xhci->op_regs->command);
1128 * Some controllers take up to 55+ ms to complete the controller
1129 * restore so setting the timeout to 100ms. Xhci specification
1130 * doesn't mention any timeout value.
1132 if (xhci_handshake(&xhci->op_regs->status,
1133 STS_RESTORE, 0, 100 * 1000)) {
1134 xhci_warn(xhci, "WARN: xHC restore state timeout\n");
1135 spin_unlock_irq(&xhci->lock);
1138 temp = readl(&xhci->op_regs->status);
1141 /* If restore operation fails, re-initialize the HC during resume */
1142 if ((temp & STS_SRE) || hibernated) {
1144 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1145 !(xhci_all_ports_seen_u0(xhci))) {
1146 del_timer_sync(&xhci->comp_mode_recovery_timer);
1147 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1148 "Compliance Mode Recovery Timer deleted!");
1151 /* Let the USB core know _both_ roothubs lost power. */
1152 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1153 usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
1155 xhci_dbg(xhci, "Stop HCD\n");
1157 xhci_zero_64b_regs(xhci);
1158 retval = xhci_reset(xhci);
1159 spin_unlock_irq(&xhci->lock);
1162 xhci_cleanup_msix(xhci);
1164 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1165 temp = readl(&xhci->op_regs->status);
1166 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
1167 temp = readl(&xhci->ir_set->irq_pending);
1168 writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
1170 xhci_dbg(xhci, "cleaning up memory\n");
1171 xhci_mem_cleanup(xhci);
1172 xhci_debugfs_exit(xhci);
1173 xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
1174 readl(&xhci->op_regs->status));
1176 /* USB core calls the PCI reinit and start functions twice:
1177 * first with the primary HCD, and then with the secondary HCD.
1178 * If we don't do the same, the host will never be started.
1180 if (!usb_hcd_is_primary_hcd(hcd))
1181 secondary_hcd = hcd;
1183 secondary_hcd = xhci->shared_hcd;
1185 xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1186 retval = xhci_init(hcd->primary_hcd);
1189 comp_timer_running = true;
1191 xhci_dbg(xhci, "Start the primary HCD\n");
1192 retval = xhci_run(hcd->primary_hcd);
1194 xhci_dbg(xhci, "Start the secondary HCD\n");
1195 retval = xhci_run(secondary_hcd);
1197 hcd->state = HC_STATE_SUSPENDED;
1198 xhci->shared_hcd->state = HC_STATE_SUSPENDED;
1202 /* step 4: set Run/Stop bit */
1203 command = readl(&xhci->op_regs->command);
1205 writel(command, &xhci->op_regs->command);
1206 xhci_handshake(&xhci->op_regs->status, STS_HALT,
1209 /* step 5: walk topology and initialize portsc,
1210 * portpmsc and portli
1212 /* this is done in bus_resume */
1214 /* step 6: restart each of the previously
1215 * Running endpoints by ringing their doorbells
1218 spin_unlock_irq(&xhci->lock);
1220 xhci_dbc_resume(xhci);
1225 * Resume roothubs only if there are pending events.
1226 * USB 3 devices resend U3 LFPS wake after a 100ms delay if
1227 * the first wake signalling failed, give it that chance.
1229 pending_portevent = xhci_pending_portevent(xhci);
1230 if (!pending_portevent) {
1232 pending_portevent = xhci_pending_portevent(xhci);
1235 if (pending_portevent) {
1236 usb_hcd_resume_root_hub(xhci->shared_hcd);
1237 usb_hcd_resume_root_hub(hcd);
1241 * If system is subject to the Quirk, Compliance Mode Timer needs to
1242 * be re-initialized Always after a system resume. Ports are subject
1243 * to suffer the Compliance Mode issue again. It doesn't matter if
1244 * ports have entered previously to U0 before system's suspension.
1246 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) && !comp_timer_running)
1247 compliance_mode_recovery_timer_init(xhci);
1249 if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
1250 usb_asmedia_modifyflowcontrol(to_pci_dev(hcd->self.controller));
1252 /* Re-enable port polling. */
1253 xhci_dbg(xhci, "%s: starting port polling.\n", __func__);
1254 set_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
1255 usb_hcd_poll_rh_status(xhci->shared_hcd);
1256 set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1257 usb_hcd_poll_rh_status(hcd);
1261 EXPORT_SYMBOL_GPL(xhci_resume);
1262 #endif /* CONFIG_PM */
1264 /*-------------------------------------------------------------------------*/
1267 * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1268 * HCDs. Find the index for an endpoint given its descriptor. Use the return
1269 * value to right shift 1 for the bitmask.
1271 * Index = (epnum * 2) + direction - 1,
1272 * where direction = 0 for OUT, 1 for IN.
1273 * For control endpoints, the IN index is used (OUT index is unused), so
1274 * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1276 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1279 if (usb_endpoint_xfer_control(desc))
1280 index = (unsigned int) (usb_endpoint_num(desc)*2);
1282 index = (unsigned int) (usb_endpoint_num(desc)*2) +
1283 (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1287 /* The reverse operation to xhci_get_endpoint_index. Calculate the USB endpoint
1288 * address from the XHCI endpoint index.
1290 unsigned int xhci_get_endpoint_address(unsigned int ep_index)
1292 unsigned int number = DIV_ROUND_UP(ep_index, 2);
1293 unsigned int direction = ep_index % 2 ? USB_DIR_OUT : USB_DIR_IN;
1294 return direction | number;
1297 /* Find the flag for this endpoint (for use in the control context). Use the
1298 * endpoint index to create a bitmask. The slot context is bit 0, endpoint 0 is
1301 static unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1303 return 1 << (xhci_get_endpoint_index(desc) + 1);
1306 /* Find the flag for this endpoint (for use in the control context). Use the
1307 * endpoint index to create a bitmask. The slot context is bit 0, endpoint 0 is
1310 static unsigned int xhci_get_endpoint_flag_from_index(unsigned int ep_index)
1312 return 1 << (ep_index + 1);
1315 /* Compute the last valid endpoint context index. Basically, this is the
1316 * endpoint index plus one. For slot contexts with more than valid endpoint,
1317 * we find the most significant bit set in the added contexts flags.
1318 * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1319 * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1321 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1323 return fls(added_ctxs) - 1;
1326 /* Returns 1 if the arguments are OK;
1327 * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1329 static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
1330 struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
1332 struct xhci_hcd *xhci;
1333 struct xhci_virt_device *virt_dev;
1335 if (!hcd || (check_ep && !ep) || !udev) {
1336 pr_debug("xHCI %s called with invalid args\n", func);
1339 if (!udev->parent) {
1340 pr_debug("xHCI %s called for root hub\n", func);
1344 xhci = hcd_to_xhci(hcd);
1345 if (check_virt_dev) {
1346 if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
1347 xhci_dbg(xhci, "xHCI %s called with unaddressed device\n",
1352 virt_dev = xhci->devs[udev->slot_id];
1353 if (virt_dev->udev != udev) {
1354 xhci_dbg(xhci, "xHCI %s called with udev and "
1355 "virt_dev does not match\n", func);
1360 if (xhci->xhc_state & XHCI_STATE_HALTED)
1366 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1367 struct usb_device *udev, struct xhci_command *command,
1368 bool ctx_change, bool must_succeed);
1371 * Full speed devices may have a max packet size greater than 8 bytes, but the
1372 * USB core doesn't know that until it reads the first 8 bytes of the
1373 * descriptor. If the usb_device's max packet size changes after that point,
1374 * we need to issue an evaluate context command and wait on it.
1376 static int xhci_check_maxpacket(struct xhci_hcd *xhci, unsigned int slot_id,
1377 unsigned int ep_index, struct urb *urb, gfp_t mem_flags)
1379 struct xhci_container_ctx *out_ctx;
1380 struct xhci_input_control_ctx *ctrl_ctx;
1381 struct xhci_ep_ctx *ep_ctx;
1382 struct xhci_command *command;
1383 int max_packet_size;
1384 int hw_max_packet_size;
1387 out_ctx = xhci->devs[slot_id]->out_ctx;
1388 ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1389 hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1390 max_packet_size = usb_endpoint_maxp(&urb->dev->ep0.desc);
1391 if (hw_max_packet_size != max_packet_size) {
1392 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1393 "Max Packet Size for ep 0 changed.");
1394 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1395 "Max packet size in usb_device = %d",
1397 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1398 "Max packet size in xHCI HW = %d",
1399 hw_max_packet_size);
1400 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1401 "Issuing evaluate context command.");
1403 /* Set up the input context flags for the command */
1404 /* FIXME: This won't work if a non-default control endpoint
1405 * changes max packet sizes.
1408 command = xhci_alloc_command(xhci, true, mem_flags);
1412 command->in_ctx = xhci->devs[slot_id]->in_ctx;
1413 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
1415 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1418 goto command_cleanup;
1420 /* Set up the modified control endpoint 0 */
1421 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
1422 xhci->devs[slot_id]->out_ctx, ep_index);
1424 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
1425 ep_ctx->ep_info &= cpu_to_le32(~EP_STATE_MASK);/* must clear */
1426 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1427 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1429 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1430 ctrl_ctx->drop_flags = 0;
1432 ret = xhci_configure_endpoint(xhci, urb->dev, command,
1435 /* Clean up the input context for later use by bandwidth
1438 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1440 kfree(command->completion);
1447 * non-error returns are a promise to giveback() the urb later
1448 * we drop ownership so next owner (or urb unlink) can get it
1450 static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1452 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1453 unsigned long flags;
1455 unsigned int slot_id, ep_index;
1456 unsigned int *ep_state;
1457 struct urb_priv *urb_priv;
1460 if (!urb || xhci_check_args(hcd, urb->dev, urb->ep,
1461 true, true, __func__) <= 0)
1464 slot_id = urb->dev->slot_id;
1465 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1466 ep_state = &xhci->devs[slot_id]->eps[ep_index].ep_state;
1468 if (!HCD_HW_ACCESSIBLE(hcd)) {
1469 if (!in_interrupt())
1470 xhci_dbg(xhci, "urb submitted during PCI suspend\n");
1473 if (xhci->devs[slot_id]->flags & VDEV_PORT_ERROR) {
1474 xhci_dbg(xhci, "Can't queue urb, port error, link inactive\n");
1478 if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1479 num_tds = urb->number_of_packets;
1480 else if (usb_endpoint_is_bulk_out(&urb->ep->desc) &&
1481 urb->transfer_buffer_length > 0 &&
1482 urb->transfer_flags & URB_ZERO_PACKET &&
1483 !(urb->transfer_buffer_length % usb_endpoint_maxp(&urb->ep->desc)))
1488 urb_priv = kzalloc(sizeof(struct urb_priv) +
1489 num_tds * sizeof(struct xhci_td), mem_flags);
1493 urb_priv->num_tds = num_tds;
1494 urb_priv->num_tds_done = 0;
1495 urb->hcpriv = urb_priv;
1497 trace_xhci_urb_enqueue(urb);
1499 if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1500 /* Check to see if the max packet size for the default control
1501 * endpoint changed during FS device enumeration
1503 if (urb->dev->speed == USB_SPEED_FULL) {
1504 ret = xhci_check_maxpacket(xhci, slot_id,
1505 ep_index, urb, mem_flags);
1507 xhci_urb_free_priv(urb_priv);
1514 spin_lock_irqsave(&xhci->lock, flags);
1516 if (xhci->xhc_state & XHCI_STATE_DYING) {
1517 xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for non-responsive xHCI host.\n",
1518 urb->ep->desc.bEndpointAddress, urb);
1522 if (*ep_state & (EP_GETTING_STREAMS | EP_GETTING_NO_STREAMS)) {
1523 xhci_warn(xhci, "WARN: Can't enqueue URB, ep in streams transition state %x\n",
1528 if (*ep_state & EP_SOFT_CLEAR_TOGGLE) {
1529 xhci_warn(xhci, "Can't enqueue URB while manually clearing toggle\n");
1534 switch (usb_endpoint_type(&urb->ep->desc)) {
1536 case USB_ENDPOINT_XFER_CONTROL:
1537 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1540 case USB_ENDPOINT_XFER_BULK:
1541 ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1544 case USB_ENDPOINT_XFER_INT:
1545 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1548 case USB_ENDPOINT_XFER_ISOC:
1549 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1555 xhci_urb_free_priv(urb_priv);
1558 spin_unlock_irqrestore(&xhci->lock, flags);
1563 * Remove the URB's TD from the endpoint ring. This may cause the HC to stop
1564 * USB transfers, potentially stopping in the middle of a TRB buffer. The HC
1565 * should pick up where it left off in the TD, unless a Set Transfer Ring
1566 * Dequeue Pointer is issued.
1568 * The TRBs that make up the buffers for the canceled URB will be "removed" from
1569 * the ring. Since the ring is a contiguous structure, they can't be physically
1570 * removed. Instead, there are two options:
1572 * 1) If the HC is in the middle of processing the URB to be canceled, we
1573 * simply move the ring's dequeue pointer past those TRBs using the Set
1574 * Transfer Ring Dequeue Pointer command. This will be the common case,
1575 * when drivers timeout on the last submitted URB and attempt to cancel.
1577 * 2) If the HC is in the middle of a different TD, we turn the TRBs into a
1578 * series of 1-TRB transfer no-op TDs. (No-ops shouldn't be chained.) The
1579 * HC will need to invalidate the any TRBs it has cached after the stop
1580 * endpoint command, as noted in the xHCI 0.95 errata.
1582 * 3) The TD may have completed by the time the Stop Endpoint Command
1583 * completes, so software needs to handle that case too.
1585 * This function should protect against the TD enqueueing code ringing the
1586 * doorbell while this code is waiting for a Stop Endpoint command to complete.
1587 * It also needs to account for multiple cancellations on happening at the same
1588 * time for the same endpoint.
1590 * Note that this function can be called in any context, or so says
1591 * usb_hcd_unlink_urb()
1593 static int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1595 unsigned long flags;
1598 struct xhci_hcd *xhci;
1599 struct urb_priv *urb_priv;
1601 unsigned int ep_index;
1602 struct xhci_ring *ep_ring;
1603 struct xhci_virt_ep *ep;
1604 struct xhci_command *command;
1605 struct xhci_virt_device *vdev;
1607 xhci = hcd_to_xhci(hcd);
1608 spin_lock_irqsave(&xhci->lock, flags);
1610 trace_xhci_urb_dequeue(urb);
1612 /* Make sure the URB hasn't completed or been unlinked already */
1613 ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1617 /* give back URB now if we can't queue it for cancel */
1618 vdev = xhci->devs[urb->dev->slot_id];
1619 urb_priv = urb->hcpriv;
1620 if (!vdev || !urb_priv)
1623 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1624 ep = &vdev->eps[ep_index];
1625 ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1626 if (!ep || !ep_ring)
1629 /* If xHC is dead take it down and return ALL URBs in xhci_hc_died() */
1630 temp = readl(&xhci->op_regs->status);
1631 if (temp == ~(u32)0 || xhci->xhc_state & XHCI_STATE_DYING) {
1637 * check ring is not re-allocated since URB was enqueued. If it is, then
1638 * make sure none of the ring related pointers in this URB private data
1639 * are touched, such as td_list, otherwise we overwrite freed data
1641 if (!td_on_ring(&urb_priv->td[0], ep_ring)) {
1642 xhci_err(xhci, "Canceled URB td not found on endpoint ring");
1643 for (i = urb_priv->num_tds_done; i < urb_priv->num_tds; i++) {
1644 td = &urb_priv->td[i];
1645 if (!list_empty(&td->cancelled_td_list))
1646 list_del_init(&td->cancelled_td_list);
1651 if (xhci->xhc_state & XHCI_STATE_HALTED) {
1652 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1653 "HC halted, freeing TD manually.");
1654 for (i = urb_priv->num_tds_done;
1655 i < urb_priv->num_tds;
1657 td = &urb_priv->td[i];
1658 if (!list_empty(&td->td_list))
1659 list_del_init(&td->td_list);
1660 if (!list_empty(&td->cancelled_td_list))
1661 list_del_init(&td->cancelled_td_list);
1666 i = urb_priv->num_tds_done;
1667 if (i < urb_priv->num_tds)
1668 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1669 "Cancel URB %p, dev %s, ep 0x%x, "
1670 "starting at offset 0x%llx",
1671 urb, urb->dev->devpath,
1672 urb->ep->desc.bEndpointAddress,
1673 (unsigned long long) xhci_trb_virt_to_dma(
1674 urb_priv->td[i].start_seg,
1675 urb_priv->td[i].first_trb));
1677 for (; i < urb_priv->num_tds; i++) {
1678 td = &urb_priv->td[i];
1679 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
1682 /* Queue a stop endpoint command, but only if this is
1683 * the first cancellation to be handled.
1685 if (!(ep->ep_state & EP_STOP_CMD_PENDING)) {
1686 command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
1691 ep->ep_state |= EP_STOP_CMD_PENDING;
1692 ep->stop_cmd_timer.expires = jiffies +
1693 XHCI_STOP_EP_CMD_TIMEOUT * HZ;
1694 add_timer(&ep->stop_cmd_timer);
1695 xhci_queue_stop_endpoint(xhci, command, urb->dev->slot_id,
1697 xhci_ring_cmd_db(xhci);
1700 spin_unlock_irqrestore(&xhci->lock, flags);
1705 xhci_urb_free_priv(urb_priv);
1706 usb_hcd_unlink_urb_from_ep(hcd, urb);
1707 spin_unlock_irqrestore(&xhci->lock, flags);
1708 usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1712 /* Drop an endpoint from a new bandwidth configuration for this device.
1713 * Only one call to this function is allowed per endpoint before
1714 * check_bandwidth() or reset_bandwidth() must be called.
1715 * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1716 * add the endpoint to the schedule with possibly new parameters denoted by a
1717 * different endpoint descriptor in usb_host_endpoint.
1718 * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1721 * The USB core will not allow URBs to be queued to an endpoint that is being
1722 * disabled, so there's no need for mutual exclusion to protect
1723 * the xhci->devs[slot_id] structure.
1725 static int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1726 struct usb_host_endpoint *ep)
1728 struct xhci_hcd *xhci;
1729 struct xhci_container_ctx *in_ctx, *out_ctx;
1730 struct xhci_input_control_ctx *ctrl_ctx;
1731 unsigned int ep_index;
1732 struct xhci_ep_ctx *ep_ctx;
1734 u32 new_add_flags, new_drop_flags;
1737 ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1740 xhci = hcd_to_xhci(hcd);
1741 if (xhci->xhc_state & XHCI_STATE_DYING)
1744 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1745 drop_flag = xhci_get_endpoint_flag(&ep->desc);
1746 if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1747 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1748 __func__, drop_flag);
1752 in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1753 out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1754 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1756 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1761 ep_index = xhci_get_endpoint_index(&ep->desc);
1762 ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1763 /* If the HC already knows the endpoint is disabled,
1764 * or the HCD has noted it is disabled, ignore this request
1766 if ((GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) ||
1767 le32_to_cpu(ctrl_ctx->drop_flags) &
1768 xhci_get_endpoint_flag(&ep->desc)) {
1769 /* Do not warn when called after a usb_device_reset */
1770 if (xhci->devs[udev->slot_id]->eps[ep_index].ring != NULL)
1771 xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1776 ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1777 new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1779 ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1780 new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1782 xhci_debugfs_remove_endpoint(xhci, xhci->devs[udev->slot_id], ep_index);
1784 xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1786 if (xhci->quirks & XHCI_MTK_HOST)
1787 xhci_mtk_drop_ep_quirk(hcd, udev, ep);
1789 xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1790 (unsigned int) ep->desc.bEndpointAddress,
1792 (unsigned int) new_drop_flags,
1793 (unsigned int) new_add_flags);
1797 /* Add an endpoint to a new possible bandwidth configuration for this device.
1798 * Only one call to this function is allowed per endpoint before
1799 * check_bandwidth() or reset_bandwidth() must be called.
1800 * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1801 * add the endpoint to the schedule with possibly new parameters denoted by a
1802 * different endpoint descriptor in usb_host_endpoint.
1803 * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1806 * The USB core will not allow URBs to be queued to an endpoint until the
1807 * configuration or alt setting is installed in the device, so there's no need
1808 * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1810 static int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1811 struct usb_host_endpoint *ep)
1813 struct xhci_hcd *xhci;
1814 struct xhci_container_ctx *in_ctx;
1815 unsigned int ep_index;
1816 struct xhci_input_control_ctx *ctrl_ctx;
1818 u32 new_add_flags, new_drop_flags;
1819 struct xhci_virt_device *virt_dev;
1822 ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1824 /* So we won't queue a reset ep command for a root hub */
1828 xhci = hcd_to_xhci(hcd);
1829 if (xhci->xhc_state & XHCI_STATE_DYING)
1832 added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1833 if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1834 /* FIXME when we have to issue an evaluate endpoint command to
1835 * deal with ep0 max packet size changing once we get the
1838 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1839 __func__, added_ctxs);
1843 virt_dev = xhci->devs[udev->slot_id];
1844 in_ctx = virt_dev->in_ctx;
1845 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1847 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1852 ep_index = xhci_get_endpoint_index(&ep->desc);
1853 /* If this endpoint is already in use, and the upper layers are trying
1854 * to add it again without dropping it, reject the addition.
1856 if (virt_dev->eps[ep_index].ring &&
1857 !(le32_to_cpu(ctrl_ctx->drop_flags) & added_ctxs)) {
1858 xhci_warn(xhci, "Trying to add endpoint 0x%x "
1859 "without dropping it.\n",
1860 (unsigned int) ep->desc.bEndpointAddress);
1864 /* If the HCD has already noted the endpoint is enabled,
1865 * ignore this request.
1867 if (le32_to_cpu(ctrl_ctx->add_flags) & added_ctxs) {
1868 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1874 * Configuration and alternate setting changes must be done in
1875 * process context, not interrupt context (or so documenation
1876 * for usb_set_interface() and usb_set_configuration() claim).
1878 if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1879 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1880 __func__, ep->desc.bEndpointAddress);
1884 if (xhci->quirks & XHCI_MTK_HOST) {
1885 ret = xhci_mtk_add_ep_quirk(hcd, udev, ep);
1887 xhci_ring_free(xhci, virt_dev->eps[ep_index].new_ring);
1888 virt_dev->eps[ep_index].new_ring = NULL;
1893 ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
1894 new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1896 /* If xhci_endpoint_disable() was called for this endpoint, but the
1897 * xHC hasn't been notified yet through the check_bandwidth() call,
1898 * this re-adds a new state for the endpoint from the new endpoint
1899 * descriptors. We must drop and re-add this endpoint, so we leave the
1902 new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1904 /* Store the usb_device pointer for later use */
1907 xhci_debugfs_create_endpoint(xhci, virt_dev, ep_index);
1909 xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1910 (unsigned int) ep->desc.bEndpointAddress,
1912 (unsigned int) new_drop_flags,
1913 (unsigned int) new_add_flags);
1917 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1919 struct xhci_input_control_ctx *ctrl_ctx;
1920 struct xhci_ep_ctx *ep_ctx;
1921 struct xhci_slot_ctx *slot_ctx;
1924 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1926 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1931 /* When a device's add flag and drop flag are zero, any subsequent
1932 * configure endpoint command will leave that endpoint's state
1933 * untouched. Make sure we don't leave any old state in the input
1934 * endpoint contexts.
1936 ctrl_ctx->drop_flags = 0;
1937 ctrl_ctx->add_flags = 0;
1938 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1939 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1940 /* Endpoint 0 is always valid */
1941 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
1942 for (i = 1; i < 31; i++) {
1943 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
1944 ep_ctx->ep_info = 0;
1945 ep_ctx->ep_info2 = 0;
1947 ep_ctx->tx_info = 0;
1951 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
1952 struct usb_device *udev, u32 *cmd_status)
1956 switch (*cmd_status) {
1957 case COMP_COMMAND_ABORTED:
1958 case COMP_COMMAND_RING_STOPPED:
1959 xhci_warn(xhci, "Timeout while waiting for configure endpoint command\n");
1962 case COMP_RESOURCE_ERROR:
1963 dev_warn(&udev->dev,
1964 "Not enough host controller resources for new device state.\n");
1966 /* FIXME: can we allocate more resources for the HC? */
1968 case COMP_BANDWIDTH_ERROR:
1969 case COMP_SECONDARY_BANDWIDTH_ERROR:
1970 dev_warn(&udev->dev,
1971 "Not enough bandwidth for new device state.\n");
1973 /* FIXME: can we go back to the old state? */
1975 case COMP_TRB_ERROR:
1976 /* the HCD set up something wrong */
1977 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
1979 "and endpoint is not disabled.\n");
1982 case COMP_INCOMPATIBLE_DEVICE_ERROR:
1983 dev_warn(&udev->dev,
1984 "ERROR: Incompatible device for endpoint configure command.\n");
1988 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1989 "Successful Endpoint Configure command");
1993 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
2001 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
2002 struct usb_device *udev, u32 *cmd_status)
2006 switch (*cmd_status) {
2007 case COMP_COMMAND_ABORTED:
2008 case COMP_COMMAND_RING_STOPPED:
2009 xhci_warn(xhci, "Timeout while waiting for evaluate context command\n");
2012 case COMP_PARAMETER_ERROR:
2013 dev_warn(&udev->dev,
2014 "WARN: xHCI driver setup invalid evaluate context command.\n");
2017 case COMP_SLOT_NOT_ENABLED_ERROR:
2018 dev_warn(&udev->dev,
2019 "WARN: slot not enabled for evaluate context command.\n");
2022 case COMP_CONTEXT_STATE_ERROR:
2023 dev_warn(&udev->dev,
2024 "WARN: invalid context state for evaluate context command.\n");
2027 case COMP_INCOMPATIBLE_DEVICE_ERROR:
2028 dev_warn(&udev->dev,
2029 "ERROR: Incompatible device for evaluate context command.\n");
2032 case COMP_MAX_EXIT_LATENCY_TOO_LARGE_ERROR:
2033 /* Max Exit Latency too large error */
2034 dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
2038 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2039 "Successful evaluate context command");
2043 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
2051 static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
2052 struct xhci_input_control_ctx *ctrl_ctx)
2054 u32 valid_add_flags;
2055 u32 valid_drop_flags;
2057 /* Ignore the slot flag (bit 0), and the default control endpoint flag
2058 * (bit 1). The default control endpoint is added during the Address
2059 * Device command and is never removed until the slot is disabled.
2061 valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2062 valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2064 /* Use hweight32 to count the number of ones in the add flags, or
2065 * number of endpoints added. Don't count endpoints that are changed
2066 * (both added and dropped).
2068 return hweight32(valid_add_flags) -
2069 hweight32(valid_add_flags & valid_drop_flags);
2072 static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
2073 struct xhci_input_control_ctx *ctrl_ctx)
2075 u32 valid_add_flags;
2076 u32 valid_drop_flags;
2078 valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2079 valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2081 return hweight32(valid_drop_flags) -
2082 hweight32(valid_add_flags & valid_drop_flags);
2086 * We need to reserve the new number of endpoints before the configure endpoint
2087 * command completes. We can't subtract the dropped endpoints from the number
2088 * of active endpoints until the command completes because we can oversubscribe
2089 * the host in this case:
2091 * - the first configure endpoint command drops more endpoints than it adds
2092 * - a second configure endpoint command that adds more endpoints is queued
2093 * - the first configure endpoint command fails, so the config is unchanged
2094 * - the second command may succeed, even though there isn't enough resources
2096 * Must be called with xhci->lock held.
2098 static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
2099 struct xhci_input_control_ctx *ctrl_ctx)
2103 added_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2104 if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
2105 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2106 "Not enough ep ctxs: "
2107 "%u active, need to add %u, limit is %u.",
2108 xhci->num_active_eps, added_eps,
2109 xhci->limit_active_eps);
2112 xhci->num_active_eps += added_eps;
2113 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2114 "Adding %u ep ctxs, %u now active.", added_eps,
2115 xhci->num_active_eps);
2120 * The configure endpoint was failed by the xHC for some other reason, so we
2121 * need to revert the resources that failed configuration would have used.
2123 * Must be called with xhci->lock held.
2125 static void xhci_free_host_resources(struct xhci_hcd *xhci,
2126 struct xhci_input_control_ctx *ctrl_ctx)
2130 num_failed_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2131 xhci->num_active_eps -= num_failed_eps;
2132 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2133 "Removing %u failed ep ctxs, %u now active.",
2135 xhci->num_active_eps);
2139 * Now that the command has completed, clean up the active endpoint count by
2140 * subtracting out the endpoints that were dropped (but not changed).
2142 * Must be called with xhci->lock held.
2144 static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
2145 struct xhci_input_control_ctx *ctrl_ctx)
2147 u32 num_dropped_eps;
2149 num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, ctrl_ctx);
2150 xhci->num_active_eps -= num_dropped_eps;
2151 if (num_dropped_eps)
2152 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2153 "Removing %u dropped ep ctxs, %u now active.",
2155 xhci->num_active_eps);
2158 static unsigned int xhci_get_block_size(struct usb_device *udev)
2160 switch (udev->speed) {
2162 case USB_SPEED_FULL:
2164 case USB_SPEED_HIGH:
2166 case USB_SPEED_SUPER:
2167 case USB_SPEED_SUPER_PLUS:
2169 case USB_SPEED_UNKNOWN:
2170 case USB_SPEED_WIRELESS:
2172 /* Should never happen */
2178 xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
2180 if (interval_bw->overhead[LS_OVERHEAD_TYPE])
2182 if (interval_bw->overhead[FS_OVERHEAD_TYPE])
2187 /* If we are changing a LS/FS device under a HS hub,
2188 * make sure (if we are activating a new TT) that the HS bus has enough
2189 * bandwidth for this new TT.
2191 static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
2192 struct xhci_virt_device *virt_dev,
2195 struct xhci_interval_bw_table *bw_table;
2196 struct xhci_tt_bw_info *tt_info;
2198 /* Find the bandwidth table for the root port this TT is attached to. */
2199 bw_table = &xhci->rh_bw[virt_dev->real_port - 1].bw_table;
2200 tt_info = virt_dev->tt_info;
2201 /* If this TT already had active endpoints, the bandwidth for this TT
2202 * has already been added. Removing all periodic endpoints (and thus
2203 * making the TT enactive) will only decrease the bandwidth used.
2207 if (old_active_eps == 0 && tt_info->active_eps != 0) {
2208 if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
2212 /* Not sure why we would have no new active endpoints...
2214 * Maybe because of an Evaluate Context change for a hub update or a
2215 * control endpoint 0 max packet size change?
2216 * FIXME: skip the bandwidth calculation in that case.
2221 static int xhci_check_ss_bw(struct xhci_hcd *xhci,
2222 struct xhci_virt_device *virt_dev)
2224 unsigned int bw_reserved;
2226 bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
2227 if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
2230 bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
2231 if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
2238 * This algorithm is a very conservative estimate of the worst-case scheduling
2239 * scenario for any one interval. The hardware dynamically schedules the
2240 * packets, so we can't tell which microframe could be the limiting factor in
2241 * the bandwidth scheduling. This only takes into account periodic endpoints.
2243 * Obviously, we can't solve an NP complete problem to find the minimum worst
2244 * case scenario. Instead, we come up with an estimate that is no less than
2245 * the worst case bandwidth used for any one microframe, but may be an
2248 * We walk the requirements for each endpoint by interval, starting with the
2249 * smallest interval, and place packets in the schedule where there is only one
2250 * possible way to schedule packets for that interval. In order to simplify
2251 * this algorithm, we record the largest max packet size for each interval, and
2252 * assume all packets will be that size.
2254 * For interval 0, we obviously must schedule all packets for each interval.
2255 * The bandwidth for interval 0 is just the amount of data to be transmitted
2256 * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2257 * the number of packets).
2259 * For interval 1, we have two possible microframes to schedule those packets
2260 * in. For this algorithm, if we can schedule the same number of packets for
2261 * each possible scheduling opportunity (each microframe), we will do so. The
2262 * remaining number of packets will be saved to be transmitted in the gaps in
2263 * the next interval's scheduling sequence.
2265 * As we move those remaining packets to be scheduled with interval 2 packets,
2266 * we have to double the number of remaining packets to transmit. This is
2267 * because the intervals are actually powers of 2, and we would be transmitting
2268 * the previous interval's packets twice in this interval. We also have to be
2269 * sure that when we look at the largest max packet size for this interval, we
2270 * also look at the largest max packet size for the remaining packets and take
2271 * the greater of the two.
2273 * The algorithm continues to evenly distribute packets in each scheduling
2274 * opportunity, and push the remaining packets out, until we get to the last
2275 * interval. Then those packets and their associated overhead are just added
2276 * to the bandwidth used.
2278 static int xhci_check_bw_table(struct xhci_hcd *xhci,
2279 struct xhci_virt_device *virt_dev,
2282 unsigned int bw_reserved;
2283 unsigned int max_bandwidth;
2284 unsigned int bw_used;
2285 unsigned int block_size;
2286 struct xhci_interval_bw_table *bw_table;
2287 unsigned int packet_size = 0;
2288 unsigned int overhead = 0;
2289 unsigned int packets_transmitted = 0;
2290 unsigned int packets_remaining = 0;
2293 if (virt_dev->udev->speed >= USB_SPEED_SUPER)
2294 return xhci_check_ss_bw(xhci, virt_dev);
2296 if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2297 max_bandwidth = HS_BW_LIMIT;
2298 /* Convert percent of bus BW reserved to blocks reserved */
2299 bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2301 max_bandwidth = FS_BW_LIMIT;
2302 bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2305 bw_table = virt_dev->bw_table;
2306 /* We need to translate the max packet size and max ESIT payloads into
2307 * the units the hardware uses.
2309 block_size = xhci_get_block_size(virt_dev->udev);
2311 /* If we are manipulating a LS/FS device under a HS hub, double check
2312 * that the HS bus has enough bandwidth if we are activing a new TT.
2314 if (virt_dev->tt_info) {
2315 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2316 "Recalculating BW for rootport %u",
2317 virt_dev->real_port);
2318 if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2319 xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2320 "newly activated TT.\n");
2323 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2324 "Recalculating BW for TT slot %u port %u",
2325 virt_dev->tt_info->slot_id,
2326 virt_dev->tt_info->ttport);
2328 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2329 "Recalculating BW for rootport %u",
2330 virt_dev->real_port);
2333 /* Add in how much bandwidth will be used for interval zero, or the
2334 * rounded max ESIT payload + number of packets * largest overhead.
2336 bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2337 bw_table->interval_bw[0].num_packets *
2338 xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2340 for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2341 unsigned int bw_added;
2342 unsigned int largest_mps;
2343 unsigned int interval_overhead;
2346 * How many packets could we transmit in this interval?
2347 * If packets didn't fit in the previous interval, we will need
2348 * to transmit that many packets twice within this interval.
2350 packets_remaining = 2 * packets_remaining +
2351 bw_table->interval_bw[i].num_packets;
2353 /* Find the largest max packet size of this or the previous
2356 if (list_empty(&bw_table->interval_bw[i].endpoints))
2359 struct xhci_virt_ep *virt_ep;
2360 struct list_head *ep_entry;
2362 ep_entry = bw_table->interval_bw[i].endpoints.next;
2363 virt_ep = list_entry(ep_entry,
2364 struct xhci_virt_ep, bw_endpoint_list);
2365 /* Convert to blocks, rounding up */
2366 largest_mps = DIV_ROUND_UP(
2367 virt_ep->bw_info.max_packet_size,
2370 if (largest_mps > packet_size)
2371 packet_size = largest_mps;
2373 /* Use the larger overhead of this or the previous interval. */
2374 interval_overhead = xhci_get_largest_overhead(
2375 &bw_table->interval_bw[i]);
2376 if (interval_overhead > overhead)
2377 overhead = interval_overhead;
2379 /* How many packets can we evenly distribute across
2380 * (1 << (i + 1)) possible scheduling opportunities?
2382 packets_transmitted = packets_remaining >> (i + 1);
2384 /* Add in the bandwidth used for those scheduled packets */
2385 bw_added = packets_transmitted * (overhead + packet_size);
2387 /* How many packets do we have remaining to transmit? */
2388 packets_remaining = packets_remaining % (1 << (i + 1));
2390 /* What largest max packet size should those packets have? */
2391 /* If we've transmitted all packets, don't carry over the
2392 * largest packet size.
2394 if (packets_remaining == 0) {
2397 } else if (packets_transmitted > 0) {
2398 /* Otherwise if we do have remaining packets, and we've
2399 * scheduled some packets in this interval, take the
2400 * largest max packet size from endpoints with this
2403 packet_size = largest_mps;
2404 overhead = interval_overhead;
2406 /* Otherwise carry over packet_size and overhead from the last
2407 * time we had a remainder.
2409 bw_used += bw_added;
2410 if (bw_used > max_bandwidth) {
2411 xhci_warn(xhci, "Not enough bandwidth. "
2412 "Proposed: %u, Max: %u\n",
2413 bw_used, max_bandwidth);
2418 * Ok, we know we have some packets left over after even-handedly
2419 * scheduling interval 15. We don't know which microframes they will
2420 * fit into, so we over-schedule and say they will be scheduled every
2423 if (packets_remaining > 0)
2424 bw_used += overhead + packet_size;
2426 if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2427 unsigned int port_index = virt_dev->real_port - 1;
2429 /* OK, we're manipulating a HS device attached to a
2430 * root port bandwidth domain. Include the number of active TTs
2431 * in the bandwidth used.
2433 bw_used += TT_HS_OVERHEAD *
2434 xhci->rh_bw[port_index].num_active_tts;
2437 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2438 "Final bandwidth: %u, Limit: %u, Reserved: %u, "
2439 "Available: %u " "percent",
2440 bw_used, max_bandwidth, bw_reserved,
2441 (max_bandwidth - bw_used - bw_reserved) * 100 /
2444 bw_used += bw_reserved;
2445 if (bw_used > max_bandwidth) {
2446 xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2447 bw_used, max_bandwidth);
2451 bw_table->bw_used = bw_used;
2455 static bool xhci_is_async_ep(unsigned int ep_type)
2457 return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2458 ep_type != ISOC_IN_EP &&
2459 ep_type != INT_IN_EP);
2462 static bool xhci_is_sync_in_ep(unsigned int ep_type)
2464 return (ep_type == ISOC_IN_EP || ep_type == INT_IN_EP);
2467 static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2469 unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2471 if (ep_bw->ep_interval == 0)
2472 return SS_OVERHEAD_BURST +
2473 (ep_bw->mult * ep_bw->num_packets *
2474 (SS_OVERHEAD + mps));
2475 return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2476 (SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2477 1 << ep_bw->ep_interval);
2481 static void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2482 struct xhci_bw_info *ep_bw,
2483 struct xhci_interval_bw_table *bw_table,
2484 struct usb_device *udev,
2485 struct xhci_virt_ep *virt_ep,
2486 struct xhci_tt_bw_info *tt_info)
2488 struct xhci_interval_bw *interval_bw;
2489 int normalized_interval;
2491 if (xhci_is_async_ep(ep_bw->type))
2494 if (udev->speed >= USB_SPEED_SUPER) {
2495 if (xhci_is_sync_in_ep(ep_bw->type))
2496 xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2497 xhci_get_ss_bw_consumed(ep_bw);
2499 xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2500 xhci_get_ss_bw_consumed(ep_bw);
2504 /* SuperSpeed endpoints never get added to intervals in the table, so
2505 * this check is only valid for HS/FS/LS devices.
2507 if (list_empty(&virt_ep->bw_endpoint_list))
2509 /* For LS/FS devices, we need to translate the interval expressed in
2510 * microframes to frames.
2512 if (udev->speed == USB_SPEED_HIGH)
2513 normalized_interval = ep_bw->ep_interval;
2515 normalized_interval = ep_bw->ep_interval - 3;
2517 if (normalized_interval == 0)
2518 bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2519 interval_bw = &bw_table->interval_bw[normalized_interval];
2520 interval_bw->num_packets -= ep_bw->num_packets;
2521 switch (udev->speed) {
2523 interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2525 case USB_SPEED_FULL:
2526 interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2528 case USB_SPEED_HIGH:
2529 interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2531 case USB_SPEED_SUPER:
2532 case USB_SPEED_SUPER_PLUS:
2533 case USB_SPEED_UNKNOWN:
2534 case USB_SPEED_WIRELESS:
2535 /* Should never happen because only LS/FS/HS endpoints will get
2536 * added to the endpoint list.
2541 tt_info->active_eps -= 1;
2542 list_del_init(&virt_ep->bw_endpoint_list);
2545 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2546 struct xhci_bw_info *ep_bw,
2547 struct xhci_interval_bw_table *bw_table,
2548 struct usb_device *udev,
2549 struct xhci_virt_ep *virt_ep,
2550 struct xhci_tt_bw_info *tt_info)
2552 struct xhci_interval_bw *interval_bw;
2553 struct xhci_virt_ep *smaller_ep;
2554 int normalized_interval;
2556 if (xhci_is_async_ep(ep_bw->type))
2559 if (udev->speed == USB_SPEED_SUPER) {
2560 if (xhci_is_sync_in_ep(ep_bw->type))
2561 xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2562 xhci_get_ss_bw_consumed(ep_bw);
2564 xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2565 xhci_get_ss_bw_consumed(ep_bw);
2569 /* For LS/FS devices, we need to translate the interval expressed in
2570 * microframes to frames.
2572 if (udev->speed == USB_SPEED_HIGH)
2573 normalized_interval = ep_bw->ep_interval;
2575 normalized_interval = ep_bw->ep_interval - 3;
2577 if (normalized_interval == 0)
2578 bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2579 interval_bw = &bw_table->interval_bw[normalized_interval];
2580 interval_bw->num_packets += ep_bw->num_packets;
2581 switch (udev->speed) {
2583 interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2585 case USB_SPEED_FULL:
2586 interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2588 case USB_SPEED_HIGH:
2589 interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2591 case USB_SPEED_SUPER:
2592 case USB_SPEED_SUPER_PLUS:
2593 case USB_SPEED_UNKNOWN:
2594 case USB_SPEED_WIRELESS:
2595 /* Should never happen because only LS/FS/HS endpoints will get
2596 * added to the endpoint list.
2602 tt_info->active_eps += 1;
2603 /* Insert the endpoint into the list, largest max packet size first. */
2604 list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2606 if (ep_bw->max_packet_size >=
2607 smaller_ep->bw_info.max_packet_size) {
2608 /* Add the new ep before the smaller endpoint */
2609 list_add_tail(&virt_ep->bw_endpoint_list,
2610 &smaller_ep->bw_endpoint_list);
2614 /* Add the new endpoint at the end of the list. */
2615 list_add_tail(&virt_ep->bw_endpoint_list,
2616 &interval_bw->endpoints);
2619 void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2620 struct xhci_virt_device *virt_dev,
2623 struct xhci_root_port_bw_info *rh_bw_info;
2624 if (!virt_dev->tt_info)
2627 rh_bw_info = &xhci->rh_bw[virt_dev->real_port - 1];
2628 if (old_active_eps == 0 &&
2629 virt_dev->tt_info->active_eps != 0) {
2630 rh_bw_info->num_active_tts += 1;
2631 rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2632 } else if (old_active_eps != 0 &&
2633 virt_dev->tt_info->active_eps == 0) {
2634 rh_bw_info->num_active_tts -= 1;
2635 rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2639 static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2640 struct xhci_virt_device *virt_dev,
2641 struct xhci_container_ctx *in_ctx)
2643 struct xhci_bw_info ep_bw_info[31];
2645 struct xhci_input_control_ctx *ctrl_ctx;
2646 int old_active_eps = 0;
2648 if (virt_dev->tt_info)
2649 old_active_eps = virt_dev->tt_info->active_eps;
2651 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2653 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2658 for (i = 0; i < 31; i++) {
2659 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2662 /* Make a copy of the BW info in case we need to revert this */
2663 memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2664 sizeof(ep_bw_info[i]));
2665 /* Drop the endpoint from the interval table if the endpoint is
2666 * being dropped or changed.
2668 if (EP_IS_DROPPED(ctrl_ctx, i))
2669 xhci_drop_ep_from_interval_table(xhci,
2670 &virt_dev->eps[i].bw_info,
2676 /* Overwrite the information stored in the endpoints' bw_info */
2677 xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2678 for (i = 0; i < 31; i++) {
2679 /* Add any changed or added endpoints to the interval table */
2680 if (EP_IS_ADDED(ctrl_ctx, i))
2681 xhci_add_ep_to_interval_table(xhci,
2682 &virt_dev->eps[i].bw_info,
2689 if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2690 /* Ok, this fits in the bandwidth we have.
2691 * Update the number of active TTs.
2693 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2697 /* We don't have enough bandwidth for this, revert the stored info. */
2698 for (i = 0; i < 31; i++) {
2699 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2702 /* Drop the new copies of any added or changed endpoints from
2703 * the interval table.
2705 if (EP_IS_ADDED(ctrl_ctx, i)) {
2706 xhci_drop_ep_from_interval_table(xhci,
2707 &virt_dev->eps[i].bw_info,
2713 /* Revert the endpoint back to its old information */
2714 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2715 sizeof(ep_bw_info[i]));
2716 /* Add any changed or dropped endpoints back into the table */
2717 if (EP_IS_DROPPED(ctrl_ctx, i))
2718 xhci_add_ep_to_interval_table(xhci,
2719 &virt_dev->eps[i].bw_info,
2729 /* Issue a configure endpoint command or evaluate context command
2730 * and wait for it to finish.
2732 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2733 struct usb_device *udev,
2734 struct xhci_command *command,
2735 bool ctx_change, bool must_succeed)
2738 unsigned long flags;
2739 struct xhci_input_control_ctx *ctrl_ctx;
2740 struct xhci_virt_device *virt_dev;
2741 struct xhci_slot_ctx *slot_ctx;
2746 spin_lock_irqsave(&xhci->lock, flags);
2748 if (xhci->xhc_state & XHCI_STATE_DYING) {
2749 spin_unlock_irqrestore(&xhci->lock, flags);
2753 virt_dev = xhci->devs[udev->slot_id];
2755 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2757 spin_unlock_irqrestore(&xhci->lock, flags);
2758 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2763 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
2764 xhci_reserve_host_resources(xhci, ctrl_ctx)) {
2765 spin_unlock_irqrestore(&xhci->lock, flags);
2766 xhci_warn(xhci, "Not enough host resources, "
2767 "active endpoint contexts = %u\n",
2768 xhci->num_active_eps);
2771 if ((xhci->quirks & XHCI_SW_BW_CHECKING) &&
2772 xhci_reserve_bandwidth(xhci, virt_dev, command->in_ctx)) {
2773 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2774 xhci_free_host_resources(xhci, ctrl_ctx);
2775 spin_unlock_irqrestore(&xhci->lock, flags);
2776 xhci_warn(xhci, "Not enough bandwidth\n");
2780 slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
2781 trace_xhci_configure_endpoint(slot_ctx);
2784 ret = xhci_queue_configure_endpoint(xhci, command,
2785 command->in_ctx->dma,
2786 udev->slot_id, must_succeed);
2788 ret = xhci_queue_evaluate_context(xhci, command,
2789 command->in_ctx->dma,
2790 udev->slot_id, must_succeed);
2792 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2793 xhci_free_host_resources(xhci, ctrl_ctx);
2794 spin_unlock_irqrestore(&xhci->lock, flags);
2795 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2796 "FIXME allocate a new ring segment");
2799 xhci_ring_cmd_db(xhci);
2800 spin_unlock_irqrestore(&xhci->lock, flags);
2802 /* Wait for the configure endpoint command to complete */
2803 wait_for_completion(command->completion);
2806 ret = xhci_configure_endpoint_result(xhci, udev,
2809 ret = xhci_evaluate_context_result(xhci, udev,
2812 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
2813 spin_lock_irqsave(&xhci->lock, flags);
2814 /* If the command failed, remove the reserved resources.
2815 * Otherwise, clean up the estimate to include dropped eps.
2818 xhci_free_host_resources(xhci, ctrl_ctx);
2820 xhci_finish_resource_reservation(xhci, ctrl_ctx);
2821 spin_unlock_irqrestore(&xhci->lock, flags);
2826 static void xhci_check_bw_drop_ep_streams(struct xhci_hcd *xhci,
2827 struct xhci_virt_device *vdev, int i)
2829 struct xhci_virt_ep *ep = &vdev->eps[i];
2831 if (ep->ep_state & EP_HAS_STREAMS) {
2832 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on set_interface, freeing streams.\n",
2833 xhci_get_endpoint_address(i));
2834 xhci_free_stream_info(xhci, ep->stream_info);
2835 ep->stream_info = NULL;
2836 ep->ep_state &= ~EP_HAS_STREAMS;
2840 /* Called after one or more calls to xhci_add_endpoint() or
2841 * xhci_drop_endpoint(). If this call fails, the USB core is expected
2842 * to call xhci_reset_bandwidth().
2844 * Since we are in the middle of changing either configuration or
2845 * installing a new alt setting, the USB core won't allow URBs to be
2846 * enqueued for any endpoint on the old config or interface. Nothing
2847 * else should be touching the xhci->devs[slot_id] structure, so we
2848 * don't need to take the xhci->lock for manipulating that.
2850 static int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2854 struct xhci_hcd *xhci;
2855 struct xhci_virt_device *virt_dev;
2856 struct xhci_input_control_ctx *ctrl_ctx;
2857 struct xhci_slot_ctx *slot_ctx;
2858 struct xhci_command *command;
2860 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2863 xhci = hcd_to_xhci(hcd);
2864 if ((xhci->xhc_state & XHCI_STATE_DYING) ||
2865 (xhci->xhc_state & XHCI_STATE_REMOVING))
2868 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2869 virt_dev = xhci->devs[udev->slot_id];
2871 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
2875 command->in_ctx = virt_dev->in_ctx;
2877 /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
2878 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2880 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2883 goto command_cleanup;
2885 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2886 ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
2887 ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
2889 /* Don't issue the command if there's no endpoints to update. */
2890 if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
2891 ctrl_ctx->drop_flags == 0) {
2893 goto command_cleanup;
2895 /* Fix up Context Entries field. Minimum value is EP0 == BIT(1). */
2896 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2897 for (i = 31; i >= 1; i--) {
2898 __le32 le32 = cpu_to_le32(BIT(i));
2900 if ((virt_dev->eps[i-1].ring && !(ctrl_ctx->drop_flags & le32))
2901 || (ctrl_ctx->add_flags & le32) || i == 1) {
2902 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2903 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(i));
2908 ret = xhci_configure_endpoint(xhci, udev, command,
2911 /* Callee should call reset_bandwidth() */
2912 goto command_cleanup;
2914 /* Free any rings that were dropped, but not changed. */
2915 for (i = 1; i < 31; i++) {
2916 if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
2917 !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1)))) {
2918 xhci_free_endpoint_ring(xhci, virt_dev, i);
2919 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2922 xhci_zero_in_ctx(xhci, virt_dev);
2924 * Install any rings for completely new endpoints or changed endpoints,
2925 * and free any old rings from changed endpoints.
2927 for (i = 1; i < 31; i++) {
2928 if (!virt_dev->eps[i].new_ring)
2930 /* Only free the old ring if it exists.
2931 * It may not if this is the first add of an endpoint.
2933 if (virt_dev->eps[i].ring) {
2934 xhci_free_endpoint_ring(xhci, virt_dev, i);
2936 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2937 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
2938 virt_dev->eps[i].new_ring = NULL;
2941 kfree(command->completion);
2947 static void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2949 struct xhci_hcd *xhci;
2950 struct xhci_virt_device *virt_dev;
2953 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2956 xhci = hcd_to_xhci(hcd);
2958 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2959 virt_dev = xhci->devs[udev->slot_id];
2960 /* Free any rings allocated for added endpoints */
2961 for (i = 0; i < 31; i++) {
2962 if (virt_dev->eps[i].new_ring) {
2963 xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
2964 xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
2965 virt_dev->eps[i].new_ring = NULL;
2968 xhci_zero_in_ctx(xhci, virt_dev);
2971 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
2972 struct xhci_container_ctx *in_ctx,
2973 struct xhci_container_ctx *out_ctx,
2974 struct xhci_input_control_ctx *ctrl_ctx,
2975 u32 add_flags, u32 drop_flags)
2977 ctrl_ctx->add_flags = cpu_to_le32(add_flags);
2978 ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
2979 xhci_slot_copy(xhci, in_ctx, out_ctx);
2980 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2983 static void xhci_setup_input_ctx_for_quirk(struct xhci_hcd *xhci,
2984 unsigned int slot_id, unsigned int ep_index,
2985 struct xhci_dequeue_state *deq_state)
2987 struct xhci_input_control_ctx *ctrl_ctx;
2988 struct xhci_container_ctx *in_ctx;
2989 struct xhci_ep_ctx *ep_ctx;
2993 in_ctx = xhci->devs[slot_id]->in_ctx;
2994 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2996 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3001 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
3002 xhci->devs[slot_id]->out_ctx, ep_index);
3003 ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
3004 addr = xhci_trb_virt_to_dma(deq_state->new_deq_seg,
3005 deq_state->new_deq_ptr);
3007 xhci_warn(xhci, "WARN Cannot submit config ep after "
3008 "reset ep command\n");
3009 xhci_warn(xhci, "WARN deq seg = %p, deq ptr = %p\n",
3010 deq_state->new_deq_seg,
3011 deq_state->new_deq_ptr);
3014 ep_ctx->deq = cpu_to_le64(addr | deq_state->new_cycle_state);
3016 added_ctxs = xhci_get_endpoint_flag_from_index(ep_index);
3017 xhci_setup_input_ctx_for_config_ep(xhci, xhci->devs[slot_id]->in_ctx,
3018 xhci->devs[slot_id]->out_ctx, ctrl_ctx,
3019 added_ctxs, added_ctxs);
3022 void xhci_cleanup_stalled_ring(struct xhci_hcd *xhci, unsigned int ep_index,
3023 unsigned int stream_id, struct xhci_td *td)
3025 struct xhci_dequeue_state deq_state;
3026 struct usb_device *udev = td->urb->dev;
3028 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
3029 "Cleaning up stalled endpoint ring");
3030 /* We need to move the HW's dequeue pointer past this TD,
3031 * or it will attempt to resend it on the next doorbell ring.
3033 xhci_find_new_dequeue_state(xhci, udev->slot_id,
3034 ep_index, stream_id, td, &deq_state);
3036 if (!deq_state.new_deq_ptr || !deq_state.new_deq_seg)
3039 /* HW with the reset endpoint quirk will use the saved dequeue state to
3040 * issue a configure endpoint command later.
3042 if (!(xhci->quirks & XHCI_RESET_EP_QUIRK)) {
3043 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
3044 "Queueing new dequeue state");
3045 xhci_queue_new_dequeue_state(xhci, udev->slot_id,
3046 ep_index, &deq_state);
3048 /* Better hope no one uses the input context between now and the
3049 * reset endpoint completion!
3050 * XXX: No idea how this hardware will react when stream rings
3053 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3054 "Setting up input context for "
3055 "configure endpoint command");
3056 xhci_setup_input_ctx_for_quirk(xhci, udev->slot_id,
3057 ep_index, &deq_state);
3062 * Called after usb core issues a clear halt control message.
3063 * The host side of the halt should already be cleared by a reset endpoint
3064 * command issued when the STALL event was received.
3066 * The reset endpoint command may only be issued to endpoints in the halted
3067 * state. For software that wishes to reset the data toggle or sequence number
3068 * of an endpoint that isn't in the halted state this function will issue a
3069 * configure endpoint command with the Drop and Add bits set for the target
3070 * endpoint. Refer to the additional note in xhci spcification section 4.6.8.
3073 static void xhci_endpoint_reset(struct usb_hcd *hcd,
3074 struct usb_host_endpoint *host_ep)
3076 struct xhci_hcd *xhci;
3077 struct usb_device *udev;
3078 struct xhci_virt_device *vdev;
3079 struct xhci_virt_ep *ep;
3080 struct xhci_input_control_ctx *ctrl_ctx;
3081 struct xhci_command *stop_cmd, *cfg_cmd;
3082 unsigned int ep_index;
3083 unsigned long flags;
3087 xhci = hcd_to_xhci(hcd);
3088 if (!host_ep->hcpriv)
3090 udev = (struct usb_device *) host_ep->hcpriv;
3091 vdev = xhci->devs[udev->slot_id];
3092 ep_index = xhci_get_endpoint_index(&host_ep->desc);
3093 ep = &vdev->eps[ep_index];
3095 /* Bail out if toggle is already being cleared by a endpoint reset */
3096 if (ep->ep_state & EP_HARD_CLEAR_TOGGLE) {
3097 ep->ep_state &= ~EP_HARD_CLEAR_TOGGLE;
3100 /* Only interrupt and bulk ep's use data toggle, USB2 spec 5.5.4-> */
3101 if (usb_endpoint_xfer_control(&host_ep->desc) ||
3102 usb_endpoint_xfer_isoc(&host_ep->desc))
3105 ep_flag = xhci_get_endpoint_flag(&host_ep->desc);
3107 if (ep_flag == SLOT_FLAG || ep_flag == EP0_FLAG)
3110 stop_cmd = xhci_alloc_command(xhci, true, GFP_NOWAIT);
3114 cfg_cmd = xhci_alloc_command_with_ctx(xhci, true, GFP_NOWAIT);
3118 spin_lock_irqsave(&xhci->lock, flags);
3120 /* block queuing new trbs and ringing ep doorbell */
3121 ep->ep_state |= EP_SOFT_CLEAR_TOGGLE;
3124 * Make sure endpoint ring is empty before resetting the toggle/seq.
3125 * Driver is required to synchronously cancel all transfer request.
3126 * Stop the endpoint to force xHC to update the output context
3129 if (!list_empty(&ep->ring->td_list)) {
3130 dev_err(&udev->dev, "EP not empty, refuse reset\n");
3131 spin_unlock_irqrestore(&xhci->lock, flags);
3132 xhci_free_command(xhci, cfg_cmd);
3136 err = xhci_queue_stop_endpoint(xhci, stop_cmd, udev->slot_id,
3139 spin_unlock_irqrestore(&xhci->lock, flags);
3140 xhci_free_command(xhci, cfg_cmd);
3141 xhci_dbg(xhci, "%s: Failed to queue stop ep command, %d ",
3146 xhci_ring_cmd_db(xhci);
3147 spin_unlock_irqrestore(&xhci->lock, flags);
3149 wait_for_completion(stop_cmd->completion);
3151 spin_lock_irqsave(&xhci->lock, flags);
3153 /* config ep command clears toggle if add and drop ep flags are set */
3154 ctrl_ctx = xhci_get_input_control_ctx(cfg_cmd->in_ctx);
3156 spin_unlock_irqrestore(&xhci->lock, flags);
3157 xhci_free_command(xhci, cfg_cmd);
3158 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3163 xhci_setup_input_ctx_for_config_ep(xhci, cfg_cmd->in_ctx, vdev->out_ctx,
3164 ctrl_ctx, ep_flag, ep_flag);
3165 xhci_endpoint_copy(xhci, cfg_cmd->in_ctx, vdev->out_ctx, ep_index);
3167 err = xhci_queue_configure_endpoint(xhci, cfg_cmd, cfg_cmd->in_ctx->dma,
3168 udev->slot_id, false);
3170 spin_unlock_irqrestore(&xhci->lock, flags);
3171 xhci_free_command(xhci, cfg_cmd);
3172 xhci_dbg(xhci, "%s: Failed to queue config ep command, %d ",
3177 xhci_ring_cmd_db(xhci);
3178 spin_unlock_irqrestore(&xhci->lock, flags);
3180 wait_for_completion(cfg_cmd->completion);
3182 xhci_free_command(xhci, cfg_cmd);
3184 xhci_free_command(xhci, stop_cmd);
3185 if (ep->ep_state & EP_SOFT_CLEAR_TOGGLE)
3186 ep->ep_state &= ~EP_SOFT_CLEAR_TOGGLE;
3189 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
3190 struct usb_device *udev, struct usb_host_endpoint *ep,
3191 unsigned int slot_id)
3194 unsigned int ep_index;
3195 unsigned int ep_state;
3199 ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
3202 if (usb_ss_max_streams(&ep->ss_ep_comp) == 0) {
3203 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
3204 " descriptor for ep 0x%x does not support streams\n",
3205 ep->desc.bEndpointAddress);
3209 ep_index = xhci_get_endpoint_index(&ep->desc);
3210 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3211 if (ep_state & EP_HAS_STREAMS ||
3212 ep_state & EP_GETTING_STREAMS) {
3213 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
3214 "already has streams set up.\n",
3215 ep->desc.bEndpointAddress);
3216 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
3217 "dynamic stream context array reallocation.\n");
3220 if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
3221 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
3222 "endpoint 0x%x; URBs are pending.\n",
3223 ep->desc.bEndpointAddress);
3229 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
3230 unsigned int *num_streams, unsigned int *num_stream_ctxs)
3232 unsigned int max_streams;
3234 /* The stream context array size must be a power of two */
3235 *num_stream_ctxs = roundup_pow_of_two(*num_streams);
3237 * Find out how many primary stream array entries the host controller
3238 * supports. Later we may use secondary stream arrays (similar to 2nd
3239 * level page entries), but that's an optional feature for xHCI host
3240 * controllers. xHCs must support at least 4 stream IDs.
3242 max_streams = HCC_MAX_PSA(xhci->hcc_params);
3243 if (*num_stream_ctxs > max_streams) {
3244 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
3246 *num_stream_ctxs = max_streams;
3247 *num_streams = max_streams;
3251 /* Returns an error code if one of the endpoint already has streams.
3252 * This does not change any data structures, it only checks and gathers
3255 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
3256 struct usb_device *udev,
3257 struct usb_host_endpoint **eps, unsigned int num_eps,
3258 unsigned int *num_streams, u32 *changed_ep_bitmask)
3260 unsigned int max_streams;
3261 unsigned int endpoint_flag;
3265 for (i = 0; i < num_eps; i++) {
3266 ret = xhci_check_streams_endpoint(xhci, udev,
3267 eps[i], udev->slot_id);
3271 max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
3272 if (max_streams < (*num_streams - 1)) {
3273 xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
3274 eps[i]->desc.bEndpointAddress,
3276 *num_streams = max_streams+1;
3279 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
3280 if (*changed_ep_bitmask & endpoint_flag)
3282 *changed_ep_bitmask |= endpoint_flag;
3287 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
3288 struct usb_device *udev,
3289 struct usb_host_endpoint **eps, unsigned int num_eps)
3291 u32 changed_ep_bitmask = 0;
3292 unsigned int slot_id;
3293 unsigned int ep_index;
3294 unsigned int ep_state;
3297 slot_id = udev->slot_id;
3298 if (!xhci->devs[slot_id])
3301 for (i = 0; i < num_eps; i++) {
3302 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3303 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3304 /* Are streams already being freed for the endpoint? */
3305 if (ep_state & EP_GETTING_NO_STREAMS) {
3306 xhci_warn(xhci, "WARN Can't disable streams for "
3308 "streams are being disabled already\n",
3309 eps[i]->desc.bEndpointAddress);
3312 /* Are there actually any streams to free? */
3313 if (!(ep_state & EP_HAS_STREAMS) &&
3314 !(ep_state & EP_GETTING_STREAMS)) {
3315 xhci_warn(xhci, "WARN Can't disable streams for "
3317 "streams are already disabled!\n",
3318 eps[i]->desc.bEndpointAddress);
3319 xhci_warn(xhci, "WARN xhci_free_streams() called "
3320 "with non-streams endpoint\n");
3323 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
3325 return changed_ep_bitmask;
3329 * The USB device drivers use this function (through the HCD interface in USB
3330 * core) to prepare a set of bulk endpoints to use streams. Streams are used to
3331 * coordinate mass storage command queueing across multiple endpoints (basically
3332 * a stream ID == a task ID).
3334 * Setting up streams involves allocating the same size stream context array
3335 * for each endpoint and issuing a configure endpoint command for all endpoints.
3337 * Don't allow the call to succeed if one endpoint only supports one stream
3338 * (which means it doesn't support streams at all).
3340 * Drivers may get less stream IDs than they asked for, if the host controller
3341 * hardware or endpoints claim they can't support the number of requested
3344 static int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
3345 struct usb_host_endpoint **eps, unsigned int num_eps,
3346 unsigned int num_streams, gfp_t mem_flags)
3349 struct xhci_hcd *xhci;
3350 struct xhci_virt_device *vdev;
3351 struct xhci_command *config_cmd;
3352 struct xhci_input_control_ctx *ctrl_ctx;
3353 unsigned int ep_index;
3354 unsigned int num_stream_ctxs;
3355 unsigned int max_packet;
3356 unsigned long flags;
3357 u32 changed_ep_bitmask = 0;
3362 /* Add one to the number of streams requested to account for
3363 * stream 0 that is reserved for xHCI usage.
3366 xhci = hcd_to_xhci(hcd);
3367 xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
3370 /* MaxPSASize value 0 (2 streams) means streams are not supported */
3371 if ((xhci->quirks & XHCI_BROKEN_STREAMS) ||
3372 HCC_MAX_PSA(xhci->hcc_params) < 4) {
3373 xhci_dbg(xhci, "xHCI controller does not support streams.\n");
3377 config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
3381 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
3383 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3385 xhci_free_command(xhci, config_cmd);
3389 /* Check to make sure all endpoints are not already configured for
3390 * streams. While we're at it, find the maximum number of streams that
3391 * all the endpoints will support and check for duplicate endpoints.
3393 spin_lock_irqsave(&xhci->lock, flags);
3394 ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
3395 num_eps, &num_streams, &changed_ep_bitmask);
3397 xhci_free_command(xhci, config_cmd);
3398 spin_unlock_irqrestore(&xhci->lock, flags);
3401 if (num_streams <= 1) {
3402 xhci_warn(xhci, "WARN: endpoints can't handle "
3403 "more than one stream.\n");
3404 xhci_free_command(xhci, config_cmd);
3405 spin_unlock_irqrestore(&xhci->lock, flags);
3408 vdev = xhci->devs[udev->slot_id];
3409 /* Mark each endpoint as being in transition, so
3410 * xhci_urb_enqueue() will reject all URBs.
3412 for (i = 0; i < num_eps; i++) {
3413 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3414 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
3416 spin_unlock_irqrestore(&xhci->lock, flags);
3418 /* Setup internal data structures and allocate HW data structures for
3419 * streams (but don't install the HW structures in the input context
3420 * until we're sure all memory allocation succeeded).
3422 xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
3423 xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
3424 num_stream_ctxs, num_streams);
3426 for (i = 0; i < num_eps; i++) {
3427 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3428 max_packet = usb_endpoint_maxp(&eps[i]->desc);
3429 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
3432 max_packet, mem_flags);
3433 if (!vdev->eps[ep_index].stream_info)
3435 /* Set maxPstreams in endpoint context and update deq ptr to
3436 * point to stream context array. FIXME
3440 /* Set up the input context for a configure endpoint command. */
3441 for (i = 0; i < num_eps; i++) {
3442 struct xhci_ep_ctx *ep_ctx;
3444 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3445 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
3447 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3448 vdev->out_ctx, ep_index);
3449 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3450 vdev->eps[ep_index].stream_info);
3452 /* Tell the HW to drop its old copy of the endpoint context info
3453 * and add the updated copy from the input context.
3455 xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
3456 vdev->out_ctx, ctrl_ctx,
3457 changed_ep_bitmask, changed_ep_bitmask);
3459 /* Issue and wait for the configure endpoint command */
3460 ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3463 /* xHC rejected the configure endpoint command for some reason, so we
3464 * leave the old ring intact and free our internal streams data
3470 spin_lock_irqsave(&xhci->lock, flags);
3471 for (i = 0; i < num_eps; i++) {
3472 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3473 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3474 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
3475 udev->slot_id, ep_index);
3476 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
3478 xhci_free_command(xhci, config_cmd);
3479 spin_unlock_irqrestore(&xhci->lock, flags);
3481 /* Subtract 1 for stream 0, which drivers can't use */
3482 return num_streams - 1;
3485 /* If it didn't work, free the streams! */
3486 for (i = 0; i < num_eps; i++) {
3487 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3488 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3489 vdev->eps[ep_index].stream_info = NULL;
3490 /* FIXME Unset maxPstreams in endpoint context and
3491 * update deq ptr to point to normal string ring.
3493 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3494 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3495 xhci_endpoint_zero(xhci, vdev, eps[i]);
3497 xhci_free_command(xhci, config_cmd);
3501 /* Transition the endpoint from using streams to being a "normal" endpoint
3504 * Modify the endpoint context state, submit a configure endpoint command,
3505 * and free all endpoint rings for streams if that completes successfully.
3507 static int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3508 struct usb_host_endpoint **eps, unsigned int num_eps,
3512 struct xhci_hcd *xhci;
3513 struct xhci_virt_device *vdev;
3514 struct xhci_command *command;
3515 struct xhci_input_control_ctx *ctrl_ctx;
3516 unsigned int ep_index;
3517 unsigned long flags;
3518 u32 changed_ep_bitmask;
3520 xhci = hcd_to_xhci(hcd);
3521 vdev = xhci->devs[udev->slot_id];
3523 /* Set up a configure endpoint command to remove the streams rings */
3524 spin_lock_irqsave(&xhci->lock, flags);
3525 changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3526 udev, eps, num_eps);
3527 if (changed_ep_bitmask == 0) {
3528 spin_unlock_irqrestore(&xhci->lock, flags);
3532 /* Use the xhci_command structure from the first endpoint. We may have
3533 * allocated too many, but the driver may call xhci_free_streams() for
3534 * each endpoint it grouped into one call to xhci_alloc_streams().
3536 ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3537 command = vdev->eps[ep_index].stream_info->free_streams_command;
3538 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3540 spin_unlock_irqrestore(&xhci->lock, flags);
3541 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3546 for (i = 0; i < num_eps; i++) {
3547 struct xhci_ep_ctx *ep_ctx;
3549 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3550 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3551 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3552 EP_GETTING_NO_STREAMS;
3554 xhci_endpoint_copy(xhci, command->in_ctx,
3555 vdev->out_ctx, ep_index);
3556 xhci_setup_no_streams_ep_input_ctx(ep_ctx,
3557 &vdev->eps[ep_index]);
3559 xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3560 vdev->out_ctx, ctrl_ctx,
3561 changed_ep_bitmask, changed_ep_bitmask);
3562 spin_unlock_irqrestore(&xhci->lock, flags);
3564 /* Issue and wait for the configure endpoint command,
3565 * which must succeed.
3567 ret = xhci_configure_endpoint(xhci, udev, command,
3570 /* xHC rejected the configure endpoint command for some reason, so we
3571 * leave the streams rings intact.
3576 spin_lock_irqsave(&xhci->lock, flags);
3577 for (i = 0; i < num_eps; i++) {
3578 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3579 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3580 vdev->eps[ep_index].stream_info = NULL;
3581 /* FIXME Unset maxPstreams in endpoint context and
3582 * update deq ptr to point to normal string ring.
3584 vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
3585 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3587 spin_unlock_irqrestore(&xhci->lock, flags);
3593 * Deletes endpoint resources for endpoints that were active before a Reset
3594 * Device command, or a Disable Slot command. The Reset Device command leaves
3595 * the control endpoint intact, whereas the Disable Slot command deletes it.
3597 * Must be called with xhci->lock held.
3599 void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
3600 struct xhci_virt_device *virt_dev, bool drop_control_ep)
3603 unsigned int num_dropped_eps = 0;
3604 unsigned int drop_flags = 0;
3606 for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
3607 if (virt_dev->eps[i].ring) {
3608 drop_flags |= 1 << i;
3612 xhci->num_active_eps -= num_dropped_eps;
3613 if (num_dropped_eps)
3614 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3615 "Dropped %u ep ctxs, flags = 0x%x, "
3617 num_dropped_eps, drop_flags,
3618 xhci->num_active_eps);
3622 * This submits a Reset Device Command, which will set the device state to 0,
3623 * set the device address to 0, and disable all the endpoints except the default
3624 * control endpoint. The USB core should come back and call
3625 * xhci_address_device(), and then re-set up the configuration. If this is
3626 * called because of a usb_reset_and_verify_device(), then the old alternate
3627 * settings will be re-installed through the normal bandwidth allocation
3630 * Wait for the Reset Device command to finish. Remove all structures
3631 * associated with the endpoints that were disabled. Clear the input device
3632 * structure? Reset the control endpoint 0 max packet size?
3634 * If the virt_dev to be reset does not exist or does not match the udev,
3635 * it means the device is lost, possibly due to the xHC restore error and
3636 * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3637 * re-allocate the device.
3639 static int xhci_discover_or_reset_device(struct usb_hcd *hcd,
3640 struct usb_device *udev)
3643 unsigned long flags;
3644 struct xhci_hcd *xhci;
3645 unsigned int slot_id;
3646 struct xhci_virt_device *virt_dev;
3647 struct xhci_command *reset_device_cmd;
3648 struct xhci_slot_ctx *slot_ctx;
3649 int old_active_eps = 0;
3651 ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3654 xhci = hcd_to_xhci(hcd);
3655 slot_id = udev->slot_id;
3656 virt_dev = xhci->devs[slot_id];
3658 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3659 "not exist. Re-allocate the device\n", slot_id);
3660 ret = xhci_alloc_dev(hcd, udev);
3667 if (virt_dev->tt_info)
3668 old_active_eps = virt_dev->tt_info->active_eps;
3670 if (virt_dev->udev != udev) {
3671 /* If the virt_dev and the udev does not match, this virt_dev
3672 * may belong to another udev.
3673 * Re-allocate the device.
3675 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3676 "not match the udev. Re-allocate the device\n",
3678 ret = xhci_alloc_dev(hcd, udev);
3685 /* If device is not setup, there is no point in resetting it */
3686 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3687 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3688 SLOT_STATE_DISABLED)
3691 trace_xhci_discover_or_reset_device(slot_ctx);
3693 xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3694 /* Allocate the command structure that holds the struct completion.
3695 * Assume we're in process context, since the normal device reset
3696 * process has to wait for the device anyway. Storage devices are
3697 * reset as part of error handling, so use GFP_NOIO instead of
3700 reset_device_cmd = xhci_alloc_command(xhci, true, GFP_NOIO);
3701 if (!reset_device_cmd) {
3702 xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3706 /* Attempt to submit the Reset Device command to the command ring */
3707 spin_lock_irqsave(&xhci->lock, flags);
3709 ret = xhci_queue_reset_device(xhci, reset_device_cmd, slot_id);
3711 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3712 spin_unlock_irqrestore(&xhci->lock, flags);
3713 goto command_cleanup;
3715 xhci_ring_cmd_db(xhci);
3716 spin_unlock_irqrestore(&xhci->lock, flags);
3718 /* Wait for the Reset Device command to finish */
3719 wait_for_completion(reset_device_cmd->completion);
3721 /* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3722 * unless we tried to reset a slot ID that wasn't enabled,
3723 * or the device wasn't in the addressed or configured state.
3725 ret = reset_device_cmd->status;
3727 case COMP_COMMAND_ABORTED:
3728 case COMP_COMMAND_RING_STOPPED:
3729 xhci_warn(xhci, "Timeout waiting for reset device command\n");
3731 goto command_cleanup;
3732 case COMP_SLOT_NOT_ENABLED_ERROR: /* 0.95 completion for bad slot ID */
3733 case COMP_CONTEXT_STATE_ERROR: /* 0.96 completion code for same thing */
3734 xhci_dbg(xhci, "Can't reset device (slot ID %u) in %s state\n",
3736 xhci_get_slot_state(xhci, virt_dev->out_ctx));
3737 xhci_dbg(xhci, "Not freeing device rings.\n");
3738 /* Don't treat this as an error. May change my mind later. */
3740 goto command_cleanup;
3742 xhci_dbg(xhci, "Successful reset device command.\n");
3745 if (xhci_is_vendor_info_code(xhci, ret))
3747 xhci_warn(xhci, "Unknown completion code %u for "
3748 "reset device command.\n", ret);
3750 goto command_cleanup;
3753 /* Free up host controller endpoint resources */
3754 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3755 spin_lock_irqsave(&xhci->lock, flags);
3756 /* Don't delete the default control endpoint resources */
3757 xhci_free_device_endpoint_resources(xhci, virt_dev, false);
3758 spin_unlock_irqrestore(&xhci->lock, flags);
3761 /* Everything but endpoint 0 is disabled, so free the rings. */
3762 for (i = 1; i < 31; i++) {
3763 struct xhci_virt_ep *ep = &virt_dev->eps[i];
3765 if (ep->ep_state & EP_HAS_STREAMS) {
3766 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on device reset, freeing streams.\n",
3767 xhci_get_endpoint_address(i));
3768 xhci_free_stream_info(xhci, ep->stream_info);
3769 ep->stream_info = NULL;
3770 ep->ep_state &= ~EP_HAS_STREAMS;
3774 xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
3775 xhci_free_endpoint_ring(xhci, virt_dev, i);
3777 if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
3778 xhci_drop_ep_from_interval_table(xhci,
3779 &virt_dev->eps[i].bw_info,
3784 xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
3786 /* If necessary, update the number of active TTs on this root port */
3787 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
3788 virt_dev->flags = 0;
3792 xhci_free_command(xhci, reset_device_cmd);
3797 * At this point, the struct usb_device is about to go away, the device has
3798 * disconnected, and all traffic has been stopped and the endpoints have been
3799 * disabled. Free any HC data structures associated with that device.
3801 static void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
3803 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3804 struct xhci_virt_device *virt_dev;
3805 struct xhci_slot_ctx *slot_ctx;
3808 #ifndef CONFIG_USB_DEFAULT_PERSIST
3810 * We called pm_runtime_get_noresume when the device was attached.
3811 * Decrement the counter here to allow controller to runtime suspend
3812 * if no devices remain.
3814 if (xhci->quirks & XHCI_RESET_ON_RESUME)
3815 pm_runtime_put_noidle(hcd->self.controller);
3818 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3819 /* If the host is halted due to driver unload, we still need to free the
3822 if (ret <= 0 && ret != -ENODEV)
3825 virt_dev = xhci->devs[udev->slot_id];
3826 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3827 trace_xhci_free_dev(slot_ctx);
3829 /* Stop any wayward timer functions (which may grab the lock) */
3830 for (i = 0; i < 31; i++) {
3831 virt_dev->eps[i].ep_state &= ~EP_STOP_CMD_PENDING;
3832 del_timer_sync(&virt_dev->eps[i].stop_cmd_timer);
3834 xhci_debugfs_remove_slot(xhci, udev->slot_id);
3835 virt_dev->udev = NULL;
3836 ret = xhci_disable_slot(xhci, udev->slot_id);
3838 xhci_free_virt_device(xhci, udev->slot_id);
3841 int xhci_disable_slot(struct xhci_hcd *xhci, u32 slot_id)
3843 struct xhci_command *command;
3844 unsigned long flags;
3848 command = xhci_alloc_command(xhci, false, GFP_KERNEL);
3852 spin_lock_irqsave(&xhci->lock, flags);
3853 /* Don't disable the slot if the host controller is dead. */
3854 state = readl(&xhci->op_regs->status);
3855 if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
3856 (xhci->xhc_state & XHCI_STATE_HALTED)) {
3857 spin_unlock_irqrestore(&xhci->lock, flags);
3862 ret = xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
3865 spin_unlock_irqrestore(&xhci->lock, flags);
3869 xhci_ring_cmd_db(xhci);
3870 spin_unlock_irqrestore(&xhci->lock, flags);
3875 * Checks if we have enough host controller resources for the default control
3878 * Must be called with xhci->lock held.
3880 static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
3882 if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
3883 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3884 "Not enough ep ctxs: "
3885 "%u active, need to add 1, limit is %u.",
3886 xhci->num_active_eps, xhci->limit_active_eps);
3889 xhci->num_active_eps += 1;
3890 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3891 "Adding 1 ep ctx, %u now active.",
3892 xhci->num_active_eps);
3898 * Returns 0 if the xHC ran out of device slots, the Enable Slot command
3899 * timed out, or allocating memory failed. Returns 1 on success.
3901 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
3903 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3904 struct xhci_virt_device *vdev;
3905 struct xhci_slot_ctx *slot_ctx;
3906 unsigned long flags;
3908 struct xhci_command *command;
3910 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
3914 spin_lock_irqsave(&xhci->lock, flags);
3915 ret = xhci_queue_slot_control(xhci, command, TRB_ENABLE_SLOT, 0);
3917 spin_unlock_irqrestore(&xhci->lock, flags);
3918 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3919 xhci_free_command(xhci, command);
3922 xhci_ring_cmd_db(xhci);
3923 spin_unlock_irqrestore(&xhci->lock, flags);
3925 wait_for_completion(command->completion);
3926 slot_id = command->slot_id;
3928 if (!slot_id || command->status != COMP_SUCCESS) {
3929 xhci_err(xhci, "Error while assigning device slot ID\n");
3930 xhci_err(xhci, "Max number of devices this xHCI host supports is %u.\n",
3932 readl(&xhci->cap_regs->hcs_params1)));
3933 xhci_free_command(xhci, command);
3937 xhci_free_command(xhci, command);
3939 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3940 spin_lock_irqsave(&xhci->lock, flags);
3941 ret = xhci_reserve_host_control_ep_resources(xhci);
3943 spin_unlock_irqrestore(&xhci->lock, flags);
3944 xhci_warn(xhci, "Not enough host resources, "
3945 "active endpoint contexts = %u\n",
3946 xhci->num_active_eps);
3949 spin_unlock_irqrestore(&xhci->lock, flags);
3951 /* Use GFP_NOIO, since this function can be called from
3952 * xhci_discover_or_reset_device(), which may be called as part of
3953 * mass storage driver error handling.
3955 if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) {
3956 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
3959 vdev = xhci->devs[slot_id];
3960 slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
3961 trace_xhci_alloc_dev(slot_ctx);
3963 udev->slot_id = slot_id;
3965 xhci_debugfs_create_slot(xhci, slot_id);
3967 #ifndef CONFIG_USB_DEFAULT_PERSIST
3969 * If resetting upon resume, we can't put the controller into runtime
3970 * suspend if there is a device attached.
3972 if (xhci->quirks & XHCI_RESET_ON_RESUME)
3973 pm_runtime_get_noresume(hcd->self.controller);
3976 /* Is this a LS or FS device under a HS hub? */
3977 /* Hub or peripherial? */
3981 ret = xhci_disable_slot(xhci, udev->slot_id);
3983 xhci_free_virt_device(xhci, udev->slot_id);
3989 * Issue an Address Device command and optionally send a corresponding
3990 * SetAddress request to the device.
3992 static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
3993 enum xhci_setup_dev setup)
3995 const char *act = setup == SETUP_CONTEXT_ONLY ? "context" : "address";
3996 unsigned long flags;
3997 struct xhci_virt_device *virt_dev;
3999 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4000 struct xhci_slot_ctx *slot_ctx;
4001 struct xhci_input_control_ctx *ctrl_ctx;
4003 struct xhci_command *command = NULL;
4005 mutex_lock(&xhci->mutex);
4007 if (xhci->xhc_state) { /* dying, removing or halted */
4012 if (!udev->slot_id) {
4013 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4014 "Bad Slot ID %d", udev->slot_id);
4019 virt_dev = xhci->devs[udev->slot_id];
4021 if (WARN_ON(!virt_dev)) {
4023 * In plug/unplug torture test with an NEC controller,
4024 * a zero-dereference was observed once due to virt_dev = 0.
4025 * Print useful debug rather than crash if it is observed again!
4027 xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
4032 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4033 trace_xhci_setup_device_slot(slot_ctx);
4035 if (setup == SETUP_CONTEXT_ONLY) {
4036 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
4037 SLOT_STATE_DEFAULT) {
4038 xhci_dbg(xhci, "Slot already in default state\n");
4043 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4049 command->in_ctx = virt_dev->in_ctx;
4051 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
4052 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
4054 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4060 * If this is the first Set Address since device plug-in or
4061 * virt_device realloaction after a resume with an xHCI power loss,
4062 * then set up the slot context.
4064 if (!slot_ctx->dev_info)
4065 xhci_setup_addressable_virt_dev(xhci, udev);
4066 /* Otherwise, update the control endpoint ring enqueue pointer. */
4068 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
4069 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
4070 ctrl_ctx->drop_flags = 0;
4072 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4073 le32_to_cpu(slot_ctx->dev_info) >> 27);
4075 spin_lock_irqsave(&xhci->lock, flags);
4076 trace_xhci_setup_device(virt_dev);
4077 ret = xhci_queue_address_device(xhci, command, virt_dev->in_ctx->dma,
4078 udev->slot_id, setup);
4080 spin_unlock_irqrestore(&xhci->lock, flags);
4081 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4082 "FIXME: allocate a command ring segment");
4085 xhci_ring_cmd_db(xhci);
4086 spin_unlock_irqrestore(&xhci->lock, flags);
4088 /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
4089 wait_for_completion(command->completion);
4091 /* FIXME: From section 4.3.4: "Software shall be responsible for timing
4092 * the SetAddress() "recovery interval" required by USB and aborting the
4093 * command on a timeout.
4095 switch (command->status) {
4096 case COMP_COMMAND_ABORTED:
4097 case COMP_COMMAND_RING_STOPPED:
4098 xhci_warn(xhci, "Timeout while waiting for setup device command\n");
4101 case COMP_CONTEXT_STATE_ERROR:
4102 case COMP_SLOT_NOT_ENABLED_ERROR:
4103 xhci_err(xhci, "Setup ERROR: setup %s command for slot %d.\n",
4104 act, udev->slot_id);
4107 case COMP_USB_TRANSACTION_ERROR:
4108 dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
4110 mutex_unlock(&xhci->mutex);
4111 ret = xhci_disable_slot(xhci, udev->slot_id);
4113 xhci_alloc_dev(hcd, udev);
4114 kfree(command->completion);
4117 case COMP_INCOMPATIBLE_DEVICE_ERROR:
4118 dev_warn(&udev->dev,
4119 "ERROR: Incompatible device for setup %s command\n", act);
4123 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4124 "Successful setup %s command", act);
4128 "ERROR: unexpected setup %s command completion code 0x%x.\n",
4129 act, command->status);
4130 trace_xhci_address_ctx(xhci, virt_dev->out_ctx, 1);
4136 temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
4137 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4138 "Op regs DCBAA ptr = %#016llx", temp_64);
4139 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4140 "Slot ID %d dcbaa entry @%p = %#016llx",
4142 &xhci->dcbaa->dev_context_ptrs[udev->slot_id],
4143 (unsigned long long)
4144 le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
4145 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4146 "Output Context DMA address = %#08llx",
4147 (unsigned long long)virt_dev->out_ctx->dma);
4148 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4149 le32_to_cpu(slot_ctx->dev_info) >> 27);
4151 * USB core uses address 1 for the roothubs, so we add one to the
4152 * address given back to us by the HC.
4154 trace_xhci_address_ctx(xhci, virt_dev->out_ctx,
4155 le32_to_cpu(slot_ctx->dev_info) >> 27);
4156 /* Zero the input context control for later use */
4157 ctrl_ctx->add_flags = 0;
4158 ctrl_ctx->drop_flags = 0;
4160 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4161 "Internal device address = %d",
4162 le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4164 mutex_unlock(&xhci->mutex);
4166 kfree(command->completion);
4172 static int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev)
4174 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ADDRESS);
4177 static int xhci_enable_device(struct usb_hcd *hcd, struct usb_device *udev)
4179 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ONLY);
4183 * Transfer the port index into real index in the HW port status
4184 * registers. Caculate offset between the port's PORTSC register
4185 * and port status base. Divide the number of per port register
4186 * to get the real index. The raw port number bases 1.
4188 int xhci_find_raw_port_number(struct usb_hcd *hcd, int port1)
4190 struct xhci_hub *rhub;
4192 rhub = xhci_get_rhub(hcd);
4193 return rhub->ports[port1 - 1]->hw_portnum + 1;
4197 * Issue an Evaluate Context command to change the Maximum Exit Latency in the
4198 * slot context. If that succeeds, store the new MEL in the xhci_virt_device.
4200 static int __maybe_unused xhci_change_max_exit_latency(struct xhci_hcd *xhci,
4201 struct usb_device *udev, u16 max_exit_latency)
4203 struct xhci_virt_device *virt_dev;
4204 struct xhci_command *command;
4205 struct xhci_input_control_ctx *ctrl_ctx;
4206 struct xhci_slot_ctx *slot_ctx;
4207 unsigned long flags;
4210 spin_lock_irqsave(&xhci->lock, flags);
4212 virt_dev = xhci->devs[udev->slot_id];
4215 * virt_dev might not exists yet if xHC resumed from hibernate (S4) and
4216 * xHC was re-initialized. Exit latency will be set later after
4217 * hub_port_finish_reset() is done and xhci->devs[] are re-allocated
4220 if (!virt_dev || max_exit_latency == virt_dev->current_mel) {
4221 spin_unlock_irqrestore(&xhci->lock, flags);
4225 /* Attempt to issue an Evaluate Context command to change the MEL. */
4226 command = xhci->lpm_command;
4227 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
4229 spin_unlock_irqrestore(&xhci->lock, flags);
4230 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4235 xhci_slot_copy(xhci, command->in_ctx, virt_dev->out_ctx);
4236 spin_unlock_irqrestore(&xhci->lock, flags);
4238 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4239 slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
4240 slot_ctx->dev_info2 &= cpu_to_le32(~((u32) MAX_EXIT));
4241 slot_ctx->dev_info2 |= cpu_to_le32(max_exit_latency);
4242 slot_ctx->dev_state = 0;
4244 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
4245 "Set up evaluate context for LPM MEL change.");
4247 /* Issue and wait for the evaluate context command. */
4248 ret = xhci_configure_endpoint(xhci, udev, command,
4252 spin_lock_irqsave(&xhci->lock, flags);
4253 virt_dev->current_mel = max_exit_latency;
4254 spin_unlock_irqrestore(&xhci->lock, flags);
4261 /* BESL to HIRD Encoding array for USB2 LPM */
4262 static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
4263 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
4265 /* Calculate HIRD/BESL for USB2 PORTPMSC*/
4266 static int xhci_calculate_hird_besl(struct xhci_hcd *xhci,
4267 struct usb_device *udev)
4269 int u2del, besl, besl_host;
4270 int besl_device = 0;
4273 u2del = HCS_U2_LATENCY(xhci->hcs_params3);
4274 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4276 if (field & USB_BESL_SUPPORT) {
4277 for (besl_host = 0; besl_host < 16; besl_host++) {
4278 if (xhci_besl_encoding[besl_host] >= u2del)
4281 /* Use baseline BESL value as default */
4282 if (field & USB_BESL_BASELINE_VALID)
4283 besl_device = USB_GET_BESL_BASELINE(field);
4284 else if (field & USB_BESL_DEEP_VALID)
4285 besl_device = USB_GET_BESL_DEEP(field);
4290 besl_host = (u2del - 51) / 75 + 1;
4293 besl = besl_host + besl_device;
4300 /* Calculate BESLD, L1 timeout and HIRDM for USB2 PORTHLPMC */
4301 static int xhci_calculate_usb2_hw_lpm_params(struct usb_device *udev)
4308 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4310 /* xHCI l1 is set in steps of 256us, xHCI 1.0 section 5.4.11.2 */
4311 l1 = udev->l1_params.timeout / 256;
4313 /* device has preferred BESLD */
4314 if (field & USB_BESL_DEEP_VALID) {
4315 besld = USB_GET_BESL_DEEP(field);
4319 return PORT_BESLD(besld) | PORT_L1_TIMEOUT(l1) | PORT_HIRDM(hirdm);
4322 static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4323 struct usb_device *udev, int enable)
4325 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4326 struct xhci_port **ports;
4327 __le32 __iomem *pm_addr, *hlpm_addr;
4328 u32 pm_val, hlpm_val, field;
4329 unsigned int port_num;
4330 unsigned long flags;
4331 int hird, exit_latency;
4334 if (xhci->quirks & XHCI_HW_LPM_DISABLE)
4337 if (hcd->speed >= HCD_USB3 || !xhci->hw_lpm_support ||
4341 if (!udev->parent || udev->parent->parent ||
4342 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4345 if (udev->usb2_hw_lpm_capable != 1)
4348 spin_lock_irqsave(&xhci->lock, flags);
4350 ports = xhci->usb2_rhub.ports;
4351 port_num = udev->portnum - 1;
4352 pm_addr = ports[port_num]->addr + PORTPMSC;
4353 pm_val = readl(pm_addr);
4354 hlpm_addr = ports[port_num]->addr + PORTHLPMC;
4356 xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
4357 enable ? "enable" : "disable", port_num + 1);
4360 /* Host supports BESL timeout instead of HIRD */
4361 if (udev->usb2_hw_lpm_besl_capable) {
4362 /* if device doesn't have a preferred BESL value use a
4363 * default one which works with mixed HIRD and BESL
4364 * systems. See XHCI_DEFAULT_BESL definition in xhci.h
4366 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4367 if ((field & USB_BESL_SUPPORT) &&
4368 (field & USB_BESL_BASELINE_VALID))
4369 hird = USB_GET_BESL_BASELINE(field);
4371 hird = udev->l1_params.besl;
4373 exit_latency = xhci_besl_encoding[hird];
4374 spin_unlock_irqrestore(&xhci->lock, flags);
4376 /* USB 3.0 code dedicate one xhci->lpm_command->in_ctx
4377 * input context for link powermanagement evaluate
4378 * context commands. It is protected by hcd->bandwidth
4379 * mutex and is shared by all devices. We need to set
4380 * the max ext latency in USB 2 BESL LPM as well, so
4381 * use the same mutex and xhci_change_max_exit_latency()
4383 mutex_lock(hcd->bandwidth_mutex);
4384 ret = xhci_change_max_exit_latency(xhci, udev,
4386 mutex_unlock(hcd->bandwidth_mutex);
4390 spin_lock_irqsave(&xhci->lock, flags);
4392 hlpm_val = xhci_calculate_usb2_hw_lpm_params(udev);
4393 writel(hlpm_val, hlpm_addr);
4397 hird = xhci_calculate_hird_besl(xhci, udev);
4400 pm_val &= ~PORT_HIRD_MASK;
4401 pm_val |= PORT_HIRD(hird) | PORT_RWE | PORT_L1DS(udev->slot_id);
4402 writel(pm_val, pm_addr);
4403 pm_val = readl(pm_addr);
4405 writel(pm_val, pm_addr);
4409 pm_val &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK | PORT_L1DS_MASK);
4410 writel(pm_val, pm_addr);
4413 if (udev->usb2_hw_lpm_besl_capable) {
4414 spin_unlock_irqrestore(&xhci->lock, flags);
4415 mutex_lock(hcd->bandwidth_mutex);
4416 xhci_change_max_exit_latency(xhci, udev, 0);
4417 mutex_unlock(hcd->bandwidth_mutex);
4418 readl_poll_timeout(ports[port_num]->addr, pm_val,
4419 (pm_val & PORT_PLS_MASK) == XDEV_U0,
4425 spin_unlock_irqrestore(&xhci->lock, flags);
4429 /* check if a usb2 port supports a given extened capability protocol
4430 * only USB2 ports extended protocol capability values are cached.
4431 * Return 1 if capability is supported
4433 static int xhci_check_usb2_port_capability(struct xhci_hcd *xhci, int port,
4434 unsigned capability)
4436 u32 port_offset, port_count;
4439 for (i = 0; i < xhci->num_ext_caps; i++) {
4440 if (xhci->ext_caps[i] & capability) {
4441 /* port offsets starts at 1 */
4442 port_offset = XHCI_EXT_PORT_OFF(xhci->ext_caps[i]) - 1;
4443 port_count = XHCI_EXT_PORT_COUNT(xhci->ext_caps[i]);
4444 if (port >= port_offset &&
4445 port < port_offset + port_count)
4452 static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4454 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4455 int portnum = udev->portnum - 1;
4457 if (hcd->speed >= HCD_USB3 || !xhci->sw_lpm_support ||
4461 /* we only support lpm for non-hub device connected to root hub yet */
4462 if (!udev->parent || udev->parent->parent ||
4463 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4466 if (xhci->hw_lpm_support == 1 &&
4467 xhci_check_usb2_port_capability(
4468 xhci, portnum, XHCI_HLC)) {
4469 udev->usb2_hw_lpm_capable = 1;
4470 udev->l1_params.timeout = XHCI_L1_TIMEOUT;
4471 udev->l1_params.besl = XHCI_DEFAULT_BESL;
4472 if (xhci_check_usb2_port_capability(xhci, portnum,
4474 udev->usb2_hw_lpm_besl_capable = 1;
4480 /*---------------------- USB 3.0 Link PM functions ------------------------*/
4482 /* Service interval in nanoseconds = 2^(bInterval - 1) * 125us * 1000ns / 1us */
4483 static unsigned long long xhci_service_interval_to_ns(
4484 struct usb_endpoint_descriptor *desc)
4486 return (1ULL << (desc->bInterval - 1)) * 125 * 1000;
4489 static u16 xhci_get_timeout_no_hub_lpm(struct usb_device *udev,
4490 enum usb3_link_state state)
4492 unsigned long long sel;
4493 unsigned long long pel;
4494 unsigned int max_sel_pel;
4499 /* Convert SEL and PEL stored in nanoseconds to microseconds */
4500 sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4501 pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4502 max_sel_pel = USB3_LPM_MAX_U1_SEL_PEL;
4506 sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4507 pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4508 max_sel_pel = USB3_LPM_MAX_U2_SEL_PEL;
4512 dev_warn(&udev->dev, "%s: Can't get timeout for non-U1 or U2 state.\n",
4514 return USB3_LPM_DISABLED;
4517 if (sel <= max_sel_pel && pel <= max_sel_pel)
4518 return USB3_LPM_DEVICE_INITIATED;
4520 if (sel > max_sel_pel)
4521 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4522 "due to long SEL %llu ms\n",
4525 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4526 "due to long PEL %llu ms\n",
4528 return USB3_LPM_DISABLED;
4531 /* The U1 timeout should be the maximum of the following values:
4532 * - For control endpoints, U1 system exit latency (SEL) * 3
4533 * - For bulk endpoints, U1 SEL * 5
4534 * - For interrupt endpoints:
4535 * - Notification EPs, U1 SEL * 3
4536 * - Periodic EPs, max(105% of bInterval, U1 SEL * 2)
4537 * - For isochronous endpoints, max(105% of bInterval, U1 SEL * 2)
4539 static unsigned long long xhci_calculate_intel_u1_timeout(
4540 struct usb_device *udev,
4541 struct usb_endpoint_descriptor *desc)
4543 unsigned long long timeout_ns;
4547 ep_type = usb_endpoint_type(desc);
4549 case USB_ENDPOINT_XFER_CONTROL:
4550 timeout_ns = udev->u1_params.sel * 3;
4552 case USB_ENDPOINT_XFER_BULK:
4553 timeout_ns = udev->u1_params.sel * 5;
4555 case USB_ENDPOINT_XFER_INT:
4556 intr_type = usb_endpoint_interrupt_type(desc);
4557 if (intr_type == USB_ENDPOINT_INTR_NOTIFICATION) {
4558 timeout_ns = udev->u1_params.sel * 3;
4561 /* Otherwise the calculation is the same as isoc eps */
4563 case USB_ENDPOINT_XFER_ISOC:
4564 timeout_ns = xhci_service_interval_to_ns(desc);
4565 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns * 105, 100);
4566 if (timeout_ns < udev->u1_params.sel * 2)
4567 timeout_ns = udev->u1_params.sel * 2;
4576 /* Returns the hub-encoded U1 timeout value. */
4577 static u16 xhci_calculate_u1_timeout(struct xhci_hcd *xhci,
4578 struct usb_device *udev,
4579 struct usb_endpoint_descriptor *desc)
4581 unsigned long long timeout_ns;
4583 /* Prevent U1 if service interval is shorter than U1 exit latency */
4584 if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4585 if (xhci_service_interval_to_ns(desc) <= udev->u1_params.mel) {
4586 dev_dbg(&udev->dev, "Disable U1, ESIT shorter than exit latency\n");
4587 return USB3_LPM_DISABLED;
4591 if (xhci->quirks & XHCI_INTEL_HOST)
4592 timeout_ns = xhci_calculate_intel_u1_timeout(udev, desc);
4594 timeout_ns = udev->u1_params.sel;
4596 /* The U1 timeout is encoded in 1us intervals.
4597 * Don't return a timeout of zero, because that's USB3_LPM_DISABLED.
4599 if (timeout_ns == USB3_LPM_DISABLED)
4602 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 1000);
4604 /* If the necessary timeout value is bigger than what we can set in the
4605 * USB 3.0 hub, we have to disable hub-initiated U1.
4607 if (timeout_ns <= USB3_LPM_U1_MAX_TIMEOUT)
4609 dev_dbg(&udev->dev, "Hub-initiated U1 disabled "
4610 "due to long timeout %llu ms\n", timeout_ns);
4611 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U1);
4614 /* The U2 timeout should be the maximum of:
4615 * - 10 ms (to avoid the bandwidth impact on the scheduler)
4616 * - largest bInterval of any active periodic endpoint (to avoid going
4617 * into lower power link states between intervals).
4618 * - the U2 Exit Latency of the device
4620 static unsigned long long xhci_calculate_intel_u2_timeout(
4621 struct usb_device *udev,
4622 struct usb_endpoint_descriptor *desc)
4624 unsigned long long timeout_ns;
4625 unsigned long long u2_del_ns;
4627 timeout_ns = 10 * 1000 * 1000;
4629 if ((usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) &&
4630 (xhci_service_interval_to_ns(desc) > timeout_ns))
4631 timeout_ns = xhci_service_interval_to_ns(desc);
4633 u2_del_ns = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat) * 1000ULL;
4634 if (u2_del_ns > timeout_ns)
4635 timeout_ns = u2_del_ns;
4640 /* Returns the hub-encoded U2 timeout value. */
4641 static u16 xhci_calculate_u2_timeout(struct xhci_hcd *xhci,
4642 struct usb_device *udev,
4643 struct usb_endpoint_descriptor *desc)
4645 unsigned long long timeout_ns;
4647 /* Prevent U2 if service interval is shorter than U2 exit latency */
4648 if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4649 if (xhci_service_interval_to_ns(desc) <= udev->u2_params.mel) {
4650 dev_dbg(&udev->dev, "Disable U2, ESIT shorter than exit latency\n");
4651 return USB3_LPM_DISABLED;
4655 if (xhci->quirks & XHCI_INTEL_HOST)
4656 timeout_ns = xhci_calculate_intel_u2_timeout(udev, desc);
4658 timeout_ns = udev->u2_params.sel;
4660 /* The U2 timeout is encoded in 256us intervals */
4661 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 256 * 1000);
4662 /* If the necessary timeout value is bigger than what we can set in the
4663 * USB 3.0 hub, we have to disable hub-initiated U2.
4665 if (timeout_ns <= USB3_LPM_U2_MAX_TIMEOUT)
4667 dev_dbg(&udev->dev, "Hub-initiated U2 disabled "
4668 "due to long timeout %llu ms\n", timeout_ns);
4669 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U2);
4672 static u16 xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4673 struct usb_device *udev,
4674 struct usb_endpoint_descriptor *desc,
4675 enum usb3_link_state state,
4678 if (state == USB3_LPM_U1)
4679 return xhci_calculate_u1_timeout(xhci, udev, desc);
4680 else if (state == USB3_LPM_U2)
4681 return xhci_calculate_u2_timeout(xhci, udev, desc);
4683 return USB3_LPM_DISABLED;
4686 static int xhci_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4687 struct usb_device *udev,
4688 struct usb_endpoint_descriptor *desc,
4689 enum usb3_link_state state,
4694 alt_timeout = xhci_call_host_update_timeout_for_endpoint(xhci, udev,
4695 desc, state, timeout);
4697 /* If we found we can't enable hub-initiated LPM, and
4698 * the U1 or U2 exit latency was too high to allow
4699 * device-initiated LPM as well, then we will disable LPM
4700 * for this device, so stop searching any further.
4702 if (alt_timeout == USB3_LPM_DISABLED) {
4703 *timeout = alt_timeout;
4706 if (alt_timeout > *timeout)
4707 *timeout = alt_timeout;
4711 static int xhci_update_timeout_for_interface(struct xhci_hcd *xhci,
4712 struct usb_device *udev,
4713 struct usb_host_interface *alt,
4714 enum usb3_link_state state,
4719 for (j = 0; j < alt->desc.bNumEndpoints; j++) {
4720 if (xhci_update_timeout_for_endpoint(xhci, udev,
4721 &alt->endpoint[j].desc, state, timeout))
4728 static int xhci_check_intel_tier_policy(struct usb_device *udev,
4729 enum usb3_link_state state)
4731 struct usb_device *parent;
4732 unsigned int num_hubs;
4734 if (state == USB3_LPM_U2)
4737 /* Don't enable U1 if the device is on a 2nd tier hub or lower. */
4738 for (parent = udev->parent, num_hubs = 0; parent->parent;
4739 parent = parent->parent)
4745 dev_dbg(&udev->dev, "Disabling U1 link state for device"
4746 " below second-tier hub.\n");
4747 dev_dbg(&udev->dev, "Plug device into first-tier hub "
4748 "to decrease power consumption.\n");
4752 static int xhci_check_tier_policy(struct xhci_hcd *xhci,
4753 struct usb_device *udev,
4754 enum usb3_link_state state)
4756 if (xhci->quirks & XHCI_INTEL_HOST)
4757 return xhci_check_intel_tier_policy(udev, state);
4762 /* Returns the U1 or U2 timeout that should be enabled.
4763 * If the tier check or timeout setting functions return with a non-zero exit
4764 * code, that means the timeout value has been finalized and we shouldn't look
4765 * at any more endpoints.
4767 static u16 xhci_calculate_lpm_timeout(struct usb_hcd *hcd,
4768 struct usb_device *udev, enum usb3_link_state state)
4770 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4771 struct usb_host_config *config;
4774 u16 timeout = USB3_LPM_DISABLED;
4776 if (state == USB3_LPM_U1)
4778 else if (state == USB3_LPM_U2)
4781 dev_warn(&udev->dev, "Can't enable unknown link state %i\n",
4786 if (xhci_check_tier_policy(xhci, udev, state) < 0)
4789 /* Gather some information about the currently installed configuration
4790 * and alternate interface settings.
4792 if (xhci_update_timeout_for_endpoint(xhci, udev, &udev->ep0.desc,
4796 config = udev->actconfig;
4800 for (i = 0; i < config->desc.bNumInterfaces; i++) {
4801 struct usb_driver *driver;
4802 struct usb_interface *intf = config->interface[i];
4807 /* Check if any currently bound drivers want hub-initiated LPM
4810 if (intf->dev.driver) {
4811 driver = to_usb_driver(intf->dev.driver);
4812 if (driver && driver->disable_hub_initiated_lpm) {
4813 dev_dbg(&udev->dev, "Hub-initiated %s disabled at request of driver %s\n",
4814 state_name, driver->name);
4815 timeout = xhci_get_timeout_no_hub_lpm(udev,
4817 if (timeout == USB3_LPM_DISABLED)
4822 /* Not sure how this could happen... */
4823 if (!intf->cur_altsetting)
4826 if (xhci_update_timeout_for_interface(xhci, udev,
4827 intf->cur_altsetting,
4834 static int calculate_max_exit_latency(struct usb_device *udev,
4835 enum usb3_link_state state_changed,
4836 u16 hub_encoded_timeout)
4838 unsigned long long u1_mel_us = 0;
4839 unsigned long long u2_mel_us = 0;
4840 unsigned long long mel_us = 0;
4846 disabling_u1 = (state_changed == USB3_LPM_U1 &&
4847 hub_encoded_timeout == USB3_LPM_DISABLED);
4848 disabling_u2 = (state_changed == USB3_LPM_U2 &&
4849 hub_encoded_timeout == USB3_LPM_DISABLED);
4851 enabling_u1 = (state_changed == USB3_LPM_U1 &&
4852 hub_encoded_timeout != USB3_LPM_DISABLED);
4853 enabling_u2 = (state_changed == USB3_LPM_U2 &&
4854 hub_encoded_timeout != USB3_LPM_DISABLED);
4856 /* If U1 was already enabled and we're not disabling it,
4857 * or we're going to enable U1, account for the U1 max exit latency.
4859 if ((udev->u1_params.timeout != USB3_LPM_DISABLED && !disabling_u1) ||
4861 u1_mel_us = DIV_ROUND_UP(udev->u1_params.mel, 1000);
4862 if ((udev->u2_params.timeout != USB3_LPM_DISABLED && !disabling_u2) ||
4864 u2_mel_us = DIV_ROUND_UP(udev->u2_params.mel, 1000);
4866 if (u1_mel_us > u2_mel_us)
4870 /* xHCI host controller max exit latency field is only 16 bits wide. */
4871 if (mel_us > MAX_EXIT) {
4872 dev_warn(&udev->dev, "Link PM max exit latency of %lluus "
4873 "is too big.\n", mel_us);
4879 /* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
4880 static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
4881 struct usb_device *udev, enum usb3_link_state state)
4883 struct xhci_hcd *xhci;
4884 u16 hub_encoded_timeout;
4888 xhci = hcd_to_xhci(hcd);
4889 /* The LPM timeout values are pretty host-controller specific, so don't
4890 * enable hub-initiated timeouts unless the vendor has provided
4891 * information about their timeout algorithm.
4893 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
4894 !xhci->devs[udev->slot_id])
4895 return USB3_LPM_DISABLED;
4897 hub_encoded_timeout = xhci_calculate_lpm_timeout(hcd, udev, state);
4898 mel = calculate_max_exit_latency(udev, state, hub_encoded_timeout);
4900 /* Max Exit Latency is too big, disable LPM. */
4901 hub_encoded_timeout = USB3_LPM_DISABLED;
4905 ret = xhci_change_max_exit_latency(xhci, udev, mel);
4908 return hub_encoded_timeout;
4911 static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
4912 struct usb_device *udev, enum usb3_link_state state)
4914 struct xhci_hcd *xhci;
4917 xhci = hcd_to_xhci(hcd);
4918 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
4919 !xhci->devs[udev->slot_id])
4922 mel = calculate_max_exit_latency(udev, state, USB3_LPM_DISABLED);
4923 return xhci_change_max_exit_latency(xhci, udev, mel);
4925 #else /* CONFIG_PM */
4927 static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4928 struct usb_device *udev, int enable)
4933 static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4938 static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
4939 struct usb_device *udev, enum usb3_link_state state)
4941 return USB3_LPM_DISABLED;
4944 static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
4945 struct usb_device *udev, enum usb3_link_state state)
4949 #endif /* CONFIG_PM */
4951 /*-------------------------------------------------------------------------*/
4953 /* Once a hub descriptor is fetched for a device, we need to update the xHC's
4954 * internal data structures for the device.
4956 static int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
4957 struct usb_tt *tt, gfp_t mem_flags)
4959 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4960 struct xhci_virt_device *vdev;
4961 struct xhci_command *config_cmd;
4962 struct xhci_input_control_ctx *ctrl_ctx;
4963 struct xhci_slot_ctx *slot_ctx;
4964 unsigned long flags;
4965 unsigned think_time;
4968 /* Ignore root hubs */
4972 vdev = xhci->devs[hdev->slot_id];
4974 xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
4978 config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
4982 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
4984 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4986 xhci_free_command(xhci, config_cmd);
4990 spin_lock_irqsave(&xhci->lock, flags);
4991 if (hdev->speed == USB_SPEED_HIGH &&
4992 xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
4993 xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
4994 xhci_free_command(xhci, config_cmd);
4995 spin_unlock_irqrestore(&xhci->lock, flags);
4999 xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
5000 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
5001 slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
5002 slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
5004 * refer to section 6.2.2: MTT should be 0 for full speed hub,
5005 * but it may be already set to 1 when setup an xHCI virtual
5006 * device, so clear it anyway.
5009 slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
5010 else if (hdev->speed == USB_SPEED_FULL)
5011 slot_ctx->dev_info &= cpu_to_le32(~DEV_MTT);
5013 if (xhci->hci_version > 0x95) {
5014 xhci_dbg(xhci, "xHCI version %x needs hub "
5015 "TT think time and number of ports\n",
5016 (unsigned int) xhci->hci_version);
5017 slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
5018 /* Set TT think time - convert from ns to FS bit times.
5019 * 0 = 8 FS bit times, 1 = 16 FS bit times,
5020 * 2 = 24 FS bit times, 3 = 32 FS bit times.
5022 * xHCI 1.0: this field shall be 0 if the device is not a
5025 think_time = tt->think_time;
5026 if (think_time != 0)
5027 think_time = (think_time / 666) - 1;
5028 if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
5029 slot_ctx->tt_info |=
5030 cpu_to_le32(TT_THINK_TIME(think_time));
5032 xhci_dbg(xhci, "xHCI version %x doesn't need hub "
5033 "TT think time or number of ports\n",
5034 (unsigned int) xhci->hci_version);
5036 slot_ctx->dev_state = 0;
5037 spin_unlock_irqrestore(&xhci->lock, flags);
5039 xhci_dbg(xhci, "Set up %s for hub device.\n",
5040 (xhci->hci_version > 0x95) ?
5041 "configure endpoint" : "evaluate context");
5043 /* Issue and wait for the configure endpoint or
5044 * evaluate context command.
5046 if (xhci->hci_version > 0x95)
5047 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5050 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5053 xhci_free_command(xhci, config_cmd);
5057 static int xhci_get_frame(struct usb_hcd *hcd)
5059 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5060 /* EHCI mods by the periodic size. Why? */
5061 return readl(&xhci->run_regs->microframe_index) >> 3;
5064 int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks)
5066 struct xhci_hcd *xhci;
5068 * TODO: Check with DWC3 clients for sysdev according to
5071 struct device *dev = hcd->self.sysdev;
5072 unsigned int minor_rev;
5075 /* Accept arbitrarily long scatter-gather lists */
5076 hcd->self.sg_tablesize = ~0;
5078 /* support to build packet from discontinuous buffers */
5079 hcd->self.no_sg_constraint = 1;
5081 /* XHCI controllers don't stop the ep queue on short packets :| */
5082 hcd->self.no_stop_on_short = 1;
5084 xhci = hcd_to_xhci(hcd);
5086 if (usb_hcd_is_primary_hcd(hcd)) {
5087 xhci->main_hcd = hcd;
5088 xhci->usb2_rhub.hcd = hcd;
5089 /* Mark the first roothub as being USB 2.0.
5090 * The xHCI driver will register the USB 3.0 roothub.
5092 hcd->speed = HCD_USB2;
5093 hcd->self.root_hub->speed = USB_SPEED_HIGH;
5095 * USB 2.0 roothub under xHCI has an integrated TT,
5096 * (rate matching hub) as opposed to having an OHCI/UHCI
5097 * companion controller.
5102 * Early xHCI 1.1 spec did not mention USB 3.1 capable hosts
5103 * should return 0x31 for sbrn, or that the minor revision
5104 * is a two digit BCD containig minor and sub-minor numbers.
5105 * This was later clarified in xHCI 1.2.
5107 * Some USB 3.1 capable hosts therefore have sbrn 0x30, and
5108 * minor revision set to 0x1 instead of 0x10.
5110 if (xhci->usb3_rhub.min_rev == 0x1)
5113 minor_rev = xhci->usb3_rhub.min_rev / 0x10;
5115 switch (minor_rev) {
5117 hcd->speed = HCD_USB32;
5118 hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5119 hcd->self.root_hub->rx_lanes = 2;
5120 hcd->self.root_hub->tx_lanes = 2;
5123 hcd->speed = HCD_USB31;
5124 hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5127 xhci_info(xhci, "Host supports USB 3.%x %sSuperSpeed\n",
5129 minor_rev ? "Enhanced " : "");
5131 xhci->usb3_rhub.hcd = hcd;
5132 /* xHCI private pointer was set in xhci_pci_probe for the second
5133 * registered roothub.
5138 mutex_init(&xhci->mutex);
5139 xhci->cap_regs = hcd->regs;
5140 xhci->op_regs = hcd->regs +
5141 HC_LENGTH(readl(&xhci->cap_regs->hc_capbase));
5142 xhci->run_regs = hcd->regs +
5143 (readl(&xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
5144 /* Cache read-only capability registers */
5145 xhci->hcs_params1 = readl(&xhci->cap_regs->hcs_params1);
5146 xhci->hcs_params2 = readl(&xhci->cap_regs->hcs_params2);
5147 xhci->hcs_params3 = readl(&xhci->cap_regs->hcs_params3);
5148 xhci->hcc_params = readl(&xhci->cap_regs->hc_capbase);
5149 xhci->hci_version = HC_VERSION(xhci->hcc_params);
5150 xhci->hcc_params = readl(&xhci->cap_regs->hcc_params);
5151 if (xhci->hci_version > 0x100)
5152 xhci->hcc_params2 = readl(&xhci->cap_regs->hcc_params2);
5154 xhci->quirks |= quirks;
5156 get_quirks(dev, xhci);
5158 /* In xhci controllers which follow xhci 1.0 spec gives a spurious
5159 * success event after a short transfer. This quirk will ignore such
5162 if (xhci->hci_version > 0x96)
5163 xhci->quirks |= XHCI_SPURIOUS_SUCCESS;
5165 /* Make sure the HC is halted. */
5166 retval = xhci_halt(xhci);
5170 xhci_zero_64b_regs(xhci);
5172 xhci_dbg(xhci, "Resetting HCD\n");
5173 /* Reset the internal HC memory state and registers. */
5174 retval = xhci_reset(xhci);
5177 xhci_dbg(xhci, "Reset complete\n");
5180 * On some xHCI controllers (e.g. R-Car SoCs), the AC64 bit (bit 0)
5181 * of HCCPARAMS1 is set to 1. However, the xHCs don't support 64-bit
5182 * address memory pointers actually. So, this driver clears the AC64
5183 * bit of xhci->hcc_params to call dma_set_coherent_mask(dev,
5184 * DMA_BIT_MASK(32)) in this xhci_gen_setup().
5186 if (xhci->quirks & XHCI_NO_64BIT_SUPPORT)
5187 xhci->hcc_params &= ~BIT(0);
5189 /* Set dma_mask and coherent_dma_mask to 64-bits,
5190 * if xHC supports 64-bit addressing */
5191 if (HCC_64BIT_ADDR(xhci->hcc_params) &&
5192 !dma_set_mask(dev, DMA_BIT_MASK(64))) {
5193 xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
5194 dma_set_coherent_mask(dev, DMA_BIT_MASK(64));
5197 * This is to avoid error in cases where a 32-bit USB
5198 * controller is used on a 64-bit capable system.
5200 retval = dma_set_mask(dev, DMA_BIT_MASK(32));
5203 xhci_dbg(xhci, "Enabling 32-bit DMA addresses.\n");
5204 dma_set_coherent_mask(dev, DMA_BIT_MASK(32));
5207 xhci_dbg(xhci, "Calling HCD init\n");
5208 /* Initialize HCD and host controller data structures. */
5209 retval = xhci_init(hcd);
5212 xhci_dbg(xhci, "Called HCD init\n");
5214 xhci_info(xhci, "hcc params 0x%08x hci version 0x%x quirks 0x%016llx\n",
5215 xhci->hcc_params, xhci->hci_version, xhci->quirks);
5219 EXPORT_SYMBOL_GPL(xhci_gen_setup);
5221 static const struct hc_driver xhci_hc_driver = {
5222 .description = "xhci-hcd",
5223 .product_desc = "xHCI Host Controller",
5224 .hcd_priv_size = sizeof(struct xhci_hcd),
5227 * generic hardware linkage
5230 .flags = HCD_MEMORY | HCD_USB3 | HCD_SHARED,
5233 * basic lifecycle operations
5235 .reset = NULL, /* set in xhci_init_driver() */
5238 .shutdown = xhci_shutdown,
5241 * managing i/o requests and associated device resources
5243 .urb_enqueue = xhci_urb_enqueue,
5244 .urb_dequeue = xhci_urb_dequeue,
5245 .alloc_dev = xhci_alloc_dev,
5246 .free_dev = xhci_free_dev,
5247 .alloc_streams = xhci_alloc_streams,
5248 .free_streams = xhci_free_streams,
5249 .add_endpoint = xhci_add_endpoint,
5250 .drop_endpoint = xhci_drop_endpoint,
5251 .endpoint_reset = xhci_endpoint_reset,
5252 .check_bandwidth = xhci_check_bandwidth,
5253 .reset_bandwidth = xhci_reset_bandwidth,
5254 .address_device = xhci_address_device,
5255 .enable_device = xhci_enable_device,
5256 .update_hub_device = xhci_update_hub_device,
5257 .reset_device = xhci_discover_or_reset_device,
5260 * scheduling support
5262 .get_frame_number = xhci_get_frame,
5267 .hub_control = xhci_hub_control,
5268 .hub_status_data = xhci_hub_status_data,
5269 .bus_suspend = xhci_bus_suspend,
5270 .bus_resume = xhci_bus_resume,
5271 .get_resuming_ports = xhci_get_resuming_ports,
5274 * call back when device connected and addressed
5276 .update_device = xhci_update_device,
5277 .set_usb2_hw_lpm = xhci_set_usb2_hardware_lpm,
5278 .enable_usb3_lpm_timeout = xhci_enable_usb3_lpm_timeout,
5279 .disable_usb3_lpm_timeout = xhci_disable_usb3_lpm_timeout,
5280 .find_raw_port_number = xhci_find_raw_port_number,
5283 void xhci_init_driver(struct hc_driver *drv,
5284 const struct xhci_driver_overrides *over)
5288 /* Copy the generic table to drv then apply the overrides */
5289 *drv = xhci_hc_driver;
5292 drv->hcd_priv_size += over->extra_priv_size;
5294 drv->reset = over->reset;
5296 drv->start = over->start;
5299 EXPORT_SYMBOL_GPL(xhci_init_driver);
5301 MODULE_DESCRIPTION(DRIVER_DESC);
5302 MODULE_AUTHOR(DRIVER_AUTHOR);
5303 MODULE_LICENSE("GPL");
5305 static int __init xhci_hcd_init(void)
5308 * Check the compiler generated sizes of structures that must be laid
5309 * out in specific ways for hardware access.
5311 BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
5312 BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
5313 BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
5314 /* xhci_device_control has eight fields, and also
5315 * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
5317 BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
5318 BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
5319 BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
5320 BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 8*32/8);
5321 BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
5322 /* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
5323 BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
5328 xhci_debugfs_create_root();
5334 * If an init function is provided, an exit function must also be provided
5335 * to allow module unload.
5337 static void __exit xhci_hcd_fini(void)
5339 xhci_debugfs_remove_root();
5342 module_init(xhci_hcd_init);
5343 module_exit(xhci_hcd_fini);